From 36a25b3bec2bb1fc400c60d33aebd02abfe1ab1f Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:44:28 -0500 Subject: [PATCH 001/152] feat(cos): parse and write COS objects (#36) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the COS object layer in Broadside.Objects: CosBoolean, CosNumber (CosInteger, CosReal), CosString, CosName, CosArray, CosDictionary, CosStream, CosNull and CosReference, with CosObject.Parse/TryParse, WriteTo and DeepEquals. ISO 32000-2 §7.2, §7.3. - Allocation-free internal lexer (ref struct over a span), proven by LexerAllocationTests and LexerBenchmarks. - Lenient internal parser that never throws and reports repairs with stable codes; the public Parse is strict on top of it. - Literal string escapes, octal, line continuation; hex strings with odd-digit padding; #xx name escapes; streams from a direct Length or from endstream. - Dirty flag on every object: false after parse, true after any mutation through the public API, aggregated over direct children. - Text strings decode PDFDocEncoding, UTF-16BE and UTF-8 with BOM detection (§7.9.2.2, Annex D). - Fuzz targets lexer and object-parser replace the pdf-header placeholder; object-parser checks the write-then-parse round trip. - Conformance rows 7.2.x, 7.3.x, 7.9.x and Annex D updated. Co-Authored-By: Claude Opus 5.5 --- bench/Broadside.Benchmarks/LexerBenchmarks.cs | 35 + docs/conformance/iso-32000-2.md | 26 +- src/Broadside/AssemblyMarker.cs | 6 - src/Broadside/Objects/CosArray.cs | 137 ++++ src/Broadside/Objects/CosBoolean.cs | 26 + src/Broadside/Objects/CosDictionary.cs | 164 +++++ src/Broadside/Objects/CosEquality.cs | 67 ++ src/Broadside/Objects/CosInteger.cs | 25 + src/Broadside/Objects/CosLexer.cs | 185 +++++ src/Broadside/Objects/CosName.cs | 64 ++ src/Broadside/Objects/CosNull.cs | 16 + src/Broadside/Objects/CosNumber.cs | 17 + src/Broadside/Objects/CosObject.cs | 132 ++++ src/Broadside/Objects/CosParser.cs | 684 ++++++++++++++++++ src/Broadside/Objects/CosReal.cs | 37 + src/Broadside/Objects/CosReference.cs | 40 + src/Broadside/Objects/CosRepair.cs | 72 ++ src/Broadside/Objects/CosStream.cs | 44 ++ src/Broadside/Objects/CosString.cs | 60 ++ src/Broadside/Objects/CosToken.cs | 50 ++ src/Broadside/Objects/CosWriter.cs | 244 +++++++ src/Broadside/Objects/KnownNames.cs | 8 + src/Broadside/Objects/TextStringDecoder.cs | 95 +++ src/Broadside/PublicAPI.Unshipped.txt | 92 +++ tests/Broadside.Fuzz/FuzzTargets.cs | 78 +- tests/Broadside.Fuzz/README.md | 16 +- tests/Broadside.Tests/CorpusSmokeTests.cs | 2 +- .../Objects/ContainerParsingTests.cs | 149 ++++ .../Objects/CorpusObjectTests.cs | 80 ++ .../Objects/DirtyTrackingTests.cs | 137 ++++ .../Objects/LexerAllocationTests.cs | 38 + .../Objects/ScalarParsingTests.cs | 118 +++ .../Objects/SerializationTests.cs | 192 +++++ .../Objects/StringAndNameParsingTests.cs | 154 ++++ .../Objects/TextStringTests.cs | 66 ++ tests/README.md | 2 +- 36 files changed, 3332 insertions(+), 26 deletions(-) create mode 100644 bench/Broadside.Benchmarks/LexerBenchmarks.cs delete mode 100644 src/Broadside/AssemblyMarker.cs create mode 100644 src/Broadside/Objects/CosArray.cs create mode 100644 src/Broadside/Objects/CosBoolean.cs create mode 100644 src/Broadside/Objects/CosDictionary.cs create mode 100644 src/Broadside/Objects/CosEquality.cs create mode 100644 src/Broadside/Objects/CosInteger.cs create mode 100644 src/Broadside/Objects/CosLexer.cs create mode 100644 src/Broadside/Objects/CosName.cs create mode 100644 src/Broadside/Objects/CosNull.cs create mode 100644 src/Broadside/Objects/CosNumber.cs create mode 100644 src/Broadside/Objects/CosObject.cs create mode 100644 src/Broadside/Objects/CosParser.cs create mode 100644 src/Broadside/Objects/CosReal.cs create mode 100644 src/Broadside/Objects/CosReference.cs create mode 100644 src/Broadside/Objects/CosRepair.cs create mode 100644 src/Broadside/Objects/CosStream.cs create mode 100644 src/Broadside/Objects/CosString.cs create mode 100644 src/Broadside/Objects/CosToken.cs create mode 100644 src/Broadside/Objects/CosWriter.cs create mode 100644 src/Broadside/Objects/KnownNames.cs create mode 100644 src/Broadside/Objects/TextStringDecoder.cs create mode 100644 tests/Broadside.Tests/Objects/ContainerParsingTests.cs create mode 100644 tests/Broadside.Tests/Objects/CorpusObjectTests.cs create mode 100644 tests/Broadside.Tests/Objects/DirtyTrackingTests.cs create mode 100644 tests/Broadside.Tests/Objects/LexerAllocationTests.cs create mode 100644 tests/Broadside.Tests/Objects/ScalarParsingTests.cs create mode 100644 tests/Broadside.Tests/Objects/SerializationTests.cs create mode 100644 tests/Broadside.Tests/Objects/StringAndNameParsingTests.cs create mode 100644 tests/Broadside.Tests/Objects/TextStringTests.cs diff --git a/bench/Broadside.Benchmarks/LexerBenchmarks.cs b/bench/Broadside.Benchmarks/LexerBenchmarks.cs new file mode 100644 index 00000000..cc8a9666 --- /dev/null +++ b/bench/Broadside.Benchmarks/LexerBenchmarks.cs @@ -0,0 +1,35 @@ +using BenchmarkDotNet.Attributes; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Benchmarks; + +/// +/// Tokenizes a whole corpus file with the COS lexer (ISO 32000-2 §7.2). The lexer is a hot path: Allocated must read +/// -; Broadside.Tests.Objects.LexerAllocationTests fails the build if it does not. +/// +[MemoryDiagnoser] +public class LexerBenchmarks +{ + private byte[] _bytes = []; + + /// The corpus file to tokenize: a text-only file and one with binary stream data. + [Params("empty-page.pdf", "text-truetype-embedded.pdf")] + public string File { get; set; } = ""; + + [GlobalSetup] + public void Setup() => _bytes = System.IO.File.ReadAllBytes(Path.Combine(CorpusLocator.CorpusDirectory, File)); + + [Benchmark] + public int Tokenize() + { + var lexer = new CosLexer(_bytes); + int count = 0; + while (lexer.Next().Kind != CosTokenKind.EndOfInput) + { + count++; + } + + return count; + } +} diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index 7082376e..1f53e14d 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -5,14 +5,32 @@ Clause numbers at the second level; split rows to the third level as clauses are | Clause | Title | Status | Implementing types | Tests | Notes | |---|---|---|---|---|---| | 7.1 | Syntax: General | not started | | | | -| 7.2 | Lexical conventions | not started | | | | -| 7.3 | Objects | not started | | | | +| 7.2.1 | General | n/a | | | Introductory text | +| 7.2.2 | Representation | done | `CosLexer`, `CosObject` | `Broadside.Tests.Objects.StringAndNameParsingTests.Literal_strings_may_hold_any_byte`, `Broadside.Tests.Objects.ContainerParsingTests.Stream_data_is_binary_and_may_contain_the_endstream_keyword_when_length_says_so`, `Broadside.Tests.Objects.LexerAllocationTests` | Lexer is internal and allocation-free (`bench/Broadside.Benchmarks/LexerBenchmarks.cs`); fuzz targets `lexer`, `object-parser` | +| 7.2.3 | Character set | done | `CosLexer` | `Broadside.Tests.Objects.ScalarParsingTests.Whitespace_and_comments_around_an_object_are_ignored`, `Broadside.Tests.Objects.ContainerParsingTests.Arrays_nest_hold_references_and_keep_null_elements`, `Broadside.Tests.Objects.SerializationTests.Writes_canonical_syntax` | | +| 7.2.4 | Comments | done | `CosLexer` | `Broadside.Tests.Objects.ScalarParsingTests.Whitespace_and_comments_around_an_object_are_ignored`, `Broadside.Tests.Objects.ScalarParsingTests.Parses_indirect_references` | Comments are skipped, not preserved (allowed by the clause) | +| 7.3.1 | General | done | `CosObject` | `Broadside.Tests.Objects.CorpusObjectTests`, `Broadside.Tests.Objects.SerializationTests.A_written_object_parses_back_to_an_equal_object` | Closed `CosObject` hierarchy; equality rules on `CosObject.DeepEquals`; dirty tracking on `CosObject.IsDirty` (`Broadside.Tests.Objects.DirtyTrackingTests`) | +| 7.3.2 | Boolean objects | done | `CosBoolean` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_booleans` | | +| 7.3.3 | Numeric objects | done | `CosNumber`, `CosInteger`, `CosReal` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_integers_from_the_spec_examples`, `Broadside.Tests.Objects.ScalarParsingTests.Parses_reals_from_the_spec_examples`, `Broadside.Tests.Objects.ScalarParsingTests.Integer_too_large_for_64_bits_is_read_as_a_real`, `Broadside.Tests.Objects.SerializationTests.Reals_round_trip_exactly_without_exponent_notation` | Integers are 64-bit; a larger integer literal reads as a real (Annex C); reals are written without exponent | +| 7.3.4 | String objects | done | `CosString` | `Broadside.Tests.Objects.StringAndNameParsingTests.Literal_strings_from_example_1_keep_balanced_parentheses`, `Broadside.Tests.Objects.StringAndNameParsingTests.Literal_strings_decode_every_escape_in_table_3`, `Broadside.Tests.Objects.StringAndNameParsingTests.Octal_escapes_take_one_to_three_digits_and_ignore_overflow`, `Broadside.Tests.Objects.StringAndNameParsingTests.Hexadecimal_strings_ignore_white_space_and_pad_an_odd_digit_with_zero`, `Broadside.Tests.Objects.SerializationTests.Every_byte_value_survives_a_round_trip_in_strings_and_names` | 7.3.4.1 to 7.3.4.3 | +| 7.3.5 | Name objects | done | `CosName` | `Broadside.Tests.Objects.StringAndNameParsingTests.Names_from_table_4_expand_number_sign_escapes`, `Broadside.Tests.Objects.StringAndNameParsingTests.Names_are_equal_when_their_expanded_bytes_are_equal`, `Broadside.Tests.Objects.SerializationTests.Names_escape_delimiters_white_space_number_signs_and_non_ascii_bytes` | | +| 7.3.6 | Array objects | done | `CosArray` | `Broadside.Tests.Objects.ContainerParsingTests.Parses_the_array_example`, `Broadside.Tests.Objects.ContainerParsingTests.Arrays_nest_hold_references_and_keep_null_elements` | | +| 7.3.7 | Dictionary objects | done | `CosDictionary` | `Broadside.Tests.Objects.ContainerParsingTests.Parses_the_dictionary_example`, `Broadside.Tests.Objects.ContainerParsingTests.A_null_valued_entry_is_the_same_as_an_absent_one` | Null-valued entries are never stored | +| 7.3.8 | Stream objects | partial | `CosStream` | `Broadside.Tests.Objects.ContainerParsingTests.A_stream_takes_its_data_from_its_length_or_from_endstream`, `Broadside.Tests.Objects.ContainerParsingTests.Streams_with_a_wrong_length_or_no_endstream_are_rejected`, `Broadside.Tests.Objects.CorpusObjectTests.The_metadata_stream_of_metadata_xmp_pdf_holds_its_declared_length` | Extent from a direct Length, else from endstream; resolving an indirect Length through the file (#37), external stream files (F, FFilter, FDecodeParms) and filters (#38) pending | +| 7.3.9 | Null object | done | `CosNull` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_null_as_the_single_null_object`, `Broadside.Tests.Objects.ContainerParsingTests.A_null_valued_entry_is_the_same_as_an_absent_one` | | +| 7.3.10 | Indirect objects | partial | `CosReference` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_indirect_references` | References (`N G R`) parse and write; `N G obj` … `endobj` definitions and resolving a reference belong to the file reader (#37) | | 7.4 | Filters | not started | | | | | 7.5 | File structure | not started | | | | | 7.6 | Encryption | not started | | | | | 7.7 | Document structure | not started | | | | | 7.8 | Content streams and resources | not started | | | | -| 7.9 | Common data structures | not started | | | | +| 7.9.1 | General | not started | | | | +| 7.9.2 | String object types | partial | `CosString` | `Broadside.Tests.Objects.TextStringTests` | Text strings decode (PDFDocEncoding, UTF-16BE, UTF-8, language escapes removed); encoding text into a string pending | +| 7.9.3 | Text streams | not started | | | | +| 7.9.4 | Dates | not started | | | | +| 7.9.5 | Rectangles | not started | | | | +| 7.9.6 | Name trees | not started | | | | +| 7.9.7 | Number trees | not started | | | | | 7.10 | Functions | not started | | | | | 7.11 | File specifications | not started | | | | | 7.12 | Extensions dictionary | not started | | | | @@ -85,7 +103,7 @@ Clause numbers at the second level; split rows to the third level as clauses are | Annex A | Operator summary | not started | | | | | Annex B | Operators in Type 4 functions | not started | | | | | Annex C | Implementation limits | not started | | | | -| Annex D | Character sets and encodings | not started | | | | +| Annex D | Character sets and encodings | partial | `CosString` | `Broadside.Tests.Objects.TextStringTests.Decodes_pdfdocencoding_when_there_is_no_byte_order_marker` | D.3 PDFDocEncoding decodes text strings; the font encodings of D.2 and D.4 to D.6 pending | | Annex E | PDF name registry | not started | | | | | Annex F | Linearized PDF | not started | | | | | Annex G | Linearized PDF access strategies | not started | | | | diff --git a/src/Broadside/AssemblyMarker.cs b/src/Broadside/AssemblyMarker.cs deleted file mode 100644 index 0fa69be1..00000000 --- a/src/Broadside/AssemblyMarker.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Broadside; - -/// Keeps the assembly non-empty until the first real type lands. -internal static class AssemblyMarker -{ -} diff --git a/src/Broadside/Objects/CosArray.cs b/src/Broadside/Objects/CosArray.cs new file mode 100644 index 00000000..580d2c8f --- /dev/null +++ b/src/Broadside/Objects/CosArray.cs @@ -0,0 +1,137 @@ +using System.Collections; +using System.Diagnostics.CodeAnalysis; + +namespace Broadside.Objects; + +/// An array object: a mutable, ordered, heterogeneous list of objects, written […]. +/// +/// ISO 32000-2 §7.3.6. Elements are never C# ; the PDF null is , which an array +/// keeps (unlike a dictionary, where null means absent). Any change through the list API marks the array dirty. +/// +[SuppressMessage("Naming", "CA1710:Identifiers should have correct suffix", Justification = "The name is the ISO 32000-2 term (§7.3.6); the Cos prefix is the convention for the COS layer.")] +public sealed class CosArray : CosObject, IList, IReadOnlyList +{ + private readonly List _items; + private bool _changed; + + /// Initializes a new, empty instance of the class. + public CosArray() => _items = []; + + /// Initializes a new instance of the class holding . + /// The elements, in order. None may be . + /// An element is . + public CosArray(IEnumerable items) + { + ArgumentNullException.ThrowIfNull(items); + _items = [.. items]; + if (_items.Contains(null!)) + { + throw new ArgumentException("An array element cannot be null; use CosNull.Instance.", nameof(items)); + } + } + + private CosArray(List items, bool owned) => _items = owned ? items : [.. items]; + + /// + public override bool IsDirty + { + get + { + if (_changed) + { + return true; + } + + foreach (CosObject item in _items) + { + if (item.IsDirty) + { + return true; + } + } + + return false; + } + } + + /// Gets the number of elements. + public int Count => _items.Count; + + /// + bool ICollection.IsReadOnly => false; + + /// Gets or sets the element at . Setting marks the array dirty. + /// The zero-based index. + public CosObject this[int index] + { + get => _items[index]; + set + { + ArgumentNullException.ThrowIfNull(value); + _items[index] = value; + _changed = true; + } + } + + /// Appends an element and marks the array dirty. + /// The element. + public void Add(CosObject item) + { + ArgumentNullException.ThrowIfNull(item); + _items.Add(item); + _changed = true; + } + + /// Inserts an element and marks the array dirty. + /// The zero-based index to insert at. + /// The element. + public void Insert(int index, CosObject item) + { + ArgumentNullException.ThrowIfNull(item); + _items.Insert(index, item); + _changed = true; + } + + /// Removes the element at and marks the array dirty. + /// The zero-based index. + public void RemoveAt(int index) + { + _items.RemoveAt(index); + _changed = true; + } + + /// Removes the first element equal to ; marks the array dirty when one was removed. + /// The element to remove, compared with . + /// when an element was removed. + public bool Remove(CosObject item) + { + bool removed = _items.Remove(item); + _changed |= removed; + return removed; + } + + /// Removes every element; marks the array dirty when it was not already empty. + public void Clear() + { + _changed |= _items.Count > 0; + _items.Clear(); + } + + /// + public int IndexOf(CosObject item) => _items.IndexOf(item); + + /// + public bool Contains(CosObject item) => _items.Contains(item); + + /// + public void CopyTo(CosObject[] array, int arrayIndex) => _items.CopyTo(array, arrayIndex); + + /// + public IEnumerator GetEnumerator() => _items.GetEnumerator(); + + /// + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + /// Wraps a list the caller gives up ownership of, without copying it and without marking the array dirty. + internal static CosArray FromOwnedList(List items) => new(items, owned: true); +} diff --git a/src/Broadside/Objects/CosBoolean.cs b/src/Broadside/Objects/CosBoolean.cs new file mode 100644 index 00000000..b2e4bb96 --- /dev/null +++ b/src/Broadside/Objects/CosBoolean.cs @@ -0,0 +1,26 @@ +namespace Broadside.Objects; + +/// A boolean object: true or false. There are exactly two instances, and . +/// ISO 32000-2 §7.3.2. +public sealed class CosBoolean : CosObject, IEquatable +{ + private CosBoolean(bool value) => Value = value; + + /// Gets the true object. + public static CosBoolean True { get; } = new(value: true); + + /// Gets the false object. + public static CosBoolean False { get; } = new(value: false); + + /// Gets the value. + public bool Value { get; } + + /// + public bool Equals(CosBoolean? other) => other is not null && other.Value == Value; + + /// + public override bool Equals(object? obj) => Equals(obj as CosBoolean); + + /// + public override int GetHashCode() => Value.GetHashCode(); +} diff --git a/src/Broadside/Objects/CosDictionary.cs b/src/Broadside/Objects/CosDictionary.cs new file mode 100644 index 00000000..9898b3ec --- /dev/null +++ b/src/Broadside/Objects/CosDictionary.cs @@ -0,0 +1,164 @@ +using System.Collections; +using System.Diagnostics.CodeAnalysis; + +namespace Broadside.Objects; + +/// A dictionary object: a mutable table from names to objects, written <<…>>. +/// +/// +/// ISO 32000-2 §7.3.7. Keys are objects. An entry whose value is null is the same as an absent entry, so a +/// dictionary never stores : setting an entry to removes it, adding one does +/// nothing, and a parser drops null-valued entries. Entries keep the order they were added in, which is the order they are +/// written in; the order carries no meaning and ignores it. +/// +/// Any change through the dictionary API marks the dictionary dirty. +/// +public sealed class CosDictionary : CosObject, IDictionary, IReadOnlyDictionary +{ + private readonly OrderedDictionary _entries; + private bool _changed; + + /// Initializes a new, empty instance of the class. + public CosDictionary() => _entries = []; + + private CosDictionary(OrderedDictionary entries) => _entries = entries; + + /// + public override bool IsDirty + { + get + { + if (_changed) + { + return true; + } + + foreach (KeyValuePair entry in _entries) + { + if (entry.Value.IsDirty) + { + return true; + } + } + + return false; + } + } + + /// Gets the number of entries. + public int Count => _entries.Count; + + /// Gets the keys, in entry order. + public ICollection Keys => _entries.Keys; + + /// Gets the values, in entry order. + public ICollection Values => _entries.Values; + + /// + IEnumerable IReadOnlyDictionary.Keys => _entries.Keys; + + /// + IEnumerable IReadOnlyDictionary.Values => _entries.Values; + + /// + bool ICollection>.IsReadOnly => false; + + /// + /// Gets or sets the value for . Setting removes the entry. Setting marks the + /// dictionary dirty. + /// + /// The key. + /// On get, the dictionary has no entry for . + [SuppressMessage("Design", "CA1043:Use integral or string argument for indexers", Justification = "Dictionary keys are names (ISO 32000-2 §7.3.7); this is the IDictionary indexer.")] + public CosObject this[CosName key] + { + get => _entries[key]; + set + { + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(value); + if (value is CosNull) + { + Remove(key); + return; + } + + _entries[key] = value; + _changed = true; + } + } + + /// Adds an entry and marks the dictionary dirty. Adding adds nothing. + /// The key. + /// The value. + /// The dictionary already has an entry for . + public void Add(CosName key, CosObject value) + { + ArgumentNullException.ThrowIfNull(key); + ArgumentNullException.ThrowIfNull(value); + if (value is CosNull) + { + if (_entries.ContainsKey(key)) + { + throw new ArgumentException("The dictionary already has an entry for this key.", nameof(key)); + } + + return; + } + + _entries.Add(key, value); + _changed = true; + } + + /// Removes the entry for ; marks the dictionary dirty when one was removed. + /// The key. + /// when an entry was removed. + public bool Remove(CosName key) + { + bool removed = _entries.Remove(key); + _changed |= removed; + return removed; + } + + /// Removes every entry; marks the dictionary dirty when it was not already empty. + public void Clear() + { + _changed |= _entries.Count > 0; + _entries.Clear(); + } + + /// + public bool ContainsKey(CosName key) => _entries.ContainsKey(key); + + /// + public bool TryGetValue(CosName key, [MaybeNullWhen(false)] out CosObject value) => _entries.TryGetValue(key, out value); + + /// Returns the entries, in entry order. + /// An enumerator over the entries. + public IEnumerator> GetEnumerator() => _entries.GetEnumerator(); + + /// + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + /// + void ICollection>.Add(KeyValuePair item) => Add(item.Key, item.Value); + + /// + bool ICollection>.Contains(KeyValuePair item) => + ((ICollection>)_entries).Contains(item); + + /// + void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) => + ((ICollection>)_entries).CopyTo(array, arrayIndex); + + /// + bool ICollection>.Remove(KeyValuePair item) + { + bool removed = ((ICollection>)_entries).Remove(item); + _changed |= removed; + return removed; + } + + /// Wraps entries the caller gives up ownership of, without copying them and without marking the dictionary dirty. + internal static CosDictionary FromOwnedEntries(OrderedDictionary entries) => new(entries); +} diff --git a/src/Broadside/Objects/CosEquality.cs b/src/Broadside/Objects/CosEquality.cs new file mode 100644 index 00000000..6010e633 --- /dev/null +++ b/src/Broadside/Objects/CosEquality.cs @@ -0,0 +1,67 @@ +namespace Broadside.Objects; + +/// Structural equality of COS objects; the rules are documented on . +/// ISO 32000-2 §7.3. +internal static class CosEquality +{ + public static bool DeepEquals(CosObject? left, CosObject? right) + { + if (ReferenceEquals(left, right)) + { + return true; + } + + return (left, right) switch + { + (null, _) or (_, null) => false, + (CosArray a, CosArray b) => ArraysEqual(a, b), + (CosDictionary a, CosDictionary b) => DictionariesEqual(a, b, ignoreLength: false), + (CosStream a, CosStream b) => DictionariesEqual(a.Dictionary, b.Dictionary, ignoreLength: true) + && a.EncodedData.Span.SequenceEqual(b.EncodedData.Span), + _ => left.Equals(right), + }; + } + + private static bool ArraysEqual(CosArray left, CosArray right) + { + if (left.Count != right.Count) + { + return false; + } + + for (int i = 0; i < left.Count; i++) + { + if (!DeepEquals(left[i], right[i])) + { + return false; + } + } + + return true; + } + + private static bool DictionariesEqual(CosDictionary left, CosDictionary right, bool ignoreLength) + { + int leftCount = left.Count - (ignoreLength && left.ContainsKey(KnownNames.Length) ? 1 : 0); + int rightCount = right.Count - (ignoreLength && right.ContainsKey(KnownNames.Length) ? 1 : 0); + if (leftCount != rightCount) + { + return false; + } + + foreach (KeyValuePair entry in left) + { + if (ignoreLength && entry.Key.Equals(KnownNames.Length)) + { + continue; + } + + if (!right.TryGetValue(entry.Key, out CosObject? other) || !DeepEquals(entry.Value, other)) + { + return false; + } + } + + return true; + } +} diff --git a/src/Broadside/Objects/CosInteger.cs b/src/Broadside/Objects/CosInteger.cs new file mode 100644 index 00000000..0dd6eca4 --- /dev/null +++ b/src/Broadside/Objects/CosInteger.cs @@ -0,0 +1,25 @@ +namespace Broadside.Objects; + +/// An integer object. +/// +/// ISO 32000-2 §7.3.3. The range is that of ; a parser reads an integer literal beyond that range as a +/// (Annex C lets a processor limit the range). +/// +/// The value. +public sealed class CosInteger(long value) : CosNumber, IEquatable +{ + /// Gets the value. + public long Value { get; } = value; + + /// + public override double ToDouble() => Value; + + /// + public bool Equals(CosInteger? other) => other is not null && other.Value == Value; + + /// + public override bool Equals(object? obj) => Equals(obj as CosInteger); + + /// + public override int GetHashCode() => Value.GetHashCode(); +} diff --git a/src/Broadside/Objects/CosLexer.cs b/src/Broadside/Objects/CosLexer.cs new file mode 100644 index 00000000..76eb557a --- /dev/null +++ b/src/Broadside/Objects/CosLexer.cs @@ -0,0 +1,185 @@ +using System.Buffers; + +namespace Broadside.Objects; + +/// Splits a byte span into COS tokens without allocating. +/// +/// ISO 32000-2 §7.2. White-space (Table 1) and comments (§7.2.4) separate tokens and are skipped; delimiters (Table 2) end a run of +/// regular characters. The lexer never fails: bytes that cannot start a token become tokens and +/// unterminated strings run to the end of input, so the parser decides what is a deviation. Every call to either +/// advances by at least one byte or returns . +/// +internal ref struct CosLexer +{ + private static readonly SearchValues Whitespace = SearchValues.Create("\0\t\n\f\r "u8); + private static readonly SearchValues EndOfRegular = SearchValues.Create("\0\t\n\f\r ()<>[]{}/%"u8); + private static readonly SearchValues NumberCharacters = SearchValues.Create("+-.0123456789"u8); + private static readonly SearchValues EndOfLine = SearchValues.Create("\r\n"u8); + private static readonly SearchValues LiteralSpecial = SearchValues.Create("()\\"u8); + + private readonly ReadOnlySpan _source; + + /// Initializes a new instance of the struct. + /// The bytes to tokenize. + /// The offset to start at. + public CosLexer(ReadOnlySpan source, int position = 0) + { + _source = source; + Position = position; + } + + /// Gets or sets the offset of the next byte to read. + public int Position { get; set; } + + /// Gets the source span. + public readonly ReadOnlySpan Source => _source; + + /// Returns whether is a white-space character (Table 1). + public static bool IsWhitespace(byte value) => Whitespace.Contains(value); + + /// Returns whether is a regular character: neither white-space nor a delimiter (§7.2.3). + public static bool IsRegular(byte value) => !EndOfRegular.Contains(value); + + /// Skips white-space and comments. + public void SkipWhitespaceAndComments() + { + int position = Position; + while (true) + { + int skip = _source[position..].IndexOfAnyExcept(Whitespace); + if (skip < 0) + { + Position = _source.Length; + return; + } + + position += skip; + if (_source[position] != (byte)'%') + { + Position = position; + return; + } + + int endOfLine = _source[position..].IndexOfAny(EndOfLine); + if (endOfLine < 0) + { + Position = _source.Length; + return; + } + + position += endOfLine; + } + } + + /// Returns the next token without consuming it. + public CosToken Peek() + { + int saved = Position; + CosToken token = Next(); + Position = saved; + return token; + } + + /// Reads the next token. + public CosToken Next() + { + SkipWhitespaceAndComments(); + int start = Position; + if (start >= _source.Length) + { + return new CosToken(CosTokenKind.EndOfInput, start, 0); + } + + CosToken token = _source[start] switch + { + (byte)'(' => new CosToken(CosTokenKind.LiteralString, start, LiteralStringLength(_source[start..])), + (byte)'<' => LessThan(start), + (byte)'>' => start + 1 < _source.Length && _source[start + 1] == (byte)'>' + ? new CosToken(CosTokenKind.DictionaryEnd, start, 2) + : new CosToken(CosTokenKind.Invalid, start, 1), + (byte)'[' => new CosToken(CosTokenKind.ArrayStart, start, 1), + (byte)']' => new CosToken(CosTokenKind.ArrayEnd, start, 1), + (byte)'{' or (byte)'}' => new CosToken(CosTokenKind.Keyword, start, 1), + (byte)')' => new CosToken(CosTokenKind.Invalid, start, 1), + (byte)'/' => new CosToken(CosTokenKind.Name, start, 1 + RegularRunLength(start + 1)), + _ => RegularRun(start), + }; + + Position = token.End; + return token; + } + + private readonly CosToken LessThan(int start) + { + if (start + 1 < _source.Length && _source[start + 1] == (byte)'<') + { + return new CosToken(CosTokenKind.DictionaryStart, start, 2); + } + + int close = _source[(start + 1)..].IndexOf((byte)'>'); + int length = close < 0 ? _source.Length - start : close + 2; + return new CosToken(CosTokenKind.HexString, start, length); + } + + private readonly CosToken RegularRun(int start) + { + int length = RegularRunLength(start); + ReadOnlySpan run = _source.Slice(start, length); + if (!run.ContainsAnyExcept(NumberCharacters) && run.ContainsAnyInRange((byte)'0', (byte)'9')) + { + return new CosToken(run.Contains((byte)'.') ? CosTokenKind.Real : CosTokenKind.Integer, start, length); + } + + return new CosToken(CosTokenKind.Keyword, start, length); + } + + private readonly int RegularRunLength(int start) + { + int end = _source[start..].IndexOfAny(EndOfRegular); + return end < 0 ? _source.Length - start : end; + } + + /// + /// The length of the literal string that starts at [0], through its matching closing parenthesis, or the + /// whole span when the string is unterminated. A backslash escapes the byte after it; other parentheses nest (§7.3.4.2). + /// + private static int LiteralStringLength(ReadOnlySpan text) + { + int depth = 1; + int index = 1; + while (true) + { + int special = text[index..].IndexOfAny(LiteralSpecial); + if (special < 0) + { + return text.Length; + } + + index += special; + switch (text[index]) + { + case (byte)'\\': + index += 2; + if (index >= text.Length) + { + return text.Length; + } + + continue; + case (byte)'(': + depth++; + break; + default: + depth--; + if (depth == 0) + { + return index + 1; + } + + break; + } + + index++; + } + } +} diff --git a/src/Broadside/Objects/CosName.cs b/src/Broadside/Objects/CosName.cs new file mode 100644 index 00000000..50259f50 --- /dev/null +++ b/src/Broadside/Objects/CosName.cs @@ -0,0 +1,64 @@ +using System.Text; + +namespace Broadside.Objects; + +/// A name object: an atomic symbol defined by a sequence of bytes, written /Name. +/// +/// ISO 32000-2 §7.3.5. The identity of a name is its bytes after #xx escapes are expanded: /A#42 and /AB are the +/// same name. A name may hold any byte except 0. When a name must be read as text (a font name, a colorant, a structure type) its +/// bytes are UTF-8, which is what returns. +/// +public sealed class CosName : CosObject, IEquatable +{ + private readonly byte[] _bytes; + private readonly int _hashCode; + private string? _value; + + /// Initializes a new instance of the class from text, encoded as UTF-8. + /// The name without the leading solidus and without escapes, for example Type or Lime Green. + /// contains U+0000. + public CosName(string value) + : this(Encoding.UTF8.GetBytes(value ?? throw new ArgumentNullException(nameof(value))), nameof(value)) + { + _value = value; + } + + /// Initializes a new instance of the class from its bytes. + /// The name's bytes without the leading solidus and with escapes expanded; copied. + /// contains the byte 0. + public CosName(ReadOnlySpan bytes) + : this(bytes.ToArray(), nameof(bytes)) + { + } + + private CosName(byte[] bytes, string parameterName) + { + if (bytes.AsSpan().Contains((byte)0)) + { + throw new ArgumentException("A PDF name cannot contain the byte 0 (ISO 32000-2 §7.3.5).", parameterName); + } + + _bytes = bytes; + var hash = new HashCode(); + hash.AddBytes(bytes); + _hashCode = hash.ToHashCode(); + } + + /// Gets the name's bytes, without the leading solidus and with #xx escapes expanded. + public ReadOnlySpan Bytes => _bytes; + + /// Gets the name's bytes decoded as UTF-8; invalid sequences decode to U+FFFD. + public string Value => _value ??= Encoding.UTF8.GetString(_bytes); + + /// + public bool Equals(CosName? other) => other is not null && (ReferenceEquals(this, other) || _bytes.AsSpan().SequenceEqual(other._bytes)); + + /// + public override bool Equals(object? obj) => Equals(obj as CosName); + + /// + public override int GetHashCode() => _hashCode; + + /// Wraps an array the caller gives up ownership of, without copying it. The array must not contain 0. + internal static CosName FromOwnedBytes(byte[] bytes) => new(bytes, nameof(bytes)); +} diff --git a/src/Broadside/Objects/CosNull.cs b/src/Broadside/Objects/CosNull.cs new file mode 100644 index 00000000..dabc254a --- /dev/null +++ b/src/Broadside/Objects/CosNull.cs @@ -0,0 +1,16 @@ +namespace Broadside.Objects; + +/// The null object. There is exactly one, . +/// +/// ISO 32000-2 §7.3.9. A dictionary entry whose value is null is the same as an absent entry, so never +/// stores one; an indirect reference to an object that does not exist resolves to null. +/// +public sealed class CosNull : CosObject +{ + private CosNull() + { + } + + /// Gets the null object. + public static CosNull Instance { get; } = new(); +} diff --git a/src/Broadside/Objects/CosNumber.cs b/src/Broadside/Objects/CosNumber.cs new file mode 100644 index 00000000..35c9c92c --- /dev/null +++ b/src/Broadside/Objects/CosNumber.cs @@ -0,0 +1,17 @@ +namespace Broadside.Objects; + +/// A numeric object: either a or a . +/// +/// ISO 32000-2 §7.3.3. "Number" in the specification means an object that is either an integer or a real; wherever a real is +/// expected an integer may be used instead, which is what is for. +/// +public abstract class CosNumber : CosObject +{ + private protected CosNumber() + { + } + + /// Returns the value as a double-precision real, whichever kind of number this is. + /// The value. Integers beyond 2^53 in magnitude round to the nearest representable double. + public abstract double ToDouble(); +} diff --git a/src/Broadside/Objects/CosObject.cs b/src/Broadside/Objects/CosObject.cs new file mode 100644 index 00000000..2c6aa4f0 --- /dev/null +++ b/src/Broadside/Objects/CosObject.cs @@ -0,0 +1,132 @@ +using System.Buffers; +using System.Diagnostics.CodeAnalysis; +using System.Text; + +namespace Broadside.Objects; + +/// +/// One COS object: a value exactly as a PDF file stores it. The hierarchy is closed; every object is one of +/// , , , , , +/// , , , or . +/// +/// +/// ISO 32000-2 §7.3. +/// +/// Mutability. Booleans, numbers, strings, names, null and references are immutable values. Arrays, dictionaries and +/// streams are mutable containers. +/// +/// +/// Dirty tracking. is for every object a parser produces and for every newly +/// constructed object, and becomes once the object, or any direct object it contains, is changed through the +/// public API. Immutable objects are never dirty; replacing one inside a container makes the container dirty. Indirect references +/// are not followed: a change to the object a points to does not make the referring container dirty. +/// +/// +/// Equality. is value equality for the immutable objects and reference identity for the +/// mutable containers, so a container is safe as a hash key while it changes. compares structure, and is +/// the equality a serialize-then-parse round trip preserves. +/// +/// +public abstract class CosObject +{ + private protected CosObject() + { + } + + /// + /// Gets a value indicating whether this object, or a direct object it contains, has been changed through the public API since it + /// was parsed or constructed. Always for immutable objects. + /// + /// ISO 32000-2 §7.5.6: the basis for writing an incremental update. + public virtual bool IsDirty => false; + + /// Parses exactly one COS object from . + /// The object's syntax, optionally surrounded by white-space and comments. + /// The parsed object. Parsed objects are not dirty. + /// + /// The bytes are empty, hold more than one object, or deviate from the syntax of ISO 32000-2 §7.2 and §7.3 in any way that a + /// reader would have to repair. Standalone parsing is strict; lenient reading with diagnostics happens when a document is read. + /// + /// + /// ISO 32000-2 §7.2 and §7.3. A stream (a dictionary followed by stream … endstream) takes its data extent from a + /// direct Length entry; when Length is an indirect reference, the data ends at the endstream keyword. + /// The N G obj … endobj wrapper of an indirect object definition is file structure (§7.3.10) and is not accepted here. + /// + public static CosObject Parse(ReadOnlySpan bytes) + { + if (TryParseCore(bytes, out CosObject? result, out CosRepair? firstRepair)) + { + return result; + } + + throw new FormatException(firstRepair!.Value.ToString()); + } + + /// Tries to parse exactly one COS object from , under the same rules as . + /// The object's syntax, optionally surrounded by white-space and comments. + /// The parsed object, or when the bytes are not exactly one well-formed object. + /// when the bytes hold exactly one well-formed object. + /// ISO 32000-2 §7.2 and §7.3. + public static bool TryParse(ReadOnlySpan bytes, [NotNullWhen(true)] out CosObject? result) => + TryParseCore(bytes, out result, out _); + + /// + /// Compares two objects by structure: the same kind of object with the same value, recursively for containers. + /// + /// The first object, or . + /// The second object, or . + /// when the two objects are structurally equal. + /// + /// ISO 32000-2 §7.3. The rules: + /// + /// The kinds must match: the integer 1 is not equal to the real 1.0. + /// Strings compare their bytes; whether a string was written in literal or hexadecimal form does not matter (§7.3.4). + /// Names compare their bytes after #xx escapes are expanded (§7.3.5). + /// Arrays compare element by element, in order. + /// Dictionaries compare their entries regardless of order (§7.3.7). A dictionary never holds a null value (see ). + /// Streams compare their dictionaries, ignoring the Length entry, and their encoded data byte for byte; Length is a property of the serialization, not of the stream (§7.3.8). + /// References compare object and generation numbers; the objects they point to are not compared (§7.3.10). + /// Two arguments are equal; never equals an object, not even . + /// + /// + public static bool DeepEquals(CosObject? left, CosObject? right) => CosEquality.DeepEquals(left, right); + + /// Writes this object's PDF syntax to . + /// The destination. + /// + /// ISO 32000-2 §7.2 and §7.3. The output parses back, through , to an object that this + /// one. A stream is written with a direct Length equal to its encoded data length. + /// + public void WriteTo(IBufferWriter writer) + { + ArgumentNullException.ThrowIfNull(writer); + CosWriter.Write(this, writer); + } + + /// Returns this object's PDF syntax, as writes it, with each byte shown as its Latin-1 character. + /// The PDF syntax of this object. + public override string ToString() + { + var buffer = new ArrayBufferWriter(); + CosWriter.Write(this, buffer); + return Encoding.Latin1.GetString(buffer.WrittenSpan); + } + + private static bool TryParseCore(ReadOnlySpan bytes, [NotNullWhen(true)] out CosObject? result, out CosRepair? firstRepair) + { + var repairs = new CosRepairLog(); + var parser = new CosParser(bytes, repairs); + CosObject parsed = parser.ParseObject(); + parser.ExpectEndOfInput(); + + firstRepair = repairs.First; + if (firstRepair is not null) + { + result = null; + return false; + } + + result = parsed; + return true; + } +} diff --git a/src/Broadside/Objects/CosParser.cs b/src/Broadside/Objects/CosParser.cs new file mode 100644 index 00000000..873962dc --- /dev/null +++ b/src/Broadside/Objects/CosParser.cs @@ -0,0 +1,684 @@ +using System.Buffers; +using System.Globalization; + +namespace Broadside.Objects; + +/// Builds COS objects from the tokens of a . +/// +/// +/// ISO 32000-2 §7.3. The parser is lenient and never throws on any input: every deviation from the syntax is repaired and reported to +/// the (ADR 0005); a caller that wants strictness checks the log. Nesting deeper than +/// is skipped, so hostile input cannot exhaust the stack. +/// +/// +/// The parser reads objects only. The N G obj … endobj wrapper, cross-reference sections and the trailer are file +/// structure (§7.5) and belong to the file reader, which positions this parser at each object. +/// +/// +internal ref struct CosParser +{ + /// The deepest nesting of arrays and dictionaries the parser builds; deeper containers are skipped and read as null. + public const int MaxDepth = 256; + + private static readonly SearchValues DigitsAndPeriod = SearchValues.Create("0123456789."u8); + + private CosLexer _lexer; + private readonly CosRepairLog? _repairs; + + /// Initializes a new instance of the struct. + /// The bytes to parse. + /// Where to report repairs, or to discard them. + /// The offset to start at. + public CosParser(ReadOnlySpan source, CosRepairLog? repairs, int position = 0) + { + _lexer = new CosLexer(source, position); + _repairs = repairs; + } + + /// Gets or sets the offset of the next byte to read. + public int Position + { + readonly get => _lexer.Position; + set => _lexer.Position = value; + } + + /// Returns whether only white-space and comments remain. + public bool IsAtEnd() + { + _lexer.SkipWhitespaceAndComments(); + return _lexer.Position >= _lexer.Source.Length; + } + + /// Reports a repair when anything other than white-space and comments remains. + public void ExpectEndOfInput() + { + if (!IsAtEnd()) + { + Report(CosRepairCodes.TrailingContent, _lexer.Position, "Expected the end of the input after the object."); + } + } + + /// Reads one object. At the end of input, or on a token that cannot start an object, reports a repair and returns null. + public CosObject ParseObject() => ParseObject(depth: 0); + + private CosObject ParseObject(int depth) + { + CosToken token = _lexer.Next(); + switch (token.Kind) + { + case CosTokenKind.EndOfInput: + Report(CosRepairCodes.UnexpectedEndOfInput, token.Start, "Expected an object."); + return CosNull.Instance; + case CosTokenKind.Integer: + return ParseIntegerOrReference(token); + case CosTokenKind.Real: + return ParseNumber(token); + case CosTokenKind.LiteralString: + return ParseLiteralString(token); + case CosTokenKind.HexString: + return ParseHexString(token); + case CosTokenKind.Name: + return ParseName(token); + case CosTokenKind.ArrayStart: + return depth >= MaxDepth ? SkipTooDeep(token) : ParseArray(token, depth + 1); + case CosTokenKind.DictionaryStart: + return depth >= MaxDepth ? SkipTooDeep(token) : ParseDictionaryOrStream(token, depth + 1); + case CosTokenKind.Keyword: + ReadOnlySpan keyword = Bytes(token); + if (keyword.SequenceEqual("true"u8)) + { + return CosBoolean.True; + } + + if (keyword.SequenceEqual("false"u8)) + { + return CosBoolean.False; + } + + if (keyword.SequenceEqual("null"u8)) + { + return CosNull.Instance; + } + + break; + } + + ReportUnexpected(token); + return CosNull.Instance; + } + + private CosObject ParseIntegerOrReference(CosToken first) + { + CosNumber number = ParseNumber(first); + if (number is not CosInteger { Value: var objectNumber }) + { + return number; + } + + int afterFirst = _lexer.Position; + CosToken second = _lexer.Next(); + if (second.Kind == CosTokenKind.Integer) + { + CosToken third = _lexer.Next(); + if (third.Kind == CosTokenKind.Keyword && Bytes(third).SequenceEqual("R"u8)) + { + bool validGeneration = TryParseStrictInteger(Bytes(second), out long generation); + if (objectNumber is >= 1 and <= int.MaxValue && validGeneration && generation is >= 0 and <= CosReference.MaxGeneration) + { + return new CosReference((int)objectNumber, (int)generation); + } + + Report( + CosRepairCodes.ReferenceInvalid, + first.Start, + "An indirect reference needs a positive object number and a generation number from 0 to 65535; read as null."); + return CosNull.Instance; + } + } + + _lexer.Position = afterFirst; + return number; + } + + private readonly CosNumber ParseNumber(CosToken token) + { + ReadOnlySpan text = Bytes(token); + if (token.Kind == CosTokenKind.Integer && TryParseStrictInteger(text, out long integer)) + { + return new CosInteger(integer); + } + + if (!IsWellFormedNumber(text)) + { + Report(CosRepairCodes.NumberMalformed, token.Start, "A number must be digits with an optional sign and at most one period."); + Span scratch = text.Length < 256 ? stackalloc byte[256] : new byte[text.Length + 2]; + ReadOnlySpan prefix = WellFormedPrefix(text, scratch); + return !prefix.Contains((byte)'.') && TryParseStrictInteger(prefix, out integer) + ? new CosInteger(integer) + : ParseReal(prefix, token); + } + + // A well-formed real, or an integer too large for 64 bits (Annex C: read as a real). + return ParseReal(text, token); + } + + private readonly CosReal ParseReal(ReadOnlySpan text, CosToken token) + { + double value = double.Parse(text, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); + if (!double.IsFinite(value)) + { + Report(CosRepairCodes.NumberOutOfRange, token.Start, "The number is too large for a double; clamped to the largest finite value."); + value = double.IsNegative(value) ? double.MinValue : double.MaxValue; + } + + return new CosReal(value); + } + + private readonly CosString ParseLiteralString(CosToken token) + { + ReadOnlySpan text = Bytes(token); + byte[]? rented = null; + Span output = text.Length <= 256 ? stackalloc byte[256] : (rented = ArrayPool.Shared.Rent(text.Length)); + int written = 0; + int depth = 1; + int index = 1; + while (index < text.Length) + { + byte current = text[index]; + switch (current) + { + case (byte)'\\': + index = ReadEscape(text, index, output, ref written); + continue; + case (byte)'(': + depth++; + break; + case (byte)')': + depth--; + if (depth == 0) + { + index = text.Length; + continue; + } + + break; + case (byte)'\r': + // §7.3.4.2: an unescaped end-of-line marker is read as a single LINE FEED. + current = (byte)'\n'; + if (index + 1 < text.Length && text[index + 1] == (byte)'\n') + { + index++; + } + + break; + } + + output[written++] = current; + index++; + } + + if (depth != 0) + { + Report(CosRepairCodes.StringUnterminated, token.Start, "The literal string has no closing parenthesis; it runs to the end of the input."); + } + + var result = CosString.FromOwnedBytes(output[..written].ToArray(), hexadecimal: false); + if (rented is not null) + { + ArrayPool.Shared.Return(rented); + } + + return result; + } + + /// Reads the escape sequence at [] (a backslash) and returns the index after it (§7.3.4.2, Table 3). + private static int ReadEscape(ReadOnlySpan text, int index, Span output, ref int written) + { + if (index + 1 >= text.Length) + { + // A backslash as the last byte of an unterminated string: nothing follows it to escape. + return text.Length; + } + + byte escaped = text[index + 1]; + switch (escaped) + { + case (byte)'n': + output[written++] = (byte)'\n'; + return index + 2; + case (byte)'r': + output[written++] = (byte)'\r'; + return index + 2; + case (byte)'t': + output[written++] = (byte)'\t'; + return index + 2; + case (byte)'b': + output[written++] = 0x08; + return index + 2; + case (byte)'f': + output[written++] = 0x0C; + return index + 2; + case (byte)'(' or (byte)')' or (byte)'\\': + output[written++] = escaped; + return index + 2; + case (byte)'\r': + // A backslash before an end-of-line marker continues the string on the next line; both are dropped. + return index + 2 < text.Length && text[index + 2] == (byte)'\n' ? index + 3 : index + 2; + case (byte)'\n': + return index + 2; + case >= (byte)'0' and <= (byte)'7': + int code = 0; + int digit = index + 1; + int end = Math.Min(index + 4, text.Length); + while (digit < end && text[digit] is >= (byte)'0' and <= (byte)'7') + { + code = (code * 8) + (text[digit] - '0'); + digit++; + } + + // High-order overflow of a three-digit code is ignored. + output[written++] = (byte)code; + return digit; + default: + // Not an escape sequence: the backslash is ignored and the byte after it is read normally. + return index + 1; + } + } + + private readonly CosString ParseHexString(CosToken token) + { + ReadOnlySpan text = Bytes(token); + bool terminated = text.Length >= 2 && text[^1] == (byte)'>'; + ReadOnlySpan digits = terminated ? text[1..^1] : text[1..]; + byte[] output = new byte[(digits.Length + 1) / 2]; + int written = 0; + int high = -1; + bool reportedInvalid = false; + foreach (byte character in digits) + { + int nibble = HexValue(character); + if (nibble < 0) + { + if (!CosLexer.IsWhitespace(character) && !reportedInvalid) + { + Report(CosRepairCodes.HexStringInvalidDigit, token.Start, "The hexadecimal string contains a byte that is neither a hexadecimal digit nor white-space; ignored."); + reportedInvalid = true; + } + + continue; + } + + if (high < 0) + { + high = nibble; + } + else + { + output[written++] = (byte)((high << 4) | nibble); + high = -1; + } + } + + if (high >= 0) + { + // §7.3.4.3: a missing final digit is read as 0. + output[written++] = (byte)(high << 4); + } + + if (!terminated) + { + Report(CosRepairCodes.HexStringUnterminated, token.Start, "The hexadecimal string has no closing angle bracket; it runs to the end of the input."); + } + + return CosString.FromOwnedBytes(written == output.Length ? output : output[..written], hexadecimal: true); + } + + private readonly CosName ParseName(CosToken token) + { + ReadOnlySpan text = Bytes(token)[1..]; + if (!text.Contains((byte)'#')) + { + return CosName.FromOwnedBytes(text.ToArray()); + } + + Span output = text.Length <= 256 ? stackalloc byte[256] : new byte[text.Length]; + int written = 0; + for (int index = 0; index < text.Length; index++) + { + byte current = text[index]; + if (current == (byte)'#') + { + int high = index + 1 < text.Length ? HexValue(text[index + 1]) : -1; + int low = index + 2 < text.Length ? HexValue(text[index + 2]) : -1; + if (high < 0 || low < 0) + { + Report(CosRepairCodes.NameInvalidEscape, token.Start, "A number sign in a name is not followed by two hexadecimal digits; read as a literal number sign."); + } + else + { + index += 2; + current = (byte)((high << 4) | low); + if (current == 0) + { + Report(CosRepairCodes.NameContainsNull, token.Start, "A name cannot contain the byte 0 (#00); dropped."); + continue; + } + } + } + + output[written++] = current; + } + + return CosName.FromOwnedBytes(output[..written].ToArray()); + } + + private CosArray ParseArray(CosToken start, int depth) + { + var items = new List(); + while (true) + { + CosToken next = _lexer.Peek(); + switch (next.Kind) + { + case CosTokenKind.ArrayEnd: + _lexer.Position = next.End; + return CosArray.FromOwnedList(items); + case CosTokenKind.EndOfInput or CosTokenKind.DictionaryEnd: + Report(CosRepairCodes.ArrayUnterminated, start.Start, "The array has no closing bracket; it ends here."); + return CosArray.FromOwnedList(items); + case CosTokenKind.Keyword when IsStructuralKeyword(Bytes(next)): + Report(CosRepairCodes.ArrayUnterminated, start.Start, "The array has no closing bracket; it ends at the next keyword."); + return CosArray.FromOwnedList(items); + case CosTokenKind.Invalid: + _lexer.Position = next.End; + ReportUnexpected(next); + continue; + default: + CosObject item = ParseObject(depth); + + // An unknown keyword (reported by ParseObject) is skipped; the keyword null is a real element. + if (next.Kind != CosTokenKind.Keyword || item is not CosNull || Bytes(next).SequenceEqual("null"u8)) + { + items.Add(item); + } + + continue; + } + } + } + + private CosObject ParseDictionaryOrStream(CosToken start, int depth) + { + var entries = new OrderedDictionary(); + while (true) + { + CosToken next = _lexer.Peek(); + if (next.Kind == CosTokenKind.DictionaryEnd) + { + _lexer.Position = next.End; + break; + } + + if (EndsContainer(next)) + { + Report(CosRepairCodes.DictionaryUnterminated, start.Start, "The dictionary has no closing angle brackets; it ends here."); + return CosDictionary.FromOwnedEntries(entries); + } + + if (next.Kind != CosTokenKind.Name) + { + Report(CosRepairCodes.DictionaryKeyNotName, next.Start, "A dictionary key must be a name; the object is skipped."); + if (next.Kind is CosTokenKind.Invalid or CosTokenKind.Keyword) + { + _lexer.Position = next.End; + } + else + { + _ = ParseObject(depth); + } + + continue; + } + + _lexer.Position = next.End; + CosName key = ParseName(next); + CosToken valueToken = _lexer.Peek(); + if (valueToken.Kind == CosTokenKind.DictionaryEnd || EndsContainer(valueToken)) + { + Report(CosRepairCodes.DictionaryValueMissing, next.Start, "The last dictionary key has no value; the key is dropped."); + continue; + } + + CosObject value = ParseObject(depth); + if (entries.Remove(key)) + { + Report(CosRepairCodes.DictionaryDuplicateKey, next.Start, "The dictionary has two entries with the same key; the last one is kept."); + } + + // §7.3.7: an entry whose value is null is the same as an absent entry. + if (value is not CosNull) + { + entries.Add(key, value); + } + } + + var dictionary = CosDictionary.FromOwnedEntries(entries); + CosToken after = _lexer.Peek(); + return after.Kind == CosTokenKind.Keyword && Bytes(after).SequenceEqual("stream"u8) + ? ParseStreamData(dictionary, after) + : dictionary; + } + + /// Reads the data of a stream whose stream keyword is , through endstream (§7.3.8). + private CosStream ParseStreamData(CosDictionary dictionary, CosToken keyword) + { + ReadOnlySpan source = _lexer.Source; + int dataStart = SkipStreamKeywordEndOfLine(keyword); + dictionary.TryGetValue(KnownNames.Length, out CosObject? lengthEntry); + long declared = lengthEntry is CosInteger { Value: >= 0 } length ? length.Value : -1; + + if (declared >= 0 && declared <= source.Length - dataStart && TryMatchEndstream(source, dataStart + (int)declared, out int afterEndstream)) + { + _lexer.Position = afterEndstream; + return new CosStream(dictionary, source.Slice(dataStart, (int)declared).ToArray()); + } + + int found = source[dataStart..].IndexOf("endstream"u8); + if (found >= 0) + { + int dataEnd = dataStart + found; + dataEnd -= EndOfLineLengthBefore(source, dataStart, dataEnd); + if (lengthEntry is not CosReference) + { + Report( + CosRepairCodes.StreamLengthInvalid, + keyword.Start, + string.Create(CultureInfo.InvariantCulture, $"The stream's Length is missing or wrong; the data runs to endstream ({dataEnd - dataStart} bytes).")); + } + + _lexer.Position = dataStart + found + "endstream"u8.Length; + return new CosStream(dictionary, source[dataStart..dataEnd].ToArray()); + } + + int end = declared >= 0 && declared <= source.Length - dataStart ? dataStart + (int)declared : source.Length; + Report(CosRepairCodes.EndstreamMissing, keyword.Start, "The stream has no endstream keyword."); + _lexer.Position = end; + return new CosStream(dictionary, source[dataStart..end].ToArray()); + } + + /// + /// Skips the end-of-line marker after the stream keyword, which shall be CRLF or LF (§7.3.8.1), and returns where the data + /// starts. A CR alone, or spaces before the marker, are repaired. + /// + private readonly int SkipStreamKeywordEndOfLine(CosToken keyword) + { + ReadOnlySpan source = _lexer.Source; + int position = keyword.End; + if (position < source.Length && source[position] == (byte)'\n') + { + return position + 1; + } + + if (position + 1 < source.Length && source[position] == (byte)'\r' && source[position + 1] == (byte)'\n') + { + return position + 2; + } + + while (position < source.Length && source[position] is (byte)' ' or (byte)'\t') + { + position++; + } + + if (position + 1 < source.Length && source[position] == (byte)'\r' && source[position + 1] == (byte)'\n') + { + position += 2; + } + else if (position < source.Length && source[position] is (byte)'\r' or (byte)'\n') + { + position++; + } + + Report(CosRepairCodes.StreamKeywordEndOfLine, keyword.Start, "The stream keyword must be followed by CRLF or LF."); + return position; + } + + /// Whether white-space and then the endstream keyword follow . + private static bool TryMatchEndstream(ReadOnlySpan source, int position, out int afterEndstream) + { + var lexer = new CosLexer(source, position); + CosToken token = lexer.Next(); + afterEndstream = token.End; + return token.Kind == CosTokenKind.Keyword && source.Slice(token.Start, token.Length).SequenceEqual("endstream"u8); + } + + /// The length of the end-of-line marker (CRLF, LF or CR) that ends just before , which is not part of the data (§7.3.8.1). + private static int EndOfLineLengthBefore(ReadOnlySpan source, int start, int end) + { + if (end - start >= 2 && source[end - 2] == (byte)'\r' && source[end - 1] == (byte)'\n') + { + return 2; + } + + return end - start >= 1 && source[end - 1] is (byte)'\r' or (byte)'\n' ? 1 : 0; + } + + /// Skips an array or dictionary nested deeper than , without recursion, and reads it as null. + private CosNull SkipTooDeep(CosToken start) + { + Report(CosRepairCodes.NestingTooDeep, start.Start, string.Create(CultureInfo.InvariantCulture, $"Arrays and dictionaries nest deeper than {MaxDepth} levels; the inner container is read as null.")); + int depth = 1; + while (depth > 0) + { + CosToken token = _lexer.Next(); + switch (token.Kind) + { + case CosTokenKind.EndOfInput: + return CosNull.Instance; + case CosTokenKind.ArrayStart or CosTokenKind.DictionaryStart: + depth++; + break; + case CosTokenKind.ArrayEnd or CosTokenKind.DictionaryEnd: + depth--; + break; + } + } + + return CosNull.Instance; + } + + private readonly bool EndsContainer(CosToken token) => + token.Kind is CosTokenKind.EndOfInput or CosTokenKind.ArrayEnd + || (token.Kind == CosTokenKind.Keyword && IsStructuralKeyword(Bytes(token))); + + /// Keywords that end an object in a file (§7.3.8, §7.3.10, §7.5); meeting one inside a container means the container was not closed. + private static bool IsStructuralKeyword(ReadOnlySpan keyword) => + keyword.SequenceEqual("endobj"u8) + || keyword.SequenceEqual("obj"u8) + || keyword.SequenceEqual("stream"u8) + || keyword.SequenceEqual("endstream"u8) + || keyword.SequenceEqual("xref"u8) + || keyword.SequenceEqual("trailer"u8) + || keyword.SequenceEqual("startxref"u8); + + private readonly void ReportUnexpected(CosToken token) => + Report(CosRepairCodes.UnexpectedToken, token.Start, "This token cannot start an object; skipped."); + + private readonly void Report(string code, int offset, string message) => _repairs?.Report(code, offset, message); + + private readonly ReadOnlySpan Bytes(CosToken token) => _lexer.Source.Slice(token.Start, token.Length); + + private static int HexValue(byte character) => character switch + { + >= (byte)'0' and <= (byte)'9' => character - '0', + >= (byte)'A' and <= (byte)'F' => character - 'A' + 10, + >= (byte)'a' and <= (byte)'f' => character - 'a' + 10, + _ => -1, + }; + + /// Parses [+-]?[0-9]+ into a ; fails on any other text or on overflow. + private static bool TryParseStrictInteger(ReadOnlySpan text, out long value) => + long.TryParse(text, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out value); + + /// Whether is [+-]?, then digits with at most one period, with at least one digit (§7.3.3). + private static bool IsWellFormedNumber(ReadOnlySpan text) + { + if (text.Length > 0 && text[0] is (byte)'+' or (byte)'-') + { + text = text[1..]; + } + + int period = text.IndexOf((byte)'.'); + if (period >= 0 && text[(period + 1)..].Contains((byte)'.')) + { + return false; + } + + return !text.ContainsAnyExcept(DigitsAndPeriod) && text.ContainsAnyInRange((byte)'0', (byte)'9'); + } + + /// + /// The lenient reading of a malformed number: leading signs collapse to one (negative if any is a minus), then digits and at most + /// one period, stopping at the first byte that does not fit. Always has at least one digit. + /// + private static ReadOnlySpan WellFormedPrefix(ReadOnlySpan text, Span scratch) + { + int index = 0; + bool negative = false; + while (index < text.Length && text[index] is (byte)'+' or (byte)'-') + { + negative |= text[index] == (byte)'-'; + index++; + } + + int length = 0; + scratch[length++] = negative ? (byte)'-' : (byte)'+'; + bool sawPeriod = false; + bool sawDigit = false; + for (; index < text.Length && length < scratch.Length; index++) + { + byte current = text[index]; + if (current == (byte)'.' && !sawPeriod) + { + sawPeriod = true; + } + else if (current is >= (byte)'0' and <= (byte)'9') + { + sawDigit = true; + } + else + { + break; + } + + scratch[length++] = current; + } + + if (!sawDigit) + { + length = 1; + scratch[length++] = (byte)'0'; + } + + return scratch[..length]; + } +} diff --git a/src/Broadside/Objects/CosReal.cs b/src/Broadside/Objects/CosReal.cs new file mode 100644 index 00000000..92df16fe --- /dev/null +++ b/src/Broadside/Objects/CosReal.cs @@ -0,0 +1,37 @@ +namespace Broadside.Objects; + +/// A real object, held as an IEEE 754 double. +/// +/// ISO 32000-2 §7.3.3 and Annex C. PDF has no exponent notation and no infinities or NaN, so only finite values are allowed. A real +/// is always written with a decimal point and without an exponent, so it parses back as a real and never as an integer. +/// +public sealed class CosReal : CosNumber, IEquatable +{ + /// Initializes a new instance of the class. + /// The value. Must be finite. + /// is infinite or NaN. + public CosReal(double value) + { + if (!double.IsFinite(value)) + { + throw new ArgumentOutOfRangeException(nameof(value), value, "A PDF real number must be finite."); + } + + Value = value; + } + + /// Gets the value. + public double Value { get; } + + /// + public override double ToDouble() => Value; + + /// + public bool Equals(CosReal? other) => other is not null && other.Value.Equals(Value); + + /// + public override bool Equals(object? obj) => Equals(obj as CosReal); + + /// + public override int GetHashCode() => Value.GetHashCode(); +} diff --git a/src/Broadside/Objects/CosReference.cs b/src/Broadside/Objects/CosReference.cs new file mode 100644 index 00000000..6fc5032a --- /dev/null +++ b/src/Broadside/Objects/CosReference.cs @@ -0,0 +1,40 @@ +namespace Broadside.Objects; + +/// An indirect reference, N G R: the object and generation numbers of an indirect object. +/// +/// ISO 32000-2 §7.3.10. A reference is a value; it does not hold or resolve the object it names. A reference to an object that +/// does not exist resolves to , which is the document's job, not this type's. +/// +public sealed class CosReference : CosObject, IEquatable +{ + /// The largest generation number a cross-reference table can record (five decimal digits, ISO 32000-2 §7.5.4). + public const int MaxGeneration = 65535; + + /// Initializes a new instance of the class. + /// The object number. Must be positive. + /// The generation number, from 0 to . + /// A number is outside its range. + public CosReference(int objectNumber, int generation) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(objectNumber); + ArgumentOutOfRangeException.ThrowIfNegative(generation); + ArgumentOutOfRangeException.ThrowIfGreaterThan(generation, MaxGeneration); + ObjectNumber = objectNumber; + Generation = generation; + } + + /// Gets the object number. + public int ObjectNumber { get; } + + /// Gets the generation number. + public int Generation { get; } + + /// + public bool Equals(CosReference? other) => other is not null && other.ObjectNumber == ObjectNumber && other.Generation == Generation; + + /// + public override bool Equals(object? obj) => Equals(obj as CosReference); + + /// + public override int GetHashCode() => HashCode.Combine(ObjectNumber, Generation); +} diff --git a/src/Broadside/Objects/CosRepair.cs b/src/Broadside/Objects/CosRepair.cs new file mode 100644 index 00000000..4ff12294 --- /dev/null +++ b/src/Broadside/Objects/CosRepair.cs @@ -0,0 +1,72 @@ +using System.Globalization; + +namespace Broadside.Objects; + +/// +/// One deviation from ISO 32000-2 §7.2 or §7.3 the parser found, and repaired, while reading objects. +/// +/// +/// Internal until the public diagnostic model lands (issue #41), which is expected to adopt as its diagnostic +/// code. Codes are stable PascalCase identifiers, listed in . +/// +/// The stable identifier of the kind of deviation. +/// The byte offset in the parsed source where the deviation was found. +/// A human-readable description of the deviation and the repair. +internal readonly record struct CosRepair(string Code, int Offset, string Message) +{ + /// + public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"{Code} at offset {Offset}: {Message}"); +} + +/// The codes of , one per kind of deviation. +internal static class CosRepairCodes +{ + public const string UnexpectedEndOfInput = nameof(UnexpectedEndOfInput); + public const string UnexpectedToken = nameof(UnexpectedToken); + public const string TrailingContent = nameof(TrailingContent); + public const string NumberMalformed = nameof(NumberMalformed); + public const string NumberOutOfRange = nameof(NumberOutOfRange); + public const string ReferenceInvalid = nameof(ReferenceInvalid); + public const string StringUnterminated = nameof(StringUnterminated); + public const string HexStringUnterminated = nameof(HexStringUnterminated); + public const string HexStringInvalidDigit = nameof(HexStringInvalidDigit); + public const string NameInvalidEscape = nameof(NameInvalidEscape); + public const string NameContainsNull = nameof(NameContainsNull); + public const string ArrayUnterminated = nameof(ArrayUnterminated); + public const string DictionaryUnterminated = nameof(DictionaryUnterminated); + public const string DictionaryKeyNotName = nameof(DictionaryKeyNotName); + public const string DictionaryValueMissing = nameof(DictionaryValueMissing); + public const string DictionaryDuplicateKey = nameof(DictionaryDuplicateKey); + public const string NestingTooDeep = nameof(NestingTooDeep); + public const string StreamKeywordEndOfLine = nameof(StreamKeywordEndOfLine); + public const string StreamLengthInvalid = nameof(StreamLengthInvalid); + public const string EndstreamMissing = nameof(EndstreamMissing); +} + +/// Collects the records a parse produces. +/// to keep every repair in ; otherwise only the first and the count are kept. +internal sealed class CosRepairLog(bool keepAll = false) +{ + private List? _all; + + /// Gets the first repair, or when there was none. + public CosRepair? First { get; private set; } + + /// Gets the number of repairs. + public int Count { get; private set; } + + /// Gets every repair, in order, when the log keeps them all; otherwise only the first. + public IReadOnlyList All => _all ?? (First is { } first ? [first] : []); + + /// Records a repair. + public void Report(string code, int offset, string message) + { + var repair = new CosRepair(code, offset, message); + First ??= repair; + Count++; + if (keepAll) + { + (_all ??= []).Add(repair); + } + } +} diff --git a/src/Broadside/Objects/CosStream.cs b/src/Broadside/Objects/CosStream.cs new file mode 100644 index 00000000..da1a9717 --- /dev/null +++ b/src/Broadside/Objects/CosStream.cs @@ -0,0 +1,44 @@ +namespace Broadside.Objects; + +/// A stream object: a stream dictionary and a sequence of bytes, written <<…>> stream … endstream. +/// +/// +/// ISO 32000-2 §7.3.8. The data is held as stored in the file, still encoded by the filters the dictionary's Filter entry +/// names (§7.4); decoding is not this type's job. The dictionary's Length entry is how a reader finds the end of the data +/// (§7.3.8.2); once the stream is read, the data's own length is authoritative, and a writer writes a direct Length equal to it. +/// +/// A stream is dirty when its data has been replaced or its dictionary is dirty. +/// +public sealed class CosStream : CosObject +{ + private ReadOnlyMemory _encodedData; + private bool _changed; + + /// Initializes a new instance of the class from its dictionary and data. + /// The stream dictionary. The stream holds this instance; it is not copied. + /// The stream's data as stored in the file, encoded by the filters names. Not copied. + public CosStream(CosDictionary dictionary, ReadOnlyMemory encodedData) + { + ArgumentNullException.ThrowIfNull(dictionary); + Dictionary = dictionary; + _encodedData = encodedData; + } + + /// Gets the stream dictionary. + public CosDictionary Dictionary { get; } + + /// Gets or sets the stream's data as stored in the file, before any filter is decoded. Setting marks the stream dirty. + /// ISO 32000-2 §7.3.8.1. Setting the data does not change the dictionary's Filter entry; keep the two consistent. + public ReadOnlyMemory EncodedData + { + get => _encodedData; + set + { + _encodedData = value; + _changed = true; + } + } + + /// + public override bool IsDirty => _changed || Dictionary.IsDirty; +} diff --git a/src/Broadside/Objects/CosString.cs b/src/Broadside/Objects/CosString.cs new file mode 100644 index 00000000..a410a661 --- /dev/null +++ b/src/Broadside/Objects/CosString.cs @@ -0,0 +1,60 @@ +namespace Broadside.Objects; + +/// A string object: a sequence of zero or more bytes, written either as a literal (…) or as hexadecimal <…>. +/// +/// ISO 32000-2 §7.3.4. The value is the bytes; the written form is kept in only so a re-written string +/// keeps the form it was read in, and it takes no part in equality. Whether the bytes are text, ASCII or binary depends on where +/// the string is used (§7.9.2); reads them as a text string. +/// +public sealed class CosString : CosObject, IEquatable +{ + private readonly byte[] _bytes; + + /// Initializes a new instance of the class. + /// The string's bytes, copied. + /// to write the string in hexadecimal form, for literal form. + public CosString(ReadOnlySpan bytes, bool hexadecimal = false) + : this(bytes.ToArray(), hexadecimal) + { + } + + private CosString(byte[] bytes, bool hexadecimal) + { + _bytes = bytes; + IsHexadecimal = hexadecimal; + } + + /// Gets the string's bytes, after literal escapes or hexadecimal digits are decoded. + public ReadOnlySpan Bytes => _bytes; + + /// Gets a value indicating whether the string is written in hexadecimal form (§7.3.4.3) rather than literal form (§7.3.4.2). + public bool IsHexadecimal { get; } + + /// Decodes the bytes as a text string. + /// The text. + /// + /// ISO 32000-2 §7.9.2.2 and Annex D. A string that starts with the byte order marker FE FF is UTF-16BE, one that starts + /// with EF BB BF is UTF-8 (PDF 2.0), and any other is PDFDocEncoding (Table D.3). The marker is not part of the text. + /// Language escape sequences in Unicode strings (§7.9.2.2.2: ESC, a two-letter language code, an optional two-letter country + /// code, ESC) are removed. Malformed UTF-16 or UTF-8 decodes to U+FFFD; a trailing odd byte of a UTF-16BE string is ignored; + /// the PDFDocEncoding codes Table D.3 leaves undefined decode to the Unicode code point with the same number. + /// + public string DecodeText() => TextStringDecoder.Decode(_bytes); + + /// + public bool Equals(CosString? other) => other is not null && _bytes.AsSpan().SequenceEqual(other._bytes); + + /// + public override bool Equals(object? obj) => Equals(obj as CosString); + + /// + public override int GetHashCode() + { + var hash = new HashCode(); + hash.AddBytes(_bytes); + return hash.ToHashCode(); + } + + /// Wraps an array the caller gives up ownership of, without copying it. + internal static CosString FromOwnedBytes(byte[] bytes, bool hexadecimal) => new(bytes, hexadecimal); +} diff --git a/src/Broadside/Objects/CosToken.cs b/src/Broadside/Objects/CosToken.cs new file mode 100644 index 00000000..0a01362a --- /dev/null +++ b/src/Broadside/Objects/CosToken.cs @@ -0,0 +1,50 @@ +namespace Broadside.Objects; + +/// The kind of a . +/// ISO 32000-2 §7.2. +internal enum CosTokenKind : byte +{ + /// No more tokens: only white-space and comments remain. + EndOfInput, + + /// A run of regular characters made of digits, signs and periods with no period: an integer, possibly malformed (§7.3.3). + Integer, + + /// A run of regular characters made of digits, signs and periods with a period: a real, possibly malformed (§7.3.3). + Real, + + /// (…), from the opening to the matching closing parenthesis or the end of input (§7.3.4.2). + LiteralString, + + /// <…>, from the opening to the closing angle bracket or the end of input (§7.3.4.3). + HexString, + + /// / followed by regular characters (§7.3.5). + Name, + + /// [ (§7.3.6). + ArrayStart, + + /// ] (§7.3.6). + ArrayEnd, + + /// << (§7.3.7). + DictionaryStart, + + /// >> (§7.3.7). + DictionaryEnd, + + /// Any other run of regular characters (true, null, R, obj, stream, garbage), or { or }. + Keyword, + + /// A delimiter that cannot start a token: ) or a lone >. + Invalid, +} + +/// One token: its kind and the byte range it occupies in the source, delimiters included. +/// ISO 32000-2 §7.2. A token holds no copy of its bytes, so producing one allocates nothing. +internal readonly record struct CosToken(CosTokenKind Kind, int Start, int Length) +{ + /// Gets the offset one past the token's last byte. + public int End => Start + Length; +} diff --git a/src/Broadside/Objects/CosWriter.cs b/src/Broadside/Objects/CosWriter.cs new file mode 100644 index 00000000..4483e731 --- /dev/null +++ b/src/Broadside/Objects/CosWriter.cs @@ -0,0 +1,244 @@ +using System.Buffers; +using System.Globalization; + +namespace Broadside.Objects; + +/// Writes the PDF syntax of COS objects. +/// +/// ISO 32000-2 §7.2 and §7.3. The output is canonical rather than a copy of any source bytes: single spaces between tokens, reals in +/// shortest round-trip form with a decimal point and no exponent, literal strings with every parenthesis and backslash escaped and +/// non-printable bytes as three-digit octal escapes, names with every byte outside !–~ and every delimiter and +/// # as a #xx escape, and streams with a direct Length. Whatever it writes parses back to an equal object. +/// +internal static class CosWriter +{ + private static readonly SearchValues NameNeedsEscape = SearchValues.Create("\0\t\n\f\r ()<>[]{}/%#"u8); + + public static void Write(CosObject value, IBufferWriter writer) + { + switch (value) + { + case CosBoolean boolean: + writer.Write(boolean.Value ? "true"u8 : "false"u8); + break; + case CosInteger integer: + WriteInteger(integer.Value, writer); + break; + case CosReal real: + WriteReal(real.Value, writer); + break; + case CosString text: + if (text.IsHexadecimal) + { + WriteHexString(text.Bytes, writer); + } + else + { + WriteLiteralString(text.Bytes, writer); + } + + break; + case CosName name: + WriteName(name.Bytes, writer); + break; + case CosArray array: + WriteArray(array, writer); + break; + case CosDictionary dictionary: + WriteDictionary(dictionary, writer, streamLength: -1); + break; + case CosStream stream: + WriteDictionary(stream.Dictionary, writer, stream.EncodedData.Length); + writer.Write("\nstream\n"u8); + writer.Write(stream.EncodedData.Span); + writer.Write("\nendstream"u8); + break; + case CosReference reference: + WriteInteger(reference.ObjectNumber, writer); + writer.Write(" "u8); + WriteInteger(reference.Generation, writer); + writer.Write(" R"u8); + break; + default: + writer.Write("null"u8); + break; + } + } + + private static void WriteInteger(long value, IBufferWriter writer) + { + Span span = writer.GetSpan(20); + value.TryFormat(span, out int written, default, CultureInfo.InvariantCulture); + writer.Advance(written); + } + + /// Writes a real with a decimal point and without an exponent, which PDF does not allow (§7.3.3). + private static void WriteReal(double value, IBufferWriter writer) + { + string roundTrip = value.ToString("R", CultureInfo.InvariantCulture); + string text = roundTrip.Contains('E', StringComparison.Ordinal) ? ExpandExponent(roundTrip) : roundTrip; + if (!text.Contains('.', StringComparison.Ordinal)) + { + text += ".0"; + } + + Span span = writer.GetSpan(text.Length); + for (int i = 0; i < text.Length; i++) + { + span[i] = (byte)text[i]; + } + + writer.Advance(text.Length); + } + + /// Rewrites -1.25E-05 as -0.0000125 and 1E+20 as 100000000000000000000. + private static string ExpandExponent(string text) + { + int exponentAt = text.IndexOf('E', StringComparison.Ordinal); + int exponent = int.Parse(text.AsSpan(exponentAt + 1), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture); + ReadOnlySpan mantissa = text.AsSpan(0, exponentAt); + bool negative = mantissa[0] == '-'; + if (negative) + { + mantissa = mantissa[1..]; + } + + int point = mantissa.IndexOf('.'); + string digits = point < 0 ? mantissa.ToString() : string.Concat(mantissa[..point], mantissa[(point + 1)..]); + int newPoint = (point < 0 ? mantissa.Length : point) + exponent; + string body = newPoint <= 0 + ? string.Concat("0.", new string('0', -newPoint), digits) + : newPoint >= digits.Length + ? string.Concat(digits, new string('0', newPoint - digits.Length)) + : string.Concat(digits.AsSpan(0, newPoint), ".", digits.AsSpan(newPoint)); + return negative ? "-" + body : body; + } + + /// Writes a literal string (§7.3.4.2). Parentheses are always escaped, so balance never matters. + private static void WriteLiteralString(ReadOnlySpan bytes, IBufferWriter writer) + { + writer.Write("("u8); + Span escape = stackalloc byte[4]; + foreach (byte value in bytes) + { + ReadOnlySpan output = value switch + { + (byte)'(' => "\\("u8, + (byte)')' => "\\)"u8, + (byte)'\\' => "\\\\"u8, + (byte)'\n' => "\\n"u8, + (byte)'\r' => "\\r"u8, + (byte)'\t' => "\\t"u8, + 0x08 => "\\b"u8, + 0x0C => "\\f"u8, + >= 0x20 and <= 0x7E => Single(value, escape), + _ => Octal(value, escape), + }; + writer.Write(output); + } + + writer.Write(")"u8); + } + + private static Span Single(byte value, Span escape) + { + escape[0] = value; + return escape[..1]; + } + + private static Span Octal(byte value, Span escape) + { + escape[0] = (byte)'\\'; + escape[1] = (byte)('0' + (value >> 6)); + escape[2] = (byte)('0' + ((value >> 3) & 7)); + escape[3] = (byte)('0' + (value & 7)); + return escape; + } + + /// Writes a hexadecimal string (§7.3.4.3) in upper case. + private static void WriteHexString(ReadOnlySpan bytes, IBufferWriter writer) + { + Span span = writer.GetSpan((bytes.Length * 2) + 2); + span[0] = (byte)'<'; + int written = 1; + foreach (byte value in bytes) + { + span[written++] = HexDigit(value >> 4); + span[written++] = HexDigit(value & 0xF); + } + + span[written++] = (byte)'>'; + writer.Advance(written); + } + + /// Writes a name (§7.3.5): #, delimiters, white-space and bytes outside !–~ as #xx. + private static void WriteName(ReadOnlySpan bytes, IBufferWriter writer) + { + Span span = writer.GetSpan((bytes.Length * 3) + 1); + span[0] = (byte)'/'; + int written = 1; + foreach (byte value in bytes) + { + if (value is < 0x21 or > 0x7E || NameNeedsEscape.Contains(value)) + { + span[written++] = (byte)'#'; + span[written++] = HexDigit(value >> 4); + span[written++] = HexDigit(value & 0xF); + } + else + { + span[written++] = value; + } + } + + writer.Advance(written); + } + + private static void WriteArray(CosArray array, IBufferWriter writer) + { + writer.Write("["u8); + for (int i = 0; i < array.Count; i++) + { + if (i > 0) + { + writer.Write(" "u8); + } + + Write(array[i], writer); + } + + writer.Write("]"u8); + } + + /// Writes a dictionary; for a stream dictionary, replaces or supplies Length. + private static void WriteDictionary(CosDictionary dictionary, IBufferWriter writer, long streamLength) + { + writer.Write("<<"u8); + bool wroteLength = false; + foreach (KeyValuePair entry in dictionary) + { + writer.Write(" "u8); + WriteName(entry.Key.Bytes, writer); + writer.Write(" "u8); + if (streamLength >= 0 && entry.Key.Equals(KnownNames.Length)) + { + WriteInteger(streamLength, writer); + wroteLength = true; + } + else + { + Write(entry.Value, writer); + } + } + + if (streamLength >= 0 && !wroteLength) + { + writer.Write(" /Length "u8); + WriteInteger(streamLength, writer); + } + + writer.Write(" >>"u8); + } + + private static byte HexDigit(int nibble) => (byte)(nibble < 10 ? '0' + nibble : 'A' + nibble - 10); +} diff --git a/src/Broadside/Objects/KnownNames.cs b/src/Broadside/Objects/KnownNames.cs new file mode 100644 index 00000000..fb611e5c --- /dev/null +++ b/src/Broadside/Objects/KnownNames.cs @@ -0,0 +1,8 @@ +namespace Broadside.Objects; + +/// Names the library itself looks up, created once. Add a name here when code needs it, not before. +internal static class KnownNames +{ + /// /Length, the stream dictionary entry that gives the extent of the data (ISO 32000-2 §7.3.8.2, Table 5). + public static readonly CosName Length = new("Length"); +} diff --git a/src/Broadside/Objects/TextStringDecoder.cs b/src/Broadside/Objects/TextStringDecoder.cs new file mode 100644 index 00000000..5d1e4fca --- /dev/null +++ b/src/Broadside/Objects/TextStringDecoder.cs @@ -0,0 +1,95 @@ +using System.Text; + +namespace Broadside.Objects; + +/// Decodes the bytes of a text string: UTF-16BE or UTF-8 with a byte order marker, otherwise PDFDocEncoding. +/// ISO 32000-2 §7.9.2.2 and Annex D, Table D.3. +internal static class TextStringDecoder +{ + private const char Escape = '\u001B'; + + /// + /// PDFDocEncoding (Table D.3) for the codes that differ from their Unicode code point: 0x18–0x1F (spacing accents) and + /// 0x80–0xA0. Codes the table leaves undefined (0x7F, 0x9F, 0xAD) and every other code map to the code point with the same number. + /// + private static readonly char[] PdfDocEncoding = BuildPdfDocEncoding(); + + public static string Decode(ReadOnlySpan bytes) + { + if (bytes.StartsWith((ReadOnlySpan)[0xFE, 0xFF])) + { + ReadOnlySpan body = bytes[2..]; + return RemoveLanguageEscapes(Encoding.BigEndianUnicode.GetString(body[..(body.Length & ~1)])); + } + + if (bytes.StartsWith((ReadOnlySpan)[0xEF, 0xBB, 0xBF])) + { + return RemoveLanguageEscapes(Encoding.UTF8.GetString(bytes[3..])); + } + + return string.Create(bytes.Length, bytes, static (chars, source) => + { + for (int i = 0; i < source.Length; i++) + { + chars[i] = PdfDocEncoding[source[i]]; + } + }); + } + + /// + /// Removes language escape sequences (§7.9.2.2.2): ESC, a two-character language code, an optional two-character country code, + /// ESC. An ESC that does not open such a sequence is kept. + /// + private static string RemoveLanguageEscapes(string text) + { + int escape = text.IndexOf(Escape, StringComparison.Ordinal); + if (escape < 0) + { + return text; + } + + var builder = new StringBuilder(text.Length); + int copied = 0; + while (escape >= 0) + { + int close = escape + 3 < text.Length && text[escape + 3] == Escape ? escape + 3 + : escape + 5 < text.Length && text[escape + 5] == Escape && text[escape + 3] != Escape ? escape + 5 + : -1; + if (close < 0) + { + escape = text.IndexOf(Escape, escape + 1); + continue; + } + + builder.Append(text, copied, escape - copied); + copied = close + 1; + escape = text.IndexOf(Escape, copied); + } + + builder.Append(text, copied, text.Length - copied); + return builder.ToString(); + } + + private static char[] BuildPdfDocEncoding() + { + char[] table = new char[256]; + for (int i = 0; i < table.Length; i++) + { + table[i] = (char)i; + } + + ReadOnlySpan accents = ['˘', 'ˇ', 'ˆ', '˙', '˝', '˛', '˚', '˜']; + accents.CopyTo(table.AsSpan(0x18)); + + ReadOnlySpan high = + [ + '•', '†', '‡', '…', '—', '–', 'ƒ', '⁄', // 0x80-0x87 + '‹', '›', '−', '‰', '„', '“', '”', '‘', // 0x88-0x8F + '’', '‚', '™', 'fi', 'fl', 'Ł', 'Œ', 'Š', // 0x90-0x97 + 'Ÿ', 'Ž', 'ı', 'ł', 'œ', 'š', 'ž', '\u009F', // 0x98-0x9F (0x9F undefined) + '€', // 0xA0 + ]; + high.CopyTo(table.AsSpan(0x80)); + return table; + } +} diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index 7dc5c581..cdd9ec48 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -1 +1,93 @@ #nullable enable +abstract Broadside.Objects.CosNumber.ToDouble() -> double +Broadside.Objects.CosArray +Broadside.Objects.CosArray.Add(Broadside.Objects.CosObject! item) -> void +Broadside.Objects.CosArray.Clear() -> void +Broadside.Objects.CosArray.Contains(Broadside.Objects.CosObject! item) -> bool +Broadside.Objects.CosArray.CopyTo(Broadside.Objects.CosObject![]! array, int arrayIndex) -> void +Broadside.Objects.CosArray.CosArray() -> void +Broadside.Objects.CosArray.CosArray(System.Collections.Generic.IEnumerable! items) -> void +Broadside.Objects.CosArray.Count.get -> int +Broadside.Objects.CosArray.GetEnumerator() -> System.Collections.Generic.IEnumerator! +Broadside.Objects.CosArray.IndexOf(Broadside.Objects.CosObject! item) -> int +Broadside.Objects.CosArray.Insert(int index, Broadside.Objects.CosObject! item) -> void +Broadside.Objects.CosArray.Remove(Broadside.Objects.CosObject! item) -> bool +Broadside.Objects.CosArray.RemoveAt(int index) -> void +Broadside.Objects.CosArray.this[int index].get -> Broadside.Objects.CosObject! +Broadside.Objects.CosArray.this[int index].set -> void +Broadside.Objects.CosBoolean +Broadside.Objects.CosBoolean.Equals(Broadside.Objects.CosBoolean? other) -> bool +Broadside.Objects.CosBoolean.Value.get -> bool +Broadside.Objects.CosDictionary +Broadside.Objects.CosDictionary.Add(Broadside.Objects.CosName! key, Broadside.Objects.CosObject! value) -> void +Broadside.Objects.CosDictionary.Clear() -> void +Broadside.Objects.CosDictionary.ContainsKey(Broadside.Objects.CosName! key) -> bool +Broadside.Objects.CosDictionary.CosDictionary() -> void +Broadside.Objects.CosDictionary.Count.get -> int +Broadside.Objects.CosDictionary.GetEnumerator() -> System.Collections.Generic.IEnumerator>! +Broadside.Objects.CosDictionary.Keys.get -> System.Collections.Generic.ICollection! +Broadside.Objects.CosDictionary.Remove(Broadside.Objects.CosName! key) -> bool +Broadside.Objects.CosDictionary.this[Broadside.Objects.CosName! key].get -> Broadside.Objects.CosObject! +Broadside.Objects.CosDictionary.this[Broadside.Objects.CosName! key].set -> void +Broadside.Objects.CosDictionary.TryGetValue(Broadside.Objects.CosName! key, out Broadside.Objects.CosObject! value) -> bool +Broadside.Objects.CosDictionary.Values.get -> System.Collections.Generic.ICollection! +Broadside.Objects.CosInteger +Broadside.Objects.CosInteger.CosInteger(long value) -> void +Broadside.Objects.CosInteger.Equals(Broadside.Objects.CosInteger? other) -> bool +Broadside.Objects.CosInteger.Value.get -> long +Broadside.Objects.CosName +Broadside.Objects.CosName.Bytes.get -> System.ReadOnlySpan +Broadside.Objects.CosName.CosName(string! value) -> void +Broadside.Objects.CosName.CosName(System.ReadOnlySpan bytes) -> void +Broadside.Objects.CosName.Equals(Broadside.Objects.CosName? other) -> bool +Broadside.Objects.CosName.Value.get -> string! +Broadside.Objects.CosNull +Broadside.Objects.CosNumber +Broadside.Objects.CosObject +Broadside.Objects.CosObject.WriteTo(System.Buffers.IBufferWriter! writer) -> void +Broadside.Objects.CosReal +Broadside.Objects.CosReal.CosReal(double value) -> void +Broadside.Objects.CosReal.Equals(Broadside.Objects.CosReal? other) -> bool +Broadside.Objects.CosReal.Value.get -> double +Broadside.Objects.CosReference +Broadside.Objects.CosReference.CosReference(int objectNumber, int generation) -> void +Broadside.Objects.CosReference.Equals(Broadside.Objects.CosReference? other) -> bool +Broadside.Objects.CosReference.Generation.get -> int +Broadside.Objects.CosReference.ObjectNumber.get -> int +Broadside.Objects.CosStream +Broadside.Objects.CosStream.CosStream(Broadside.Objects.CosDictionary! dictionary, System.ReadOnlyMemory encodedData) -> void +Broadside.Objects.CosStream.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Objects.CosStream.EncodedData.get -> System.ReadOnlyMemory +Broadside.Objects.CosStream.EncodedData.set -> void +Broadside.Objects.CosString +Broadside.Objects.CosString.Bytes.get -> System.ReadOnlySpan +Broadside.Objects.CosString.CosString(System.ReadOnlySpan bytes, bool hexadecimal = false) -> void +Broadside.Objects.CosString.DecodeText() -> string! +Broadside.Objects.CosString.Equals(Broadside.Objects.CosString? other) -> bool +Broadside.Objects.CosString.IsHexadecimal.get -> bool +const Broadside.Objects.CosReference.MaxGeneration = 65535 -> int +override Broadside.Objects.CosArray.IsDirty.get -> bool +override Broadside.Objects.CosBoolean.Equals(object? obj) -> bool +override Broadside.Objects.CosBoolean.GetHashCode() -> int +override Broadside.Objects.CosDictionary.IsDirty.get -> bool +override Broadside.Objects.CosInteger.Equals(object? obj) -> bool +override Broadside.Objects.CosInteger.GetHashCode() -> int +override Broadside.Objects.CosInteger.ToDouble() -> double +override Broadside.Objects.CosName.Equals(object? obj) -> bool +override Broadside.Objects.CosName.GetHashCode() -> int +override Broadside.Objects.CosObject.ToString() -> string! +override Broadside.Objects.CosReal.Equals(object? obj) -> bool +override Broadside.Objects.CosReal.GetHashCode() -> int +override Broadside.Objects.CosReal.ToDouble() -> double +override Broadside.Objects.CosReference.Equals(object? obj) -> bool +override Broadside.Objects.CosReference.GetHashCode() -> int +override Broadside.Objects.CosStream.IsDirty.get -> bool +override Broadside.Objects.CosString.Equals(object? obj) -> bool +override Broadside.Objects.CosString.GetHashCode() -> int +static Broadside.Objects.CosBoolean.False.get -> Broadside.Objects.CosBoolean! +static Broadside.Objects.CosBoolean.True.get -> Broadside.Objects.CosBoolean! +static Broadside.Objects.CosNull.Instance.get -> Broadside.Objects.CosNull! +static Broadside.Objects.CosObject.DeepEquals(Broadside.Objects.CosObject? left, Broadside.Objects.CosObject? right) -> bool +static Broadside.Objects.CosObject.Parse(System.ReadOnlySpan bytes) -> Broadside.Objects.CosObject! +static Broadside.Objects.CosObject.TryParse(System.ReadOnlySpan bytes, out Broadside.Objects.CosObject? result) -> bool +virtual Broadside.Objects.CosObject.IsDirty.get -> bool diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 30df68cc..3aa2081e 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -1,3 +1,4 @@ +using Broadside.Objects; using SharpFuzz; namespace Broadside.Fuzz; @@ -11,19 +12,82 @@ internal static class FuzzTargets /// Every registered target. Names are the stable identifiers used on the command line and in CI. public static IReadOnlyDictionary All { get; } = new Dictionary(StringComparer.Ordinal) { - ["pdf-header"] = PdfHeader, + ["lexer"] = Lexer, + ["object-parser"] = ObjectParser, }; /// - /// Placeholder until the lexer lands (#11): decides whether the input starts with the %PDF- header marker. + /// Tokenizes the whole input. Every token must lie inside the input and start at or after the previous one's end, and the lexer + /// must reach the end of input. /// - /// ISO 32000-2 §7.5.2. - private static void PdfHeader(ReadOnlySpan data) + /// ISO 32000-2 §7.2. + private static void Lexer(ReadOnlySpan data) { - bool hasHeader = data.StartsWith("%PDF-"u8); - if (hasHeader && data.Length < "%PDF-"u8.Length) + var lexer = new CosLexer(data); + int previousEnd = 0; + while (true) { - throw new InvalidOperationException("StartsWith claimed a header shorter than the marker; the input cannot be both."); + CosToken token = lexer.Next(); + if (token.Start < previousEnd || token.Length < 0 || token.End > data.Length) + { + throw new InvalidOperationException($"Token {token} lies outside the input of {data.Length} bytes or before the previous token's end {previousEnd}."); + } + + if (token.Kind == CosTokenKind.EndOfInput) + { + return; + } + + if (token.Length == 0) + { + throw new InvalidOperationException($"Token {token} is empty; the lexer would not make progress."); + } + + previousEnd = token.End; + } + } + + /// + /// Parses the input as a sequence of objects in lenient mode, the way a reader scans a file body, then checks the round-trip + /// property for each object: what writes parses back, with no repair, to an equal object. Also + /// runs the strict public over the whole input, which must not throw. + /// + /// ISO 32000-2 §7.3. + private static void ObjectParser(ReadOnlySpan data) + { + _ = CosObject.TryParse(data, out _); + + var parser = new CosParser(data, repairs: null); + while (!parser.IsAtEnd()) + { + int start = parser.Position; + CosObject parsed = parser.ParseObject(); + if (parser.Position <= start) + { + throw new InvalidOperationException($"The parser did not advance past offset {start}."); + } + + CheckRoundTrip(parsed); + } + } + + private static void CheckRoundTrip(CosObject parsed) + { + var buffer = new System.Buffers.ArrayBufferWriter(); + parsed.WriteTo(buffer); + + var repairs = new CosRepairLog(); + var reparser = new CosParser(buffer.WrittenSpan, repairs); + CosObject reparsed = reparser.ParseObject(); + reparser.ExpectEndOfInput(); + if (repairs.First is { } repair) + { + throw new InvalidOperationException($"Writing {parsed.GetType().Name} produced syntax that needs a repair: {repair}."); + } + + if (!CosObject.DeepEquals(parsed, reparsed)) + { + throw new InvalidOperationException($"Writing and reparsing a {parsed.GetType().Name} changed it: {parsed} became {reparsed}."); } } } diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index e87688de..eedbf364 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,25 +6,27 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The only target today is `pdf-header`, a placeholder that checks for the `%PDF-` marker; the lexer target replaces it when #11 lands, and every parser and codec after that adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`). Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. ## Smoke mode: no fuzzer needed ```sh -dotnet run -c Release --project tests/Broadside.Fuzz -- --smoke pdf-header 10 # 10 seconds, random seed -dotnet run -c Release --project tests/Broadside.Fuzz -- --smoke pdf-header 60 12345 # 60 seconds, fixed seed +dotnet run -c Release --project tests/Broadside.Fuzz -- --smoke object-parser 10 # 10 seconds, random seed +dotnet run -c Release --project tests/Broadside.Fuzz -- --smoke object-parser 60 12345 # 60 seconds, fixed seed ``` `--smoke [seconds] [seed]` runs the target over every file in `tests/Corpus/`, then for the given time (default 10 s) over random mutations of those files: bit flips, byte overwrites, truncation, insertion, deletion and chunk copies, one to four per input. It needs no instrumentation and no external binary, so it is what CI runs (60 s per target, issue #4) and what you run before opening a PR. The seed is printed; pass it back to replay a run. On a finding the input is written to `artifacts/fuzz//` and the command to replay it is printed: ```sh -dotnet run -c Release --project tests/Broadside.Fuzz -- --run pdf-header artifacts/fuzz/pdf-header/smoke-seed12345-iter1234.bin +dotnet run -c Release --project tests/Broadside.Fuzz -- --run object-parser artifacts/fuzz/object-parser/smoke-seed12345-iter1234.bin ``` `--run ` executes the target once on one input, which is also how to replay a crash found by libFuzzer or AFL. +Whole corpus files are the right seeds for both `lexer` and `object-parser`, which read any bytes as a file body. + Smoke mode is a regression net, not a fuzzer: it has no coverage feedback and finds only shallow bugs. Use a real fuzzer for anything that parses. ## Real fuzzing @@ -39,7 +41,7 @@ dotnet build -c Release tests/Broadside.Fuzz sharpfuzz artifacts/bin/Broadside.Fuzz/release/Broadside.dll ``` -The instrumented file replaces the original in place; rebuild to get a clean one back. The `pdf-header` placeholder calls only the BCL, so with it alone the fuzzer reports no coverage; that is expected until a target calls instrumented code. +The instrumented file replaces the original in place; rebuild to get a clean one back. ### 2a. libFuzzer (`--fuzz`): the primary driver @@ -60,7 +62,7 @@ Run, with the corpus as the seed directory (any directory of inputs works; libFu ```sh mkdir -p artifacts/fuzz/seeds && cp tests/Corpus/*.pdf artifacts/fuzz/seeds/ -BROADSIDE_FUZZ_TARGET=pdf-header ./libfuzzer-dotnet \ +BROADSIDE_FUZZ_TARGET=object-parser ./libfuzzer-dotnet \ --target_path=dotnet \ --target_arg=artifacts/bin/Broadside.Fuzz/release/Broadside.Fuzz.dll \ artifacts/fuzz/seeds @@ -75,7 +77,7 @@ Crashes land as `crash-` files in the working directory; replay them with ```sh mkdir -p artifacts/fuzz/seeds && cp tests/Corpus/*.pdf artifacts/fuzz/seeds/ afl-fuzz -i artifacts/fuzz/seeds -o artifacts/fuzz/findings -t 5000 -m none \ - dotnet artifacts/bin/Broadside.Fuzz/release/Broadside.Fuzz.dll --afl pdf-header + dotnet artifacts/bin/Broadside.Fuzz/release/Broadside.Fuzz.dll --afl object-parser ``` On macOS afl-fuzz refuses to start until the crash reporter is disabled; it prints the `launchctl` commands to run. Findings land in `artifacts/fuzz/findings/crashes/`. diff --git a/tests/Broadside.Tests/CorpusSmokeTests.cs b/tests/Broadside.Tests/CorpusSmokeTests.cs index d55bc814..271d3b9d 100644 --- a/tests/Broadside.Tests/CorpusSmokeTests.cs +++ b/tests/Broadside.Tests/CorpusSmokeTests.cs @@ -48,6 +48,6 @@ public Task Corpus_file_names_match_snapshot() [Fact] public void Package_assembly_loads() { - Assert.Equal("Broadside", typeof(AssemblyMarker).Assembly.GetName().Name); + Assert.Equal("Broadside", typeof(Broadside.Objects.CosObject).Assembly.GetName().Name); } } diff --git a/tests/Broadside.Tests/Objects/ContainerParsingTests.cs b/tests/Broadside.Tests/Objects/ContainerParsingTests.cs new file mode 100644 index 00000000..468e3372 --- /dev/null +++ b/tests/Broadside.Tests/Objects/ContainerParsingTests.cs @@ -0,0 +1,149 @@ +using System.Text; +using Broadside.Objects; +using static Broadside.Tests.Objects.ScalarParsingTests; + +namespace Broadside.Tests.Objects; + +/// ISO 32000-2 §7.3.6 (arrays), §7.3.7 (dictionaries) and §7.3.8 (streams). +public class ContainerParsingTests +{ + [Fact] + public void Parses_the_array_example() + { + CosArray array = Assert.IsType(CosObject.Parse("[549 3.14 false (Ralph) /SomeName]"u8)); + + Assert.Collection( + array, + item => Assert.Equal(549, Assert.IsType(item).Value), + item => Assert.Equal(3.14, Assert.IsType(item).Value), + item => Assert.Same(CosBoolean.False, item), + item => Assert.Equal("Ralph"u8.ToArray(), Assert.IsType(item).Bytes.ToArray()), + item => Assert.Equal(new CosName("SomeName"), item)); + } + + [Fact] + public void Arrays_nest_hold_references_and_keep_null_elements() + { + CosArray array = Assert.IsType(CosObject.Parse("[[] [1 [2]] 3 0 R null<<>>]"u8)); + + Assert.Equal(5, array.Count); + Assert.Empty(Assert.IsType(array[0])); + Assert.Equal(2, Assert.IsType(array[1]).Count); + Assert.Equal(new CosReference(3, 0), array[2]); + Assert.Same(CosNull.Instance, array[3]); + Assert.Empty(Assert.IsType(array[4])); + } + + [Fact] + public void Parses_the_dictionary_example() + { + CosDictionary dictionary = Assert.IsType(CosObject.Parse(""" + <> + >> + """u8)); + + Assert.Equal(new CosName("Example"), dictionary[new CosName("Type")]); + Assert.Equal(new CosName("DictionaryExample"), dictionary[new CosName("Subtype")]); + Assert.Equal(0.01, Assert.IsType(dictionary[new CosName("Version")]).Value); + Assert.Equal(12, Assert.IsType(dictionary[new CosName("IntegerItem")]).Value); + Assert.Equal("a string"u8.ToArray(), Assert.IsType(dictionary[new CosName("StringItem")]).Bytes.ToArray()); + CosDictionary subdictionary = Assert.IsType(dictionary[new CosName("Subdictionary")]); + Assert.Equal(["Item1", "Item2", "LastItem", "VeryLastItem"], subdictionary.Keys.Select(static key => key.Value)); + Assert.Same(CosBoolean.True, subdictionary[new CosName("Item2")]); + } + + [Fact] + public void A_null_valued_entry_is_the_same_as_an_absent_one() + { + CosDictionary dictionary = Assert.IsType(CosObject.Parse("<< /A null /B 1 >>"u8)); + + Assert.False(dictionary.ContainsKey(new CosName("A"))); + Assert.Single(dictionary); + Assert.True(CosObject.DeepEquals(dictionary, CosObject.Parse("<< /B 1 >>"u8))); + } + + [Theory] + [InlineData("[1 2")] + [InlineData("<< /A 1")] + [InlineData("<< /A >>")] + [InlineData("<< 1 2 >>")] + [InlineData("<< /A 1 /A 2 >>")] + [InlineData("[1 2 >>")] + [InlineData("[1 foo]")] + public void Malformed_containers_are_rejected(string syntax) + { + Assert.Throws(() => CosObject.Parse(Latin1(syntax))); + } + + [Fact] + public void Nesting_beyond_the_parser_limit_is_rejected_without_overflowing_the_stack() + { + byte[] deep = Encoding.ASCII.GetBytes(new string('[', 100_000) + new string(']', 100_000)); + + Assert.False(CosObject.TryParse(deep, out _)); + } + + [Fact] + public void Nesting_within_the_parser_limit_parses() + { + byte[] nested = Encoding.ASCII.GetBytes(new string('[', 200) + new string(']', 200)); + + Assert.IsType(CosObject.Parse(nested)); + } + + [Theory] + [InlineData("<< /Length 11 >>\nstream\nhello world\nendstream")] + [InlineData("<< /Length 11 >>\r\nstream\r\nhello world\r\nendstream")] + [InlineData("<< /Length 11 >>stream\nhello worldendstream")] + [InlineData("<< /Length 8 0 R >>\nstream\nhello world\nendstream")] + [InlineData("<< /Length 8 0 R >>\nstream\r\nhello world\r\nendstream")] + public void A_stream_takes_its_data_from_its_length_or_from_endstream(string syntax) + { + CosStream stream = Assert.IsType(CosObject.Parse(Latin1(syntax))); + + Assert.Equal("hello world"u8.ToArray(), stream.EncodedData.ToArray()); + Assert.True(stream.Dictionary.ContainsKey(new CosName("Length"))); + } + + [Fact] + public void Stream_data_is_binary_and_may_contain_the_endstream_keyword_when_length_says_so() + { + byte[] syntax = [.. "<< /Length 13 /Filter /FlateDecode >>\nstream\n"u8, 0x00, 0xFF, .. "endstream\r\n"u8, 0x0D, 0x0A, .. "\nendstream"u8]; + + CosStream stream = Assert.IsType(CosObject.Parse(syntax)); + + Assert.Equal(13, stream.EncodedData.Length); + Assert.Equal(new CosName("FlateDecode"), stream.Dictionary[new CosName("Filter")]); + } + + [Theory] + [InlineData("<< /Length 3 >>\nstream\nhello world\nendstream")] + [InlineData("<< >>\nstream\nhello world\nendstream")] + [InlineData("<< /Length 11 >>\nstream\nhello world")] + [InlineData("<< /Length 11 >>\rstream\rhello world\nendstream")] + public void Streams_with_a_wrong_length_or_no_endstream_are_rejected(string syntax) + { + Assert.Throws(() => CosObject.Parse(Latin1(syntax))); + } + + [Fact] + public void A_stream_is_built_from_its_dictionary_and_data() + { + var dictionary = new CosDictionary { [new CosName("Filter")] = new CosName("ASCIIHexDecode") }; + + var stream = new CosStream(dictionary, "48656C6C6F>"u8.ToArray()); + + Assert.Same(dictionary, stream.Dictionary); + Assert.Equal("48656C6C6F>"u8.ToArray(), stream.EncodedData.ToArray()); + } +} diff --git a/tests/Broadside.Tests/Objects/CorpusObjectTests.cs b/tests/Broadside.Tests/Objects/CorpusObjectTests.cs new file mode 100644 index 00000000..965cf071 --- /dev/null +++ b/tests/Broadside.Tests/Objects/CorpusObjectTests.cs @@ -0,0 +1,80 @@ +using System.Buffers; +using System.Text; +using System.Text.RegularExpressions; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Objects; + +/// +/// Every indirect object in the minimal corpus, cut out between N G obj and endobj by the test (file structure is +/// issue #37's), parses through and survives a write-then-parse round trip. ISO 32000-2 §7.3. +/// +public partial class CorpusObjectTests +{ + [Theory] + [MemberData(nameof(Corpus.WellFormedFiles), MemberType = typeof(Corpus))] + public void Every_object_in_a_well_formed_file_parses_and_round_trips(string fileName) + { + IReadOnlyList<(int Number, byte[] Body)> objects = IndirectObjects(Corpus.Bytes(fileName)); + Assert.NotEmpty(objects); + + foreach ((int number, byte[] body) in objects) + { + CosObject parsed = CosObject.Parse(body); + var buffer = new ArrayBufferWriter(); + parsed.WriteTo(buffer); + + Assert.False(parsed.IsDirty, $"{fileName} object {number}"); + Assert.True(CosObject.DeepEquals(parsed, CosObject.Parse(buffer.WrittenSpan)), $"{fileName} object {number} did not round-trip"); + } + } + + [Fact] + public void The_page_of_empty_page_pdf_has_a_letter_media_box() + { + byte[] body = IndirectObjects(Corpus.Bytes("empty-page.pdf")).Single(static entry => entry.Number == 3).Body; + + CosDictionary page = Assert.IsType(CosObject.Parse(body)); + + Assert.Equal(new CosName("Page"), page[new CosName("Type")]); + Assert.Equal(new CosReference(2, 0), page[new CosName("Parent")]); + CosArray mediaBox = Assert.IsType(page[new CosName("MediaBox")]); + Assert.Equal([0d, 0d, 612d, 792d], mediaBox.Cast().Select(static number => number.ToDouble())); + } + + [Fact] + public void The_metadata_stream_of_metadata_xmp_pdf_holds_its_declared_length() + { + IReadOnlyList<(int Number, byte[] Body)> objects = IndirectObjects(Corpus.Bytes("metadata-xmp.pdf")); + + CosStream metadata = Assert.IsType(CosObject.Parse(objects.Single(static entry => entry.Number == 4).Body)); + CosDictionary info = Assert.IsType(CosObject.Parse(objects.Single(static entry => entry.Number == 5).Body)); + + Assert.Equal(new CosName("XML"), metadata.Dictionary[new CosName("Subtype")]); + Assert.Equal(391, metadata.EncodedData.Length); + Assert.StartsWith("(info[new CosName("Title")]).DecodeText()); + } + + [Fact] + public void The_stream_with_a_wrong_length_is_rejected_by_strict_parsing() + { + byte[] body = IndirectObjects(Corpus.Bytes("wrong-stream-length.pdf")).Single(static entry => entry.Number == 4).Body; + + FormatException error = Assert.Throws(() => CosObject.Parse(body)); + + Assert.StartsWith("StreamLengthInvalid", error.Message, StringComparison.Ordinal); + } + + private static List<(int Number, byte[] Body)> IndirectObjects(byte[] file) + { + string text = Encoding.Latin1.GetString(file); + return [.. IndirectObjectPattern().Matches(text).Select(match => ( + int.Parse(match.Groups["number"].Value, System.Globalization.CultureInfo.InvariantCulture), + file[match.Groups["body"].Index..(match.Groups["body"].Index + match.Groups["body"].Length)]))]; + } + + [GeneratedRegex(@"(?<=^|[\r\n])(?\d+) \d+ obj(?.*?)endobj", RegexOptions.Singleline | RegexOptions.CultureInvariant)] + private static partial Regex IndirectObjectPattern(); +} diff --git a/tests/Broadside.Tests/Objects/DirtyTrackingTests.cs b/tests/Broadside.Tests/Objects/DirtyTrackingTests.cs new file mode 100644 index 00000000..732a7d49 --- /dev/null +++ b/tests/Broadside.Tests/Objects/DirtyTrackingTests.cs @@ -0,0 +1,137 @@ +using Broadside.Objects; + +namespace Broadside.Tests.Objects; + +/// +/// Every COS object carries a dirty flag: false after parse, true after any mutation through the public API. The flag is what an +/// incremental update (ISO 32000-2 §7.5.6) writes from. +/// +public class DirtyTrackingTests +{ + private static readonly CosName A = new("A"); + private static readonly CosName B = new("B"); + + [Theory] + [InlineData("true")] + [InlineData("-12")] + [InlineData("3.5")] + [InlineData("(text)")] + [InlineData("<00FF>")] + [InlineData("/Name")] + [InlineData("null")] + [InlineData("4 0 R")] + [InlineData("[1 [2 << /A [3] >>]]")] + [InlineData("<< /A << /B [1 2] >> /C 5 0 R >>")] + [InlineData("<< /Length 3 >>\nstream\nabc\nendstream")] + public void Nothing_is_dirty_after_parse(string syntax) + { + CosObject parsed = CosObject.Parse(ScalarParsingTests.Latin1(syntax)); + + Assert.False(parsed.IsDirty); + Assert.All(Descendants(parsed), static item => Assert.False(item.IsDirty)); + } + + [Fact] + public void A_newly_constructed_container_is_clean_until_changed() + { + Assert.False(new CosArray().IsDirty); + Assert.False(new CosArray([CosNull.Instance]).IsDirty); + Assert.False(new CosDictionary().IsDirty); + Assert.False(new CosStream(new CosDictionary(), ReadOnlyMemory.Empty).IsDirty); + } + + public static TheoryData> ArrayMutations => new() + { + { "add", static array => array.Add(CosBoolean.True) }, + { "insert", static array => array.Insert(0, CosBoolean.True) }, + { "set", static array => array[0] = new CosInteger(9) }, + { "remove at", static array => array.RemoveAt(0) }, + { "remove", static array => array.Remove(new CosInteger(1)) }, + { "clear", static array => array.Clear() }, + }; + + [Theory] + [MemberData(nameof(ArrayMutations))] + public void Any_array_mutation_marks_it_dirty(string mutation, Action mutate) + { + _ = mutation; + CosArray array = Assert.IsType(CosObject.Parse("[1 2]"u8)); + + mutate(array); + + Assert.True(array.IsDirty); + } + + public static TheoryData> DictionaryMutations => new() + { + { "add", static dictionary => dictionary.Add(B, CosBoolean.True) }, + { "set", static dictionary => dictionary[A] = new CosInteger(9) }, + { "set null", static dictionary => dictionary[A] = CosNull.Instance }, + { "remove", static dictionary => dictionary.Remove(A) }, + { "clear", static dictionary => dictionary.Clear() }, + { "remove pair", static dictionary => ((ICollection>)dictionary).Remove(new(A, new CosInteger(1))) }, + }; + + [Theory] + [MemberData(nameof(DictionaryMutations))] + public void Any_dictionary_mutation_marks_it_dirty(string mutation, Action mutate) + { + _ = mutation; + CosDictionary dictionary = Assert.IsType(CosObject.Parse("<< /A 1 >>"u8)); + + mutate(dictionary); + + Assert.True(dictionary.IsDirty); + } + + [Fact] + public void Operations_that_change_nothing_leave_the_object_clean() + { + CosArray array = Assert.IsType(CosObject.Parse("[1]"u8)); + CosDictionary dictionary = Assert.IsType(CosObject.Parse("<< /A 1 >>"u8)); + + Assert.False(array.Remove(new CosInteger(7))); + Assert.False(dictionary.Remove(B)); + dictionary[B] = CosNull.Instance; + + Assert.False(array.IsDirty); + Assert.False(dictionary.IsDirty); + } + + [Fact] + public void Replacing_stream_data_or_changing_its_dictionary_marks_the_stream_dirty() + { + CosStream replaced = Assert.IsType(CosObject.Parse("<< /Length 3 >>\nstream\nabc\nendstream"u8)); + CosStream edited = Assert.IsType(CosObject.Parse("<< /Length 3 >>\nstream\nabc\nendstream"u8)); + + replaced.EncodedData = "xyz"u8.ToArray(); + edited.Dictionary[new CosName("Filter")] = new CosName("FlateDecode"); + + Assert.True(replaced.IsDirty); + Assert.True(edited.IsDirty); + } + + [Fact] + public void A_change_to_a_nested_direct_object_makes_every_container_above_it_dirty() + { + CosDictionary root = Assert.IsType(CosObject.Parse("<< /A [1 << /B [2] >>] /C 3 >>"u8)); + CosArray outer = Assert.IsType(root[A]); + CosDictionary middle = Assert.IsType(outer[1]); + CosArray inner = Assert.IsType(middle[B]); + + inner.Add(new CosInteger(4)); + + Assert.True(inner.IsDirty); + Assert.True(middle.IsDirty); + Assert.True(outer.IsDirty); + Assert.True(root.IsDirty); + } + + private static IEnumerable Descendants(CosObject value) => value switch + { + CosArray array => array.SelectMany(static item => Descendants(item).Prepend(item)), + CosDictionary dictionary => dictionary.Values.SelectMany(static item => Descendants(item).Prepend(item)), + CosStream stream => Descendants(stream.Dictionary).Prepend(stream.Dictionary), + _ => [], + }; +} diff --git a/tests/Broadside.Tests/Objects/LexerAllocationTests.cs b/tests/Broadside.Tests/Objects/LexerAllocationTests.cs new file mode 100644 index 00000000..7c745ea7 --- /dev/null +++ b/tests/Broadside.Tests/Objects/LexerAllocationTests.cs @@ -0,0 +1,38 @@ +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Objects; + +/// +/// The lexer is a hot path and allocates nothing per token (CLAUDE.md, "Code conventions"). This is the build-breaking half of +/// that rule; LexerBenchmarks in bench/Broadside.Benchmarks is the measuring half. It drives the internal lexer +/// because no public seam exposes tokens. +/// +public class LexerAllocationTests +{ + [Fact] + public void Tokenizing_the_whole_corpus_allocates_nothing() + { + byte[] bytes = [.. Corpus.AllFileNames.SelectMany(Corpus.Bytes)]; + Tokenize(bytes); + + long before = GC.GetAllocatedBytesForCurrentThread(); + int tokens = Tokenize(bytes); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.True(tokens > 1_000, $"Only {tokens} tokens; the input is too small to show per-token allocations."); + Assert.Equal(0, allocated); + } + + private static int Tokenize(ReadOnlySpan bytes) + { + var lexer = new CosLexer(bytes); + int count = 0; + while (lexer.Next().Kind != CosTokenKind.EndOfInput) + { + count++; + } + + return count; + } +} diff --git a/tests/Broadside.Tests/Objects/ScalarParsingTests.cs b/tests/Broadside.Tests/Objects/ScalarParsingTests.cs new file mode 100644 index 00000000..341f7634 --- /dev/null +++ b/tests/Broadside.Tests/Objects/ScalarParsingTests.cs @@ -0,0 +1,118 @@ +using Broadside.Objects; + +namespace Broadside.Tests.Objects; + +/// ISO 32000-2 §7.3.2, §7.3.3, §7.3.9 and §7.3.10: the scalar objects, parsed through . +public class ScalarParsingTests +{ + [Theory] + [InlineData("true", true)] + [InlineData("false", false)] + public void Parses_booleans(string syntax, bool expected) + { + CosObject parsed = CosObject.Parse(Latin1(syntax)); + + Assert.Equal(expected, Assert.IsType(parsed).Value); + } + + [Theory] + [InlineData("123", 123L)] + [InlineData("43445", 43445L)] + [InlineData("+17", 17L)] + [InlineData("-98", -98L)] + [InlineData("0", 0L)] + [InlineData("-0", 0L)] + [InlineData("9223372036854775807", long.MaxValue)] + public void Parses_integers_from_the_spec_examples(string syntax, long expected) + { + CosObject parsed = CosObject.Parse(Latin1(syntax)); + + Assert.Equal(expected, Assert.IsType(parsed).Value); + } + + [Theory] + [InlineData("34.5", 34.5)] + [InlineData("-3.62", -3.62)] + [InlineData("+123.6", 123.6)] + [InlineData("4.", 4.0)] + [InlineData("-.002", -0.002)] + [InlineData("0.0", 0.0)] + [InlineData(".5", 0.5)] + public void Parses_reals_from_the_spec_examples(string syntax, double expected) + { + CosObject parsed = CosObject.Parse(Latin1(syntax)); + + Assert.Equal(expected, Assert.IsType(parsed).Value); + } + + [Fact] + public void Integer_too_large_for_64_bits_is_read_as_a_real() + { + CosObject parsed = CosObject.Parse("12345678901234567890"u8); + + Assert.Equal(12345678901234567890d, Assert.IsType(parsed).Value); + } + + [Fact] + public void Integers_and_reals_are_both_numbers() + { + var integer = (CosNumber)CosObject.Parse("7"u8); + var real = (CosNumber)CosObject.Parse("7.25"u8); + + Assert.Equal(7d, integer.ToDouble()); + Assert.Equal(7.25d, real.ToDouble()); + } + + [Fact] + public void Parses_null_as_the_single_null_object() + { + CosObject parsed = CosObject.Parse("null"u8); + + Assert.Same(CosNull.Instance, parsed); + } + + [Theory] + [InlineData("12 0 R", 12, 0)] + [InlineData("1 65535 R", 1, 65535)] + [InlineData(" 7\r\n3%comment\nR ", 7, 3)] + public void Parses_indirect_references(string syntax, int objectNumber, int generation) + { + CosObject parsed = CosObject.Parse(Latin1(syntax)); + + CosReference reference = Assert.IsType(parsed); + Assert.Equal(objectNumber, reference.ObjectNumber); + Assert.Equal(generation, reference.Generation); + } + + [Theory] + [InlineData("")] + [InlineData(" % only a comment")] + [InlineData("1 2")] + [InlineData("12 0 obj")] + [InlineData("0 0 R")] + [InlineData("1 -1 R")] + [InlineData("1e5")] + [InlineData("1.2.3")] + [InlineData("--5")] + [InlineData("nul")] + [InlineData(")")] + [InlineData(">")] + [InlineData("]")] + [InlineData(">>")] + public void Rejects_input_that_is_not_exactly_one_object(string syntax) + { + Assert.Throws(() => CosObject.Parse(Latin1(syntax))); + Assert.False(CosObject.TryParse(Latin1(syntax), out CosObject? result)); + Assert.Null(result); + } + + [Fact] + public void Whitespace_and_comments_around_an_object_are_ignored() + { + CosObject parsed = CosObject.Parse("\0\t\n\f\r %a comment\r\n true % trailing\n"u8); + + Assert.Same(CosBoolean.True, parsed); + } + + internal static byte[] Latin1(string text) => System.Text.Encoding.Latin1.GetBytes(text); +} diff --git a/tests/Broadside.Tests/Objects/SerializationTests.cs b/tests/Broadside.Tests/Objects/SerializationTests.cs new file mode 100644 index 00000000..152e6de1 --- /dev/null +++ b/tests/Broadside.Tests/Objects/SerializationTests.cs @@ -0,0 +1,192 @@ +using System.Buffers; +using System.Text; +using Broadside.Objects; +using static Broadside.Tests.Objects.ScalarParsingTests; + +namespace Broadside.Tests.Objects; + +/// +/// Writing COS objects back to bytes (ISO 32000-2 §7.2, §7.3) and the equality a write-then-parse round trip preserves. +/// +public class SerializationTests +{ + public static TheoryData CanonicalSyntax => new() + { + { "true", "true" }, + { "false", "false" }, + { "null", "null" }, + { "+17", "17" }, + { "-98", "-98" }, + { "12 0 R", "12 0 R" }, + { "34.5", "34.5" }, + { "4.", "4.0" }, + { "-.002", "-0.002" }, + { "0.00001", "0.00001" }, + { "12345678901234567890", "12345678901234567000.0" }, + { "/Lime#20Green", "/Lime#20Green" }, + { "/The_Key_of_F#23_Minor", "/The_Key_of_F#23_Minor" }, + { "/A#42", "/AB" }, + { "/", "/" }, + { "(It has zero (0) length.)", @"(It has zero \(0\) length.)" }, + { "(a\\\\b\nc\rd\te\bf\fg)", @"(a\\b\nc\nd\te\bf\fg)" }, + { @"(\000\177\200\377)", @"(\000\177\200\377)" }, + { "<901fa>", "<901FA0>" }, + { "[549 3.14 false (Ralph) /SomeName]", "[549 3.14 false (Ralph) /SomeName]" }, + { "[ ]", "[]" }, + { "<>>>", "<< /Type /Page /MediaBox [0 0 612 792] /Resources << >> >>" }, + }; + + [Theory] + [MemberData(nameof(CanonicalSyntax))] + public void Writes_canonical_syntax(string syntax, string expected) + { + CosObject parsed = CosObject.Parse(Latin1(syntax)); + + Assert.Equal(expected, Write(parsed)); + Assert.Equal(expected, parsed.ToString()); + } + + public static TheoryData NameEscapes => new() + { + { "paired()parentheses", "/paired#28#29parentheses" }, + { "Lime Green", "/Lime#20Green" }, + { "a/b%ce[f]g{h}i#j", "/a#2Fb#25c#3Cd#3Ee#5Bf#5Dg#7Bh#7Di#23j" }, + { "Café", "/Caf#C3#A9" }, + }; + + [Theory] + [MemberData(nameof(NameEscapes))] + public void Names_escape_delimiters_white_space_number_signs_and_non_ascii_bytes(string name, string expected) + { + Assert.Equal(expected, Write(new CosName(name))); + } + + [Fact] + public void Writes_a_stream_with_a_direct_length_equal_to_its_data() + { + CosObject parsed = CosObject.Parse("<< /Filter /AHx /Length 9 0 R >>\nstream\n414243>\nendstream"u8); + + Assert.Equal("<< /Filter /AHx /Length 7 >>\nstream\n414243>\nendstream", Write(parsed)); + Assert.Equal("<< /Length 0 >>\nstream\n\nendstream", Write(new CosStream(new CosDictionary(), ReadOnlyMemory.Empty))); + } + + [Theory] + [InlineData(0.1)] + [InlineData(-0.1)] + [InlineData(1e-7)] + [InlineData(1.0 / 3.0)] + [InlineData(123456789.123456789)] + [InlineData(1e21)] + [InlineData(-1e300)] + [InlineData(double.Epsilon)] + [InlineData(double.MaxValue)] + [InlineData(double.MinValue)] + [InlineData(5.0)] + public void Reals_round_trip_exactly_without_exponent_notation(double value) + { + string written = Write(new CosReal(value)); + + Assert.DoesNotContain('E', written); + Assert.Contains('.', written); + Assert.Equal(value, Assert.IsType(CosObject.Parse(Encoding.ASCII.GetBytes(written))).Value); + } + + [Fact] + public void A_real_must_be_finite() + { + Assert.Throws(() => new CosReal(double.NaN)); + Assert.Throws(() => new CosReal(double.PositiveInfinity)); + } + + public static TheoryData RoundTripSyntax => new() + { + { "[549 3.14 false (Ralph) /SomeName]" }, + { "<< /A [1 2.5 << /B (x) >>] /C 3 0 R /D <00FF> /E null /F /G#20H >>" }, + { "(Strings can contain balanced parentheses ()\nand special characters ( * ! & } ^ %and so on) .)" }, + { "<< /Length 8 0 R >>\nstream\r\nline one\nline two\r\nendstream" }, + { "<< /Length 0 >>\nstream\n\nendstream" }, + }; + + [Theory] + [MemberData(nameof(RoundTripSyntax))] + public void A_written_object_parses_back_to_an_equal_object(string syntax) + { + CosObject original = CosObject.Parse(Latin1(syntax)); + + CosObject reparsed = CosObject.Parse(WriteBytes(original)); + + Assert.True(CosObject.DeepEquals(original, reparsed), $"{original} != {reparsed}"); + Assert.Equal(Write(original), Write(reparsed)); + } + + [Fact] + public void Every_byte_value_survives_a_round_trip_in_strings_and_names() + { + byte[] everyByte = [.. Enumerable.Range(0, 256).Select(static value => (byte)value)]; + byte[] everyByteButZero = everyByte[1..]; + var array = new CosArray([new CosString(everyByte), new CosString(everyByte, hexadecimal: true), new CosName(everyByteButZero)]); + + CosArray reparsed = Assert.IsType(CosObject.Parse(WriteBytes(array))); + + Assert.True(CosObject.DeepEquals(array, reparsed)); + Assert.Equal(everyByte, Assert.IsType(reparsed[0]).Bytes.ToArray()); + Assert.Equal(everyByteButZero, Assert.IsType(reparsed[2]).Bytes.ToArray()); + } + + [Fact] + public void A_constructed_tree_round_trips() + { + var page = new CosDictionary + { + [new CosName("Type")] = new CosName("Page"), + [new CosName("MediaBox")] = new CosArray([new CosInteger(0), new CosInteger(0), new CosReal(595.276), new CosReal(841.89)]), + [new CosName("Parent")] = new CosReference(2, 0), + [new CosName("Contents")] = new CosStream(new CosDictionary(), "BT ET"u8.ToArray()), + }; + + Assert.True(CosObject.DeepEquals(page, CosObject.Parse(WriteBytes(page)))); + } + + [Fact] + public void Deep_equality_requires_the_same_kind_of_object() + { + Assert.False(CosObject.DeepEquals(new CosInteger(1), new CosReal(1))); + Assert.False(CosObject.DeepEquals(new CosName("A"), new CosString("A"u8))); + Assert.False(CosObject.DeepEquals(CosNull.Instance, null)); + Assert.True(CosObject.DeepEquals(null, null)); + } + + [Fact] + public void Deep_equality_ignores_string_form_dictionary_order_and_stream_length() + { + Assert.True(CosObject.DeepEquals(CosObject.Parse("(AB)"u8), CosObject.Parse("<4142>"u8))); + Assert.True(CosObject.DeepEquals(CosObject.Parse("<< /A 1 /B 2 >>"u8), CosObject.Parse("<< /B 2 /A 1 >>"u8))); + Assert.True(CosObject.DeepEquals( + CosObject.Parse("<< /Length 3 >>\nstream\nabc\nendstream"u8), + new CosStream(new CosDictionary(), "abc"u8.ToArray()))); + Assert.False(CosObject.DeepEquals( + CosObject.Parse("<< /Length 3 >>\nstream\nabc\nendstream"u8), + new CosStream(new CosDictionary(), "abd"u8.ToArray()))); + Assert.False(CosObject.DeepEquals(CosObject.Parse("[1 2]"u8), CosObject.Parse("[2 1]"u8))); + } + + [Fact] + public void Equals_is_value_equality_for_immutable_objects_and_identity_for_containers() + { + Assert.Equal(new CosInteger(5), new CosInteger(5)); + Assert.Equal(new CosString("x"u8), new CosString("x"u8, hexadecimal: true)); + Assert.Equal(new CosReference(1, 0), CosObject.Parse("1 0 R"u8)); + Assert.Equal(new CosName("Type").GetHashCode(), CosObject.Parse("/Typ#65"u8).GetHashCode()); + Assert.False(new CosArray().Equals(new CosArray())); + Assert.False(new CosDictionary().Equals(new CosDictionary())); + } + + private static string Write(CosObject value) => Encoding.Latin1.GetString(WriteBytes(value)); + + private static byte[] WriteBytes(CosObject value) + { + var buffer = new ArrayBufferWriter(); + value.WriteTo(buffer); + return buffer.WrittenSpan.ToArray(); + } +} diff --git a/tests/Broadside.Tests/Objects/StringAndNameParsingTests.cs b/tests/Broadside.Tests/Objects/StringAndNameParsingTests.cs new file mode 100644 index 00000000..01a03b89 --- /dev/null +++ b/tests/Broadside.Tests/Objects/StringAndNameParsingTests.cs @@ -0,0 +1,154 @@ +using Broadside.Objects; +using static Broadside.Tests.Objects.ScalarParsingTests; + +namespace Broadside.Tests.Objects; + +/// ISO 32000-2 §7.3.4 (strings) and §7.3.5 (names), with the expected values taken from the clauses' own examples. +public class StringAndNameParsingTests +{ + [Theory] + [InlineData("(This is a string)", "This is a string")] + [InlineData("(Strings can contain newlines\nand such.)", "Strings can contain newlines\nand such.")] + [InlineData("(Strings can contain balanced parentheses ()\nand special characters ( * ! & } ^ %and so on) .)", "Strings can contain balanced parentheses ()\nand special characters ( * ! & } ^ %and so on) .")] + [InlineData("()", "")] + [InlineData("(It has zero (0) length.)", "It has zero (0) length.")] + public void Literal_strings_from_example_1_keep_balanced_parentheses(string syntax, string expected) + { + Assert.Equal(Latin1(expected), StringBytes(syntax)); + } + + [Theory] + [InlineData(@"(\n)", "\n")] + [InlineData(@"(\r)", "\r")] + [InlineData(@"(\t)", "\t")] + [InlineData(@"(\b)", "\b")] + [InlineData(@"(\f)", "\f")] + [InlineData(@"(\()", "(")] + [InlineData(@"(\))", ")")] + [InlineData(@"(\\)", "\\")] + [InlineData(@"(\q)", "q")] + [InlineData(@"(unbalanced \( only)", "unbalanced ( only")] + public void Literal_strings_decode_every_escape_in_table_3(string syntax, string expected) + { + Assert.Equal(Latin1(expected), StringBytes(syntax)); + } + + [Theory] + [InlineData("(These \\\ntwo strings \\\nare the same.)")] + [InlineData("(These \\\r\ntwo strings \\\rare the same.)")] + [InlineData("(These two strings are the same.)")] + public void A_backslash_before_an_end_of_line_continues_the_string(string syntax) + { + Assert.Equal("These two strings are the same."u8.ToArray(), StringBytes(syntax)); + } + + [Theory] + [InlineData("(This string has an end-of-line at the end of it.\n)")] + [InlineData("(This string has an end-of-line at the end of it.\r)")] + [InlineData("(This string has an end-of-line at the end of it.\r\n)")] + [InlineData(@"(This string has an end-of-line at the end of it.\n)")] + public void An_unescaped_end_of_line_is_read_as_a_line_feed(string syntax) + { + Assert.Equal("This string has an end-of-line at the end of it.\n"u8.ToArray(), StringBytes(syntax)); + } + + [Theory] + [InlineData(@"(This string contains \245two octal characters\307.)", "This string contains ¥two octal charactersÇ.")] + [InlineData(@"(\0053)", "\u0005" + "3")] + [InlineData(@"(\053)", "+")] + [InlineData(@"(\53)", "+")] + [InlineData(@"(\5)", "\u0005")] + [InlineData(@"(\777)", "ÿ")] + [InlineData(@"(\1234)", "S4")] + public void Octal_escapes_take_one_to_three_digits_and_ignore_overflow(string syntax, string expected) + { + Assert.Equal(Latin1(expected), StringBytes(syntax)); + } + + [Fact] + public void Literal_strings_may_hold_any_byte() + { + byte[] syntax = [(byte)'(', 0x00, 0x80, 0xFF, (byte)'%', (byte)')']; + + Assert.Equal(new byte[] { 0x00, 0x80, 0xFF, (byte)'%' }, Assert.IsType(CosObject.Parse(syntax)).Bytes.ToArray()); + } + + [Theory] + [InlineData("<4E6F762073686D6F7A206B6120706F702E>", "Nov shmoz ka pop.")] + [InlineData("<901FA3>", "\u0090\u001F£")] + [InlineData("<901FA>", "\u0090\u001F ")] + [InlineData("<>", "")] + [InlineData("< 4e 6F\r\n76\t>", "Nov")] + public void Hexadecimal_strings_ignore_white_space_and_pad_an_odd_digit_with_zero(string syntax, string expected) + { + CosString parsed = Assert.IsType(CosObject.Parse(Latin1(syntax))); + + Assert.Equal(Latin1(expected), parsed.Bytes.ToArray()); + Assert.True(parsed.IsHexadecimal); + } + + [Theory] + [InlineData("(unterminated")] + [InlineData("(unterminated \\)")] + [InlineData("<4E6F")] + [InlineData("<4G>")] + public void Malformed_strings_are_rejected(string syntax) + { + Assert.Throws(() => CosObject.Parse(Latin1(syntax))); + } + + [Theory] + [InlineData("/Name1", "Name1")] + [InlineData("/ASomewhatLongerName", "ASomewhatLongerName")] + [InlineData("/A;Name_With-Various***Characters?", "A;Name_With-Various***Characters?")] + [InlineData("/1.2", "1.2")] + [InlineData("/$$", "$$")] + [InlineData("/@pattern", "@pattern")] + [InlineData("/.notdef", ".notdef")] + [InlineData("/Lime#20Green", "Lime Green")] + [InlineData("/paired#28#29parentheses", "paired()parentheses")] + [InlineData("/The_Key_of_F#23_Minor", "The_Key_of_F#_Minor")] + [InlineData("/A#42", "AB")] + [InlineData("/", "")] + public void Names_from_table_4_expand_number_sign_escapes(string syntax, string expected) + { + CosName parsed = Assert.IsType(CosObject.Parse(Latin1(syntax))); + + Assert.Equal(Latin1(expected), parsed.Bytes.ToArray()); + Assert.Equal(new CosName(expected), parsed); + } + + [Fact] + public void Names_are_equal_when_their_expanded_bytes_are_equal() + { + Assert.Equal(CosObject.Parse("/A#42"u8), CosObject.Parse("/AB"u8)); + Assert.NotEqual(CosObject.Parse("/ab"u8), CosObject.Parse("/AB"u8)); + } + + [Fact] + public void Name_value_is_the_utf8_reading_of_its_bytes() + { + CosName parsed = Assert.IsType(CosObject.Parse("/Caf#C3#A9"u8)); + + Assert.Equal("Café", parsed.Value); + } + + [Theory] + [InlineData("/Bad#2")] + [InlineData("/Bad#ZZ")] + [InlineData("/Null#00")] + public void Malformed_names_are_rejected(string syntax) + { + Assert.Throws(() => CosObject.Parse(Latin1(syntax))); + } + + [Fact] + public void A_name_cannot_hold_the_byte_zero() + { + Assert.Throws(() => new CosName("A\0B")); + Assert.Throws(() => new CosName([0x41, 0x00])); + } + + private static byte[] StringBytes(string syntax) => + Assert.IsType(CosObject.Parse(Latin1(syntax))).Bytes.ToArray(); +} diff --git a/tests/Broadside.Tests/Objects/TextStringTests.cs b/tests/Broadside.Tests/Objects/TextStringTests.cs new file mode 100644 index 00000000..5f67a5d1 --- /dev/null +++ b/tests/Broadside.Tests/Objects/TextStringTests.cs @@ -0,0 +1,66 @@ +using Broadside.Objects; + +namespace Broadside.Tests.Objects; + +/// ISO 32000-2 §7.9.2.2 and Annex D: decoding string objects as text strings. +public class TextStringTests +{ + [Fact] + public void Decodes_utf16be_after_its_byte_order_marker() + { + // §7.9.2.2.1 Example 2: the Russian word for "test". + var text = new CosString([0xFE, 0xFF, 0x04, 0x42, 0x04, 0x35, 0x04, 0x41, 0x04, 0x42]); + + Assert.Equal("тест", text.DecodeText()); + } + + [Fact] + public void Decodes_utf16be_supplementary_characters() + { + var text = new CosString([0xFE, 0xFF, 0xD8, 0x3D, 0xDE, 0x00]); + + Assert.Equal("\U0001F600", text.DecodeText()); + } + + [Fact] + public void Decodes_utf8_after_its_byte_order_marker() + { + var text = new CosString([0xEF, 0xBB, 0xBF, .. "Café"u8]); + + Assert.Equal("Café", text.DecodeText()); + } + + [Fact] + public void Decodes_pdfdocencoding_when_there_is_no_byte_order_marker() + { + // §7.9.2.2.1 Example 1: 0x8B is the per-mille sign; the others are rows of Table D.3. + var text = new CosString([.. "text"u8, 0x8B, 0x18, 0x80, 0x93, 0xA0, 0xE9, 0x9F]); + + Assert.Equal("text‰˘•fi€é\u009F", text.DecodeText()); + } + + [Fact] + public void Decodes_a_hexadecimal_string_the_same_way() + { + CosString text = Assert.IsType(CosObject.Parse(""u8)); + + Assert.Equal("A", text.DecodeText()); + } + + [Fact] + public void Removes_language_escape_sequences_from_unicode_text() + { + byte[] utf16 = [0xFE, 0xFF, 0x00, 0x1B, 0x00, (byte)'e', 0x00, (byte)'n', 0x00, 0x1B, 0x00, (byte)'H', 0x00, 0x1B, 0x00, (byte)'j', 0x00, (byte)'a', 0x00, (byte)'J', 0x00, (byte)'P', 0x00, 0x1B, 0x00, (byte)'i']; + byte[] utf8 = [0xEF, 0xBB, 0xBF, 0x1B, .. "en"u8, 0x1B, .. "Hi"u8]; + + Assert.Equal("Hi", new CosString(utf16).DecodeText()); + Assert.Equal("Hi", new CosString(utf8).DecodeText()); + } + + [Fact] + public void Tolerates_malformed_unicode() + { + Assert.Equal("A", new CosString([0xFE, 0xFF, 0x00, 0x41, 0x42]).DecodeText()); + Assert.Equal("�", new CosString([0xEF, 0xBB, 0xBF, 0xC3]).DecodeText()); + } +} diff --git a/tests/README.md b/tests/README.md index 5daef8bb..19e0bbac 100644 --- a/tests/README.md +++ b/tests/README.md @@ -83,5 +83,5 @@ dotnet run -c Release --project bench/Broadside.Benchmarks -- --list flat `tests/Broadside.Fuzz` holds one SharpFuzz target per parser and codec. Without any fuzzer installed, `--smoke [seconds]` runs the target over the corpus and random mutations of it; CI runs that for 60 s per target. Real fuzzing with libFuzzer or AFL is described in [Broadside.Fuzz/README.md](Broadside.Fuzz/README.md). ```sh -dotnet run -c Release --project tests/Broadside.Fuzz -- --smoke pdf-header 10 +dotnet run -c Release --project tests/Broadside.Fuzz -- --smoke object-parser 10 ``` From 11aaeaf2942d14ea80b71437437f66d1a2bde393 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:47:13 -0500 Subject: [PATCH 002/152] docs(skills): conformance map type cells use simple names The checker (#7) resolves Implementing types by simple name; the skill still showed fully qualified names. Found by the #36 implementer. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/updating-the-conformance-map/SKILL.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.claude/skills/updating-the-conformance-map/SKILL.md b/.claude/skills/updating-the-conformance-map/SKILL.md index 5c7d20ab..6875ea1f 100644 --- a/.claude/skills/updating-the-conformance-map/SKILL.md +++ b/.claude/skills/updating-the-conformance-map/SKILL.md @@ -26,8 +26,8 @@ Today every row is at the second level (`7.2`, `7.3`, ...), all `not started`. - **Clause**: the number as the spec prints it (`7.2`, `7.2.3`), no `§`, no trailing dot. - **Title**: the heading from `Specs/`, read with `pdftotext Specs/ISO_32000-2_sponsored_EC3.pdf - | grep -nE '^7\.2\.[0-9] '`, never from memory. - **Status**: one of `not started`, `partial`, `done`, `n/a`. `n/a` is for clauses with no implementable content or that `CLAUDE.md` lists as out of scope; say which in Notes. -- **Implementing types**: fully qualified type names, each in backticks, comma-separated: `` `Broadside.Cos.CosLexer`, `Broadside.Cos.CosToken` ``. Leave empty for `not started` and `n/a`. -- **Tests**: fully qualified test identifiers `Namespace.Class.Method`, each in backticks, comma-separated: `` `Broadside.Tests.Objects.LexerTests.Tokenizes_names` ``. For a theory, name the method once. A `done` row needs at least one; give `partial` rows their tests too so the checker's counts mean something. Issue #7 formalizes these two cell formats; use them now. +- **Implementing types**: simple type names (no namespace, no type arguments), each in backticks, comma-separated: `` `CosDictionary`, `CosParser` ``. Each must be declared as a class, struct, interface, enum or record under `src/`. Leave empty for `not started` and `n/a`. +- **Tests**: fully qualified test identifiers `Namespace.Class.Method`, each in backticks, comma-separated: `` `Broadside.Tests.Objects.LexerTests.Tokenizes_names` ``. For a theory, name the method once. A `done` row needs at least one; give `partial` rows their tests too so the checker's counts mean something. The authoritative formats are in `docs/conformance/README.md`; the checker enforces them. - **Notes**: for `partial`, what is still missing; for `n/a`, why; otherwise anything a reader needs to find the code (an ADR number, a corpus file name). Keep cells on one line; the table has no multi-line cells. @@ -91,7 +91,7 @@ and `CosLexer` carries `ISO 32000-2 §7.2.`. When the follow- - [ ] Every clause the PR touches has a row in the right `docs/conformance/.md` - [ ] Status is one of the four values; `done` rows name at least one test -- [ ] Types and tests are fully qualified, backticked, comma-separated +- [ ] Types are simple names and tests are fully qualified, all backticked and comma-separated - [ ] Split to third-level rows where statuses differ; titles copied from `Specs/` - [ ] Each implementing public type and member carries `ISO 32000-2 §x.y.z` - [ ] `dotnet run --project tools/ConformanceCheck -- --root . --summary` passes (once #7 has landed) From c4eb111b26aeb5e252e9dbbed605f183dbda6bd6 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:11:01 -0500 Subject: [PATCH 003/152] feat(document): open a file and read its pages (#37) PdfDocument.Open (path, stream, bytes) and PdfEngine read the header, the last startxref, classic cross-reference tables through the Prev chain, the trailer and the catalog, then walk the page tree lazily. PdfPage is a live view: media, crop, bleed, trim and art boxes with the Table 31 defaults and clipping to the media box (14.11.2), rotation normalized to 0-270, user unit, and Resources/MediaBox/CropBox/Rotate inherited as-is from the nearest ancestor. The effective version is the later of the header and the catalog Version. Offsets are long and relative to the %PDF- header (7.5.2). Lenient reading records Diagnostics (public Diagnostic, DiagnosticSeverity, DiagnosticException); strict mode throws the first one. PdfOptions (UseLenient/UseStrict) is snapshotted by the engine; the static entry points use the same engine code path. Create is a stub. Internal seams for the next tickets: PdfSource (positional reads, #45), CrossReference with per-section data and Compressed entries (#39, #40), ObjectLoader with hooks in fixed order (stream extent #41, decryption #42, cache #45), DiagnosticSink with an observer (#46), and EngineConfiguration for new options. The COS parser resolves indirect stream Length through the loader. Adds the `document` fuzz target, DocumentOpenBenchmarks and conformance rows 7.3.10, 7.5.1-7.5.8, 7.7.1-7.7.4, 7.9.5 and 14.11.1-14.11.7. Co-Authored-By: Claude Opus 5.5 --- .../DocumentOpenBenchmarks.cs | 35 +++ docs/conformance/iso-32000-2.md | 28 +- src/Broadside/Diagnostics/Diagnostic.cs | 67 ++++ .../Diagnostics/DiagnosticException.cs | 45 +++ .../Diagnostics/DiagnosticSeverity.cs | 12 + src/Broadside/EngineConfiguration.cs | 21 ++ src/Broadside/IO/PdfSource.cs | 94 ++++++ src/Broadside/Objects/CosParser.cs | 18 +- .../Objects/IStreamLengthResolver.cs | 15 + src/Broadside/Objects/KnownNames.cs | 57 ++++ src/Broadside/PageTreeReader.cs | 286 ++++++++++++++++++ src/Broadside/Parsing/CrossReference.cs | 114 +++++++ src/Broadside/Parsing/CrossReferenceReader.cs | 197 ++++++++++++ src/Broadside/Parsing/DiagnosticCodes.cs | 57 ++++ src/Broadside/Parsing/DiagnosticSink.cs | 72 +++++ src/Broadside/Parsing/FileHeader.cs | 59 ++++ src/Broadside/Parsing/ObjectLoader.cs | 175 +++++++++++ src/Broadside/Parsing/ObjectLoaderHooks.cs | 137 +++++++++ src/Broadside/Parsing/StructureTokens.cs | 45 +++ src/Broadside/Parsing/XrefTableReader.cs | 148 +++++++++ src/Broadside/PdfDocument.cs | 237 +++++++++++++++ src/Broadside/PdfEngine.cs | 73 +++++ src/Broadside/PdfOptions.cs | 32 ++ src/Broadside/PdfPage.cs | 203 +++++++++++++ src/Broadside/PdfPageCollection.cs | 32 ++ src/Broadside/PdfReadingMode.cs | 12 + src/Broadside/PdfRectangle.cs | 78 +++++ src/Broadside/PdfVersion.cs | 109 +++++++ src/Broadside/PublicAPI.Unshipped.txt | 95 ++++++ tests/Broadside.Fuzz/FuzzTargets.cs | 50 +++ tests/Broadside.Fuzz/README.md | 4 +- .../Document/DocumentProjection.cs | 20 ++ tests/Broadside.Tests/Document/EngineTests.cs | 116 +++++++ .../Document/FileStructureTests.cs | 215 +++++++++++++ .../Document/OpenDocumentTests.cs | 96 ++++++ .../Document/PageAttributeTests.cs | 190 ++++++++++++ .../Broadside.Tests/Document/PageTreeTests.cs | 162 ++++++++++ tests/Broadside.Tests/Document/TestPdf.cs | 51 ++++ .../Broadside.Tests/Document/VersionTests.cs | 72 +++++ .../Document/WellFormedCorpusTests.cs | 47 +++ 40 files changed, 3565 insertions(+), 11 deletions(-) create mode 100644 bench/Broadside.Benchmarks/DocumentOpenBenchmarks.cs create mode 100644 src/Broadside/Diagnostics/Diagnostic.cs create mode 100644 src/Broadside/Diagnostics/DiagnosticException.cs create mode 100644 src/Broadside/Diagnostics/DiagnosticSeverity.cs create mode 100644 src/Broadside/EngineConfiguration.cs create mode 100644 src/Broadside/IO/PdfSource.cs create mode 100644 src/Broadside/Objects/IStreamLengthResolver.cs create mode 100644 src/Broadside/PageTreeReader.cs create mode 100644 src/Broadside/Parsing/CrossReference.cs create mode 100644 src/Broadside/Parsing/CrossReferenceReader.cs create mode 100644 src/Broadside/Parsing/DiagnosticCodes.cs create mode 100644 src/Broadside/Parsing/DiagnosticSink.cs create mode 100644 src/Broadside/Parsing/FileHeader.cs create mode 100644 src/Broadside/Parsing/ObjectLoader.cs create mode 100644 src/Broadside/Parsing/ObjectLoaderHooks.cs create mode 100644 src/Broadside/Parsing/StructureTokens.cs create mode 100644 src/Broadside/Parsing/XrefTableReader.cs create mode 100644 src/Broadside/PdfDocument.cs create mode 100644 src/Broadside/PdfEngine.cs create mode 100644 src/Broadside/PdfOptions.cs create mode 100644 src/Broadside/PdfPage.cs create mode 100644 src/Broadside/PdfPageCollection.cs create mode 100644 src/Broadside/PdfReadingMode.cs create mode 100644 src/Broadside/PdfRectangle.cs create mode 100644 src/Broadside/PdfVersion.cs create mode 100644 tests/Broadside.Tests/Document/DocumentProjection.cs create mode 100644 tests/Broadside.Tests/Document/EngineTests.cs create mode 100644 tests/Broadside.Tests/Document/FileStructureTests.cs create mode 100644 tests/Broadside.Tests/Document/OpenDocumentTests.cs create mode 100644 tests/Broadside.Tests/Document/PageAttributeTests.cs create mode 100644 tests/Broadside.Tests/Document/PageTreeTests.cs create mode 100644 tests/Broadside.Tests/Document/TestPdf.cs create mode 100644 tests/Broadside.Tests/Document/VersionTests.cs create mode 100644 tests/Broadside.Tests/Document/WellFormedCorpusTests.cs diff --git a/bench/Broadside.Benchmarks/DocumentOpenBenchmarks.cs b/bench/Broadside.Benchmarks/DocumentOpenBenchmarks.cs new file mode 100644 index 00000000..ed8ea8c4 --- /dev/null +++ b/bench/Broadside.Benchmarks/DocumentOpenBenchmarks.cs @@ -0,0 +1,35 @@ +using BenchmarkDotNet.Attributes; +using Broadside.TestSupport; + +namespace Broadside.Benchmarks; + +/// +/// Opens a corpus file from memory and walks its pages: header, startxref, cross-reference table, trailer, catalog, page tree +/// and every page's boxes (ISO 32000-2 §7.5, §7.7). Opening allocates the document model by design, so Allocated is a +/// baseline to watch, not a zero to assert; the per-token hot path underneath is . +/// +[MemoryDiagnoser] +public class DocumentOpenBenchmarks +{ + private byte[] _bytes = []; + + /// The corpus file to open: one page, and a two-level page tree with inheritance. + [Params("empty-page.pdf", "page-tree-inherited.pdf")] + public string File { get; set; } = ""; + + [GlobalSetup] + public void Setup() => _bytes = System.IO.File.ReadAllBytes(Path.Combine(CorpusLocator.CorpusDirectory, File)); + + [Benchmark] + public double OpenAndWalkPages() + { + using PdfDocument document = PdfDocument.Open(_bytes); + double area = 0; + foreach (PdfPage page in document.Pages) + { + area += page.CropBox.Width * page.CropBox.Height; + } + + return area; + } +} diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index 1f53e14d..655fac59 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -16,19 +16,29 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.3.5 | Name objects | done | `CosName` | `Broadside.Tests.Objects.StringAndNameParsingTests.Names_from_table_4_expand_number_sign_escapes`, `Broadside.Tests.Objects.StringAndNameParsingTests.Names_are_equal_when_their_expanded_bytes_are_equal`, `Broadside.Tests.Objects.SerializationTests.Names_escape_delimiters_white_space_number_signs_and_non_ascii_bytes` | | | 7.3.6 | Array objects | done | `CosArray` | `Broadside.Tests.Objects.ContainerParsingTests.Parses_the_array_example`, `Broadside.Tests.Objects.ContainerParsingTests.Arrays_nest_hold_references_and_keep_null_elements` | | | 7.3.7 | Dictionary objects | done | `CosDictionary` | `Broadside.Tests.Objects.ContainerParsingTests.Parses_the_dictionary_example`, `Broadside.Tests.Objects.ContainerParsingTests.A_null_valued_entry_is_the_same_as_an_absent_one` | Null-valued entries are never stored | -| 7.3.8 | Stream objects | partial | `CosStream` | `Broadside.Tests.Objects.ContainerParsingTests.A_stream_takes_its_data_from_its_length_or_from_endstream`, `Broadside.Tests.Objects.ContainerParsingTests.Streams_with_a_wrong_length_or_no_endstream_are_rejected`, `Broadside.Tests.Objects.CorpusObjectTests.The_metadata_stream_of_metadata_xmp_pdf_holds_its_declared_length` | Extent from a direct Length, else from endstream; resolving an indirect Length through the file (#37), external stream files (F, FFilter, FDecodeParms) and filters (#38) pending | +| 7.3.8 | Stream objects | partial | `CosStream` | `Broadside.Tests.Objects.ContainerParsingTests.A_stream_takes_its_data_from_its_length_or_from_endstream`, `Broadside.Tests.Objects.ContainerParsingTests.Streams_with_a_wrong_length_or_no_endstream_are_rejected`, `Broadside.Tests.Objects.CorpusObjectTests.The_metadata_stream_of_metadata_xmp_pdf_holds_its_declared_length` | Extent from a direct or indirect Length (`Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length`), else from endstream; external stream files (F, FFilter, FDecodeParms) and filters (#38) pending | | 7.3.9 | Null object | done | `CosNull` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_null_as_the_single_null_object`, `Broadside.Tests.Objects.ContainerParsingTests.A_null_valued_entry_is_the_same_as_an_absent_one` | | -| 7.3.10 | Indirect objects | partial | `CosReference` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_indirect_references` | References (`N G R`) parse and write; `N G obj` … `endobj` definitions and resolving a reference belong to the file reader (#37) | +| 7.3.10 | Indirect objects | done | `CosReference`, `PdfDocument` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_indirect_references`, `Broadside.Tests.Document.FileStructureTests.References_to_missing_free_or_other_generation_objects_resolve_to_null_without_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.An_object_without_endobj_is_read_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_reads_as_null_with_a_diagnostic` | `PdfDocument.Resolve`; references to missing, free or other-generation objects are null with no diagnostic; loading goes through the internal `ObjectLoader` (hooks for #41, #42, #45); a misplaced object reads as null until #41 searches for it | | 7.4 | Filters | not started | | | | -| 7.5 | File structure | not started | | | | +| 7.5.1 | General | done | `PdfDocument`, `CrossReferenceReader` | `Broadside.Tests.Document.OpenDocumentTests.A_file_opens_identically_from_a_path_a_stream_and_bytes_with_no_diagnostics`, `Broadside.Tests.Document.WellFormedCorpusTests.A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics` | Read from the end through startxref, the cross-reference table and the trailer, never serially; linearized files (Annex F) are #40 | +| 7.5.2 | File header | done | `FileHeader`, `PdfVersion`, `PdfDocument` | `Broadside.Tests.Document.FileStructureTests.Offsets_count_from_the_header_so_bytes_before_it_do_not_matter`, `Broadside.Tests.Document.FileStructureTests.A_file_without_a_header_opens_from_byte_0_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_header_without_a_valid_version_takes_the_catalog_version_with_a_diagnostic` | Header searched in the first 1024 bytes; every stated offset is relative to it; missing header: offsets from byte 0, version 1.4 unless the catalog says otherwise; the unshifted-offset retry is #41 | +| 7.5.3 | File body | done | `ObjectLoader` | `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length` | Objects load lazily by cross-reference entry; object streams are #39 | +| 7.5.4 | Cross-reference table | partial | `XrefTableReader`, `CrossReference` | `Broadside.Tests.Document.FileStructureTests.Entries_are_read_as_tokens_not_fixed_width_records`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_reads_as_null_with_a_diagnostic` | Subsections and n/f entries read as tokens; offset-0 in-use entries read as free; reconstruction by scanning when the table is wrong, and diagnostics for non-20-byte entries and comments, are #41 | +| 7.5.5 | File trailer | partial | `CrossReferenceReader`, `CrossReference`, `PdfDocument` | `Broadside.Tests.Document.FileStructureTests.A_startxref_offset_on_the_white_space_before_xref_is_repaired_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_file_with_no_startxref_cannot_be_read_even_leniently`, `Broadside.Tests.Document.FileStructureTests.A_trailer_without_root_cannot_be_read`, `Broadside.Tests.Document.FileStructureTests.A_prev_chain_that_loops_ends_with_a_diagnostic` | Last startxref, Prev chain with loop guard, Root; trailer merged newest-first; ignoring entries beyond Size, startxref recovery and trailer reconstruction are #41; Encrypt is #42 | +| 7.5.6 | Incremental updates | not started | | | The Prev chain is read (`Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`); revisions are #40 | +| 7.5.7 | Object streams | not started | | | #39 | +| 7.5.8 | Cross-reference streams | not started | | | #39; files with only a cross-reference stream fail to open with XrefStreamUnsupported until then | | 7.6 | Encryption | not started | | | | -| 7.7 | Document structure | not started | | | | +| 7.7.1 | General | n/a | | | Introductory text | +| 7.7.2 | Document catalog dictionary | partial | `PdfDocument`, `PdfVersion` | `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_catalog_version_written_as_a_number_is_read_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.A_malformed_catalog_version_is_ignored_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_catalog_without_its_type_is_read_with_a_diagnostic` | Type, Version (effective version = later of header and catalog) and Pages; the other Table 29 entries arrive with their features (outlines, names, AcroForm, ...) | +| 7.7.3 | Page tree | done | `PdfPage`, `PdfPageCollection`, `PageTreeReader` | `Broadside.Tests.Document.OpenDocumentTests.Page_tree_inherited_pdf_pages_inherit_media_box_and_resources_from_the_intermediate_node`, `Broadside.Tests.Document.PageTreeTests.Pages_come_in_kids_order_depth_first_across_intermediate_nodes`, `Broadside.Tests.Document.PageTreeTests.The_nearest_ancestor_wins_and_values_are_inherited_as_is_without_merging`, `Broadside.Tests.Document.PageTreeTests.A_change_to_an_ancestor_node_shows_through_the_pages_that_inherit_from_it`, `Broadside.Tests.Document.PageTreeTests.Page_count_comes_from_the_kids_not_the_count_entry_which_is_checked`, `Broadside.Tests.Document.PageTreeTests.A_node_referenced_twice_is_read_once_with_a_diagnostic`, `Broadside.Tests.Document.PageAttributeTests.Crop_bleed_trim_and_art_boxes_default_to_the_media_box_through_the_crop_box`, `Broadside.Tests.Document.PageAttributeTests.Rotation_is_a_multiple_of_90_normalized_into_0_to_270` | 7.7.3.1 to 7.7.3.4: Kids walk with cycle guard, Count checked not trusted, Resources/MediaBox/CropBox/Rotate inherited as-is from the nearest node; page boxes, Rotate and UserUnit from Table 31; other Table 31 entries arrive with their features | +| 7.7.4 | Name dictionary | not started | | | | | 7.8 | Content streams and resources | not started | | | | | 7.9.1 | General | not started | | | | | 7.9.2 | String object types | partial | `CosString` | `Broadside.Tests.Objects.TextStringTests` | Text strings decode (PDFDocEncoding, UTF-16BE, UTF-8, language escapes removed); encoding text into a string pending | | 7.9.3 | Text streams | not started | | | | | 7.9.4 | Dates | not started | | | | -| 7.9.5 | Rectangles | not started | | | | +| 7.9.5 | Rectangles | done | `PdfRectangle` | `Broadside.Tests.Document.PageAttributeTests.Rectangles_given_by_any_two_opposite_corners_are_normalized`, `Broadside.Tests.Document.PageAttributeTests.A_box_and_its_numbers_may_be_indirect_objects`, `Broadside.Tests.Document.PageAttributeTests.A_malformed_box_reads_as_its_default_with_a_diagnostic` | Any two opposite corners, normalized | | 7.9.6 | Name trees | not started | | | | | 7.9.7 | Number trees | not started | | | | | 7.10 | Functions | not started | | | | @@ -97,7 +107,13 @@ Clause numbers at the second level; split rows to the third level as clauses are | 14.8 | Tagged PDF | not started | | | | | 14.9 | Repurposing and accessibility support | not started | | | | | 14.10 | Web capture | not started | | | | -| 14.11 | Prepress support | not started | | | | +| 14.11.1 | General | n/a | | | Introductory text | +| 14.11.2 | Page boundaries | partial | `PdfPage` | `Broadside.Tests.Document.PageAttributeTests.Boxes_that_extend_beyond_the_media_box_are_reduced_to_their_intersection_with_it`, `Broadside.Tests.Document.PageAttributeTests.Bleed_trim_and_art_boxes_default_to_the_crop_box`, `Broadside.Tests.Document.PageAttributeTests.Each_box_reads_its_own_entry` | 14.11.2.1 defaults and clipping to the media box done; 14.11.2.2 BoxColorInfo display not started | +| 14.11.3 | Printer’s marks | not started | | | | +| 14.11.4 | Separation dictionaries | not started | | | | +| 14.11.5 | Output intents | not started | | | | +| 14.11.6 | Trapping support | not started | | | | +| 14.11.7 | Open prepress interface (OPI) | not started | | | | | 14.12 | Document parts | not started | | | | | 14.13 | Associated files | not started | | | | | Annex A | Operator summary | not started | | | | diff --git a/src/Broadside/Diagnostics/Diagnostic.cs b/src/Broadside/Diagnostics/Diagnostic.cs new file mode 100644 index 00000000..dfd390ba --- /dev/null +++ b/src/Broadside/Diagnostics/Diagnostic.cs @@ -0,0 +1,67 @@ +using System.Globalization; +using System.Text; +using Broadside.Objects; + +namespace Broadside.Diagnostics; + +/// A record of one deviation from the specification found while reading a file, and what was done about it. +/// +/// +/// ADR 0005: in lenient mode a reader repairs what it can and records a diagnostic on the document; in strict mode the first +/// diagnostic is thrown as a . A well-formed file produces no diagnostics: a diagnostic means a +/// "shall" of ISO 32000-2 was violated or the reader changed what it read, never that a "should" was not followed. +/// +/// Codes are stable PascalCase identifiers, such as StreamLengthInvalid or PageTreeCountMismatch. +/// +public sealed class Diagnostic +{ + /// Initializes a new instance of the class. + /// The stable identifier of the kind of deviation. + /// How much the repair may have changed the document. + /// A human-readable description of the deviation and the repair. + /// The byte offset in the file where the deviation was found, when known. + /// The indirect object the deviation is in, when known. + public Diagnostic(string code, DiagnosticSeverity severity, string message, long? offset = null, CosReference? objectReference = null) + { + ArgumentException.ThrowIfNullOrEmpty(code); + ArgumentNullException.ThrowIfNull(message); + Code = code; + Severity = severity; + Message = message; + Offset = offset; + ObjectReference = objectReference; + } + + /// Gets the stable identifier of the kind of deviation. + public string Code { get; } + + /// Gets how much the repair may have changed the document. + public DiagnosticSeverity Severity { get; } + + /// Gets a human-readable description of the deviation and the repair. + public string Message { get; } + + /// Gets the byte offset from the start of the file where the deviation was found, or when unknown. + public long? Offset { get; } + + /// Gets the indirect object the deviation is in, or when unknown or not in an object. + public CosReference? ObjectReference { get; } + + /// + public override string ToString() + { + var text = new StringBuilder(); + text.Append(CultureInfo.InvariantCulture, $"{Severity} {Code}"); + if (ObjectReference is { } reference) + { + text.Append(CultureInfo.InvariantCulture, $" in object {reference.ObjectNumber} {reference.Generation}"); + } + + if (Offset is { } offset) + { + text.Append(CultureInfo.InvariantCulture, $" at offset {offset}"); + } + + return text.Append(": ").Append(Message).ToString(); + } +} diff --git a/src/Broadside/Diagnostics/DiagnosticException.cs b/src/Broadside/Diagnostics/DiagnosticException.cs new file mode 100644 index 00000000..ca9cbb98 --- /dev/null +++ b/src/Broadside/Diagnostics/DiagnosticException.cs @@ -0,0 +1,45 @@ +namespace Broadside.Diagnostics; + +/// +/// The exception a reader throws for a : in strict mode for the first deviation found, and in +/// either mode when the file cannot be read at all. +/// +/// ADR 0005. The carries the code, offset and object of the deviation. +public sealed class DiagnosticException : FormatException +{ + private const string UnspecifiedCode = "Unspecified"; + + /// Initializes a new instance of the class for a diagnostic. + /// The deviation that stopped reading. + public DiagnosticException(Diagnostic diagnostic) + : base(diagnostic?.ToString()) + { + ArgumentNullException.ThrowIfNull(diagnostic); + Diagnostic = diagnostic; + } + + /// Initializes a new instance of the class with an unspecified diagnostic. + public DiagnosticException() + : this(UnspecifiedMessage(null)) + { + } + + /// Initializes a new instance of the class with an unspecified diagnostic. + /// The message. + public DiagnosticException(string? message) + : this(message, null) + { + } + + /// Initializes a new instance of the class with an unspecified diagnostic. + /// The message. + /// The exception that caused this one. + public DiagnosticException(string? message, Exception? innerException) + : base(UnspecifiedMessage(message), innerException) => + Diagnostic = new Diagnostic(UnspecifiedCode, DiagnosticSeverity.Error, UnspecifiedMessage(message)); + + /// Gets the deviation that stopped reading. + public Diagnostic Diagnostic { get; } + + private static string UnspecifiedMessage(string? message) => message ?? "The file deviates from ISO 32000-2."; +} diff --git a/src/Broadside/Diagnostics/DiagnosticSeverity.cs b/src/Broadside/Diagnostics/DiagnosticSeverity.cs new file mode 100644 index 00000000..03aa8a9b --- /dev/null +++ b/src/Broadside/Diagnostics/DiagnosticSeverity.cs @@ -0,0 +1,12 @@ +namespace Broadside.Diagnostics; + +/// How much the repair recorded by a may have changed the document. +/// ADR 0005. There is no informational level: a well-formed file produces no diagnostics at all. +public enum DiagnosticSeverity +{ + /// The file deviates from the specification, and the repair is believed to have kept all of its content. + Warning = 0, + + /// The file deviates from the specification, and the repair probably lost or invented content. + Error = 1, +} diff --git a/src/Broadside/EngineConfiguration.cs b/src/Broadside/EngineConfiguration.cs new file mode 100644 index 00000000..c03f38e0 --- /dev/null +++ b/src/Broadside/EngineConfiguration.cs @@ -0,0 +1,21 @@ +namespace Broadside; + +/// +/// The immutable snapshot of an engine takes at construction and every document it opens reads from. +/// +/// +/// Each option a later issue adds (filters #38, security handlers #42, sources and limits #45, logging #46) gets a field here, +/// copied from the options in , so no engine ever observes a change made to an options object after it was built. +/// +internal sealed class EngineConfiguration +{ + private EngineConfiguration(PdfReadingMode readingMode) => ReadingMode = readingMode; + + /// Gets how deviations are treated. + public PdfReadingMode ReadingMode { get; } + + /// Copies the current values of . + /// The options. + /// The snapshot. + public static EngineConfiguration From(PdfOptions options) => new(options.ReadingMode); +} diff --git a/src/Broadside/IO/PdfSource.cs b/src/Broadside/IO/PdfSource.cs new file mode 100644 index 00000000..8291a900 --- /dev/null +++ b/src/Broadside/IO/PdfSource.cs @@ -0,0 +1,94 @@ +namespace Broadside.IO; + +/// The bytes of one PDF file, read by position. +/// +/// +/// ISO 32000-2 §7.5.1: a file is read at random, through its cross-reference table, never serially. A source therefore has no +/// cursor: every read names its offset, so concurrent readers never interfere. Offsets are everywhere. +/// +/// +/// Issue #37 ships the in-memory source only; paths and streams are copied into memory. Issue #45 adds file, memory-mapped and +/// windowed stream sources behind this same contract. +/// +/// +internal abstract class PdfSource : IDisposable +{ + private bool _disposed; + + /// Gets the length of the file in bytes. + public abstract long Length { get; } + + /// Creates a source over bytes the caller promises not to change while the source is in use. The bytes are not copied. + /// The file. + /// The source. + public static PdfSource FromMemory(ReadOnlyMemory bytes) => new MemorySource(bytes); + + /// Creates a source over the file at . + /// The file path. + /// The source. + public static PdfSource FromFile(string path) => new MemorySource(File.ReadAllBytes(path)); + + /// Creates a source over the bytes of from its current position to its end. + /// The stream; read once, not disposed. + /// The source. + public static PdfSource FromStream(Stream stream) + { + using var copy = new MemoryStream(); + stream.CopyTo(copy); + return new MemorySource(copy.ToArray()); + } + + /// Copies the bytes at into . + /// The offset of the first byte to copy. + /// Where to copy to. + /// The number of bytes copied: fewer than the destination holds only at the end of the file. + public abstract int Read(long offset, Span destination); + + /// + /// Returns a contiguous view of the bytes from on, for the span-based parsers. The view ends at the end + /// of the file or, for a source that cannot map the whole file, at the end of the source's window; parsers treat its end as the + /// end of input. + /// + /// The offset of the first byte of the view. + /// The view, empty when is at or past the end of the file. + public abstract ReadOnlyMemory GetWindow(long offset); + + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// Releases what the source holds. + /// when called from . + protected virtual void Dispose(bool disposing) => _disposed = true; + + /// Throws once the source is disposed. + protected void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this); + + private sealed class MemorySource(ReadOnlyMemory bytes) : PdfSource + { + public override long Length => bytes.Length; + + public override int Read(long offset, Span destination) + { + ThrowIfDisposed(); + if (offset < 0 || offset >= bytes.Length) + { + return 0; + } + + ReadOnlySpan available = bytes.Span[(int)offset..]; + int count = Math.Min(available.Length, destination.Length); + available[..count].CopyTo(destination); + return count; + } + + public override ReadOnlyMemory GetWindow(long offset) + { + ThrowIfDisposed(); + return offset < 0 || offset >= bytes.Length ? ReadOnlyMemory.Empty : bytes[(int)offset..]; + } + } +} diff --git a/src/Broadside/Objects/CosParser.cs b/src/Broadside/Objects/CosParser.cs index 873962dc..abbef6b5 100644 --- a/src/Broadside/Objects/CosParser.cs +++ b/src/Broadside/Objects/CosParser.cs @@ -24,15 +24,21 @@ internal ref struct CosParser private CosLexer _lexer; private readonly CosRepairLog? _repairs; + private readonly IStreamLengthResolver? _lengthResolver; /// Initializes a new instance of the struct. /// The bytes to parse. /// Where to report repairs, or to discard them. /// The offset to start at. - public CosParser(ReadOnlySpan source, CosRepairLog? repairs, int position = 0) + /// + /// Resolves a stream's Length entry when it is an indirect reference (§7.3.8.2), or when there is no + /// file to resolve it in; the data then ends at endstream without a repair. + /// + public CosParser(ReadOnlySpan source, CosRepairLog? repairs, int position = 0, IStreamLengthResolver? lengthResolver = null) { _lexer = new CosLexer(source, position); _repairs = repairs; + _lengthResolver = lengthResolver; } /// Gets or sets the offset of the next byte to read. @@ -475,7 +481,12 @@ private CosStream ParseStreamData(CosDictionary dictionary, CosToken keyword) ReadOnlySpan source = _lexer.Source; int dataStart = SkipStreamKeywordEndOfLine(keyword); dictionary.TryGetValue(KnownNames.Length, out CosObject? lengthEntry); - long declared = lengthEntry is CosInteger { Value: >= 0 } length ? length.Value : -1; + long declared = lengthEntry switch + { + CosInteger { Value: >= 0 } length => length.Value, + CosReference when _lengthResolver?.ResolveLength(lengthEntry) is >= 0 and long resolved => resolved, + _ => -1, + }; if (declared >= 0 && declared <= source.Length - dataStart && TryMatchEndstream(source, dataStart + (int)declared, out int afterEndstream)) { @@ -488,7 +499,8 @@ private CosStream ParseStreamData(CosDictionary dictionary, CosToken keyword) { int dataEnd = dataStart + found; dataEnd -= EndOfLineLengthBefore(source, dataStart, dataEnd); - if (lengthEntry is not CosReference) + // Without a resolver an indirect Length cannot be checked, so finding the data by endstream is not a repair. + if (lengthEntry is not CosReference || _lengthResolver is not null) { Report( CosRepairCodes.StreamLengthInvalid, diff --git a/src/Broadside/Objects/IStreamLengthResolver.cs b/src/Broadside/Objects/IStreamLengthResolver.cs new file mode 100644 index 00000000..a382b9c5 --- /dev/null +++ b/src/Broadside/Objects/IStreamLengthResolver.cs @@ -0,0 +1,15 @@ +namespace Broadside.Objects; + +/// Resolves the value of a stream dictionary's Length entry when it is an indirect reference. +/// +/// ISO 32000-2 §7.3.8.2 (Table 5): Length may be an indirect reference to an integer object, which only the file reader can +/// resolve. The parser calls the resolver for an indirect Length; when the result is , or the data does +/// not end at endstream, the parser finds the data by scanning for endstream and reports a repair. +/// +internal interface IStreamLengthResolver +{ + /// Returns the byte count stands for, or when it cannot be resolved. + /// The Length entry as stored in the stream dictionary. + /// The length, or . + long? ResolveLength(CosObject lengthEntry); +} diff --git a/src/Broadside/Objects/KnownNames.cs b/src/Broadside/Objects/KnownNames.cs index fb611e5c..3068731e 100644 --- a/src/Broadside/Objects/KnownNames.cs +++ b/src/Broadside/Objects/KnownNames.cs @@ -5,4 +5,61 @@ internal static class KnownNames { /// /Length, the stream dictionary entry that gives the extent of the data (ISO 32000-2 §7.3.8.2, Table 5). public static readonly CosName Length = new("Length"); + + /// /Type, the entry naming the type of a dictionary. + public static readonly CosName Type = new("Type"); + + /// /Size, the trailer entry giving the number of cross-reference entries (§7.5.5, Table 15). + public static readonly CosName Size = new("Size"); + + /// /Prev, the trailer entry giving the offset of the previous cross-reference section (§7.5.5, Table 15). + public static readonly CosName Prev = new("Prev"); + + /// /Root, the trailer entry referring to the catalog (§7.5.5, Table 15). + public static readonly CosName Root = new("Root"); + + /// /Catalog, the type of the document catalog (§7.7.2, Table 29). + public static readonly CosName Catalog = new("Catalog"); + + /// /Version, the catalog entry that overrides the header version when later (§7.7.2, Table 29). + public static readonly CosName Version = new("Version"); + + /// /Pages, the catalog entry referring to the page tree root, and the type of a page tree node (§7.7.2, §7.7.3.2). + public static readonly CosName Pages = new("Pages"); + + /// /Page, the type of a page object (§7.7.3.3, Table 31). + public static readonly CosName Page = new("Page"); + + /// /Kids, the children of a page tree node (§7.7.3.2, Table 30). + public static readonly CosName Kids = new("Kids"); + + /// /Count, the number of leaf pages under a page tree node (§7.7.3.2, Table 30). + public static readonly CosName Count = new("Count"); + + /// /Parent, the parent of a page tree node or page object (§7.7.3.2, §7.7.3.3). + public static readonly CosName Parent = new("Parent"); + + /// /Resources, the inheritable resource dictionary of a page (§7.7.3.3, Table 31). + public static readonly CosName Resources = new("Resources"); + + /// /MediaBox, the inheritable media box of a page (§7.7.3.3, Table 31). + public static readonly CosName MediaBox = new("MediaBox"); + + /// /CropBox, the inheritable crop box of a page (§7.7.3.3, Table 31). + public static readonly CosName CropBox = new("CropBox"); + + /// /BleedBox, the bleed box of a page (§7.7.3.3, Table 31). + public static readonly CosName BleedBox = new("BleedBox"); + + /// /TrimBox, the trim box of a page (§7.7.3.3, Table 31). + public static readonly CosName TrimBox = new("TrimBox"); + + /// /ArtBox, the art box of a page (§7.7.3.3, Table 31). + public static readonly CosName ArtBox = new("ArtBox"); + + /// /Rotate, the inheritable rotation of a page (§7.7.3.3, Table 31). + public static readonly CosName Rotate = new("Rotate"); + + /// /UserUnit, the size of a default user space unit (§7.7.3.3, Table 31). + public static readonly CosName UserUnit = new("UserUnit"); } diff --git a/src/Broadside/PageTreeReader.cs b/src/Broadside/PageTreeReader.cs new file mode 100644 index 00000000..9a7d03b5 --- /dev/null +++ b/src/Broadside/PageTreeReader.cs @@ -0,0 +1,286 @@ +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// Walks a document's page tree into its list of pages, checking each node and page as it goes. +/// +/// +/// ISO 32000-2 §7.7.3. Depth first with an explicit stack, in Kids order. Lenient rules, each with a diagnostic: a node +/// without a correct Type is a page when it has no Kids (as pdf.js decides); a node reached twice is skipped (§7.7.3.2 +/// forbids it, and it would loop); a kid that is a direct dictionary is accepted; a kid that is not a dictionary is skipped; a +/// Parent that disagrees with the path the node was reached by is reported, and the path wins; a wrong Count is reported. +/// +/// Each page's attributes are checked here, once, so the getters can apply defaults silently. +/// +internal static class PageTreeReader +{ + /// The deepest page tree the reader descends into. + public const int MaxDepth = 256; + + /// Reads the pages of . + /// The document. + /// Where to report deviations. + /// The pages in page order. + public static IReadOnlyList Read(PdfDocument document, DiagnosticSink diagnostics) + { + document.Catalog.TryGetValue(KnownNames.Pages, out CosObject? rootEntry); + if (document.Resolve(rootEntry) is not CosDictionary root) + { + diagnostics.Report( + DiagnosticCodes.PagesMissing, + DiagnosticSeverity.Error, + "The catalog has no Pages entry that resolves to the page tree root; the document has no pages."); + return []; + } + + var pages = new List(); + var visitedReferences = new HashSet(); + var visitedDictionaries = new HashSet(ReferenceEqualityComparer.Instance); + var rootReference = rootEntry as CosReference; + if (rootReference is not null) + { + visitedReferences.Add(rootReference); + } + + visitedDictionaries.Add(root); + var stack = new Stack(); + stack.Push(new Frame(root, rootReference, null, null, 0)); + while (stack.TryPop(out Frame frame)) + { + CheckParent(frame, diagnostics); + if (IsLeaf(frame, diagnostics)) + { + var page = new PdfPage(document, frame.Node, frame.Reference, frame.Ancestors); + CheckPage(page, diagnostics); + pages.Add(page); + continue; + } + + if (frame.Depth >= MaxDepth) + { + diagnostics.Report( + DiagnosticCodes.PageTreeTooDeep, + DiagnosticSeverity.Error, + string.Create(CultureInfo.InvariantCulture, $"The page tree is deeper than {MaxDepth} levels; the deeper nodes are skipped."), + objectReference: frame.Reference); + continue; + } + + var ancestors = new PageTreeAncestor(frame.Node, frame.Ancestors); + List kids = ReadKids(document, frame, ancestors, visitedReferences, visitedDictionaries, diagnostics); + for (int index = kids.Count - 1; index >= 0; index--) + { + stack.Push(kids[index]); + } + } + + if (root.TryGetValue(KnownNames.Count, out CosObject? count) + && root.TryGetValue(KnownNames.Kids, out _) + && (document.Resolve(count) is not CosInteger { Value: var stated } || stated != pages.Count)) + { + diagnostics.Report( + DiagnosticCodes.PageTreeCountMismatch, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The page tree root's Count is not the number of pages found by walking the tree ({pages.Count})."), + objectReference: rootReference); + } + + return pages; + } + + private static List ReadKids( + PdfDocument document, + Frame frame, + PageTreeAncestor ancestors, + HashSet visitedReferences, + HashSet visitedDictionaries, + DiagnosticSink diagnostics) + { + var kids = new List(); + frame.Node.TryGetValue(KnownNames.Kids, out CosObject? kidsEntry); + if (document.Resolve(kidsEntry) is not CosArray array) + { + diagnostics.Report( + DiagnosticCodes.PageTreeKidsInvalid, + DiagnosticSeverity.Error, + "A page tree node has no Kids array; it contributes no pages.", + objectReference: frame.Reference); + return kids; + } + + foreach (CosObject kid in array) + { + var reference = kid as CosReference; + if (reference is null && kid is CosDictionary) + { + diagnostics.Report( + DiagnosticCodes.PageTreeKidNotIndirect, + DiagnosticSeverity.Warning, + "A Kids entry shall be an indirect reference; it is a direct dictionary, used as is.", + objectReference: frame.Reference); + } + + if (document.Resolve(kid) is not CosDictionary child) + { + diagnostics.Report( + DiagnosticCodes.PageTreeKidInvalid, + DiagnosticSeverity.Error, + "A Kids entry does not resolve to a page tree node or page object; it is skipped.", + objectReference: reference ?? frame.Reference); + continue; + } + + if ((reference is not null && !visitedReferences.Add(reference)) || !visitedDictionaries.Add(child)) + { + diagnostics.Report( + DiagnosticCodes.PageTreeCycle, + DiagnosticSeverity.Error, + "A page tree node or page is referenced more than once in the page tree; the repeat is skipped.", + objectReference: reference ?? frame.Reference); + continue; + } + + kids.Add(new Frame(child, reference, ancestors, frame.Reference, frame.Depth + 1)); + } + + return kids; + } + + /// Decides whether a node is a page (§7.7.3.3) or an intermediate node (§7.7.3.2), reporting a missing or wrong Type. + private static bool IsLeaf(Frame frame, DiagnosticSink diagnostics) + { + frame.Node.TryGetValue(KnownNames.Type, out CosObject? type); + if (KnownNames.Page.Equals(type)) + { + return true; + } + + if (KnownNames.Pages.Equals(type)) + { + return false; + } + + bool hasKids = frame.Node.ContainsKey(KnownNames.Kids); + diagnostics.Report( + DiagnosticCodes.PageTreeNodeTypeInvalid, + DiagnosticSeverity.Warning, + hasKids + ? "A page tree node's Type is not /Pages; it has Kids, so it is read as an intermediate node." + : "A page object's Type is not /Page; it has no Kids, so it is read as a page.", + objectReference: frame.Reference); + return !hasKids; + } + + /// Reports a Parent that is not the node the page tree reached this node through (§7.7.3.2, Table 30). + private static void CheckParent(Frame frame, DiagnosticSink diagnostics) + { + if (frame.Ancestors is null || frame.ParentReference is not { } expected) + { + return; + } + + if (!frame.Node.TryGetValue(KnownNames.Parent, out CosObject? parent) || !expected.Equals(parent)) + { + diagnostics.Report( + DiagnosticCodes.PageTreeParentMismatch, + DiagnosticSeverity.Warning, + "The Parent entry does not refer to the page tree node whose Kids list this node; inheritance follows the tree.", + objectReference: frame.Reference); + } + } + + /// Checks the attributes of a page object (Table 31) and reports each one that will read as its default. + private static void CheckPage(PdfPage page, DiagnosticSink diagnostics) + { + CosReference? reference = page.Reference; + switch (page.ReadBox(KnownNames.MediaBox, inheritable: true, out _)) + { + case PageAttributeState.Absent: + diagnostics.Report( + DiagnosticCodes.PageMediaBoxMissing, + DiagnosticSeverity.Error, + "The page has no MediaBox, on itself or an ancestor; US Letter [0 0 612 792] is used.", + objectReference: reference); + break; + case PageAttributeState.Invalid: + ReportInvalidBox(KnownNames.MediaBox, "US Letter [0 0 612 792] is used", reference, diagnostics); + break; + } + + CheckOptionalBox(page, KnownNames.CropBox, inheritable: true, "the media box is used", diagnostics); + CheckOptionalBox(page, KnownNames.BleedBox, inheritable: false, "the crop box is used", diagnostics); + CheckOptionalBox(page, KnownNames.TrimBox, inheritable: false, "the crop box is used", diagnostics); + CheckOptionalBox(page, KnownNames.ArtBox, inheritable: false, "the crop box is used", diagnostics); + + switch (page.ReadRotation(out _)) + { + case PageAttributeState.Repaired: + diagnostics.Report( + DiagnosticCodes.PageRotateInvalid, + DiagnosticSeverity.Warning, + "The page's Rotate shall be an integer; it is a real holding a multiple of 90, used as that integer.", + objectReference: reference); + break; + case PageAttributeState.Invalid: + diagnostics.Report( + DiagnosticCodes.PageRotateInvalid, + DiagnosticSeverity.Warning, + "The page's Rotate is not a multiple of 90; 0 is used.", + objectReference: reference); + break; + } + + switch (page.ReadResources()) + { + case PageAttributeState.Absent: + diagnostics.Report( + DiagnosticCodes.PageResourcesMissing, + DiagnosticSeverity.Warning, + "The page has no Resources, on itself or an ancestor; it is read as having none.", + objectReference: reference); + break; + case PageAttributeState.Invalid: + diagnostics.Report( + DiagnosticCodes.PageResourcesInvalid, + DiagnosticSeverity.Error, + "The page's Resources is not a dictionary; it is read as having none.", + objectReference: reference); + break; + } + + if (page.ReadUserUnit(out _) == PageAttributeState.Invalid) + { + diagnostics.Report( + DiagnosticCodes.PageUserUnitInvalid, + DiagnosticSeverity.Warning, + "The page's UserUnit is not a positive number; 1.0 is used.", + objectReference: reference); + } + } + + private static void CheckOptionalBox(PdfPage page, CosName key, bool inheritable, string fallback, DiagnosticSink diagnostics) + { + if (page.ReadBox(key, inheritable, out _) == PageAttributeState.Invalid) + { + ReportInvalidBox(key, fallback, page.Reference, diagnostics); + } + } + + private static void ReportInvalidBox(CosName key, string fallback, CosReference? reference, DiagnosticSink diagnostics) => + diagnostics.Report( + DiagnosticCodes.PageBoxInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The page's {key.Value} is not a rectangle of four numbers; {fallback}."), + objectReference: reference); + + /// A node waiting to be visited. + /// The node's dictionary. + /// The node's reference, or for a direct dictionary. + /// The nodes above it, nearest first; for the root. + /// The reference of the node whose Kids listed it. + /// 0 for the root. + private readonly record struct Frame(CosDictionary Node, CosReference? Reference, PageTreeAncestor? Ancestors, CosReference? ParentReference, int Depth); +} diff --git a/src/Broadside/Parsing/CrossReference.cs b/src/Broadside/Parsing/CrossReference.cs new file mode 100644 index 00000000..7c26e8b1 --- /dev/null +++ b/src/Broadside/Parsing/CrossReference.cs @@ -0,0 +1,114 @@ +using Broadside.Objects; + +namespace Broadside.Parsing; + +/// The kind of a cross-reference entry. +/// ISO 32000-2 §7.5.4 (free and in-use entries) and §7.5.8.3, Table 18 (compressed entries, type 2). +internal enum XrefEntryKind : byte +{ + /// A free (deleted or never used) object number. A reference to it resolves to null (§7.3.10). + Free, + + /// An object stored in the file body at a byte offset. + InUse, + + /// An object stored inside an object stream (§7.5.7). Read by issue #39. + Compressed, +} + +/// One cross-reference entry. +/// Whether the entry is free, in use or compressed. +/// +/// : the byte offset of the object, relative to the %PDF- header (§7.5.2). +/// : the next free object number. : the object number of the +/// object stream. +/// +/// +/// and : the generation number. +/// : the index of the object inside the object stream. +/// +internal readonly record struct XrefEntry(XrefEntryKind Kind, long Offset, int Generation) +{ + /// A free entry with no successor, what an absent or zero-offset entry reads as. + public static readonly XrefEntry Free = new(XrefEntryKind.Free, 0, 0); +} + +/// Whether a cross-reference section is a classic table (§7.5.4) or a cross-reference stream (§7.5.8). +internal enum XrefSectionKind : byte +{ + /// A classic xref table followed by trailer. + Table, + + /// A cross-reference stream (issue #39). + Stream, +} + +/// One cross-reference section as read from the file: its entries and its trailer. +/// ISO 32000-2 §7.5.4 and §7.5.5. Kept per section, never only merged, for incremental updates (#40) and repair (#41). +/// The absolute byte offset of the section (the xref keyword, or the stream object). +/// The absolute byte offset just past the section's trailer dictionary. +/// Table or stream. +/// The entries, by object number. Object number 0 is never present. +/// The section's trailer dictionary (for a stream, the stream dictionary). +internal sealed record XrefSection(long Offset, long End, XrefSectionKind Kind, IReadOnlyDictionary Entries, CosDictionary Trailer) +{ + /// Gets the offset of the hybrid-file cross-reference stream this table's trailer names (§7.5.8.4), when issue #39 follows it. + public long? XRefStreamOffset { get; init; } +} + +/// +/// The cross-reference information of a file: its sections, newest first, and the lookup they define together. +/// +/// +/// ISO 32000-2 §7.5.4, §7.5.5 and §7.5.6. Lookup is newest first, first write wins: an object number takes its entry from the most +/// recent section that lists it. The trailer is the newest section's, with keys only an older trailer has filled in (a lenient +/// fallback; §7.5.6 says each update's trailer repeats them). +/// +internal sealed class CrossReference +{ + private readonly Dictionary _merged = []; + + /// Initializes a new instance of the class. + /// The sections, newest first. At least one. + public CrossReference(IReadOnlyList sections) + { + ArgumentOutOfRangeException.ThrowIfZero(sections.Count); + Sections = sections; + var trailer = new OrderedDictionary(); + foreach (XrefSection section in sections) + { + foreach ((int number, XrefEntry entry) in section.Entries) + { + _merged.TryAdd(number, entry); + } + + foreach (KeyValuePair entry in section.Trailer) + { + trailer.TryAdd(entry.Key, entry.Value); + } + } + + Trailer = CosDictionary.FromOwnedEntries(trailer); + } + + /// Gets the sections, newest first. + public IReadOnlyList Sections { get; } + + /// Gets the merged trailer dictionary. + public CosDictionary Trailer { get; } + + /// Finds the entry for an object number. + /// The object number. + /// The newest entry, or when no section lists the number. + /// when a section lists the number. + public bool TryGetEntry(int objectNumber, out XrefEntry entry) + { + if (_merged.TryGetValue(objectNumber, out entry)) + { + return true; + } + + entry = XrefEntry.Free; + return false; + } +} diff --git a/src/Broadside/Parsing/CrossReferenceReader.cs b/src/Broadside/Parsing/CrossReferenceReader.cs new file mode 100644 index 00000000..39085e5b --- /dev/null +++ b/src/Broadside/Parsing/CrossReferenceReader.cs @@ -0,0 +1,197 @@ +using Broadside.Diagnostics; +using Broadside.IO; +using Broadside.Objects; + +namespace Broadside.Parsing; + +/// +/// Reads a file's cross-reference information from its end: startxref, then the section it points to, then each older +/// section through the trailer's Prev entry. +/// +/// +/// +/// ISO 32000-2 §7.5.4, §7.5.5 and §7.5.6. Every offset the file states is relative to the %PDF- header (§7.5.2). The +/// Prev chain is guarded by a set of visited offsets, so a loop ends the chain with a diagnostic instead of hanging. +/// +/// +/// Extension: issue #39 reads cross-reference streams in and follows a hybrid file's +/// XRefStm before Prev; issue #41 locates startxref when it is wrong and reconstructs the table when nothing +/// here can be read ( returns ). +/// +/// +internal static class CrossReferenceReader +{ + /// How many bytes the backward search for startxref reads at a time. + private const int TailWindow = 1024; + + /// Reads the cross-reference sections of . + /// The file. + /// The header, whose offset every stated offset is relative to. + /// Where to report deviations. + /// The cross-reference information, or when no section could be read. + public static CrossReference? Read(PdfSource source, FileHeader header, DiagnosticSink diagnostics) + { + if (!TryReadStartxref(source, header, diagnostics, out long first)) + { + return null; + } + + var sections = new List(); + var visited = new HashSet(); + long? next = first; + while (next is { } offset) + { + if (!visited.Add(offset)) + { + diagnostics.Report( + DiagnosticCodes.XrefPrevLoop, + DiagnosticSeverity.Error, + "The Prev chain of cross-reference sections loops back to a section already read; the chain ends here.", + offset); + break; + } + + XrefSection? section = ReadSection(source, offset, isFirst: sections.Count == 0, diagnostics); + if (section is null) + { + break; + } + + sections.Add(section); + next = PreviousSectionOffset(section, header, diagnostics); + } + + return sections.Count == 0 ? null : new CrossReference(sections); + } + + /// Finds the last startxref in the file and reads the offset after it (§7.5.5). + private static bool TryReadStartxref(PdfSource source, FileHeader header, DiagnosticSink diagnostics, out long offset) + { + offset = 0; + long keyword = FindLast(source, "startxref"u8); + if (keyword < 0) + { + diagnostics.Report(DiagnosticCodes.StartxrefMissing, DiagnosticSeverity.Error, "The file has no startxref keyword."); + return false; + } + + Span tail = stackalloc byte[TailWindow]; + tail = tail[..source.Read(keyword, tail)]; + var lexer = new CosLexer(tail, "startxref"u8.Length); + if (!StructureTokens.TryReadUnsigned(ref lexer, out long stated) || stated > long.MaxValue - header.Offset) + { + diagnostics.Report( + DiagnosticCodes.StartxrefInvalid, + DiagnosticSeverity.Error, + "The startxref keyword is not followed by a byte offset.", + keyword); + return false; + } + + if (tail[lexer.Position..].IndexOf("%%EOF"u8) < 0) + { + diagnostics.Report( + DiagnosticCodes.EndOfFileMarkerMissing, + DiagnosticSeverity.Warning, + "The startxref offset is not followed by the %%EOF marker.", + keyword + lexer.Position); + } + + offset = header.Offset + stated; + return true; + } + + /// Reads the section at : a table when it starts with xref, else a stream. + private static XrefSection? ReadSection(PdfSource source, long offset, bool isFirst, DiagnosticSink diagnostics) + { + ReadOnlySpan window = source.GetWindow(offset).Span; + var lexer = new CosLexer(window); + CosToken first = lexer.Next(); + bool isTable = StructureTokens.IsKeyword(window, first, "xref"u8); + if (isTable || first.Kind == CosTokenKind.Integer) + { + if (first.Start != 0) + { + // The offset points at white-space or a comment before the section: read from the section itself. + diagnostics.Report( + isFirst ? DiagnosticCodes.StartxrefInvalid : DiagnosticCodes.TrailerPrevInvalid, + DiagnosticSeverity.Warning, + "The offset points before the cross-reference section rather than at it.", + offset); + offset += first.Start; + window = window[first.Start..]; + } + + return isTable ? XrefTableReader.Read(window, offset, diagnostics) : ReadStreamSection(source, offset, diagnostics); + } + + diagnostics.Report( + isFirst ? DiagnosticCodes.StartxrefInvalid : DiagnosticCodes.TrailerPrevInvalid, + DiagnosticSeverity.Error, + isFirst + ? "The startxref offset does not point at a cross-reference section." + : "The Prev offset does not point at a cross-reference section.", + offset); + return null; + } + + /// Reads a cross-reference stream section (§7.5.8). Issue #39. + private static XrefSection? ReadStreamSection(PdfSource source, long offset, DiagnosticSink diagnostics) + { + _ = source; + diagnostics.Report( + DiagnosticCodes.XrefStreamUnsupported, + DiagnosticSeverity.Error, + "The cross-reference section is a cross-reference stream, which this version cannot read yet.", + offset); + return null; + } + + /// Returns the absolute offset of the section before , from its trailer's Prev entry. + private static long? PreviousSectionOffset(XrefSection section, FileHeader header, DiagnosticSink diagnostics) + { + if (!section.Trailer.TryGetValue(KnownNames.Prev, out CosObject? prev)) + { + return null; + } + + if (prev is CosInteger { Value: >= 0 } stated && stated.Value <= long.MaxValue - header.Offset) + { + return header.Offset + stated.Value; + } + + diagnostics.Report( + DiagnosticCodes.TrailerPrevInvalid, + DiagnosticSeverity.Error, + "The trailer's Prev entry is not a direct, non-negative integer; older sections are not read.", + section.Offset); + return null; + } + + /// Finds the last occurrence of in the file, searching backwards one window at a time. + private static long FindLast(PdfSource source, ReadOnlySpan value) + { + Span buffer = stackalloc byte[TailWindow]; + long end = source.Length; + while (end > 0) + { + long start = Math.Max(0, end - TailWindow); + Span window = buffer[..source.Read(start, buffer[..(int)(end - start)])]; + int found = window.LastIndexOf(value); + if (found >= 0) + { + return start + found; + } + + if (start == 0) + { + break; + } + + // Overlap the windows so a keyword split across a boundary is still found. + end = start + value.Length - 1; + } + + return -1; + } +} diff --git a/src/Broadside/Parsing/DiagnosticCodes.cs b/src/Broadside/Parsing/DiagnosticCodes.cs new file mode 100644 index 00000000..910077f7 --- /dev/null +++ b/src/Broadside/Parsing/DiagnosticCodes.cs @@ -0,0 +1,57 @@ +namespace Broadside.Parsing; + +/// +/// The codes of the diagnostics the file reader and the document model record, grouped by area. Object syntax codes are in +/// . Codes are stable: tests, logs and users match on them. +/// +/// Issue #41 owns the public catalogue of codes; every ticket adds its own group here. +internal static class DiagnosticCodes +{ + // File header (ISO 32000-2 §7.5.2). + public const string HeaderMissing = nameof(HeaderMissing); + public const string HeaderVersionInvalid = nameof(HeaderVersionInvalid); + + // File trailer and startxref (§7.5.5). + public const string StartxrefMissing = nameof(StartxrefMissing); + public const string StartxrefInvalid = nameof(StartxrefInvalid); + public const string EndOfFileMarkerMissing = nameof(EndOfFileMarkerMissing); + public const string TrailerMissing = nameof(TrailerMissing); + public const string TrailerPrevInvalid = nameof(TrailerPrevInvalid); + public const string RootMissing = nameof(RootMissing); + public const string RootNotIndirect = nameof(RootNotIndirect); + + // Cross-reference table (§7.5.4). + public const string XrefSectionInvalid = nameof(XrefSectionInvalid); + public const string XrefEntryInvalid = nameof(XrefEntryInvalid); + public const string XrefPrevLoop = nameof(XrefPrevLoop); + public const string XrefStreamUnsupported = nameof(XrefStreamUnsupported); + + // Indirect objects (§7.3.10). + public const string XrefEntryOffsetInvalid = nameof(XrefEntryOffsetInvalid); + public const string MissingEndobj = nameof(MissingEndobj); + public const string ReferenceChainTooDeep = nameof(ReferenceChainTooDeep); + + // Document catalog (§7.7.2). + public const string CatalogTypeInvalid = nameof(CatalogTypeInvalid); + public const string CatalogVersionNotName = nameof(CatalogVersionNotName); + public const string CatalogVersionInvalid = nameof(CatalogVersionInvalid); + public const string PagesMissing = nameof(PagesMissing); + + // Page tree (§7.7.3). + public const string PageTreeNodeTypeInvalid = nameof(PageTreeNodeTypeInvalid); + public const string PageTreeKidsInvalid = nameof(PageTreeKidsInvalid); + public const string PageTreeKidInvalid = nameof(PageTreeKidInvalid); + public const string PageTreeKidNotIndirect = nameof(PageTreeKidNotIndirect); + public const string PageTreeCycle = nameof(PageTreeCycle); + public const string PageTreeTooDeep = nameof(PageTreeTooDeep); + public const string PageTreeParentMismatch = nameof(PageTreeParentMismatch); + public const string PageTreeCountMismatch = nameof(PageTreeCountMismatch); + + // Page objects (§7.7.3.3, §7.9.5). + public const string PageMediaBoxMissing = nameof(PageMediaBoxMissing); + public const string PageBoxInvalid = nameof(PageBoxInvalid); + public const string PageRotateInvalid = nameof(PageRotateInvalid); + public const string PageResourcesMissing = nameof(PageResourcesMissing); + public const string PageResourcesInvalid = nameof(PageResourcesInvalid); + public const string PageUserUnitInvalid = nameof(PageUserUnitInvalid); +} diff --git a/src/Broadside/Parsing/DiagnosticSink.cs b/src/Broadside/Parsing/DiagnosticSink.cs new file mode 100644 index 00000000..8a14ea65 --- /dev/null +++ b/src/Broadside/Parsing/DiagnosticSink.cs @@ -0,0 +1,72 @@ +using System.Diagnostics.CodeAnalysis; +using Broadside.Diagnostics; +using Broadside.Objects; + +namespace Broadside.Parsing; + +/// +/// The one place a document's reader records deviations. Lenient: append and continue. Strict: append, then throw a +/// for the first deviation (ADR 0005). +/// +/// +/// Thread-safe: objects load lazily after open, possibly on several threads (issue #45), and every load reports here. The +/// optional observer sees each diagnostic before strict mode throws (issue #46 logs through it). +/// +internal sealed class DiagnosticSink(bool strict, Action? observer = null) +{ + private readonly Lock _gate = new(); + private readonly List _diagnostics = []; + + /// Gets a value indicating whether the first deviation throws. + public bool IsStrict => strict; + + /// Records a deviation; in strict mode, throws it. + /// The diagnostic code, from or . + /// How much the repair may have changed the document. + /// What was wrong and what the reader did. + /// The absolute byte offset in the file, when known. + /// The object the deviation is in, when known. + /// The sink is strict. + public void Report(string code, DiagnosticSeverity severity, string message, long? offset = null, CosReference? objectReference = null) + { + var diagnostic = new Diagnostic(code, severity, message, offset, objectReference); + Add(diagnostic); + if (strict) + { + throw new DiagnosticException(diagnostic); + } + } + + /// Records a deviation the reader cannot repair, and throws it in either mode. + /// The diagnostic code. + /// What was wrong. + /// The absolute byte offset in the file, when known. + /// Always. + [DoesNotReturn] + public void Fail(string code, string message, long? offset = null) + { + var diagnostic = new Diagnostic(code, DiagnosticSeverity.Error, message, offset); + Add(diagnostic); + throw new DiagnosticException(diagnostic); + } + + /// Returns the diagnostics recorded so far, in the order they were reported. + /// A snapshot; later reports do not change it. + public Diagnostic[] Snapshot() + { + lock (_gate) + { + return [.. _diagnostics]; + } + } + + private void Add(Diagnostic diagnostic) + { + lock (_gate) + { + _diagnostics.Add(diagnostic); + } + + observer?.Invoke(diagnostic); + } +} diff --git a/src/Broadside/Parsing/FileHeader.cs b/src/Broadside/Parsing/FileHeader.cs new file mode 100644 index 00000000..7c417cf8 --- /dev/null +++ b/src/Broadside/Parsing/FileHeader.cs @@ -0,0 +1,59 @@ +using System.Buffers; +using Broadside.Diagnostics; +using Broadside.IO; + +namespace Broadside.Parsing; + +/// Where the %PDF- header is and the version it states. +/// +/// ISO 32000-2 §7.5.2. Byte offsets in the file (startxref, cross-reference entries, Prev) are counted from the +/// percent sign of the header, and arbitrary bytes may precede it (NOTE 1), so every offset the file states is relative to +/// . Issue #41 adds the retry with unshifted offsets for files whose writer counted from byte 0 anyway. +/// +/// The absolute position of the % of %PDF-; 0 when no header was found. +/// The version the header states, or when it is missing or malformed. +internal readonly record struct FileHeader(long Offset, PdfVersion? Version) +{ + /// How far into the file the header is searched for, as pdf.js does. + public const int SearchLength = 1024; + + /// The version assumed when neither the header nor the catalog states a valid one, as PDFBox does. + public static readonly PdfVersion DefaultVersion = new(1, 4); + + private static readonly SearchValues VersionCharacters = SearchValues.Create("0123456789."u8); + + /// Finds the header in the first bytes of . + /// The file. + /// Where to report a missing or malformed header. + /// The header. + public static FileHeader Locate(PdfSource source, DiagnosticSink diagnostics) + { + Span start = stackalloc byte[SearchLength]; + start = start[..source.Read(0, start)]; + int marker = start.IndexOf("%PDF-"u8); + if (marker < 0) + { + diagnostics.Report( + DiagnosticCodes.HeaderMissing, + DiagnosticSeverity.Warning, + "The file does not start with a %PDF- header; offsets are counted from byte 0 and the version is taken from the catalog.", + offset: 0); + return new FileHeader(0, null); + } + + ReadOnlySpan afterMarker = start[(marker + "%PDF-"u8.Length)..]; + int end = afterMarker.IndexOfAnyExcept(VersionCharacters); + ReadOnlySpan versionText = end < 0 ? afterMarker : afterMarker[..end]; + if (PdfVersion.TryParse(versionText, out PdfVersion version) && version.Major is 1 or 2) + { + return new FileHeader(marker, version); + } + + diagnostics.Report( + DiagnosticCodes.HeaderVersionInvalid, + DiagnosticSeverity.Warning, + "The header does not state a version of the form 1.n or 2.n; the version is taken from the catalog.", + offset: marker); + return new FileHeader(marker, null); + } +} diff --git a/src/Broadside/Parsing/ObjectLoader.cs b/src/Broadside/Parsing/ObjectLoader.cs new file mode 100644 index 00000000..8dbec034 --- /dev/null +++ b/src/Broadside/Parsing/ObjectLoader.cs @@ -0,0 +1,175 @@ +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.IO; +using Broadside.Objects; + +namespace Broadside.Parsing; + +/// +/// Loads indirect objects on demand: cross-reference entry, then N G obj … endobj at its offset, then the hooks. +/// The single choke point every object of a document is read through. +/// +/// +/// +/// ISO 32000-2 §7.3.10 and §7.5.4. A reference to an object number with no entry, a free entry, or a different generation resolves +/// to without a diagnostic: the specification defines it so. +/// +/// +/// Order for every object (see ): cache lookup; locate; parse, with hook 1 resolving stream extents; +/// hook 2 decryption; hook 3 cache publication. Issue #39 adds entries in +/// ; issue #41 adds recovery when the header at an offset does not match in . +/// +/// +internal sealed class ObjectLoader +{ + /// How many loads may nest (an indirect Length loads while its stream loads) before the inner one reads null. + public const int MaxDepth = 32; + + private readonly PdfSource _source; + private readonly DiagnosticSink _diagnostics; + + /// Initializes a new instance of the class. + /// The file. + /// The header; entry offsets are relative to it. + /// The cross-reference information. + /// Where to report deviations. + /// The hooks. + public ObjectLoader(PdfSource source, FileHeader header, CrossReference crossReference, DiagnosticSink diagnostics, ObjectLoaderHooks hooks) + { + _source = source; + Header = header; + CrossReference = crossReference; + _diagnostics = diagnostics; + Hooks = hooks; + } + + /// Gets the file header. + public FileHeader Header { get; } + + /// Gets the cross-reference information the loader locates objects with. + public CrossReference CrossReference { get; } + + /// Gets the hooks. + public ObjectLoaderHooks Hooks { get; } + + /// Returns , or the object it refers to when it is an indirect reference. + /// A direct object, a reference, or for an absent entry. + /// The direct object; for an absent entry or a reference to nothing. + public CosObject Resolve(CosObject? value) => value switch + { + null => CosNull.Instance, + CosReference reference => Load(reference), + _ => value, + }; + + /// Loads the object names. + /// The object's number and generation. + /// The object, or . + public CosObject Load(CosReference reference) => Load(reference, depth: 0); + + /// Loads the object names, loads deep. + /// The object's number and generation. + /// How many loads are in progress beneath this one. + /// The object, or . + public CosObject Load(CosReference reference, int depth) + { + if (Hooks.Cache.TryGet(reference, out CosObject? cached)) + { + return cached; + } + + if (!CrossReference.TryGetEntry(reference.ObjectNumber, out XrefEntry entry)) + { + return CosNull.Instance; + } + + if (depth > MaxDepth) + { + _diagnostics.Report( + DiagnosticCodes.ReferenceChainTooDeep, + DiagnosticSeverity.Error, + string.Create(CultureInfo.InvariantCulture, $"Loading the object needs more than {MaxDepth} nested loads; read as null."), + objectReference: reference); + return CosNull.Instance; + } + + CosObject loaded; + ObjectLoadContext context; + switch (entry.Kind) + { + case XrefEntryKind.InUse when entry.Generation == reference.Generation: + context = new ObjectLoadContext(reference, Header.Offset + entry.Offset, ObjectOrigin.FileBody, depth); + loaded = ParseIndirectObject(context); + break; + case XrefEntryKind.Compressed when reference.Generation == 0: + return LoadCompressed(reference, entry, depth); + default: + return CosNull.Instance; + } + + loaded = Hooks.Decryptor.Decrypt(loaded, context); + return Hooks.Cache.Publish(reference, loaded); + } + + /// Loads an object stored in an object stream (§7.5.7). Issue #39. + private static CosNull LoadCompressed(CosReference reference, XrefEntry entry, int depth) + { + _ = (reference, entry, depth); + return CosNull.Instance; + } + + /// Handles an entry whose offset does not hold the expected N G obj header. Issue #41 searches for the object. + private CosNull LoadMisplaced(in ObjectLoadContext context) + { + _diagnostics.Report( + DiagnosticCodes.XrefEntryOffsetInvalid, + DiagnosticSeverity.Error, + "The cross-reference entry's offset does not point at the object's header; read as null.", + context.Offset, + context.Reference); + return CosNull.Instance; + } + + /// Parses N G obj object endobj at the context's offset (§7.3.10). + private CosObject ParseIndirectObject(in ObjectLoadContext context) + { + ReadOnlySpan window = _source.GetWindow(context.Offset).Span; + var lexer = new CosLexer(window); + if (!StructureTokens.TryReadUnsigned(ref lexer, out long number) + || !StructureTokens.TryReadUnsigned(ref lexer, out long generation) + || !StructureTokens.TryReadKeyword(ref lexer, "obj"u8) + || number != context.Reference.ObjectNumber + || generation != context.Reference.Generation) + { + return LoadMisplaced(context); + } + + var repairs = new CosRepairLog(keepAll: true); + var parser = new CosParser(window, repairs, lexer.Position, new LengthResolver(this, context)); + CosObject value = parser.ParseObject(); + foreach (CosRepair repair in repairs.All) + { + _diagnostics.Report(repair.Code, DiagnosticSeverity.Warning, repair.Message, context.Offset + repair.Offset, context.Reference); + } + + lexer.Position = parser.Position; + CosToken end = lexer.Next(); + if (!StructureTokens.IsKeyword(window, end, "endobj"u8)) + { + _diagnostics.Report( + DiagnosticCodes.MissingEndobj, + DiagnosticSeverity.Warning, + "The object is not followed by the endobj keyword; it ends here.", + context.Offset + end.Start, + context.Reference); + } + + return value; + } + + /// Adapts hook 1 to the parser's resolver contract for one object load. + private sealed class LengthResolver(ObjectLoader loader, ObjectLoadContext context) : IStreamLengthResolver + { + public long? ResolveLength(CosObject lengthEntry) => loader.Hooks.StreamExtent.ResolveLength(lengthEntry, loader, context); + } +} diff --git a/src/Broadside/Parsing/ObjectLoaderHooks.cs b/src/Broadside/Parsing/ObjectLoaderHooks.cs new file mode 100644 index 00000000..1fa11d03 --- /dev/null +++ b/src/Broadside/Parsing/ObjectLoaderHooks.cs @@ -0,0 +1,137 @@ +using System.Collections.Concurrent; +using System.Diagnostics.CodeAnalysis; +using Broadside.Objects; + +namespace Broadside.Parsing; + +/// Where an object being loaded comes from. +internal enum ObjectOrigin : byte +{ + /// An indirect object in the file body, located by a cross-reference entry (§7.3.10). + FileBody, + + /// An object inside an object stream (§7.5.7; issue #39). Never decrypted on its own (§7.6.2). + ObjectStream, +} + +/// What the loader knows about the object it is loading, passed to every hook. +/// The object's number and generation. +/// The absolute byte offset of the object's N G obj header; for an object-stream member, of the object stream. +/// Whether the object is in the file body or in an object stream. +/// How many loads are in progress beneath this one (an indirect Length loads while its stream loads). +internal readonly record struct ObjectLoadContext(CosReference Reference, long Offset, ObjectOrigin Origin, int Depth); + +/// +/// Hook 1 of the object loader: resolves a stream's Length so the parser can find the end of the data (§7.3.8.2). Runs during +/// parsing. Issue #41 extends recovery of wrong lengths behind it. +/// +internal interface IStreamExtentResolver +{ + /// Returns the byte count a stream's Length entry stands for, or when unknown. + /// The Length entry as stored, a direct integer or an indirect reference. + /// The loader, to resolve a reference with. + /// The stream object being loaded. + /// The length, or . + long? ResolveLength(CosObject lengthEntry, ObjectLoader loader, in ObjectLoadContext context); +} + +/// +/// Hook 2 of the object loader: decrypts the strings and stream data of a freshly parsed object (§7.6). Runs after parsing and before +/// the object is published to the cache. Issue #42 supplies the security-handler implementation; until a file's Encrypt +/// dictionary has been read the loader uses . +/// +/// +/// Must not decrypt cross-reference streams, objects inside object streams (, already decrypted +/// with their container), or the Encrypt dictionary itself (§7.6.2). Must not mark anything dirty (ADR 0004). +/// +internal interface IObjectDecryptor +{ + /// Returns with its strings and stream data decrypted. + /// The object as parsed. + /// The object being loaded. + /// The decrypted object; may be itself. + CosObject Decrypt(CosObject value, in ObjectLoadContext context); +} + +/// +/// Hook 3 of the object loader: the cache loaded objects are published to, so each indirect object is parsed once and every +/// reference to it yields the same instance (a live view needs one instance to view). Issue #45 replaces the default with a +/// lazy-once, memory-bounded cache under the concurrency contract. +/// +internal interface IObjectCache +{ + /// Looks up a loaded object. + /// The object's number and generation. + /// The object, when cached. + /// when cached. + bool TryGet(CosReference reference, [NotNullWhen(true)] out CosObject? value); + + /// Publishes a loaded object, or returns the one another thread published first. + /// The object's number and generation. + /// The loaded object. + /// The cached instance, which every caller must use. + CosObject Publish(CosReference reference, CosObject value); +} + +/// The default : a direct integer, or an indirect reference loaded through the loader. +internal sealed class DefaultStreamExtentResolver : IStreamExtentResolver +{ + /// Gets the shared instance; it holds no state. + public static DefaultStreamExtentResolver Instance { get; } = new(); + + /// + public long? ResolveLength(CosObject lengthEntry, ObjectLoader loader, in ObjectLoadContext context) + { + CosObject value = lengthEntry is CosReference reference && !reference.Equals(context.Reference) + ? loader.Load(reference, context.Depth + 1) + : lengthEntry; + return value is CosInteger { Value: >= 0 } length ? length.Value : null; + } +} + +/// The of an unencrypted file: returns every object unchanged. +internal sealed class NullObjectDecryptor : IObjectDecryptor +{ + /// Gets the shared instance; it holds no state. + public static NullObjectDecryptor Instance { get; } = new(); + + /// + public CosObject Decrypt(CosObject value, in ObjectLoadContext context) => value; +} + +/// The default : an unbounded concurrent dictionary, first publisher wins. +internal sealed class ConcurrentObjectCache : IObjectCache +{ + private readonly ConcurrentDictionary _objects = new(); + + /// + public bool TryGet(CosReference reference, [NotNullWhen(true)] out CosObject? value) => _objects.TryGetValue(reference, out value); + + /// + public CosObject Publish(CosReference reference, CosObject value) => _objects.GetOrAdd(reference, value); +} + +/// +/// The hooks of one document's , which runs them in a fixed order for every object: stream extent (during +/// parsing), then decryption, then cache publication. Later issues implement a hook; they do not restructure the loader. +/// +internal sealed class ObjectLoaderHooks +{ + private volatile IObjectDecryptor _decryptor = NullObjectDecryptor.Instance; + + /// Gets hook 1, stream extent resolution (issue #41 extends it). + public IStreamExtentResolver StreamExtent { get; init; } = DefaultStreamExtentResolver.Instance; + + /// + /// Gets or sets hook 2, decryption (issue #42). Set once during open, after the Encrypt dictionary is read and before the + /// catalog is loaded; objects loaded before then (the Encrypt dictionary) are never decrypted. + /// + public IObjectDecryptor Decryptor + { + get => _decryptor; + set => _decryptor = value; + } + + /// Gets hook 3, cache publication (issue #45 replaces it). + public IObjectCache Cache { get; init; } = new ConcurrentObjectCache(); +} diff --git a/src/Broadside/Parsing/StructureTokens.cs b/src/Broadside/Parsing/StructureTokens.cs new file mode 100644 index 00000000..9566940a --- /dev/null +++ b/src/Broadside/Parsing/StructureTokens.cs @@ -0,0 +1,45 @@ +using System.Globalization; +using Broadside.Objects; + +namespace Broadside.Parsing; + +/// Reads the tokens of file structure (§7.5): unsigned integers and keywords, from a . +internal static class StructureTokens +{ + /// Reads the next token as an unsigned decimal integer. + /// The lexer; advanced past the token whether or not it is an integer. + /// The value. + /// when the token is digits only and fits a . + public static bool TryReadUnsigned(ref CosLexer lexer, out long value) + { + CosToken token = lexer.Next(); + return TryParseUnsigned(lexer.Source.Slice(token.Start, token.Length), token.Kind, out value); + } + + /// Reads the next token and returns whether it is the keyword . + /// The lexer; advanced past the token. + /// The expected keyword. + /// when it is. + public static bool TryReadKeyword(ref CosLexer lexer, ReadOnlySpan keyword) + { + CosToken token = lexer.Next(); + return IsKeyword(lexer.Source, token, keyword); + } + + /// Returns whether is the keyword . + /// The bytes the token is in. + /// The token. + /// The keyword. + /// when it is. + public static bool IsKeyword(ReadOnlySpan source, CosToken token, ReadOnlySpan keyword) => + token.Kind == CosTokenKind.Keyword && source.Slice(token.Start, token.Length).SequenceEqual(keyword); + + private static bool TryParseUnsigned(ReadOnlySpan text, CosTokenKind kind, out long value) + { + value = 0; + return kind == CosTokenKind.Integer + && text.Length > 0 + && text[0] is >= (byte)'0' and <= (byte)'9' + && long.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out value); + } +} diff --git a/src/Broadside/Parsing/XrefTableReader.cs b/src/Broadside/Parsing/XrefTableReader.cs new file mode 100644 index 00000000..4d3a02f5 --- /dev/null +++ b/src/Broadside/Parsing/XrefTableReader.cs @@ -0,0 +1,148 @@ +using Broadside.Diagnostics; +using Broadside.Objects; + +namespace Broadside.Parsing; + +/// Reads one classic cross-reference section: xref, its subsections, and the trailer dictionary after trailer. +/// +/// +/// ISO 32000-2 §7.5.4 and §7.5.5. Entries are read as tokens, not as fixed 20-byte records, so a table with wrong line endings or +/// padding still reads (as pdf.js and PDFBox do); whether such a table is reported is issue #41's decision. +/// +/// +/// An in-use entry with offset 0 is read as free (as pdf.js does) with a diagnostic, and object number 0 is always free (§7.5.4) +/// and never appears in . +/// +/// +internal static class XrefTableReader +{ + /// Reads the section that starts at the beginning of , whose first token is xref. + /// The bytes from the section's xref keyword on. + /// The absolute offset of [0]. + /// Where to report deviations. + /// The section, or when it has no trailer dictionary. + public static XrefSection? Read(ReadOnlySpan window, long sectionOffset, DiagnosticSink diagnostics) + { + var lexer = new CosLexer(window); + _ = lexer.Next(); // xref + var entries = new Dictionary(); + if (!ReadSubsections(ref lexer, entries, sectionOffset, diagnostics)) + { + int trailerKeyword = window[lexer.Position..].IndexOf("trailer"u8); + if (trailerKeyword < 0) + { + diagnostics.Report( + DiagnosticCodes.TrailerMissing, + DiagnosticSeverity.Error, + "The cross-reference section has no trailer keyword.", + sectionOffset); + return null; + } + + lexer.Position += trailerKeyword + "trailer"u8.Length; + } + + var repairs = new CosRepairLog(keepAll: true); + var parser = new CosParser(window, repairs, lexer.Position); + CosObject trailer = parser.ParseObject(); + foreach (CosRepair repair in repairs.All) + { + diagnostics.Report(repair.Code, DiagnosticSeverity.Warning, repair.Message, sectionOffset + repair.Offset); + } + + if (trailer is not CosDictionary dictionary) + { + diagnostics.Report( + DiagnosticCodes.TrailerMissing, + DiagnosticSeverity.Error, + "The trailer keyword is not followed by a dictionary.", + sectionOffset + lexer.Position); + return null; + } + + return new XrefSection(sectionOffset, sectionOffset + parser.Position, XrefSectionKind.Table, entries, dictionary); + } + + /// Reads subsections up to and including the trailer keyword. + /// when the table is malformed; the lexer is then somewhere inside it. + private static bool ReadSubsections(ref CosLexer lexer, Dictionary entries, long sectionOffset, DiagnosticSink diagnostics) + { + while (true) + { + CosToken next = lexer.Peek(); + if (StructureTokens.IsKeyword(lexer.Source, next, "trailer"u8)) + { + lexer.Position = next.End; + return true; + } + + long subsectionStart = sectionOffset + next.Start; + if (!StructureTokens.TryReadUnsigned(ref lexer, out long first) || !StructureTokens.TryReadUnsigned(ref lexer, out long count)) + { + diagnostics.Report( + DiagnosticCodes.XrefSectionInvalid, + DiagnosticSeverity.Error, + "Expected a subsection header (first object number and entry count) or the trailer keyword.", + subsectionStart); + return false; + } + + for (long index = 0; index < count; index++) + { + long entryStart = sectionOffset + lexer.Peek().Start; + long number = first + index; + if (!TryReadEntry(ref lexer, out XrefEntry entry) || number > int.MaxValue) + { + diagnostics.Report( + DiagnosticCodes.XrefEntryInvalid, + DiagnosticSeverity.Error, + "Expected a cross-reference entry: a 10-digit offset, a 5-digit generation and n or f.", + entryStart); + return false; + } + + if (entry.Kind == XrefEntryKind.InUse && entry.Offset == 0) + { + diagnostics.Report( + DiagnosticCodes.XrefEntryOffsetInvalid, + DiagnosticSeverity.Error, + "An in-use entry has offset 0, where the header is; the object is read as free.", + entryStart); + entry = XrefEntry.Free; + } + + // §7.5.4: object number 0 is always free and is the head of the free list; it never names an object. + if (number != 0) + { + entries.TryAdd((int)number, entry); + } + } + } + } + + private static bool TryReadEntry(ref CosLexer lexer, out XrefEntry entry) + { + entry = XrefEntry.Free; + if (!StructureTokens.TryReadUnsigned(ref lexer, out long offset) + || !StructureTokens.TryReadUnsigned(ref lexer, out long generation) + || generation > CosReference.MaxGeneration) + { + return false; + } + + CosToken kind = lexer.Next(); + if (StructureTokens.IsKeyword(lexer.Source, kind, "n"u8)) + { + entry = new XrefEntry(XrefEntryKind.InUse, offset, (int)generation); + return true; + } + + if (StructureTokens.IsKeyword(lexer.Source, kind, "f"u8)) + { + entry = new XrefEntry(XrefEntryKind.Free, offset, (int)generation); + return true; + } + + return false; + } +} diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs new file mode 100644 index 00000000..7d8beeba --- /dev/null +++ b/src/Broadside/PdfDocument.cs @@ -0,0 +1,237 @@ +using Broadside.Diagnostics; +using Broadside.IO; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// A PDF document: the entry point for reading a file and the root of the document model. +/// +/// +/// ISO 32000-2 §7.5 (file structure) and §7.7.2 (document catalog). Opening reads the header, the cross-reference information, the +/// trailer and the catalog; every other object, the page tree included, loads on first use. The document is a live view over its +/// COS objects (, , ), so a change made through the COS layer is +/// visible through the document model. +/// +/// +/// Reading is lenient by default: deviations are repaired and recorded in . In strict mode the first +/// deviation throws a ; deviations in objects loaded after open (the page tree, for instance) throw +/// from the member that loads them. +/// +/// Safe for concurrent reads from several threads while nobody changes it; changes are single-threaded. +/// +public sealed class PdfDocument : IDisposable +{ + private readonly PdfSource _source; + private readonly DiagnosticSink _diagnostics; + private readonly ObjectLoader _loader; + + private PdfDocument(PdfSource source, DiagnosticSink diagnostics, ObjectLoader loader, CosDictionary catalog) + { + _source = source; + _diagnostics = diagnostics; + _loader = loader; + Catalog = catalog; + Pages = new PdfPageCollection(() => PageTreeReader.Read(this, diagnostics)); + } + + /// + /// Gets the version of the specification the document conforms to: the header's version, or the catalog's Version entry + /// when that is later. + /// + /// + /// ISO 32000-2 §7.5.2 and §7.7.2, Table 29. Read from the catalog on every call. When neither states a valid version, 1.4. + /// + public PdfVersion Version + { + get + { + PdfVersion? catalogVersion = ReadCatalogVersion(Catalog, diagnostics: null); + PdfVersion? headerVersion = _loader.Header.Version; + return (headerVersion, catalogVersion) switch + { + ({ } header, { } catalog) => catalog > header ? catalog : header, + ({ } header, null) => header, + (null, { } catalog) => catalog, + _ => FileHeader.DefaultVersion, + }; + } + } + + /// Gets the document catalog dictionary, the root of the document's object hierarchy. + /// ISO 32000-2 §7.7.2. + public CosDictionary Catalog { get; } + + /// Gets the trailer dictionary: the newest trailer, with entries only older trailers hold filled in. + /// ISO 32000-2 §7.5.5, Table 15. + public CosDictionary Trailer => _loader.CrossReference.Trailer; + + /// Gets the pages, in page order. The page tree is read on first use. + /// ISO 32000-2 §7.7.3. + public PdfPageCollection Pages { get; } + + /// Gets the deviations found so far, in the order they were found. Empty for a well-formed file. + /// + /// ADR 0005. A snapshot: objects load lazily, so reading more of the document can add diagnostics, which a later call returns. + /// + public IReadOnlyList Diagnostics => _diagnostics.Snapshot(); + + /// Opens the PDF file at with default options. + /// The file path. + /// The document. Dispose it when done. + /// The file cannot be read at all. + /// ISO 32000-2 §7.5. The same as on an engine with default options. + public static PdfDocument Open(string path) => PdfEngine.Default.Open(path); + + /// Opens the PDF file at . + /// The file path. + /// The options. + /// The document. Dispose it when done. + /// The file cannot be read at all, or, in strict mode, deviates from ISO 32000-2. + /// ISO 32000-2 §7.5. The same as on an engine built from . + public static PdfDocument Open(string path, PdfOptions options) => new PdfEngine(options).Open(path); + + /// Opens the PDF file held by , from its current position, with default options. + /// The stream. It is not disposed; keep it open and unchanged until the document is disposed. + /// The document. Dispose it when done. + /// The file cannot be read at all. + /// ISO 32000-2 §7.5. + public static PdfDocument Open(Stream stream) => PdfEngine.Default.Open(stream); + + /// Opens the PDF file held by , from its current position. + /// The stream. It is not disposed; keep it open and unchanged until the document is disposed. + /// The options. + /// The document. Dispose it when done. + /// The file cannot be read at all, or, in strict mode, deviates from ISO 32000-2. + /// ISO 32000-2 §7.5. + public static PdfDocument Open(Stream stream, PdfOptions options) => new PdfEngine(options).Open(stream); + + /// Opens the PDF file held in with default options. + /// The file. Not copied: do not change it until the document is disposed. + /// The document. Dispose it when done. + /// The file cannot be read at all. + /// ISO 32000-2 §7.5. + public static PdfDocument Open(ReadOnlyMemory bytes) => PdfEngine.Default.Open(bytes); + + /// Opens the PDF file held in . + /// The file. Not copied: do not change it until the document is disposed. + /// The options. + /// The document. Dispose it when done. + /// The file cannot be read at all, or, in strict mode, deviates from ISO 32000-2. + /// ISO 32000-2 §7.5. + public static PdfDocument Open(ReadOnlyMemory bytes, PdfOptions options) => new PdfEngine(options).Open(bytes); + + /// Creates a new, empty document with default options. + /// The document. + /// Always, for now: writing arrives in a later version. + public static PdfDocument Create() => PdfEngine.Default.Create(); + + /// Creates a new, empty document. + /// The options. + /// The document. + /// Always, for now: writing arrives in a later version. + public static PdfDocument Create(PdfOptions options) => new PdfEngine(options).Create(); + + /// Returns , or the indirect object it refers to when it is a . + /// A COS object from this document, or . + /// + /// The direct object. A reference to an object that does not exist, and , resolve to + /// . Resolving the same reference twice returns the same instance. + /// + /// ISO 32000-2 §7.3.10. + public CosObject Resolve(CosObject? value) => _loader.Resolve(value); + + /// + public void Dispose() => _source.Dispose(); + + /// The open path shared by every entry point: header, cross-reference information, trailer, catalog. + /// The file; owned by the document, disposed if opening fails. + /// The engine's configuration. + /// The document. + internal static PdfDocument Read(PdfSource source, EngineConfiguration configuration) + { + try + { + var diagnostics = new DiagnosticSink(configuration.ReadingMode == PdfReadingMode.Strict); + FileHeader header = FileHeader.Locate(source, diagnostics); + CrossReference crossReference = CrossReferenceReader.Read(source, header, diagnostics) ?? Reconstruct(diagnostics); + var loader = new ObjectLoader(source, header, crossReference, diagnostics, new ObjectLoaderHooks()); + CosDictionary catalog = ReadCatalog(loader, diagnostics); + return new PdfDocument(source, diagnostics, loader, catalog); + } + catch + { + source.Dispose(); + throw; + } + } + + /// Rebuilds the cross-reference information by scanning the file when it cannot be read (§7.5.4). Issue #41. + private static CrossReference Reconstruct(DiagnosticSink diagnostics) => + throw new DiagnosticException(diagnostics.Snapshot() is [.., var last] + ? last + : new Diagnostic(DiagnosticCodes.StartxrefMissing, DiagnosticSeverity.Error, "The cross-reference information cannot be read.")); + + /// Loads the catalog through the trailer's Root and checks its Type and Version (§7.7.2). + private static CosDictionary ReadCatalog(ObjectLoader loader, DiagnosticSink diagnostics) + { + CosDictionary trailer = loader.CrossReference.Trailer; + trailer.TryGetValue(KnownNames.Root, out CosObject? root); + if (root is CosDictionary) + { + diagnostics.Report( + DiagnosticCodes.RootNotIndirect, + DiagnosticSeverity.Warning, + "The trailer's Root entry shall be an indirect reference; it is a direct dictionary."); + } + + if (loader.Resolve(root) is not CosDictionary catalog) + { + diagnostics.Fail(DiagnosticCodes.RootMissing, "The trailer has no Root entry that resolves to the catalog dictionary."); + return null; + } + + if (!catalog.TryGetValue(KnownNames.Type, out CosObject? type) || !KnownNames.Catalog.Equals(type)) + { + diagnostics.Report( + DiagnosticCodes.CatalogTypeInvalid, + DiagnosticSeverity.Warning, + "The catalog dictionary's Type entry shall be /Catalog.", + objectReference: root as CosReference); + } + + _ = ReadCatalogVersion(catalog, diagnostics, root as CosReference); + return catalog; + } + + /// Reads the catalog's Version entry; reports deviations when is given. + private static PdfVersion? ReadCatalogVersion(CosDictionary catalog, DiagnosticSink? diagnostics, CosReference? catalogReference = null) + { + if (!catalog.TryGetValue(KnownNames.Version, out CosObject? entry)) + { + return null; + } + + if (entry is CosName name && PdfVersion.TryParse(name.Bytes, out PdfVersion version)) + { + return version; + } + + if (entry is CosNumber number && PdfVersion.TryFromNumber(number, out version)) + { + diagnostics?.Report( + DiagnosticCodes.CatalogVersionNotName, + DiagnosticSeverity.Warning, + "The catalog's Version entry shall be a name such as /1.7; it is a number, read as that version.", + objectReference: catalogReference); + return version; + } + + diagnostics?.Report( + DiagnosticCodes.CatalogVersionInvalid, + DiagnosticSeverity.Warning, + "The catalog's Version entry is not a version name such as /1.7; it is ignored.", + objectReference: catalogReference); + return null; + } +} diff --git a/src/Broadside/PdfEngine.cs b/src/Broadside/PdfEngine.cs new file mode 100644 index 00000000..c4abbdb9 --- /dev/null +++ b/src/Broadside/PdfEngine.cs @@ -0,0 +1,73 @@ +using Broadside.IO; + +namespace Broadside; + +/// +/// Opens and creates documents under one configuration. The static methods use an engine +/// too, so both paths behave identically. +/// +/// +/// An engine is immutable and safe to share between threads; it holds no global or static state, so two engines with different +/// options never interfere. Its options are copied at construction. +/// +public sealed class PdfEngine +{ + private readonly EngineConfiguration _configuration; + + /// Initializes a new instance of the class with default options. + public PdfEngine() + : this(new PdfOptions()) + { + } + + /// Initializes a new instance of the class. + /// The options; copied, so later changes to them do not affect this engine. + public PdfEngine(PdfOptions options) + { + ArgumentNullException.ThrowIfNull(options); + _configuration = EngineConfiguration.From(options); + } + + /// Gets the engine the static entry points use when no options are given: default options, no state. + internal static PdfEngine Default { get; } = new(); + + /// Opens the PDF file at . + /// The file path. + /// The document. Dispose it when done. + /// + /// The file cannot be read at all, or, in strict mode, deviates from ISO 32000-2. + /// + /// ISO 32000-2 §7.5. + public PdfDocument Open(string path) + { + ArgumentException.ThrowIfNullOrEmpty(path); + return PdfDocument.Read(PdfSource.FromFile(path), _configuration); + } + + /// Opens the PDF file held by , from its current position. + /// The stream. It is not disposed; keep it open and unchanged until the document is disposed. + /// The document. Dispose it when done. + /// + /// The file cannot be read at all, or, in strict mode, deviates from ISO 32000-2. + /// + /// ISO 32000-2 §7.5. + public PdfDocument Open(Stream stream) + { + ArgumentNullException.ThrowIfNull(stream); + return PdfDocument.Read(PdfSource.FromStream(stream), _configuration); + } + + /// Opens the PDF file held in . + /// The file. Not copied: do not change it until the document is disposed. + /// The document. Dispose it when done. + /// + /// The file cannot be read at all, or, in strict mode, deviates from ISO 32000-2. + /// + /// ISO 32000-2 §7.5. + public PdfDocument Open(ReadOnlyMemory bytes) => PdfDocument.Read(PdfSource.FromMemory(bytes), _configuration); + + /// Creates a new, empty document. + /// The document. + /// Always, for now: writing arrives in a later version. + public PdfDocument Create() => throw new NotSupportedException("Creating a document is not implemented yet."); +} diff --git a/src/Broadside/PdfOptions.cs b/src/Broadside/PdfOptions.cs new file mode 100644 index 00000000..f78cc55c --- /dev/null +++ b/src/Broadside/PdfOptions.cs @@ -0,0 +1,32 @@ +namespace Broadside; + +/// +/// The configuration of a , set fluently: Use* methods select an implementation or behavior, +/// With* methods set a value. +/// +/// +/// An engine copies its options when it is constructed, so changing an options object afterwards does not change any engine built +/// from it. The properties are settable so the same type binds through the options pattern of dependency injection. +/// +public sealed class PdfOptions +{ + /// Gets or sets how deviations from the specification are treated. The default is . + /// ADR 0005. + public PdfReadingMode ReadingMode { get; set; } = PdfReadingMode.Lenient; + + /// Repairs deviations and records them as diagnostics on the document. The default. + /// These options. + public PdfOptions UseLenient() + { + ReadingMode = PdfReadingMode.Lenient; + return this; + } + + /// Throws a for the first deviation. + /// These options. + public PdfOptions UseStrict() + { + ReadingMode = PdfReadingMode.Strict; + return this; + } +} diff --git a/src/Broadside/PdfPage.cs b/src/Broadside/PdfPage.cs new file mode 100644 index 00000000..b7d9ae5b --- /dev/null +++ b/src/Broadside/PdfPage.cs @@ -0,0 +1,203 @@ +using Broadside.Objects; + +namespace Broadside; + +/// One page of a document: a live view over a page object and the page tree nodes it inherits attributes from. +/// +/// +/// ISO 32000-2 §7.7.3.3 (page objects, Table 31), §7.7.3.4 (inheritance) and §14.11.2 (page boundaries). Every property reads the COS +/// objects when called, so a change made through or an ancestor node is visible at once. +/// +/// +/// Resources, MediaBox, CropBox and Rotate are inherited: when the page does not have the entry, the +/// nearest ancestor node that has it supplies it, as-is and never merged (§7.7.3.4). Ancestors are the nodes on the path from the +/// page tree root that the page was found through. A value that is missing or malformed reads as the default the specification +/// gives; the reader records a diagnostic for it when it first walks the page tree. +/// +/// +public sealed class PdfPage +{ + /// The media box used when a page has none, US Letter, as pdf.js and PDFBox use. + private static readonly PdfRectangle DefaultMediaBox = new(0, 0, 612, 792); + + private readonly PdfDocument _document; + private readonly PageTreeAncestor? _ancestors; + + internal PdfPage(PdfDocument document, CosDictionary dictionary, CosReference? reference, PageTreeAncestor? ancestors) + { + _document = document; + _ancestors = ancestors; + Dictionary = dictionary; + Reference = reference; + } + + /// Gets the page object. + /// ISO 32000-2 §7.7.3.3, Table 31. + public CosDictionary Dictionary { get; } + + /// Gets the indirect reference to the page object, or when the page tree holds it directly. + public CosReference? Reference { get; } + + /// Gets the media box: the boundaries of the physical medium the page is displayed or printed on. Inheritable. + /// ISO 32000-2 §7.7.3.3, Table 31, and §14.11.2. Required; when missing or malformed, US Letter [0 0 612 792]. + public PdfRectangle MediaBox => ReadBox(KnownNames.MediaBox, inheritable: true, out PdfRectangle box) == PageAttributeState.Valid ? box : DefaultMediaBox; + + /// Gets the crop box: the region the page's contents are clipped to when displayed or printed. Inheritable. + /// ISO 32000-2 §7.7.3.3, Table 31, and §14.11.2. Defaults to the media box; reduced to its intersection with the media box. + public PdfRectangle CropBox => ClipToMediaBox(KnownNames.CropBox, inheritable: true, MediaBox); + + /// Gets the bleed box: the region the contents are clipped to in a production environment. + /// ISO 32000-2 §7.7.3.3, Table 31, and §14.11.2. Defaults to the crop box; reduced to its intersection with the media box. + public PdfRectangle BleedBox => ClipToMediaBox(KnownNames.BleedBox, inheritable: false, CropBox); + + /// Gets the trim box: the intended dimensions of the finished page after trimming. + /// ISO 32000-2 §7.7.3.3, Table 31, and §14.11.2. Defaults to the crop box; reduced to its intersection with the media box. + public PdfRectangle TrimBox => ClipToMediaBox(KnownNames.TrimBox, inheritable: false, CropBox); + + /// Gets the art box: the extent of the page's meaningful content. + /// ISO 32000-2 §7.7.3.3, Table 31, and §14.11.2. Defaults to the crop box; reduced to its intersection with the media box. + public PdfRectangle ArtBox => ClipToMediaBox(KnownNames.ArtBox, inheritable: false, CropBox); + + /// Gets the number of degrees the page is rotated clockwise when displayed or printed: 0, 90, 180 or 270. Inheritable. + /// + /// ISO 32000-2 §7.7.3.3, Table 31. The entry shall be a multiple of 90; it is normalized into 0 to 270 (−90 reads as 270, 450 as + /// 90). A value that is not a multiple of 90 reads as 0. + /// + public int Rotation => ReadRotation(out int degrees) is PageAttributeState.Valid or PageAttributeState.Repaired ? degrees : 0; + + /// Gets the resource dictionary the page's content streams use, or when the page has none. Inheritable. + /// ISO 32000-2 §7.7.3.3, Table 31, and §7.8.3. + public CosDictionary? Resources => FindInheritable(KnownNames.Resources) as CosDictionary; + + /// Gets the size of a default user space unit in multiples of 1/72 inch. 1.0 when absent or not positive. + /// ISO 32000-2 §7.7.3.3, Table 31 (PDF 1.6). + public double UserUnit => ReadUserUnit(out double value) == PageAttributeState.Valid ? value : 1.0; + + /// Reads a page boundary; for an inheritable one, from the nearest node that has it. + internal PageAttributeState ReadBox(CosName key, bool inheritable, out PdfRectangle box) + { + box = default; + CosObject? value = inheritable ? FindInheritable(key) : Find(key); + if (value is null) + { + return PageAttributeState.Absent; + } + + if (_document.Resolve(value) is not CosArray { Count: 4 } array) + { + return PageAttributeState.Invalid; + } + + Span corners = stackalloc double[4]; + for (int index = 0; index < 4; index++) + { + if (_document.Resolve(array[index]) is not CosNumber number) + { + return PageAttributeState.Invalid; + } + + corners[index] = number.ToDouble(); + } + + box = new PdfRectangle(corners[0], corners[1], corners[2], corners[3]); + return PageAttributeState.Valid; + } + + /// Reads Rotate normalized into 0 to 270; a real holding a multiple of 90 is . + internal PageAttributeState ReadRotation(out int degrees) + { + degrees = 0; + switch (FindInheritable(KnownNames.Rotate)) + { + case null: + return PageAttributeState.Absent; + case CosInteger { Value: var value } when value % 90 == 0: + degrees = (int)(((value % 360) + 360) % 360); + return PageAttributeState.Valid; + case CosReal { Value: var value } when value % 90 == 0 && Math.Abs(value) <= int.MaxValue: + degrees = (((int)value % 360) + 360) % 360; + return PageAttributeState.Repaired; + default: + return PageAttributeState.Invalid; + } + } + + /// Reads Resources. + internal PageAttributeState ReadResources() => FindInheritable(KnownNames.Resources) switch + { + null => PageAttributeState.Absent, + CosDictionary => PageAttributeState.Valid, + _ => PageAttributeState.Invalid, + }; + + /// Reads UserUnit, which shall be positive. + internal PageAttributeState ReadUserUnit(out double value) + { + value = 1.0; + switch (Find(KnownNames.UserUnit)) + { + case null: + return PageAttributeState.Absent; + case CosNumber number when number.ToDouble() > 0: + value = number.ToDouble(); + return PageAttributeState.Valid; + default: + return PageAttributeState.Invalid; + } + } + + /// A box that defaults to , reduced to its intersection with the media box (§14.11.2). + private PdfRectangle ClipToMediaBox(CosName key, bool inheritable, PdfRectangle fallback) + { + if (ReadBox(key, inheritable, out PdfRectangle box) != PageAttributeState.Valid) + { + return fallback; + } + + return box.Intersect(MediaBox) ?? fallback; + } + + /// The page's own entry, resolved; when absent or a reference to nothing. + private CosObject? Find(CosName key) => + Dictionary.TryGetValue(key, out CosObject? value) && _document.Resolve(value) is not CosNull and var resolved ? resolved : null; + + /// The page's entry, or the nearest ancestor's, resolved, used as-is (§7.7.3.4). + private CosObject? FindInheritable(CosName key) + { + if (Find(key) is { } own) + { + return own; + } + + for (PageTreeAncestor? node = _ancestors; node is not null; node = node.Parent) + { + if (node.Dictionary.TryGetValue(key, out CosObject? value) && _document.Resolve(value) is not CosNull and var resolved) + { + return resolved; + } + } + + return null; + } +} + +/// A page tree node on the path from the root to a page, nearest first: the nodes a page inherits from (§7.7.3.4). +/// The node's dictionary. +/// The node above it, or for the root. +internal sealed record PageTreeAncestor(CosDictionary Dictionary, PageTreeAncestor? Parent); + +/// What reading a page attribute found. +internal enum PageAttributeState : byte +{ + /// The entry is absent; the default applies. + Absent, + + /// The entry is well-formed. + Valid, + + /// The entry deviates from its type but its value can be used. + Repaired, + + /// The entry is malformed; the default applies. + Invalid, +} diff --git a/src/Broadside/PdfPageCollection.cs b/src/Broadside/PdfPageCollection.cs new file mode 100644 index 00000000..18ea55a5 --- /dev/null +++ b/src/Broadside/PdfPageCollection.cs @@ -0,0 +1,32 @@ +using System.Collections; + +namespace Broadside; + +/// The pages of a document, in page order: the leaves of the page tree. +/// +/// ISO 32000-2 §7.7.3. The page tree is walked on first use (count, index or enumeration), once, by its Kids arrays; its +/// Count entries are only checked, never trusted (§7.7.3.2 calls them redundant). Each is a live view over +/// its page object, but the list itself is the tree's shape at the first walk: the page editing API (a later version) keeps it current. +/// +public sealed class PdfPageCollection : IReadOnlyList +{ + private readonly Lazy> _pages; + + internal PdfPageCollection(Func> walk) => + _pages = new Lazy>(walk, LazyThreadSafetyMode.ExecutionAndPublication); + + /// Gets the number of pages. + public int Count => _pages.Value.Count; + + /// Gets the page at a zero-based index. + /// The index: 0 for the first page. + /// The page. + /// is negative or not less than . + public PdfPage this[int index] => _pages.Value[index]; + + /// + public IEnumerator GetEnumerator() => _pages.Value.GetEnumerator(); + + /// + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); +} diff --git a/src/Broadside/PdfReadingMode.cs b/src/Broadside/PdfReadingMode.cs new file mode 100644 index 00000000..5e79a5f7 --- /dev/null +++ b/src/Broadside/PdfReadingMode.cs @@ -0,0 +1,12 @@ +namespace Broadside; + +/// How a reader treats a deviation from the specification. +/// ADR 0005. +public enum PdfReadingMode +{ + /// The default: repair what can be repaired, record a on the document, continue. + Lenient = 0, + + /// The first deviation throws a . + Strict = 1, +} diff --git a/src/Broadside/PdfRectangle.cs b/src/Broadside/PdfRectangle.cs new file mode 100644 index 00000000..622dadb4 --- /dev/null +++ b/src/Broadside/PdfRectangle.cs @@ -0,0 +1,78 @@ +using System.Globalization; + +namespace Broadside; + +/// A rectangle in default user space, such as a page boundary. +/// +/// ISO 32000-2 §7.9.5. A file writes a rectangle as two diagonally opposite corners in any order; this type always holds them +/// normalized, so is at most and at most . +/// +public readonly struct PdfRectangle : IEquatable +{ + /// Initializes a new instance of the struct from two diagonally opposite corners, in any order. + /// The x coordinate of one corner. + /// The y coordinate of the same corner. + /// The x coordinate of the opposite corner. + /// The y coordinate of the opposite corner. + public PdfRectangle(double x1, double y1, double x2, double y2) + { + Left = Math.Min(x1, x2); + Right = Math.Max(x1, x2); + Bottom = Math.Min(y1, y2); + Top = Math.Max(y1, y2); + } + + /// Gets the smaller x coordinate. + public double Left { get; } + + /// Gets the smaller y coordinate. + public double Bottom { get; } + + /// Gets the larger x coordinate. + public double Right { get; } + + /// Gets the larger y coordinate. + public double Top { get; } + + /// Gets the width, never negative. + public double Width => Right - Left; + + /// Gets the height, never negative. + public double Height => Top - Bottom; + + /// Returns whether two rectangles have the same coordinates. + /// The first rectangle. + /// The second rectangle. + /// when they are equal. + public static bool operator ==(PdfRectangle left, PdfRectangle right) => left.Equals(right); + + /// Returns whether two rectangles differ. + /// The first rectangle. + /// The second rectangle. + /// when they differ. + public static bool operator !=(PdfRectangle left, PdfRectangle right) => !left.Equals(right); + + /// + public bool Equals(PdfRectangle other) => + Left.Equals(other.Left) && Bottom.Equals(other.Bottom) && Right.Equals(other.Right) && Top.Equals(other.Top); + + /// + public override bool Equals(object? obj) => obj is PdfRectangle other && Equals(other); + + /// + public override int GetHashCode() => HashCode.Combine(Left, Bottom, Right, Top); + + /// Returns the rectangle as a PDF array would write it, such as [0 0 612 792]. + /// The rectangle text. + public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"[{Left} {Bottom} {Right} {Top}]"); + + /// Returns the overlap of two rectangles, or when they do not overlap. + internal PdfRectangle? Intersect(PdfRectangle other) + { + double left = Math.Max(Left, other.Left); + double right = Math.Min(Right, other.Right); + double bottom = Math.Max(Bottom, other.Bottom); + double top = Math.Min(Top, other.Top); + return left <= right && bottom <= top ? new PdfRectangle(left, bottom, right, top) : null; + } +} diff --git a/src/Broadside/PdfVersion.cs b/src/Broadside/PdfVersion.cs new file mode 100644 index 00000000..ad672de1 --- /dev/null +++ b/src/Broadside/PdfVersion.cs @@ -0,0 +1,109 @@ +using System.Globalization; +using Broadside.Objects; + +namespace Broadside; + +/// A version of the PDF specification, major.minor, as a file header or a catalog's Version entry states it. +/// +/// ISO 32000-2 §7.5.2 (the header is %PDF-1.n or %PDF-2.n with a single-digit n) and §7.7.2, Table 29 (the +/// catalog's Version is a name such as /1.7). Versions compare numerically on the major, then the minor number. +/// +public readonly struct PdfVersion : IEquatable, IComparable +{ + /// Initializes a new instance of the struct. + /// The major version number. + /// The minor version number. + /// A number is negative. + public PdfVersion(int major, int minor) + { + ArgumentOutOfRangeException.ThrowIfNegative(major); + ArgumentOutOfRangeException.ThrowIfNegative(minor); + Major = major; + Minor = minor; + } + + /// Gets the major version number: 1 or 2 for every published version. + public int Major { get; } + + /// Gets the minor version number. + public int Minor { get; } + + /// Returns whether two versions are equal. + /// The first version. + /// The second version. + /// when they are equal. + public static bool operator ==(PdfVersion left, PdfVersion right) => left.Equals(right); + + /// Returns whether two versions differ. + /// The first version. + /// The second version. + /// when they differ. + public static bool operator !=(PdfVersion left, PdfVersion right) => !left.Equals(right); + + /// Returns whether is an earlier version than . + /// The first version. + /// The second version. + /// The comparison result. + public static bool operator <(PdfVersion left, PdfVersion right) => left.CompareTo(right) < 0; + + /// Returns whether is a later version than . + /// The first version. + /// The second version. + /// The comparison result. + public static bool operator >(PdfVersion left, PdfVersion right) => left.CompareTo(right) > 0; + + /// Returns whether is the same as or earlier than . + /// The first version. + /// The second version. + /// The comparison result. + public static bool operator <=(PdfVersion left, PdfVersion right) => left.CompareTo(right) <= 0; + + /// Returns whether is the same as or later than . + /// The first version. + /// The second version. + /// The comparison result. + public static bool operator >=(PdfVersion left, PdfVersion right) => left.CompareTo(right) >= 0; + + /// + public int CompareTo(PdfVersion other) => Major != other.Major ? Major.CompareTo(other.Major) : Minor.CompareTo(other.Minor); + + /// + public bool Equals(PdfVersion other) => Major == other.Major && Minor == other.Minor; + + /// + public override bool Equals(object? obj) => obj is PdfVersion other && Equals(other); + + /// + public override int GetHashCode() => HashCode.Combine(Major, Minor); + + /// Returns the version as the header and the catalog write it, such as 1.7. + /// The version text. + public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"{Major}.{Minor}"); + + /// Parses d.d with a major version from 1 to 9, the form a header and a catalog Version name use. + internal static bool TryParse(ReadOnlySpan text, out PdfVersion version) + { + if (text.Length == 3 && text[0] is >= (byte)'1' and <= (byte)'9' && text[1] == (byte)'.' && text[2] is >= (byte)'0' and <= (byte)'9') + { + version = new PdfVersion(text[0] - '0', text[2] - '0'); + return true; + } + + version = default; + return false; + } + + /// Reads a version written as a number (1.7 instead of /1.7), a common writer error. + internal static bool TryFromNumber(CosNumber number, out PdfVersion version) + { + double tenths = Math.Round(number.ToDouble() * 10); + if (tenths is >= 10 and < 100) + { + version = new PdfVersion((int)(tenths / 10), (int)(tenths % 10)); + return true; + } + + version = default; + return false; + } +} diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index cdd9ec48..6b193443 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -91,3 +91,98 @@ static Broadside.Objects.CosObject.DeepEquals(Broadside.Objects.CosObject? left, static Broadside.Objects.CosObject.Parse(System.ReadOnlySpan bytes) -> Broadside.Objects.CosObject! static Broadside.Objects.CosObject.TryParse(System.ReadOnlySpan bytes, out Broadside.Objects.CosObject? result) -> bool virtual Broadside.Objects.CosObject.IsDirty.get -> bool +Broadside.Diagnostics.Diagnostic +Broadside.Diagnostics.Diagnostic.Code.get -> string! +Broadside.Diagnostics.Diagnostic.Diagnostic(string! code, Broadside.Diagnostics.DiagnosticSeverity severity, string! message, long? offset = null, Broadside.Objects.CosReference? objectReference = null) -> void +Broadside.Diagnostics.Diagnostic.Message.get -> string! +Broadside.Diagnostics.Diagnostic.ObjectReference.get -> Broadside.Objects.CosReference? +Broadside.Diagnostics.Diagnostic.Offset.get -> long? +Broadside.Diagnostics.Diagnostic.Severity.get -> Broadside.Diagnostics.DiagnosticSeverity +Broadside.Diagnostics.DiagnosticException +Broadside.Diagnostics.DiagnosticException.Diagnostic.get -> Broadside.Diagnostics.Diagnostic! +Broadside.Diagnostics.DiagnosticException.DiagnosticException() -> void +Broadside.Diagnostics.DiagnosticException.DiagnosticException(Broadside.Diagnostics.Diagnostic! diagnostic) -> void +Broadside.Diagnostics.DiagnosticException.DiagnosticException(string? message) -> void +Broadside.Diagnostics.DiagnosticException.DiagnosticException(string? message, System.Exception? innerException) -> void +Broadside.Diagnostics.DiagnosticSeverity +Broadside.Diagnostics.DiagnosticSeverity.Error = 1 -> Broadside.Diagnostics.DiagnosticSeverity +Broadside.Diagnostics.DiagnosticSeverity.Warning = 0 -> Broadside.Diagnostics.DiagnosticSeverity +Broadside.PdfDocument +Broadside.PdfDocument.Catalog.get -> Broadside.Objects.CosDictionary! +Broadside.PdfDocument.Diagnostics.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfDocument.Dispose() -> void +Broadside.PdfDocument.Pages.get -> Broadside.PdfPageCollection! +Broadside.PdfDocument.Resolve(Broadside.Objects.CosObject? value) -> Broadside.Objects.CosObject! +Broadside.PdfDocument.Trailer.get -> Broadside.Objects.CosDictionary! +Broadside.PdfDocument.Version.get -> Broadside.PdfVersion +Broadside.PdfEngine +Broadside.PdfEngine.Create() -> Broadside.PdfDocument! +Broadside.PdfEngine.Open(string! path) -> Broadside.PdfDocument! +Broadside.PdfEngine.Open(System.IO.Stream! stream) -> Broadside.PdfDocument! +Broadside.PdfEngine.Open(System.ReadOnlyMemory bytes) -> Broadside.PdfDocument! +Broadside.PdfEngine.PdfEngine() -> void +Broadside.PdfEngine.PdfEngine(Broadside.PdfOptions! options) -> void +Broadside.PdfOptions +Broadside.PdfOptions.PdfOptions() -> void +Broadside.PdfOptions.ReadingMode.get -> Broadside.PdfReadingMode +Broadside.PdfOptions.ReadingMode.set -> void +Broadside.PdfOptions.UseLenient() -> Broadside.PdfOptions! +Broadside.PdfOptions.UseStrict() -> Broadside.PdfOptions! +Broadside.PdfPage +Broadside.PdfPage.ArtBox.get -> Broadside.PdfRectangle +Broadside.PdfPage.BleedBox.get -> Broadside.PdfRectangle +Broadside.PdfPage.CropBox.get -> Broadside.PdfRectangle +Broadside.PdfPage.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfPage.MediaBox.get -> Broadside.PdfRectangle +Broadside.PdfPage.Reference.get -> Broadside.Objects.CosReference? +Broadside.PdfPage.Resources.get -> Broadside.Objects.CosDictionary? +Broadside.PdfPage.Rotation.get -> int +Broadside.PdfPage.TrimBox.get -> Broadside.PdfRectangle +Broadside.PdfPage.UserUnit.get -> double +Broadside.PdfPageCollection +Broadside.PdfPageCollection.Count.get -> int +Broadside.PdfPageCollection.GetEnumerator() -> System.Collections.Generic.IEnumerator! +Broadside.PdfPageCollection.this[int index].get -> Broadside.PdfPage! +Broadside.PdfReadingMode +Broadside.PdfReadingMode.Lenient = 0 -> Broadside.PdfReadingMode +Broadside.PdfReadingMode.Strict = 1 -> Broadside.PdfReadingMode +Broadside.PdfRectangle +Broadside.PdfRectangle.Bottom.get -> double +Broadside.PdfRectangle.Equals(Broadside.PdfRectangle other) -> bool +Broadside.PdfRectangle.Height.get -> double +Broadside.PdfRectangle.Left.get -> double +Broadside.PdfRectangle.PdfRectangle() -> void +Broadside.PdfRectangle.PdfRectangle(double x1, double y1, double x2, double y2) -> void +Broadside.PdfRectangle.Right.get -> double +Broadside.PdfRectangle.Top.get -> double +Broadside.PdfRectangle.Width.get -> double +Broadside.PdfVersion +Broadside.PdfVersion.CompareTo(Broadside.PdfVersion other) -> int +Broadside.PdfVersion.Equals(Broadside.PdfVersion other) -> bool +Broadside.PdfVersion.Major.get -> int +Broadside.PdfVersion.Minor.get -> int +Broadside.PdfVersion.PdfVersion() -> void +Broadside.PdfVersion.PdfVersion(int major, int minor) -> void +override Broadside.Diagnostics.Diagnostic.ToString() -> string! +override Broadside.PdfRectangle.Equals(object? obj) -> bool +override Broadside.PdfRectangle.GetHashCode() -> int +override Broadside.PdfRectangle.ToString() -> string! +override Broadside.PdfVersion.Equals(object? obj) -> bool +override Broadside.PdfVersion.GetHashCode() -> int +override Broadside.PdfVersion.ToString() -> string! +static Broadside.PdfDocument.Create() -> Broadside.PdfDocument! +static Broadside.PdfDocument.Create(Broadside.PdfOptions! options) -> Broadside.PdfDocument! +static Broadside.PdfDocument.Open(string! path) -> Broadside.PdfDocument! +static Broadside.PdfDocument.Open(string! path, Broadside.PdfOptions! options) -> Broadside.PdfDocument! +static Broadside.PdfDocument.Open(System.IO.Stream! stream) -> Broadside.PdfDocument! +static Broadside.PdfDocument.Open(System.IO.Stream! stream, Broadside.PdfOptions! options) -> Broadside.PdfDocument! +static Broadside.PdfDocument.Open(System.ReadOnlyMemory bytes) -> Broadside.PdfDocument! +static Broadside.PdfDocument.Open(System.ReadOnlyMemory bytes, Broadside.PdfOptions! options) -> Broadside.PdfDocument! +static Broadside.PdfRectangle.operator !=(Broadside.PdfRectangle left, Broadside.PdfRectangle right) -> bool +static Broadside.PdfRectangle.operator ==(Broadside.PdfRectangle left, Broadside.PdfRectangle right) -> bool +static Broadside.PdfVersion.operator !=(Broadside.PdfVersion left, Broadside.PdfVersion right) -> bool +static Broadside.PdfVersion.operator <(Broadside.PdfVersion left, Broadside.PdfVersion right) -> bool +static Broadside.PdfVersion.operator <=(Broadside.PdfVersion left, Broadside.PdfVersion right) -> bool +static Broadside.PdfVersion.operator ==(Broadside.PdfVersion left, Broadside.PdfVersion right) -> bool +static Broadside.PdfVersion.operator >(Broadside.PdfVersion left, Broadside.PdfVersion right) -> bool +static Broadside.PdfVersion.operator >=(Broadside.PdfVersion left, Broadside.PdfVersion right) -> bool diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 3aa2081e..ee0219ec 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -1,3 +1,4 @@ +using Broadside.Diagnostics; using Broadside.Objects; using SharpFuzz; @@ -14,8 +15,57 @@ internal static class FuzzTargets { ["lexer"] = Lexer, ["object-parser"] = ObjectParser, + ["document"] = Document, }; + /// + /// Opens the input as a whole file in lenient mode and reads everything the document model exposes: version, trailer, every + /// page's boxes, rotation, user unit and resources. A is the one documented outcome for a file + /// whose cross-reference information cannot be read at all (until issue #41 reconstructs it); any other exception is a finding. + /// Every box must be normalized and every rotation one of 0, 90, 180, 270. + /// + /// ISO 32000-2 §7.5.1 to §7.5.5, §7.7.2, §7.7.3. + private static void Document(ReadOnlySpan data) + { + using PdfDocument? document = OpenOrNull(data); + if (document is null) + { + return; + } + + _ = document.Version; + _ = document.Trailer.Count; + foreach (PdfPage page in document.Pages) + { + foreach (PdfRectangle box in (ReadOnlySpan)[page.MediaBox, page.CropBox, page.BleedBox, page.TrimBox, page.ArtBox]) + { + if (!(box.Left <= box.Right && box.Bottom <= box.Top)) + { + throw new InvalidOperationException($"Page box {box} is not normalized."); + } + } + + if (page.Rotation is not (0 or 90 or 180 or 270) || page.UserUnit <= 0) + { + throw new InvalidOperationException($"Rotation {page.Rotation} or user unit {page.UserUnit} is out of range."); + } + + _ = page.Resources; + } + } + + private static PdfDocument? OpenOrNull(ReadOnlySpan data) + { + try + { + return PdfDocument.Open(data.ToArray()); + } + catch (DiagnosticException) + { + return null; + } + } + /// /// Tokenizes the whole input. Every token must lie inside the input and start at or after the previous one's end, and the lexer /// must reach the end of input. diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index eedbf364..ce3d0824 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`). Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources; a `DiagnosticException` for a file whose cross-reference information cannot be read is the one allowed outcome until #41 reconstructs it). Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. @@ -25,7 +25,7 @@ dotnet run -c Release --project tests/Broadside.Fuzz -- --run object-parser arti `--run ` executes the target once on one input, which is also how to replay a crash found by libFuzzer or AFL. -Whole corpus files are the right seeds for both `lexer` and `object-parser`, which read any bytes as a file body. +Whole corpus files are the right seeds for `lexer` and `object-parser`, which read any bytes as a file body, and for `document`, which reads whole files. Smoke mode is a regression net, not a fuzzer: it has no coverage feedback and finds only shallow bugs. Use a real fuzzer for anything that parses. diff --git a/tests/Broadside.Tests/Document/DocumentProjection.cs b/tests/Broadside.Tests/Document/DocumentProjection.cs new file mode 100644 index 00000000..bf71d54b --- /dev/null +++ b/tests/Broadside.Tests/Document/DocumentProjection.cs @@ -0,0 +1,20 @@ +using Broadside.Objects; + +namespace Broadside.Tests.Document; + +/// What a reader exposes about a document, as a value: two opens of the same file must project equal. +internal sealed record DocumentProjection(string Version, string Pages, string Diagnostics) +{ + public static DocumentProjection Of(PdfDocument document) + { + IEnumerable pages = document.Pages.Select(static page => + $"{Describe(page.Reference)} media {page.MediaBox} crop {page.CropBox} bleed {page.BleedBox} trim {page.TrimBox} art {page.ArtBox} " + + $"rotate {page.Rotation} unit {page.UserUnit} resources {page.Resources}"); + return new DocumentProjection( + document.Version.ToString(), + string.Join('\n', pages), + string.Join('\n', document.Diagnostics.Select(static diagnostic => diagnostic.ToString()))); + } + + private static string Describe(CosReference? reference) => reference is null ? "direct" : $"{reference.ObjectNumber} {reference.Generation} R"; +} diff --git a/tests/Broadside.Tests/Document/EngineTests.cs b/tests/Broadside.Tests/Document/EngineTests.cs new file mode 100644 index 00000000..96a8f0b6 --- /dev/null +++ b/tests/Broadside.Tests/Document/EngineTests.cs @@ -0,0 +1,116 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// The engine and options: one open path for the static entry point and engine instances, lenient and strict reading (ADR 0005). +public class EngineTests +{ + [Theory] + [MemberData(nameof(Corpus.WellFormedFiles), MemberType = typeof(Corpus))] + public void The_static_entry_point_and_an_engine_instance_open_documents_identically(string fileName) + { + Assert.SkipWhen(WellFormedCorpusTests.NeedsCrossReferenceStreams(fileName), "Needs cross-reference streams (#39)."); + + var engine = new PdfEngine(new PdfOptions()); + using PdfDocument fromEngine = engine.Open(Corpus.Bytes(fileName)); + using PdfDocument fromStatic = PdfDocument.Open(Corpus.Bytes(fileName)); + + Assert.Equal(DocumentProjection.Of(fromStatic), DocumentProjection.Of(fromEngine)); + } + + [Fact] + public void Strict_mode_throws_the_first_deviation_and_lenient_mode_records_it() + { + byte[] file = TestPdf.OnePage(string.Empty); + + using (PdfDocument lenient = PdfDocument.Open(file, new PdfOptions().UseLenient())) + { + Assert.Single(lenient.Pages); + Assert.Equal("PageMediaBoxMissing", Assert.Single(lenient.Diagnostics).Code); + } + + using PdfDocument strict = new PdfEngine(new PdfOptions().UseStrict()).Open(file); + DiagnosticException error = Assert.Throws(() => strict.Pages.Count); + Assert.Equal("PageMediaBoxMissing", error.Diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Error, error.Diagnostic.Severity); + Assert.IsAssignableFrom(error); + } + + [Fact] + public void Strict_mode_throws_during_open_for_a_deviation_in_what_open_reads() + { + byte[] file = new TestPdf().Build("<< /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>"); + + DiagnosticException error = Assert.Throws(() => PdfDocument.Open(file, new PdfOptions().UseStrict())); + + Assert.Equal("CatalogTypeInvalid", error.Diagnostic.Code); + Assert.Equal(new CosReference(1, 0), error.Diagnostic.ObjectReference); + } + + [Fact] + public void Strict_mode_throws_from_the_member_that_loads_a_deviating_object() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("missing-endobj.pdf"), new PdfOptions().UseStrict()); + + DiagnosticException error = Assert.Throws(() => document.Pages.Count); + + Assert.Equal("MissingEndobj", error.Diagnostic.Code); + Assert.Equal(new CosReference(3, 0), error.Diagnostic.ObjectReference); + } + + [Theory] + [MemberData(nameof(Corpus.WellFormedFiles), MemberType = typeof(Corpus))] + public void Strict_mode_opens_every_well_formed_file(string fileName) + { + Assert.SkipWhen(WellFormedCorpusTests.NeedsCrossReferenceStreams(fileName), "Needs cross-reference streams (#39)."); + + using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName), new PdfOptions().UseStrict()); + + Assert.NotEmpty(document.Pages); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void An_engine_copies_its_options_so_later_changes_do_not_affect_it() + { + var options = new PdfOptions(); + var engine = new PdfEngine(options); + options.UseStrict(); + + using PdfDocument document = engine.Open(TestPdf.OnePage(string.Empty)); + + Assert.Single(document.Pages); + Assert.Equal(PdfReadingMode.Strict, options.ReadingMode); + Assert.Equal("PageMediaBoxMissing", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void Options_are_lenient_by_default_and_fluent() + { + var options = new PdfOptions(); + + Assert.Equal(PdfReadingMode.Lenient, options.ReadingMode); + Assert.Same(options, options.UseStrict()); + Assert.Equal(PdfReadingMode.Strict, options.ReadingMode); + Assert.Same(options, options.UseLenient()); + Assert.Equal(PdfReadingMode.Lenient, options.ReadingMode); + } + + [Fact] + public void Create_is_a_stub_until_writing_lands() + { + Assert.Throws(() => PdfDocument.Create()); + Assert.Throws(() => new PdfEngine().Create()); + } + + [Fact] + public void A_disposed_document_cannot_load_more_objects() + { + PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + document.Dispose(); + + Assert.Throws(() => document.Pages.Count); + } +} diff --git a/tests/Broadside.Tests/Document/FileStructureTests.cs b/tests/Broadside.Tests/Document/FileStructureTests.cs new file mode 100644 index 00000000..d464a478 --- /dev/null +++ b/tests/Broadside.Tests/Document/FileStructureTests.cs @@ -0,0 +1,215 @@ +using System.Text; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// Header, cross-reference table, trailer and indirect objects. ISO 32000-2 §7.3.10, §7.5.1 to §7.5.5. +public class FileStructureTests +{ + [Fact] + public void Offsets_count_from_the_header_so_bytes_before_it_do_not_matter() + { + byte[] junk = Encoding.Latin1.GetBytes("Junk\r\n"); + byte[] file = [.. junk, .. Corpus.Bytes("empty-page.pdf")]; + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal(new PdfRectangle(0, 0, 612, 792), Assert.Single(document.Pages).MediaBox); + Assert.Equal(new PdfVersion(1, 7), document.Version); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_file_without_a_header_opens_from_byte_0_with_a_diagnostic() + { + byte[] file = Corpus.Bytes("empty-page.pdf"); + file[1] = (byte)'X'; + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Single(document.Pages); + Assert.Equal(new PdfVersion(1, 4), document.Version); + Assert.Equal("HeaderMissing", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void The_newest_section_wins_and_older_sections_are_read_through_prev() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("incremental-update.pdf")); + + Assert.Equal(new PdfRectangle(0, 0, 595, 842), Assert.Single(document.Pages).MediaBox); + Assert.IsType(document.Resolve(new CosReference(1, 0))); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_prev_chain_that_loops_ends_with_a_diagnostic() + { + byte[] file = WithTrailerEntries(xref => $"/Prev {xref}"); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Single(document.Pages); + Assert.Equal("XrefPrevLoop", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void Entries_are_read_as_tokens_not_fixed_width_records() + { + string text = Encoding.Latin1.GetString(Corpus.Bytes("empty-page.pdf")).Replace(" \n", "\r\n", StringComparison.Ordinal); + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + + Assert.Single(document.Pages); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_startxref_offset_on_the_white_space_before_xref_is_repaired_with_a_diagnostic() + { + string text = Encoding.Latin1.GetString(Corpus.Bytes("empty-page.pdf")).Replace("startxref\n203", "startxref\n202", StringComparison.Ordinal); + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + + Assert.Single(document.Pages); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("StartxrefInvalid", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); + } + + [Fact] + public void A_file_with_no_startxref_cannot_be_read_even_leniently() + { + string text = Encoding.Latin1.GetString(Corpus.Bytes("empty-page.pdf")).Replace("startxref", "startxrex", StringComparison.Ordinal); + + DiagnosticException error = Assert.Throws(() => PdfDocument.Open(Encoding.Latin1.GetBytes(text))); + + Assert.Equal("StartxrefMissing", error.Diagnostic.Code); + } + + [Fact] + public void A_trailer_without_root_cannot_be_read() + { + string text = Encoding.Latin1.GetString(Corpus.Bytes("empty-page.pdf")).Replace("/Root 1 0 R", "/Rood 1 0 R", StringComparison.Ordinal); + + DiagnosticException error = Assert.Throws(() => PdfDocument.Open(Encoding.Latin1.GetBytes(text))); + + Assert.Equal("RootMissing", error.Diagnostic.Code); + } + + [Fact] + public void A_catalog_without_its_type_is_read_with_a_diagnostic() + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build( + "<< /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>")); + + Assert.Single(document.Pages); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("CatalogTypeInvalid", diagnostic.Code); + Assert.Equal(new CosReference(1, 0), diagnostic.ObjectReference); + } + + [Fact] + public void References_to_missing_free_or_other_generation_objects_resolve_to_null_without_a_diagnostic() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + + Assert.Same(CosNull.Instance, document.Resolve(new CosReference(99, 0))); + Assert.Same(CosNull.Instance, document.Resolve(new CosReference(1, 1))); + Assert.Same(CosNull.Instance, document.Resolve(null)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + var reference = new CosReference(3, 0); + + CosObject page = document.Resolve(reference); + + Assert.Same(page, document.Resolve(reference)); + Assert.Same(page, document.Pages[0].Dictionary); + Assert.Same(document.Catalog, document.Resolve(document.Catalog)); + Assert.Same(document.Catalog, document.Resolve(document.Trailer[new CosName("Root")])); + } + + [Fact] + public void A_stream_takes_its_extent_from_an_indirect_length() + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] /Contents 4 0 R >>", + "<< /Length 5 0 R >>\nstream\nendstream inside\nendstream", + "16")); + + CosStream contents = Assert.IsType(document.Resolve(new CosReference(4, 0))); + + Assert.Equal("endstream inside", Encoding.Latin1.GetString(contents.EncodedData.Span)); + Assert.False(contents.IsDirty); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void An_indirect_length_that_is_wrong_falls_back_to_endstream_with_a_diagnostic_on_the_stream() + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Length 3 0 R >>\nstream\nabc\nendstream", + "99")); + + CosStream stream = Assert.IsType(document.Resolve(new CosReference(2, 0))); + + Assert.Equal("abc", Encoding.Latin1.GetString(stream.EncodedData.Span)); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("StreamLengthInvalid", diagnostic.Code); + Assert.Equal(new CosReference(2, 0), diagnostic.ObjectReference); + } + + [Fact] + public void An_entry_whose_offset_does_not_hold_the_object_reads_as_null_with_a_diagnostic() + { + byte[] file = new TestPdf().Build("<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>", "(three)"); + string text = Encoding.Latin1.GetString(file); + int third = text.IndexOf("3 0 obj", StringComparison.Ordinal); + text = text.Replace($"{third:D10} 00000 n", $"{third + 1:D10} 00000 n", StringComparison.Ordinal); + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + + Assert.Same(CosNull.Instance, document.Resolve(new CosReference(3, 0))); + Assert.Same(CosNull.Instance, document.Resolve(new CosReference(3, 0))); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("XrefEntryOffsetInvalid", diagnostic.Code); + Assert.Equal(new CosReference(3, 0), diagnostic.ObjectReference); + Assert.Equal(third + 1, diagnostic.Offset); + } + + [Fact] + public void An_object_without_endobj_is_read_with_a_diagnostic() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("missing-endobj.pdf")); + + Assert.Equal(new PdfRectangle(0, 0, 612, 792), Assert.Single(document.Pages).MediaBox); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("MissingEndobj", diagnostic.Code); + Assert.Equal(new CosReference(3, 0), diagnostic.ObjectReference); + } + + private static byte[] WithTrailerEntries(Func entries) + { + byte[] probe = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>"); + int xref = Encoding.Latin1.GetString(probe).IndexOf("xref", StringComparison.Ordinal); + return new TestPdf { TrailerEntries = entries(xref) }.Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>"); + } +} diff --git a/tests/Broadside.Tests/Document/OpenDocumentTests.cs b/tests/Broadside.Tests/Document/OpenDocumentTests.cs new file mode 100644 index 00000000..cc6145f8 --- /dev/null +++ b/tests/Broadside.Tests/Document/OpenDocumentTests.cs @@ -0,0 +1,96 @@ +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// Where a test opens a file from. +public enum SourceKind +{ + Path, + Stream, + Bytes, +} + +/// Opening a well-formed file through the public document API. ISO 32000-2 §7.5.1 to §7.5.5, §7.7.2, §7.7.3. +public class OpenDocumentTests +{ + public static TheoryData AcceptanceFilesBySource => new() + { + { "empty-page.pdf", SourceKind.Path }, + { "empty-page.pdf", SourceKind.Stream }, + { "empty-page.pdf", SourceKind.Bytes }, + { "pdf20-header.pdf", SourceKind.Path }, + { "pdf20-header.pdf", SourceKind.Stream }, + { "pdf20-header.pdf", SourceKind.Bytes }, + { "page-tree-inherited.pdf", SourceKind.Path }, + { "page-tree-inherited.pdf", SourceKind.Stream }, + { "page-tree-inherited.pdf", SourceKind.Bytes }, + }; + + [Fact] + public void Empty_page_pdf_has_one_letter_page_and_no_diagnostics() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + + PdfPage page = Assert.Single(document.Pages); + Assert.Equal(new PdfRectangle(0, 0, 612, 792), page.MediaBox); + Assert.Equal(new PdfVersion(1, 7), document.Version); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [MemberData(nameof(AcceptanceFilesBySource))] + public void A_file_opens_identically_from_a_path_a_stream_and_bytes_with_no_diagnostics(string fileName, SourceKind kind) + { + using PdfDocument fromPath = PdfDocument.Open(Corpus.Path(fileName)); + using PdfDocument document = Open(fileName, kind); + + Assert.Equal(DocumentProjection.Of(fromPath), DocumentProjection.Of(document)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Page_tree_inherited_pdf_pages_inherit_media_box_and_resources_from_the_intermediate_node() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("page-tree-inherited.pdf")); + + Assert.Equal(2, document.Pages.Count); + var intermediate = (CosDictionary)document.Resolve(new CosReference(3, 0)); + CosObject nodeResources = intermediate[new CosName("Resources")]; + foreach (PdfPage page in document.Pages) + { + Assert.False(page.Dictionary.ContainsKey(new CosName("MediaBox"))); + Assert.Equal(new PdfRectangle(0, 0, 612, 792), page.MediaBox); + Assert.Same(nodeResources, page.Resources); + } + + Assert.Equal([new CosReference(4, 0), new CosReference(5, 0)], document.Pages.Select(static page => page.Reference)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Pdf20_header_pdf_reports_version_2_0() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("pdf20-header.pdf")); + + Assert.Equal(new PdfVersion(2, 0), document.Version); + Assert.Equal("2.0", document.Version.ToString()); + } + + private static PdfDocument Open(string fileName, SourceKind kind) + { + switch (kind) + { + case SourceKind.Path: + return PdfDocument.Open(Corpus.Path(fileName)); + case SourceKind.Stream: + using (FileStream stream = Corpus.Open(fileName)) + { + return PdfDocument.Open(stream); + } + + default: + return PdfDocument.Open(Corpus.Bytes(fileName)); + } + } +} diff --git a/tests/Broadside.Tests/Document/PageAttributeTests.cs b/tests/Broadside.Tests/Document/PageAttributeTests.cs new file mode 100644 index 00000000..1e9d279d --- /dev/null +++ b/tests/Broadside.Tests/Document/PageAttributeTests.cs @@ -0,0 +1,190 @@ +using Broadside.Diagnostics; +using Broadside.Objects; + +namespace Broadside.Tests.Document; + +/// +/// Page boundaries, rotation and user unit with the defaults the specification defines. ISO 32000-2 §7.7.3.3 Table 31, §7.9.5, +/// §14.11.2. +/// +public class PageAttributeTests +{ + private static readonly PdfRectangle Letter = new(0, 0, 612, 792); + + [Fact] + public void Crop_bleed_trim_and_art_boxes_default_to_the_media_box_through_the_crop_box() + { + PdfPage page = SinglePage("/MediaBox [0 0 612 792]", out PdfDocument document); + using (document) + { + Assert.Equal(Letter, page.CropBox); + Assert.Equal(Letter, page.BleedBox); + Assert.Equal(Letter, page.TrimBox); + Assert.Equal(Letter, page.ArtBox); + Assert.Equal(0, page.Rotation); + Assert.Equal(1.0, page.UserUnit); + Assert.Empty(document.Diagnostics); + } + } + + [Fact] + public void Bleed_trim_and_art_boxes_default_to_the_crop_box() + { + PdfPage page = SinglePage("/MediaBox [0 0 612 792] /CropBox [10 20 600 780]", out PdfDocument document); + using (document) + { + var crop = new PdfRectangle(10, 20, 600, 780); + Assert.Equal(crop, page.CropBox); + Assert.Equal(crop, page.BleedBox); + Assert.Equal(crop, page.TrimBox); + Assert.Equal(crop, page.ArtBox); + } + } + + [Fact] + public void Each_box_reads_its_own_entry() + { + PdfPage page = SinglePage( + "/MediaBox [0 0 612 792] /CropBox [5 5 607 787] /BleedBox [6 6 606 786] /TrimBox [7 7 605 785] /ArtBox [8 8 604 784] /UserUnit 2.5", + out PdfDocument document); + using (document) + { + Assert.Equal(new PdfRectangle(5, 5, 607, 787), page.CropBox); + Assert.Equal(new PdfRectangle(6, 6, 606, 786), page.BleedBox); + Assert.Equal(new PdfRectangle(7, 7, 605, 785), page.TrimBox); + Assert.Equal(new PdfRectangle(8, 8, 604, 784), page.ArtBox); + Assert.Equal(2.5, page.UserUnit); + Assert.Empty(document.Diagnostics); + } + } + + [Fact] + public void Rectangles_given_by_any_two_opposite_corners_are_normalized() + { + PdfPage page = SinglePage("/MediaBox [612 792 0 0] /CropBox [600 20 10 780]", out PdfDocument document); + using (document) + { + Assert.Equal(Letter, page.MediaBox); + Assert.Equal(new PdfRectangle(10, 20, 600, 780), page.CropBox); + Assert.Equal(10, page.CropBox.Left); + Assert.Equal(780, page.CropBox.Top); + Assert.Equal(590, page.CropBox.Width); + Assert.Empty(document.Diagnostics); + } + } + + [Fact] + public void Boxes_that_extend_beyond_the_media_box_are_reduced_to_their_intersection_with_it() + { + PdfPage page = SinglePage("/MediaBox [0 0 612 792] /CropBox [-10 -10 700 400] /TrimBox [500 700 900 900]", out PdfDocument document); + using (document) + { + Assert.Equal(new PdfRectangle(0, 0, 612, 400), page.CropBox); + Assert.Equal(new PdfRectangle(500, 700, 612, 792), page.TrimBox); + Assert.Empty(document.Diagnostics); + } + } + + [Fact] + public void A_missing_media_box_reads_as_us_letter_with_a_diagnostic() + { + PdfPage page = SinglePage(string.Empty, out PdfDocument document); + using (document) + { + Assert.Equal(Letter, page.MediaBox); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("PageMediaBoxMissing", diagnostic.Code); + Assert.Equal(new CosReference(3, 0), diagnostic.ObjectReference); + } + } + + [Fact] + public void A_malformed_box_reads_as_its_default_with_a_diagnostic() + { + PdfPage page = SinglePage("/MediaBox [0 0 612 792] /CropBox [0 0 100]", out PdfDocument document); + using (document) + { + Assert.Equal(Letter, page.CropBox); + Assert.Equal("PageBoxInvalid", Assert.Single(document.Diagnostics).Code); + } + } + + [Fact] + public void A_box_and_its_numbers_may_be_indirect_objects() + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox 4 0 R >>", + "[0 0 5 0 R 842]", + "595")); + + Assert.Equal(new PdfRectangle(0, 0, 595, 842), Assert.Single(document.Pages).MediaBox); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [InlineData("0", 0)] + [InlineData("90", 90)] + [InlineData("180", 180)] + [InlineData("270", 270)] + [InlineData("-90", 270)] + [InlineData("450", 90)] + [InlineData("-720", 0)] + public void Rotation_is_a_multiple_of_90_normalized_into_0_to_270(string rotate, int expected) + { + PdfPage page = SinglePage($"/MediaBox [0 0 612 792] /Rotate {rotate}", out PdfDocument document); + using (document) + { + Assert.Equal(expected, page.Rotation); + Assert.Empty(document.Diagnostics); + } + } + + [Theory] + [InlineData("45", 0)] + [InlineData("/Ninety", 0)] + [InlineData("90.0", 90)] + public void A_rotation_that_is_not_an_integer_multiple_of_90_is_reported(string rotate, int expected) + { + PdfPage page = SinglePage($"/MediaBox [0 0 612 792] /Rotate {rotate}", out PdfDocument document); + using (document) + { + Assert.Equal(expected, page.Rotation); + Assert.Equal("PageRotateInvalid", Assert.Single(document.Diagnostics).Code); + } + } + + [Fact] + public void A_user_unit_that_is_not_positive_reads_as_1_with_a_diagnostic() + { + PdfPage page = SinglePage("/MediaBox [0 0 612 792] /UserUnit -2", out PdfDocument document); + using (document) + { + Assert.Equal(1.0, page.UserUnit); + Assert.Equal("PageUserUnitInvalid", Assert.Single(document.Diagnostics).Code); + } + } + + [Fact] + public void A_page_is_a_live_view_a_change_to_its_dictionary_shows_at_once() + { + PdfPage page = SinglePage("/MediaBox [0 0 612 792]", out PdfDocument document); + using (document) + { + page.Dictionary[new CosName("MediaBox")] = new CosArray([new CosInteger(0), new CosInteger(0), new CosInteger(595), new CosInteger(842)]); + page.Dictionary[new CosName("Rotate")] = new CosInteger(90); + + Assert.Equal(new PdfRectangle(0, 0, 595, 842), page.MediaBox); + Assert.Equal(new PdfRectangle(0, 0, 595, 842), page.ArtBox); + Assert.Equal(90, page.Rotation); + Assert.True(page.Dictionary.IsDirty); + } + } + + private static PdfPage SinglePage(string pageEntries, out PdfDocument document) + { + document = PdfDocument.Open(TestPdf.OnePage(pageEntries)); + return Assert.Single(document.Pages); + } +} diff --git a/tests/Broadside.Tests/Document/PageTreeTests.cs b/tests/Broadside.Tests/Document/PageTreeTests.cs new file mode 100644 index 00000000..07ab7435 --- /dev/null +++ b/tests/Broadside.Tests/Document/PageTreeTests.cs @@ -0,0 +1,162 @@ +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// Walking the page tree and inheriting page attributes. ISO 32000-2 §7.7.3.1 to §7.7.3.4. +public class PageTreeTests +{ + [Fact] + public void Pages_come_in_kids_order_depth_first_across_intermediate_nodes() + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R 6 0 R] /Count 3 /MediaBox [0 0 100 100] >>", + "<< /Type /Pages /Parent 2 0 R /Kids [4 0 R 5 0 R] /Count 2 >>", + "<< /Type /Page /Parent 3 0 R /Resources << >> /UserUnit 1 >>", + "<< /Type /Page /Parent 3 0 R /Resources << >> /UserUnit 2 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /UserUnit 3 >>")); + + Assert.Equal([1.0, 2.0, 3.0], document.Pages.Select(static page => page.UserUnit)); + Assert.Equal(new PdfRectangle(0, 0, 100, 100), document.Pages[2].MediaBox); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void The_nearest_ancestor_wins_and_values_are_inherited_as_is_without_merging() + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 2 /Rotate 90 /MediaBox [0 0 100 100] /Resources << /Font << /F1 7 0 R >> >> >>", + "<< /Type /Pages /Parent 2 0 R /Kids [4 0 R 5 0 R] /Count 2 /Rotate 180 /Resources << /XObject << >> >> >>", + "<< /Type /Page /Parent 3 0 R >>", + "<< /Type /Page /Parent 3 0 R /Rotate 270 /MediaBox [0 0 50 50] /Resources << >> >>", + "null", + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>")); + + PdfPage first = document.Pages[0]; + Assert.Equal(180, first.Rotation); + Assert.Equal(new PdfRectangle(0, 0, 100, 100), first.MediaBox); + CosDictionary resources = Assert.IsType(first.Resources); + Assert.True(resources.ContainsKey(new CosName("XObject"))); + Assert.False(resources.ContainsKey(new CosName("Font"))); + + PdfPage second = document.Pages[1]; + Assert.Equal(270, second.Rotation); + Assert.Equal(new PdfRectangle(0, 0, 50, 50), second.MediaBox); + Assert.Empty(Assert.IsType(second.Resources)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_change_to_an_ancestor_node_shows_through_the_pages_that_inherit_from_it() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("page-tree-inherited.pdf")); + PdfPage page = document.Pages[1]; + + var node = (CosDictionary)document.Resolve(new CosReference(3, 0)); + node[new CosName("MediaBox")] = new CosArray([new CosInteger(0), new CosInteger(0), new CosInteger(595), new CosInteger(842)]); + node[new CosName("Rotate")] = new CosInteger(-90); + + Assert.Equal(new PdfRectangle(0, 0, 595, 842), page.MediaBox); + Assert.Equal(270, page.Rotation); + } + + [Fact] + public void Page_count_comes_from_the_kids_not_the_count_entry_which_is_checked() + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 5 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>")); + + Assert.Single(document.Pages); + Assert.Equal("PageTreeCountMismatch", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_node_referenced_twice_is_read_once_with_a_diagnostic() + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R 3 0 R 2 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>")); + + Assert.Single(document.Pages); + Assert.Equal(["PageTreeCycle", "PageTreeCycle"], document.Diagnostics.Select(static diagnostic => diagnostic.Code)); + } + + [Fact] + public void Nodes_without_a_type_are_pages_when_they_have_no_kids_and_nodes_when_they_do() + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Kids [3 0 R] /Count 1 >>", + "<< /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>")); + + PdfPage page = Assert.Single(document.Pages); + Assert.Equal(new CosReference(3, 0), page.Reference); + Assert.Equal(["PageTreeNodeTypeInvalid", "PageTreeNodeTypeInvalid"], document.Diagnostics.Select(static diagnostic => diagnostic.Code)); + } + + [Fact] + public void A_root_that_is_itself_a_page_is_the_only_page() + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Page /Resources << >> /MediaBox [0 0 612 792] >>")); + + Assert.Equal(new CosReference(2, 0), Assert.Single(document.Pages).Reference); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Kids_that_are_direct_dictionaries_are_used_and_kids_that_are_not_dictionaries_are_skipped() + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 10 10] >> 9 0 R 3 0 R (text)] /Count 2 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>")); + + Assert.Equal(2, document.Pages.Count); + Assert.Null(document.Pages[0].Reference); + Assert.Equal(new PdfRectangle(0, 0, 10, 10), document.Pages[0].MediaBox); + Assert.Equal( + ["PageTreeKidNotIndirect", "PageTreeKidInvalid", "PageTreeKidInvalid"], + document.Diagnostics.Select(static diagnostic => diagnostic.Code)); + } + + [Fact] + public void A_parent_entry_that_disagrees_with_the_tree_is_reported_and_the_tree_wins() + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>", + "<< /Type /Page /Parent 4 0 R /Resources << >> >>", + "<< /Type /Pages /Kids [] /Count 0 /MediaBox [0 0 1 1] >>")); + + Assert.Equal(new PdfRectangle(0, 0, 612, 792), Assert.Single(document.Pages).MediaBox); + Assert.Equal("PageTreeParentMismatch", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_catalog_without_pages_has_no_pages_and_a_diagnostic() + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build("<< /Type /Catalog >>")); + + Assert.Empty(document.Pages); + Assert.Equal("PagesMissing", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_page_without_resources_on_itself_or_an_ancestor_is_reported() + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>")); + + Assert.Null(Assert.Single(document.Pages).Resources); + Assert.Equal("PageResourcesMissing", Assert.Single(document.Diagnostics).Code); + } +} diff --git a/tests/Broadside.Tests/Document/TestPdf.cs b/tests/Broadside.Tests/Document/TestPdf.cs new file mode 100644 index 00000000..19616348 --- /dev/null +++ b/tests/Broadside.Tests/Document/TestPdf.cs @@ -0,0 +1,51 @@ +using System.Globalization; +using System.Text; + +namespace Broadside.Tests.Document; + +/// +/// Builds a small, classic-xref PDF in memory for a test that needs one variation the corpus does not have. Object i of the +/// objects list is written as object number i + 1; the trailer's Root is object 1. Offsets are computed from the header, +/// so a before it exercises ISO 32000-2 §7.5.2 (offsets count from the percent sign of %PDF-). +/// +internal sealed class TestPdf +{ + /// Gets the header line, without its end-of-line marker. + public string Header { get; init; } = "%PDF-1.7"; + + /// Gets bytes written before the header. + public string Prefix { get; init; } = string.Empty; + + /// Gets extra trailer entries, written after /Size and /Root. + public string TrailerEntries { get; init; } = string.Empty; + + /// A catalog, a page tree root and one page with the given extra page entries: the shape most tests vary. + public static byte[] OnePage(string pageEntries, string catalogEntries = "", string header = "%PDF-1.7") => + new TestPdf { Header = header }.Build( + $"<< /Type /Catalog /Pages 2 0 R {catalogEntries} >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + $"<< /Type /Page /Parent 2 0 R /Resources << >> {pageEntries} >>"); + + /// Writes the file. + public byte[] Build(params string[] objects) + { + var text = new StringBuilder(); + text.Append(Prefix).Append(Header).Append('\n'); + var offsets = new List(); + for (int index = 0; index < objects.Length; index++) + { + offsets.Add(text.Length - Prefix.Length); + text.Append(CultureInfo.InvariantCulture, $"{index + 1} 0 obj\n{objects[index]}\nendobj\n"); + } + + int xref = text.Length - Prefix.Length; + text.Append(CultureInfo.InvariantCulture, $"xref\n0 {objects.Length + 1}\n0000000000 65535 f \n"); + foreach (int offset in offsets) + { + text.Append(CultureInfo.InvariantCulture, $"{offset:D10} 00000 n \n"); + } + + text.Append(CultureInfo.InvariantCulture, $"trailer\n<< /Size {objects.Length + 1} /Root 1 0 R {TrailerEntries} >>\nstartxref\n{xref}\n%%EOF\n"); + return Encoding.Latin1.GetBytes(text.ToString()); + } +} diff --git a/tests/Broadside.Tests/Document/VersionTests.cs b/tests/Broadside.Tests/Document/VersionTests.cs new file mode 100644 index 00000000..2f7a9b8b --- /dev/null +++ b/tests/Broadside.Tests/Document/VersionTests.cs @@ -0,0 +1,72 @@ +using Broadside.Diagnostics; +using Broadside.Objects; + +namespace Broadside.Tests.Document; + +/// The document's effective version: the header's, overridden by the catalog's Version when later. ISO 32000-2 §7.5.2, §7.7.2 Table 29. +public class VersionTests +{ + [Theory] + [InlineData("%PDF-1.4", "/Version /1.7", "1.7")] + [InlineData("%PDF-1.7", "/Version /1.4", "1.7")] + [InlineData("%PDF-1.7", "/Version /2.0", "2.0")] + [InlineData("%PDF-2.0", "", "2.0")] + [InlineData("%PDF-1.0", "", "1.0")] + public void The_catalog_version_overrides_the_header_only_when_later(string header, string catalogEntries, string expected) + { + using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", catalogEntries, header)); + + Assert.Equal(expected, document.Version.ToString()); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Versions_compare_numerically_on_major_then_minor() + { + Assert.True(new PdfVersion(1, 10) > new PdfVersion(1, 9)); + Assert.True(new PdfVersion(2, 0) > new PdfVersion(1, 7)); + Assert.True(new PdfVersion(1, 4) <= new PdfVersion(1, 4)); + Assert.NotEqual(new PdfVersion(1, 7), new PdfVersion(1, 4)); + } + + [Fact] + public void A_catalog_version_written_as_a_number_is_read_with_a_diagnostic() + { + using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", "/Version 1.7", "%PDF-1.4")); + + Assert.Equal(new PdfVersion(1, 7), document.Version); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("CatalogVersionNotName", diagnostic.Code); + Assert.Equal(new CosReference(1, 0), diagnostic.ObjectReference); + } + + [Fact] + public void A_malformed_catalog_version_is_ignored_with_a_diagnostic() + { + using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", "/Version /latest", "%PDF-1.6")); + + Assert.Equal(new PdfVersion(1, 6), document.Version); + Assert.Equal("CatalogVersionInvalid", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_header_without_a_valid_version_takes_the_catalog_version_with_a_diagnostic() + { + using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", "/Version /1.5", "%PDF-x.y")); + + Assert.Equal(new PdfVersion(1, 5), document.Version); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("HeaderVersionInvalid", diagnostic.Code); + Assert.Equal(0, diagnostic.Offset); + } + + [Fact] + public void The_version_is_read_from_the_catalog_on_every_call() + { + using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", header: "%PDF-1.4")); + + document.Catalog[new CosName("Version")] = new CosName("1.6"); + + Assert.Equal(new PdfVersion(1, 6), document.Version); + } +} diff --git a/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs b/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs new file mode 100644 index 00000000..fe69dc73 --- /dev/null +++ b/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs @@ -0,0 +1,47 @@ +using Broadside.Diagnostics; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// +/// Every well-formed corpus file opens with zero diagnostics (tests/Corpus/README.md, "Well-formed files"; ADR 0005): a diagnostic +/// means a "shall" was violated or data was repaired, never that a "should" was not followed. ISO 32000-2 §7.5, §7.7. +/// +public class WellFormedCorpusTests +{ + /// Files whose only cross-reference section is a stream; issue #39 reads them and removes this list. + private static readonly string[] CrossReferenceStreamFiles = ["xref-stream.pdf", "object-stream.pdf", "png-predictor.pdf"]; + + internal static bool NeedsCrossReferenceStreams(string fileName) => CrossReferenceStreamFiles.Contains(fileName); + + [Theory] + [MemberData(nameof(Corpus.WellFormedFiles), MemberType = typeof(Corpus))] + public void A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics(string fileName) + { + Assert.SkipWhen(NeedsCrossReferenceStreams(fileName), "Needs cross-reference streams (#39)."); + + using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName)); + + int expectedPages = fileName == "page-tree-inherited.pdf" ? 2 : 1; + Assert.Equal(expectedPages, document.Pages.Count); + foreach (PdfPage page in document.Pages) + { + Assert.True(page.MediaBox.Width > 0 && page.MediaBox.Height > 0); + Assert.NotNull(page.Resources); + } + + Assert.Empty(document.Diagnostics); + } + + [Theory] + [InlineData("xref-stream.pdf")] + [InlineData("object-stream.pdf")] + [InlineData("png-predictor.pdf")] + public void A_file_with_only_a_cross_reference_stream_is_not_readable_yet(string fileName) + { + // Pins the boundary of this version: issue #39 turns this into a successful open and deletes the test. + DiagnosticException error = Assert.Throws(() => PdfDocument.Open(Corpus.Path(fileName))); + + Assert.Equal("XrefStreamUnsupported", error.Diagnostic.Code); + } +} From 100394d2d316f200002b0d8dc81c12cf9a9b7538 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:19:29 -0500 Subject: [PATCH 004/152] feat(hosting): dependency injection parity (#46) AddBroadside registers one PdfEngine singleton built from PdfOptions through the options pattern (TryAddSingleton, so a second call only adds its configure delegate). The engine's new PdfEngine(IOptions, ILoggerFactory?) constructor snapshots IOptions.Value once through the same EngineConfiguration.From the fluent path uses, so both open documents through one code path. Diagnostics are also logged through source-generated [LoggerMessage] methods (category Broadside.PdfDocument, event 1 "Diagnostic", Warning or Error after the severity), via the DiagnosticSink observer, before strict mode throws. PdfOptions.WithLoggerFactory lets the static path log too and wins over the container's factory. No observer is installed without a logger factory. The core keeps referencing only DI.Abstractions, Logging.Abstractions and Options; hosts bind configuration with their own Options.ConfigurationExtensions. Test-only packages: DependencyInjection, Logging, Configuration, Options.ConfigurationExtensions. Co-Authored-By: Claude Opus 5.5 --- Directory.Packages.props | 5 + .../BroadsideServiceCollectionExtensions.cs | 57 +++++ src/Broadside/Diagnostics/DiagnosticLog.cs | 51 ++++ src/Broadside/EngineConfiguration.cs | 15 +- src/Broadside/PdfDocument.cs | 2 +- src/Broadside/PdfEngine.cs | 23 ++ src/Broadside/PdfOptions.cs | 24 ++ src/Broadside/PublicAPI.Unshipped.txt | 5 + tests/Broadside.Tests/Broadside.Tests.csproj | 4 + .../Hosting/CapturingLoggerProvider.cs | 43 ++++ .../Hosting/DependencyInjectionTests.cs | 239 ++++++++++++++++++ 11 files changed, 466 insertions(+), 2 deletions(-) create mode 100644 src/Broadside/BroadsideServiceCollectionExtensions.cs create mode 100644 src/Broadside/Diagnostics/DiagnosticLog.cs create mode 100644 tests/Broadside.Tests/Hosting/CapturingLoggerProvider.cs create mode 100644 tests/Broadside.Tests/Hosting/DependencyInjectionTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index b630c192..b1c4693d 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -33,6 +33,11 @@ + + + + + diff --git a/src/Broadside/BroadsideServiceCollectionExtensions.cs b/src/Broadside/BroadsideServiceCollectionExtensions.cs new file mode 100644 index 00000000..b4b110fc --- /dev/null +++ b/src/Broadside/BroadsideServiceCollectionExtensions.cs @@ -0,0 +1,57 @@ +using Broadside; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +// The registration lives in the container's namespace, as the Microsoft.Extensions convention asks, so AddBroadside is found +// next to AddLogging and AddOptions without another using directive. +#pragma warning disable IDE0130 // Namespace does not match folder structure +namespace Microsoft.Extensions.DependencyInjection; +#pragma warning restore IDE0130 + +/// Registers Broadside with a dependency-injection container. +/// +/// +/// Spec #33, user stories 43 to 45: a hosted application gets one , a singleton, built from the same +/// the fluent entry point takes, so it opens documents exactly as +/// does. Nothing is registered globally: two containers hold two independent engines. +/// +/// +/// The options go through the options pattern, so configuration delegates run in registration order and post-configuration runs +/// last. To bind them from configuration, the host adds its own binding, for instance +/// services.AddOptions<PdfOptions>().BindConfiguration("Broadside") from +/// Microsoft.Extensions.Options.ConfigurationExtensions. When the container has an , every +/// diagnostic is also logged through it. Documents are not registered: the caller opens and disposes them. +/// +/// +public static class BroadsideServiceCollectionExtensions +{ + /// Registers the singleton and its , with default options. + /// The service collection. + /// , for chaining. + public static IServiceCollection AddBroadside(this IServiceCollection services) + { + ArgumentNullException.ThrowIfNull(services); + services.AddOptions(); + services.TryAddSingleton(static provider => new PdfEngine( + provider.GetRequiredService>(), + provider.GetService())); + return services; + } + + /// + /// Registers the singleton and its , configured by . + /// + /// The service collection. + /// + /// Sets the options fluently, as on the static entry point, for instance options => options.UseStrict(). Calling + /// AddBroadside again registers no second engine; it adds its delegate, which runs after this one. + /// + /// , for chaining. + public static IServiceCollection AddBroadside(this IServiceCollection services, Action configure) + { + ArgumentNullException.ThrowIfNull(configure); + services.AddBroadside().Configure(configure); + return services; + } +} diff --git a/src/Broadside/Diagnostics/DiagnosticLog.cs b/src/Broadside/Diagnostics/DiagnosticLog.cs new file mode 100644 index 00000000..88da980f --- /dev/null +++ b/src/Broadside/Diagnostics/DiagnosticLog.cs @@ -0,0 +1,51 @@ +using Broadside.Objects; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Broadside.Diagnostics; + +/// +/// Logs diagnostics through the logging abstractions, in addition to recording them on the document (ADR 0005; spec #33, user +/// story 45). The log methods are source-generated, so nothing is formatted or boxed unless the level is enabled. +/// +internal static partial class DiagnosticLog +{ + /// The logging category: diagnostics belong to the document being read. + public const string Category = "Broadside.PdfDocument"; + + /// Returns the observer an engine hands every document's diagnostic sink, or when nothing logs. + /// The logger factory, or . + /// The observer. The logger is created once, here, per engine. + public static Action? CreateObserver(ILoggerFactory? loggerFactory) + { + if (loggerFactory is null or NullLoggerFactory) + { + return null; + } + + ILogger logger = loggerFactory.CreateLogger(Category); + return diagnostic => Log(logger, diagnostic); + } + + /// Logs at the level its severity maps to. + /// The logger. + /// The diagnostic. + public static void Log(ILogger logger, Diagnostic diagnostic) => DiagnosticRecorded( + logger, + diagnostic.Severity == DiagnosticSeverity.Error ? LogLevel.Error : LogLevel.Warning, + diagnostic.Severity, + diagnostic.Code, + diagnostic.ObjectReference, + diagnostic.Offset, + diagnostic.Message); + + [LoggerMessage(EventId = 1, EventName = "Diagnostic", Message = "{Severity} {Code} in object {ObjectReference} at offset {Offset}: {Message}")] + private static partial void DiagnosticRecorded( + ILogger logger, + LogLevel level, + DiagnosticSeverity severity, + string code, + CosReference? objectReference, + long? offset, + string message); +} diff --git a/src/Broadside/EngineConfiguration.cs b/src/Broadside/EngineConfiguration.cs index c03f38e0..16e5082c 100644 --- a/src/Broadside/EngineConfiguration.cs +++ b/src/Broadside/EngineConfiguration.cs @@ -1,3 +1,6 @@ +using Broadside.Diagnostics; +using Microsoft.Extensions.Logging; + namespace Broadside; /// @@ -14,8 +17,18 @@ internal sealed class EngineConfiguration /// Gets how deviations are treated. public PdfReadingMode ReadingMode { get; } + /// + /// Gets what sees each diagnostic as it is recorded, before strict mode throws it: the logger, or when + /// nothing logs, so a document without logging pays nothing. + /// + public Action? DiagnosticObserver { get; private init; } + /// Copies the current values of . /// The options. + /// The container's logger factory, used when the options set none. /// The snapshot. - public static EngineConfiguration From(PdfOptions options) => new(options.ReadingMode); + public static EngineConfiguration From(PdfOptions options, ILoggerFactory? hostLoggerFactory = null) => new(options.ReadingMode) + { + DiagnosticObserver = DiagnosticLog.CreateObserver(options.LoggerFactory ?? hostLoggerFactory), + }; } diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 7d8beeba..b65d6842 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -152,7 +152,7 @@ internal static PdfDocument Read(PdfSource source, EngineConfiguration configura { try { - var diagnostics = new DiagnosticSink(configuration.ReadingMode == PdfReadingMode.Strict); + var diagnostics = new DiagnosticSink(configuration.ReadingMode == PdfReadingMode.Strict, configuration.DiagnosticObserver); FileHeader header = FileHeader.Locate(source, diagnostics); CrossReference crossReference = CrossReferenceReader.Read(source, header, diagnostics) ?? Reconstruct(diagnostics); var loader = new ObjectLoader(source, header, crossReference, diagnostics, new ObjectLoaderHooks()); diff --git a/src/Broadside/PdfEngine.cs b/src/Broadside/PdfEngine.cs index c4abbdb9..cc6fecb7 100644 --- a/src/Broadside/PdfEngine.cs +++ b/src/Broadside/PdfEngine.cs @@ -1,4 +1,6 @@ using Broadside.IO; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; namespace Broadside; @@ -28,6 +30,27 @@ public PdfEngine(PdfOptions options) _configuration = EngineConfiguration.From(options); } + /// + /// Initializes a new instance of the class from the options pattern: the constructor dependency injection + /// uses, which + /// registers. + /// + /// + /// The options. Their is read once, here, and copied, so the engine behaves exactly like + /// one built with from the same values. + /// + /// + /// Where diagnostics are logged, unless the options name their own logger factory through + /// ; logs nothing. + /// + /// Spec #33, user stories 43 and 45: one engine for the fluent and the hosted paths. + public PdfEngine(IOptions options, ILoggerFactory? loggerFactory = null) + { + ArgumentNullException.ThrowIfNull(options); + PdfOptions value = options.Value ?? throw new ArgumentException("The options have no value.", nameof(options)); + _configuration = EngineConfiguration.From(value, loggerFactory); + } + /// Gets the engine the static entry points use when no options are given: default options, no state. internal static PdfEngine Default { get; } = new(); diff --git a/src/Broadside/PdfOptions.cs b/src/Broadside/PdfOptions.cs index f78cc55c..087fe0a3 100644 --- a/src/Broadside/PdfOptions.cs +++ b/src/Broadside/PdfOptions.cs @@ -1,3 +1,5 @@ +using Microsoft.Extensions.Logging; + namespace Broadside; /// @@ -29,4 +31,26 @@ public PdfOptions UseStrict() ReadingMode = PdfReadingMode.Strict; return this; } + + /// Gets the logger factory set by , or . + /// Not a property, so configuration binding never sees it. + internal ILoggerFactory? LoggerFactory { get; private set; } + + /// + /// Logs every diagnostic through as well as recording it on the document. Without it, an engine + /// built through dependency injection logs through the container's logger factory and any other engine logs nothing. + /// + /// The logger factory, or to use the container's or none. + /// These options. + /// + /// ADR 0005 and spec #33, user story 45. Diagnostics are logged under the category Broadside.PdfDocument with event id 1, + /// Diagnostic, at or after their severity, with the structured + /// values Code, Severity, Offset, ObjectReference and Message. In strict mode the deviation is + /// logged before it is thrown. + /// + public PdfOptions WithLoggerFactory(ILoggerFactory? loggerFactory) + { + LoggerFactory = loggerFactory; + return this; + } } diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index 6b193443..b701fa46 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -186,3 +186,8 @@ static Broadside.PdfVersion.operator <=(Broadside.PdfVersion left, Broadside.Pdf static Broadside.PdfVersion.operator ==(Broadside.PdfVersion left, Broadside.PdfVersion right) -> bool static Broadside.PdfVersion.operator >(Broadside.PdfVersion left, Broadside.PdfVersion right) -> bool static Broadside.PdfVersion.operator >=(Broadside.PdfVersion left, Broadside.PdfVersion right) -> bool +Broadside.PdfEngine.PdfEngine(Microsoft.Extensions.Options.IOptions! options, Microsoft.Extensions.Logging.ILoggerFactory? loggerFactory = null) -> void +Broadside.PdfOptions.WithLoggerFactory(Microsoft.Extensions.Logging.ILoggerFactory? loggerFactory) -> Broadside.PdfOptions! +Microsoft.Extensions.DependencyInjection.BroadsideServiceCollectionExtensions +static Microsoft.Extensions.DependencyInjection.BroadsideServiceCollectionExtensions.AddBroadside(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! +static Microsoft.Extensions.DependencyInjection.BroadsideServiceCollectionExtensions.AddBroadside(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, System.Action! configure) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! diff --git a/tests/Broadside.Tests/Broadside.Tests.csproj b/tests/Broadside.Tests/Broadside.Tests.csproj index b2914fb2..3211ca57 100644 --- a/tests/Broadside.Tests/Broadside.Tests.csproj +++ b/tests/Broadside.Tests/Broadside.Tests.csproj @@ -5,6 +5,10 @@ + + + + diff --git a/tests/Broadside.Tests/Hosting/CapturingLoggerProvider.cs b/tests/Broadside.Tests/Hosting/CapturingLoggerProvider.cs new file mode 100644 index 00000000..fe19023b --- /dev/null +++ b/tests/Broadside.Tests/Hosting/CapturingLoggerProvider.cs @@ -0,0 +1,43 @@ +using System.Collections.Concurrent; +using Microsoft.Extensions.Logging; + +namespace Broadside.Tests.Hosting; + +/// One log entry as a host's logging pipeline receives it, with the structured values the message template names. +internal sealed record LogEntry(string Category, LogLevel Level, EventId EventId, string Message, IReadOnlyDictionary State); + +/// A logger provider that keeps every entry it is given, so a test can assert what reached the pipeline. +internal sealed class CapturingLoggerProvider : ILoggerProvider +{ + private readonly ConcurrentQueue _entries = new(); + + public IReadOnlyList Entries => [.. _entries]; + + public ILogger CreateLogger(string categoryName) => new CapturingLogger(categoryName, _entries); + + public void Dispose() + { + } + + private sealed class CapturingLogger(string category, ConcurrentQueue entries) : ILogger + { + public IDisposable? BeginScope(TState state) + where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + var values = new Dictionary(); + if (state is IEnumerable> pairs) + { + foreach (KeyValuePair pair in pairs) + { + values[pair.Key] = pair.Value; + } + } + + entries.Enqueue(new LogEntry(category, logLevel, eventId, formatter(state, exception), values)); + } + } +} diff --git a/tests/Broadside.Tests/Hosting/DependencyInjectionTests.cs b/tests/Broadside.Tests/Hosting/DependencyInjectionTests.cs new file mode 100644 index 00000000..9d14fcae --- /dev/null +++ b/tests/Broadside.Tests/Hosting/DependencyInjectionTests.cs @@ -0,0 +1,239 @@ +using System.Reflection; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Tests.Document; +using Broadside.TestSupport; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace Broadside.Tests.Hosting; + +/// +/// A hosted application registers Broadside once and gets the same behavior as the static entry point, with options bound +/// through the options pattern and diagnostics logged to its pipeline (spec #33 user stories 43 to 45; issue #46; ADR 0005). +/// +public class DependencyInjectionTests +{ + [Theory] + [MemberData(nameof(Corpus.WellFormedFiles), MemberType = typeof(Corpus))] + public void The_registered_engine_and_the_static_entry_point_open_documents_identically(string fileName) + { + Assert.SkipWhen(WellFormedCorpusTests.NeedsCrossReferenceStreams(fileName), "Needs cross-reference streams (#39)."); + using ServiceProvider services = new ServiceCollection().AddBroadside().BuildServiceProvider(); + + using PdfDocument fromContainer = services.GetRequiredService().Open(Corpus.Bytes(fileName)); + using PdfDocument fromStatic = PdfDocument.Open(Corpus.Bytes(fileName)); + + Assert.Equal(DocumentProjection.Of(fromStatic), DocumentProjection.Of(fromContainer)); + Assert.Equal(fromStatic.Pages.Count, fromContainer.Pages.Count); + Assert.Empty(fromContainer.Diagnostics); + } + + [Fact] + public void The_registered_engine_and_the_static_entry_point_record_the_same_diagnostics_for_a_broken_file() + { + using ServiceProvider services = new ServiceCollection().AddBroadside().BuildServiceProvider(); + + using PdfDocument fromContainer = services.GetRequiredService().Open(Corpus.Bytes("missing-endobj.pdf")); + using PdfDocument fromStatic = PdfDocument.Open(Corpus.Bytes("missing-endobj.pdf")); + + Assert.Equal(DocumentProjection.Of(fromStatic), DocumentProjection.Of(fromContainer)); + Assert.Equal("MissingEndobj", Assert.Single(fromContainer.Diagnostics).Code); + } + + [Fact] + public void The_engine_is_one_singleton_even_when_registered_twice() + { + using ServiceProvider services = new ServiceCollection().AddBroadside().AddBroadside().BuildServiceProvider(); + + PdfEngine engine = Assert.Single(services.GetServices()); + Assert.Same(engine, services.GetRequiredService()); + } + + [Fact] + public void The_fluent_delegate_configures_the_registered_engine() + { + using ServiceProvider services = new ServiceCollection().AddBroadside(static options => options.UseStrict()).BuildServiceProvider(); + + using PdfDocument document = services.GetRequiredService().Open(TestPdf.OnePage(string.Empty)); + + DiagnosticException error = Assert.Throws(() => document.Pages.Count); + Assert.Equal("PageMediaBoxMissing", error.Diagnostic.Code); + } + + [Fact] + public void Configuration_delegates_and_bound_configuration_apply_in_registration_order_and_post_configuration_last() + { + IConfiguration strictSection = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary { ["Broadside:ReadingMode"] = "Strict" }) + .Build() + .GetSection("Broadside"); + + Assert.Equal(PdfReadingMode.Strict, ReadingModeOf(services => services.AddBroadside(static o => o.UseLenient()).Configure(strictSection))); + Assert.Equal(PdfReadingMode.Lenient, ReadingModeOf(services => services.Configure(strictSection).AddBroadside(static o => o.UseLenient()))); + Assert.Equal(PdfReadingMode.Lenient, ReadingModeOf(services => services.AddBroadside(static o => o.UseStrict()).AddBroadside(static o => o.UseLenient()))); + Assert.Equal( + PdfReadingMode.Lenient, + ReadingModeOf(services => services.PostConfigure(static o => o.UseLenient()).AddBroadside(static o => o.UseStrict()))); + } + + [Fact] + public void The_engine_reads_its_options_once_so_later_changes_do_not_affect_it() + { + using ServiceProvider services = new ServiceCollection().AddBroadside().BuildServiceProvider(); + PdfEngine engine = services.GetRequiredService(); + + services.GetRequiredService>().Value.UseStrict(); + using PdfDocument document = engine.Open(TestPdf.OnePage(string.Empty)); + + Assert.Single(document.Pages); + Assert.Equal("PageMediaBoxMissing", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void Engines_in_two_containers_and_the_static_entry_point_do_not_interfere() + { + using ServiceProvider strict = new ServiceCollection().AddBroadside(static o => o.UseStrict()).BuildServiceProvider(); + using ServiceProvider lenient = new ServiceCollection().AddBroadside().BuildServiceProvider(); + byte[] file = TestPdf.OnePage(string.Empty); + + using PdfDocument fromStrict = strict.GetRequiredService().Open(file); + using PdfDocument fromLenient = lenient.GetRequiredService().Open(file); + using PdfDocument fromStatic = PdfDocument.Open(file); + + Assert.Throws(() => fromStrict.Pages.Count); + Assert.Single(fromLenient.Pages); + Assert.Single(fromStatic.Pages); + } + + [Fact] + public void Each_diagnostic_is_also_logged_to_the_hosts_pipeline() + { + using var logs = new CapturingLoggerProvider(); + using ServiceProvider services = new ServiceCollection() + .AddLogging(logging => logging.AddProvider(logs)) + .AddBroadside() + .BuildServiceProvider(); + + using PdfDocument document = services.GetRequiredService().Open(Corpus.Bytes("missing-endobj.pdf")); + _ = document.Pages.Count; + + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + LogEntry entry = Assert.Single(logs.Entries); + Assert.Equal("Broadside.PdfDocument", entry.Category); + Assert.Equal(LogLevel.Warning, entry.Level); + Assert.Equal(new EventId(1, "Diagnostic"), entry.EventId); + Assert.Equal("MissingEndobj", entry.State["Code"]); + Assert.Equal(DiagnosticSeverity.Warning, entry.State["Severity"]); + Assert.Equal(new CosReference(3, 0), entry.State["ObjectReference"]); + Assert.Equal(diagnostic.Offset, entry.State["Offset"]); + Assert.Equal(diagnostic.Message, entry.State["Message"]); + Assert.Contains("MissingEndobj", entry.Message, StringComparison.Ordinal); + } + + [Fact] + public void Strict_mode_logs_the_deviation_before_throwing_it() + { + using var logs = new CapturingLoggerProvider(); + using ServiceProvider services = new ServiceCollection() + .AddLogging(logging => logging.AddProvider(logs)) + .AddBroadside(static options => options.UseStrict()) + .BuildServiceProvider(); + using PdfDocument document = services.GetRequiredService().Open(TestPdf.OnePage(string.Empty)); + + DiagnosticException error = Assert.Throws(() => document.Pages.Count); + + LogEntry entry = Assert.Single(logs.Entries); + Assert.Equal("PageMediaBoxMissing", entry.State["Code"]); + Assert.Equal(LogLevel.Error, entry.Level); + Assert.Equal(error.Diagnostic.Code, entry.State["Code"]); + } + + [Fact] + public void The_fluent_path_logs_through_a_logger_factory_set_on_the_options() + { + using var logs = new CapturingLoggerProvider(); + using var loggerFactory = LoggerFactory.Create(logging => logging.AddProvider(logs)); + + using PdfDocument document = PdfDocument.Open(TestPdf.OnePage(string.Empty), new PdfOptions().WithLoggerFactory(loggerFactory)); + _ = document.Pages.Count; + + LogEntry entry = Assert.Single(logs.Entries); + Assert.Equal("PageMediaBoxMissing", entry.State["Code"]); + Assert.Equal(LogLevel.Error, entry.Level); + } + + [Fact] + public void A_logger_factory_set_on_the_options_takes_precedence_over_the_containers() + { + using var containerLogs = new CapturingLoggerProvider(); + using var optionsLogs = new CapturingLoggerProvider(); + using var optionsLoggerFactory = LoggerFactory.Create(logging => logging.AddProvider(optionsLogs)); + using ServiceProvider services = new ServiceCollection() + .AddLogging(logging => logging.AddProvider(containerLogs)) + .AddBroadside(options => options.WithLoggerFactory(optionsLoggerFactory)) + .BuildServiceProvider(); + + using PdfDocument document = services.GetRequiredService().Open(TestPdf.OnePage(string.Empty)); + _ = document.Pages.Count; + + Assert.Single(optionsLogs.Entries); + Assert.Empty(containerLogs.Entries); + } + + [Fact] + public void Logging_below_the_enabled_level_records_the_diagnostic_on_the_document_only() + { + using var logs = new CapturingLoggerProvider(); + using ServiceProvider services = new ServiceCollection() + .AddLogging(logging => logging.AddProvider(logs).SetMinimumLevel(LogLevel.Critical)) + .AddBroadside() + .BuildServiceProvider(); + + using PdfDocument document = services.GetRequiredService().Open(TestPdf.OnePage(string.Empty)); + + Assert.Single(document.Pages); + Assert.Single(document.Diagnostics); + Assert.Empty(logs.Entries); + } + + [Fact] + public void The_core_references_only_the_base_library_and_the_Microsoft_abstractions_for_injection_options_and_logging() + { + string[] allowedExtensions = + [ + "Microsoft.Extensions.DependencyInjection.Abstractions", + "Microsoft.Extensions.Logging.Abstractions", + "Microsoft.Extensions.Options", + "Microsoft.Extensions.Primitives", + ]; + + AssemblyName[] references = typeof(PdfEngine).Assembly.GetReferencedAssemblies(); + + Assert.All(references, reference => Assert.True( + reference.Name is "System" or "netstandard" or "mscorlib" + || reference.Name!.StartsWith("System.", StringComparison.Ordinal) + || allowedExtensions.Contains(reference.Name), + $"The core references {reference.Name}, which ADR 0001 does not allow.")); + Assert.Contains(references, static reference => reference.Name == "Microsoft.Extensions.Logging.Abstractions"); + } + + private static PdfReadingMode ReadingModeOf(Action register) + { + var collection = new ServiceCollection(); + register(collection); + using ServiceProvider services = collection.BuildServiceProvider(); + using PdfDocument document = services.GetRequiredService().Open(TestPdf.OnePage(string.Empty)); + try + { + _ = document.Pages.Count; + return PdfReadingMode.Lenient; + } + catch (DiagnosticException) + { + return PdfReadingMode.Strict; + } + } +} From 0cc431104516f4f6855867c09461739d59eaf9ca Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:19:31 -0500 Subject: [PATCH 005/152] docs(conformance): correct ISO 32000-2 chapter 10, 12.10-12.11, 13.2 and annex titles The original skeleton was written from memory. Titles now match the spec's table of contents: chapter 10 rows were shifted by one, 12.10 is Geospatial features with Document requirements at 12.11, and the annex list is A-Q as published (Annex K XFA forms is n/a, parse-and-preserve). Found by the Phase 2 exploration. Co-Authored-By: Claude Opus 5.5 --- docs/conformance/iso-32000-2.md | 42 ++++++++++++++++----------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index 655fac59..ee815dcf 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -56,7 +56,7 @@ Clause numbers at the second level; split rows to the third level as clauses are | 8.10 | Form XObjects | not started | | | | | 8.11 | Optional content | not started | | | | | 9.1 | Text: General | not started | | | | -| 9.2 | Organization and use of fonts | not started | | | | +| 9.2 | Organisation and use of fonts | not started | | | | | 9.3 | Text state parameters and operators | not started | | | | | 9.4 | Text objects | not started | | | | | 9.5 | Introduction to font data structures | not started | | | | @@ -66,13 +66,13 @@ Clause numbers at the second level; split rows to the third level as clauses are | 9.9 | Embedded font programs | not started | | | | | 9.10 | Extraction of text content | not started | | | | | 10.1 | Rendering: General | not started | | | | -| 10.2 | CIE-based colour to device colour | not started | | | | -| 10.3 | Conversions among device colour spaces | not started | | | | -| 10.4 | Transfer functions | not started | | | | -| 10.5 | Halftones | not started | | | | -| 10.6 | Scan conversion details | not started | | | | -| 10.7 | Rendering intents | not started | | | | -| 10.8 | Black point compensation | not started | | | | +| 10.2 | Raster output device native colour | not started | | | | +| 10.3 | CIE-based colour to device colour | not started | | | | +| 10.4 | Conversions among device colour spaces | not started | | | | +| 10.5 | Transfer functions | not started | | | | +| 10.6 | Halftones | not started | | | | +| 10.7 | Scan conversion details | not started | | | | +| 10.8 | Rendering for separations | not started | | | | | 11.1 | Transparency: General | not started | | | | | 11.2 | Overview of transparency | not started | | | | | 11.3 | Basic compositing computations | not started | | | | @@ -89,9 +89,10 @@ Clause numbers at the second level; split rows to the third level as clauses are | 12.7 | Forms | not started | | | | | 12.8 | Digital signatures | not started | | | | | 12.9 | Measurement properties | not started | | | | -| 12.10 | Document requirements | not started | | | | +| 12.10 | Geospatial features | not started | | | | +| 12.11 | Document requirements | not started | | | | | 13.1 | Multimedia: General | not started | | | | -| 13.2 | Multimedia (legacy) | not started | | | | +| 13.2 | Multimedia | not started | | | | | 13.3 | Sounds | not started | | | | | 13.4 | Movies | not started | | | | | 13.5 | Alternate presentations | not started | | | | @@ -118,19 +119,18 @@ Clause numbers at the second level; split rows to the third level as clauses are | 14.13 | Associated files | not started | | | | | Annex A | Operator summary | not started | | | | | Annex B | Operators in Type 4 functions | not started | | | | -| Annex C | Implementation limits | not started | | | | +| Annex C | Advice on maximising portability | not started | | | | | Annex D | Character sets and encodings | partial | `CosString` | `Broadside.Tests.Objects.TextStringTests.Decodes_pdfdocencoding_when_there_is_no_byte_order_marker` | D.3 PDFDocEncoding decodes text strings; the font encodings of D.2 and D.4 to D.6 pending | -| Annex E | PDF name registry | not started | | | | +| Annex E | Extending PDF | not started | | | | | Annex F | Linearized PDF | not started | | | | | Annex G | Linearized PDF access strategies | not started | | | | | Annex H | Example PDF files | not started | | | | | Annex I | PDF versions and compatibility | not started | | | | -| Annex J | Compatibility and implementation notes | not started | | | | -| Annex K | Colour spaces (informative) | not started | | | | -| Annex L | Example files (informative) | not started | | | | -| Annex M | 3D artwork (informative) | not started | | | | -| Annex N | Rich media (informative) | not started | | | | -| Annex O | Standard structure namespace | not started | | | | -| Annex P | Media clip data | not started | | | | -| Annex Q | Extension dictionary example | not started | | | | -| Annex R | Spec file and glyph lists | not started | | | | +| Annex J | XObject comparison | not started | | | | +| Annex K | XFA forms | n/a | | | XFA is parse-and-preserve (CLAUDE.md out of scope) | +| Annex L | Parent-child relationships between the standard structure elements | not started | | | | +| Annex M | Differences between the standard structure namespaces | not started | | | | +| Annex N | Best practice for halftones | not started | | | | +| Annex O | Fragment identifiers | not started | | | | +| Annex P | Actual blending colour space of a transparency group | not started | | | | +| Annex Q | Method for determining transparency on a page | not started | | | | From 13ecb998bb896006b5cb729d5e73400dc3777603 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:34:11 -0500 Subject: [PATCH 006/152] feat(document): incremental update revisions and linearization detection (#40) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Revisions (ISO 32000-2 §7.5.6): PdfDocument.Revisions lists the original file and each update, oldest first, as the byte prefix up to the %%EOF marker (and end-of-line) that terminates the revision's trailer, with the revision's own trailer. A linearized file's first-page and main sections form one revision (the first-page Prev points forward); a hybrid XRefStm joins its table's revision. Root, Info, Encrypt or ID missing from the newest trailer are taken from an older one with a TrailerEntryFromOlderRevision diagnostic; an earlier revision without its %%EOF reports EndOfFileMarkerMissing. Linearization (Annex F): PdfDocument.IsLinearized and Linearization expose the parameter dictionary (Table F.1, validated, L checked against the file length per G.7), the first-page object set (the in-use entries of the first-page cross-reference section) and, lazily, the page offset and shared object hint tables (F.4.1-F.4.3, qpdf's per-column byte alignment, offsets at or after H[0] moved past the hint stream). Corpus: linearized.pdf is qpdf 12.4.2 output from page-tree-inherited.pdf (classic tables, unfiltered hint stream), checked in with its command. hybrid-xref.pdf now ends its main section with startxref and %%EOF as the 7.5.8.4 example does (7.5.6 requires it). Fuzz: new hint-tables target; the document target reads revisions and hints. Benchmark: DocumentOpenBenchmarks covers the updated and linearized files and reads the file structure. Co-Authored-By: Claude Opus 5.5 --- .../DocumentOpenBenchmarks.cs | 15 +- docs/conformance/iso-32000-2.md | 19 +- src/Broadside/Objects/KnownNames.cs | 9 + src/Broadside/Parsing/CrossReference.cs | 80 +++++- src/Broadside/Parsing/CrossReferenceReader.cs | 28 +- src/Broadside/Parsing/DiagnosticCodes.cs | 7 + src/Broadside/Parsing/HintBitReader.cs | 92 ++++++ src/Broadside/Parsing/HintTableLayout.cs | 15 + src/Broadside/Parsing/HintTableReader.cs | 271 ++++++++++++++++++ src/Broadside/Parsing/LinearizationReader.cs | 146 ++++++++++ src/Broadside/Parsing/RevisionReader.cs | 97 +++++++ src/Broadside/PdfDocument.cs | 53 +++- src/Broadside/PdfLinearization.cs | 87 ++++++ src/Broadside/PdfLinearizationHints.cs | 36 +++ src/Broadside/PdfPageHint.cs | 38 +++ src/Broadside/PdfRevision.cs | 42 +++ src/Broadside/PdfSharedObjectHint.cs | 30 ++ src/Broadside/PublicAPI.Unshipped.txt | 30 ++ tests/Broadside.Fuzz/FuzzTargets.cs | 59 +++- tests/Broadside.Fuzz/README.md | 9 +- tests/Broadside.TestSupport/Corpus.cs | 1 + .../Document/IncrementalUpdateTests.cs | 153 ++++++++++ .../Document/LinearizationTests.cs | 162 +++++++++++ tests/Broadside.Tests/Document/TestPdf.cs | 34 +++ .../Document/WellFormedCorpusTests.cs | 2 +- ...pus_file_names_match_snapshot.verified.txt | 1 + tests/Corpus/README.md | 14 +- tests/Corpus/generate.py | 5 +- tests/Corpus/hybrid-xref.pdf | Bin 700 -> 720 bytes tests/Corpus/linearized.pdf | Bin 0 -> 1627 bytes 30 files changed, 1508 insertions(+), 27 deletions(-) create mode 100644 src/Broadside/Parsing/HintBitReader.cs create mode 100644 src/Broadside/Parsing/HintTableLayout.cs create mode 100644 src/Broadside/Parsing/HintTableReader.cs create mode 100644 src/Broadside/Parsing/LinearizationReader.cs create mode 100644 src/Broadside/Parsing/RevisionReader.cs create mode 100644 src/Broadside/PdfLinearization.cs create mode 100644 src/Broadside/PdfLinearizationHints.cs create mode 100644 src/Broadside/PdfPageHint.cs create mode 100644 src/Broadside/PdfRevision.cs create mode 100644 src/Broadside/PdfSharedObjectHint.cs create mode 100644 tests/Broadside.Tests/Document/IncrementalUpdateTests.cs create mode 100644 tests/Broadside.Tests/Document/LinearizationTests.cs create mode 100644 tests/Corpus/linearized.pdf diff --git a/bench/Broadside.Benchmarks/DocumentOpenBenchmarks.cs b/bench/Broadside.Benchmarks/DocumentOpenBenchmarks.cs index ed8ea8c4..ad6f6d34 100644 --- a/bench/Broadside.Benchmarks/DocumentOpenBenchmarks.cs +++ b/bench/Broadside.Benchmarks/DocumentOpenBenchmarks.cs @@ -13,8 +13,8 @@ public class DocumentOpenBenchmarks { private byte[] _bytes = []; - /// The corpus file to open: one page, and a two-level page tree with inheritance. - [Params("empty-page.pdf", "page-tree-inherited.pdf")] + /// The corpus file to open: one page, a two-level page tree with inheritance, an updated file and a linearized file. + [Params("empty-page.pdf", "page-tree-inherited.pdf", "incremental-update.pdf", "linearized.pdf")] public string File { get; set; } = ""; [GlobalSetup] @@ -32,4 +32,15 @@ public double OpenAndWalkPages() return area; } + + /// + /// Opens the file and reads its file structure: the revisions (§7.5.6) and, for a linearized file, the parameter dictionary and + /// the page offset and shared object hint tables (Annex F, F.4). + /// + [Benchmark] + public int OpenAndReadFileStructure() + { + using PdfDocument document = PdfDocument.Open(_bytes); + return document.Revisions.Count + (document.Linearization?.Hints?.Pages.Count ?? 0); + } } diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index 655fac59..a4a1c6e0 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -20,12 +20,12 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.3.9 | Null object | done | `CosNull` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_null_as_the_single_null_object`, `Broadside.Tests.Objects.ContainerParsingTests.A_null_valued_entry_is_the_same_as_an_absent_one` | | | 7.3.10 | Indirect objects | done | `CosReference`, `PdfDocument` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_indirect_references`, `Broadside.Tests.Document.FileStructureTests.References_to_missing_free_or_other_generation_objects_resolve_to_null_without_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.An_object_without_endobj_is_read_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_reads_as_null_with_a_diagnostic` | `PdfDocument.Resolve`; references to missing, free or other-generation objects are null with no diagnostic; loading goes through the internal `ObjectLoader` (hooks for #41, #42, #45); a misplaced object reads as null until #41 searches for it | | 7.4 | Filters | not started | | | | -| 7.5.1 | General | done | `PdfDocument`, `CrossReferenceReader` | `Broadside.Tests.Document.OpenDocumentTests.A_file_opens_identically_from_a_path_a_stream_and_bytes_with_no_diagnostics`, `Broadside.Tests.Document.WellFormedCorpusTests.A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics` | Read from the end through startxref, the cross-reference table and the trailer, never serially; linearized files (Annex F) are #40 | +| 7.5.1 | General | done | `PdfDocument`, `CrossReferenceReader` | `Broadside.Tests.Document.OpenDocumentTests.A_file_opens_identically_from_a_path_a_stream_and_bytes_with_no_diagnostics`, `Broadside.Tests.Document.WellFormedCorpusTests.A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics` | Read from the end through startxref, the cross-reference table and the trailer, never serially; linearized files read through the same path (Annex F) | | 7.5.2 | File header | done | `FileHeader`, `PdfVersion`, `PdfDocument` | `Broadside.Tests.Document.FileStructureTests.Offsets_count_from_the_header_so_bytes_before_it_do_not_matter`, `Broadside.Tests.Document.FileStructureTests.A_file_without_a_header_opens_from_byte_0_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_header_without_a_valid_version_takes_the_catalog_version_with_a_diagnostic` | Header searched in the first 1024 bytes; every stated offset is relative to it; missing header: offsets from byte 0, version 1.4 unless the catalog says otherwise; the unshifted-offset retry is #41 | | 7.5.3 | File body | done | `ObjectLoader` | `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length` | Objects load lazily by cross-reference entry; object streams are #39 | -| 7.5.4 | Cross-reference table | partial | `XrefTableReader`, `CrossReference` | `Broadside.Tests.Document.FileStructureTests.Entries_are_read_as_tokens_not_fixed_width_records`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_reads_as_null_with_a_diagnostic` | Subsections and n/f entries read as tokens; offset-0 in-use entries read as free; reconstruction by scanning when the table is wrong, and diagnostics for non-20-byte entries and comments, are #41 | -| 7.5.5 | File trailer | partial | `CrossReferenceReader`, `CrossReference`, `PdfDocument` | `Broadside.Tests.Document.FileStructureTests.A_startxref_offset_on_the_white_space_before_xref_is_repaired_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_file_with_no_startxref_cannot_be_read_even_leniently`, `Broadside.Tests.Document.FileStructureTests.A_trailer_without_root_cannot_be_read`, `Broadside.Tests.Document.FileStructureTests.A_prev_chain_that_loops_ends_with_a_diagnostic` | Last startxref, Prev chain with loop guard, Root; trailer merged newest-first; ignoring entries beyond Size, startxref recovery and trailer reconstruction are #41; Encrypt is #42 | -| 7.5.6 | Incremental updates | not started | | | The Prev chain is read (`Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`); revisions are #40 | +| 7.5.4 | Cross-reference table | partial | `XrefTableReader`, `CrossReference` | `Broadside.Tests.Document.FileStructureTests.Entries_are_read_as_tokens_not_fixed_width_records`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_reads_as_null_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation` | Subsections and n/f entries read as tokens; offset-0 in-use entries read as free; reconstruction by scanning when the table is wrong, and diagnostics for non-20-byte entries and comments, are #41 | +| 7.5.5 | File trailer | partial | `CrossReferenceReader`, `CrossReference`, `PdfDocument` | `Broadside.Tests.Document.FileStructureTests.A_startxref_offset_on_the_white_space_before_xref_is_repaired_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_file_with_no_startxref_cannot_be_read_even_leniently`, `Broadside.Tests.Document.FileStructureTests.A_trailer_without_root_cannot_be_read`, `Broadside.Tests.Document.FileStructureTests.A_prev_chain_that_loops_ends_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic` | Last startxref, Prev chain with loop guard, Root; trailer merged newest-first; ignoring entries beyond Size, startxref recovery and trailer reconstruction are #41; Encrypt is #42 | +| 7.5.6 | Incremental updates | done | `CrossReference`, `RevisionReader`, `PdfRevision`, `PdfDocument` | `Broadside.Tests.Document.IncrementalUpdateTests.An_updated_file_has_one_revision_per_update_and_the_first_is_the_original_file`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_is_the_file_as_it_was_after_that_save`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_has_its_own_trailer`, `Broadside.Tests.Document.IncrementalUpdateTests.A_hybrid_file_has_its_main_section_and_its_update_section_as_two_revisions`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_earlier_revision_without_its_end_of_file_marker_ends_after_its_startxref_offset_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev` | Revisions oldest first, each the byte prefix up to its %%EOF and end-of-line; newest section decides per object number, free hides older copies, a reference must match the live generation; Root, Info, Encrypt and ID missing from the newest trailer are taken from an older one with TrailerEntryFromOlderRevision; a linearized pair is one revision; a hybrid XRefStm joins its table's revision (#39 re-verifies); writing updates is #44 | | 7.5.7 | Object streams | not started | | | #39 | | 7.5.8 | Cross-reference streams | not started | | | #39; files with only a cross-reference stream fail to open with XrefStreamUnsupported until then | | 7.6 | Encryption | not started | | | | @@ -121,7 +121,16 @@ Clause numbers at the second level; split rows to the third level as clauses are | Annex C | Implementation limits | not started | | | | | Annex D | Character sets and encodings | partial | `CosString` | `Broadside.Tests.Objects.TextStringTests.Decodes_pdfdocencoding_when_there_is_no_byte_order_marker` | D.3 PDFDocEncoding decodes text strings; the font encodings of D.2 and D.4 to D.6 pending | | Annex E | PDF name registry | not started | | | | -| Annex F | Linearized PDF | not started | | | | +| F.1 | General | n/a | | | Introductory text | +| F.2 | Background and assumptions | n/a | | | Informative background | +| F.3 | Linearized PDF document structure | partial | `LinearizationReader`, `PdfLinearization`, `CrossReference`, `PdfDocument` | `Broadside.Tests.Document.LinearizationTests.A_linearized_file_is_detected_and_exposes_its_parameter_dictionary`, `Broadside.Tests.Document.LinearizationTests.The_first_page_objects_are_those_in_the_first_page_cross_reference_section`, `Broadside.Tests.Document.LinearizationTests.A_linearized_file_is_one_revision`, `Broadside.Tests.Document.LinearizationTests.A_file_that_is_not_linearized_reports_false`, `Broadside.Tests.Document.LinearizationTests.An_update_appended_to_a_linearized_file_makes_it_an_ordinary_two_revision_file`, `Broadside.Tests.Document.LinearizationTests.A_malformed_linearization_dictionary_is_ignored_with_a_diagnostic` | Reading: detection by the first object in the first 1024 bytes, Table F.1 validation, L against the file length (G.7), first-page objects from the first-page section, first-page and main sections as one revision; part ordering is not validated and writing linearized files is not started; linearized.pdf (qpdf) | +| F.4.1 | General | done | `HintTableReader`, `HintBitReader`, `PdfLinearizationHints` | `Broadside.Tests.Document.LinearizationTests.The_page_offset_hint_table_locates_each_page`, `Broadside.Tests.Document.LinearizationTests.Hint_offsets_count_from_byte_0_of_the_file_when_bytes_precede_the_header`, `Broadside.Tests.Document.LinearizationTests.A_malformed_hint_table_leaves_the_file_linearized_without_hints_and_with_a_diagnostic` | MSB-first bit stream, each item column byte-aligned (qpdf, Acrobat); positions at or after H[0] moved by H[1]; overflow stream appended; a filtered hint stream yields no hints until #38 decodes it | +| F.4.2 | Page offset hint table | partial | `HintTableReader`, `PdfPageHint` | `Broadside.Tests.Document.LinearizationTests.The_page_offset_hint_table_locates_each_page` | Items 1 to 4 per page; item 5 (numerators) and items 6 and 7 (content stream offset and length, Acrobat placeholders) are not exposed | +| F.4.3 | Shared object hint table | done | `HintTableReader`, `PdfSharedObjectHint` | `Broadside.Tests.Document.LinearizationTests.The_shared_object_hint_table_locates_each_group` | MD5 signatures skipped; Table F.6 item 1 cites Table F.3 item 4 for the first page location, read as item 2 (qpdf) | +| F.4.4 | Thumbnail hint table | not started | | | | +| F.4.5 | Generic hint tables | not started | | | | +| F.4.6 | Extended generic hint tables | not started | | | | +| F.4.7 | Embedded file stream hint tables | not started | | | | | Annex G | Linearized PDF access strategies | not started | | | | | Annex H | Example PDF files | not started | | | | | Annex I | PDF versions and compatibility | not started | | | | diff --git a/src/Broadside/Objects/KnownNames.cs b/src/Broadside/Objects/KnownNames.cs index 3068731e..c23a8e68 100644 --- a/src/Broadside/Objects/KnownNames.cs +++ b/src/Broadside/Objects/KnownNames.cs @@ -62,4 +62,13 @@ internal static class KnownNames /// /UserUnit, the size of a default user space unit (§7.7.3.3, Table 31). public static readonly CosName UserUnit = new("UserUnit"); + + /// /Info, the trailer's document information dictionary (§7.5.5, Table 15). + public static readonly CosName Info = new("Info"); + + /// /Encrypt, the trailer's encryption dictionary (§7.5.5, Table 15). + public static readonly CosName Encrypt = new("Encrypt"); + + /// /ID, the trailer's file identifier (§7.5.5, Table 15). + public static readonly CosName ID = new("ID"); } diff --git a/src/Broadside/Parsing/CrossReference.cs b/src/Broadside/Parsing/CrossReference.cs index 7c26e8b1..fd7440ac 100644 --- a/src/Broadside/Parsing/CrossReference.cs +++ b/src/Broadside/Parsing/CrossReference.cs @@ -74,26 +74,52 @@ public CrossReference(IReadOnlyList sections) { ArgumentOutOfRangeException.ThrowIfZero(sections.Count); Sections = sections; + Revisions = GroupRevisions(sections); var trailer = new OrderedDictionary(); - foreach (XrefSection section in sections) + var inherited = new List(); + for (int revision = Revisions.Count - 1; revision >= 0; revision--) { - foreach ((int number, XrefEntry entry) in section.Entries) + foreach (XrefSection section in Revisions[revision].Sections) { - _merged.TryAdd(number, entry); - } - - foreach (KeyValuePair entry in section.Trailer) - { - trailer.TryAdd(entry.Key, entry.Value); + foreach ((int number, XrefEntry entry) in section.Entries) + { + _merged.TryAdd(number, entry); + } + + foreach (KeyValuePair entry in section.Trailer) + { + if (trailer.TryAdd(entry.Key, entry.Value) && revision < Revisions.Count - 1) + { + inherited.Add(entry.Key); + } + } } } Trailer = CosDictionary.FromOwnedEntries(trailer); + InheritedTrailerKeys = inherited; } /// Gets the sections, newest first. public IReadOnlyList Sections { get; } + /// Gets the revisions the sections form, oldest first (§7.5.6). + /// + /// + /// Each update appends one revision. A revision usually has one section; it has more when the file is linearized (the + /// first-page section and the main section, F.3.4, form the original revision: the first-page section's Prev points + /// forward, to a higher offset, which an appended update never does) or, with issue #39, when a hybrid file's table names a + /// cross-reference stream through XRefStm (§7.5.8.4: the stream belongs to its table's revision). + /// + /// + public IReadOnlyList Revisions { get; } + + /// + /// Gets the trailer keys the newest revision's trailer lacks and an older revision's trailer supplied (§7.5.6: an update's + /// trailer shall repeat every entry of the previous one except Prev). + /// + public IReadOnlyList InheritedTrailerKeys { get; } + /// Gets the merged trailer dictionary. public CosDictionary Trailer { get; } @@ -111,4 +137,42 @@ public bool TryGetEntry(int objectNumber, out XrefEntry entry) entry = XrefEntry.Free; return false; } + + /// Splits the sections, newest first, into revisions, oldest first. + private static List GroupRevisions(IReadOnlyList sections) + { + var revisions = new List(); + var current = new List { sections[0] }; + for (int index = 1; index < sections.Count; index++) + { + XrefSection section = sections[index]; + bool forward = section.Offset > current[0].Offset; + bool namedStream = section.Offset == sections[index - 1].XRefStreamOffset; + if (!forward && !namedStream) + { + revisions.Add(new XrefRevision(current)); + current = []; + } + + current.Add(section); + } + + revisions.Add(new XrefRevision(current)); + revisions.Reverse(); + return revisions; + } +} + +/// One revision of a file: the sections one save wrote. ISO 32000-2 §7.5.6, F.3.4. +/// The sections, in Prev chain order: the first is the one the revision's trailer is taken from. +internal sealed record XrefRevision(IReadOnlyList Sections) +{ + /// Gets the section the chain reaches first; its trailer is the revision's trailer. + public XrefSection Newest => Sections[0]; + + /// Gets the section stored last in the file; the revision ends with its trailer's %%EOF marker. + public XrefSection LastInFile => Sections.MaxBy(section => section.Offset)!; + + /// Gets a value indicating whether the revision is a linearized file's first-page and main sections (F.3.4). + public bool IsLinearizedPair => Sections.Count > 1 && Sections[1].Offset > Sections[0].Offset; } diff --git a/src/Broadside/Parsing/CrossReferenceReader.cs b/src/Broadside/Parsing/CrossReferenceReader.cs index 39085e5b..25efda67 100644 --- a/src/Broadside/Parsing/CrossReferenceReader.cs +++ b/src/Broadside/Parsing/CrossReferenceReader.cs @@ -61,7 +61,33 @@ internal static class CrossReferenceReader next = PreviousSectionOffset(section, header, diagnostics); } - return sections.Count == 0 ? null : new CrossReference(sections); + if (sections.Count == 0) + { + return null; + } + + var crossReference = new CrossReference(sections); + ReportInheritedTrailerEntries(crossReference, diagnostics); + return crossReference; + } + + /// + /// Reports the document-level trailer entries the newest revision's trailer lacks and an older one supplied: §7.5.6 says an + /// update's trailer shall repeat every entry of the previous trailer except Prev. The older value is used. + /// + private static void ReportInheritedTrailerEntries(CrossReference crossReference, DiagnosticSink diagnostics) + { + foreach (CosName key in crossReference.InheritedTrailerKeys) + { + if (key.Equals(KnownNames.Root) || key.Equals(KnownNames.Info) || key.Equals(KnownNames.Encrypt) || key.Equals(KnownNames.ID)) + { + diagnostics.Report( + DiagnosticCodes.TrailerEntryFromOlderRevision, + DiagnosticSeverity.Warning, + $"The newest trailer has no {key} entry, which every update's trailer shall repeat; the entry of an older revision's trailer is used.", + crossReference.Sections[0].Offset); + } + } } /// Finds the last startxref in the file and reads the offset after it (§7.5.5). diff --git a/src/Broadside/Parsing/DiagnosticCodes.cs b/src/Broadside/Parsing/DiagnosticCodes.cs index 910077f7..7c28e36c 100644 --- a/src/Broadside/Parsing/DiagnosticCodes.cs +++ b/src/Broadside/Parsing/DiagnosticCodes.cs @@ -26,6 +26,13 @@ internal static class DiagnosticCodes public const string XrefPrevLoop = nameof(XrefPrevLoop); public const string XrefStreamUnsupported = nameof(XrefStreamUnsupported); + // Incremental updates (§7.5.6). + public const string TrailerEntryFromOlderRevision = nameof(TrailerEntryFromOlderRevision); + + // Linearized files (Annex F). + public const string LinearizationDictionaryInvalid = nameof(LinearizationDictionaryInvalid); + public const string LinearizationHintsInvalid = nameof(LinearizationHintsInvalid); + // Indirect objects (§7.3.10). public const string XrefEntryOffsetInvalid = nameof(XrefEntryOffsetInvalid); public const string MissingEndobj = nameof(MissingEndobj); diff --git a/src/Broadside/Parsing/HintBitReader.cs b/src/Broadside/Parsing/HintBitReader.cs new file mode 100644 index 00000000..6d600fd3 --- /dev/null +++ b/src/Broadside/Parsing/HintBitReader.cs @@ -0,0 +1,92 @@ +namespace Broadside.Parsing; + +/// Reads unsigned fields of 0 to 32 bits from hint table data, most significant bit first (F.4.1). +/// +/// ISO 32000-2 F.4.1. A field of width 0 reads 0 and consumes nothing. Reading past the end, or a field width over 32, sets +/// and reads 0 from then on, so a caller checks once after a group of reads. +/// +internal ref struct HintBitReader +{ + private readonly ReadOnlySpan _data; + private long _bit; + + /// Initializes a new instance of the struct at the start of . + /// The hint table data. + public HintBitReader(ReadOnlySpan data) => _data = data; + + /// Gets a value indicating whether a read ran past the data or asked for an invalid width. + public bool Failed { get; private set; } + + /// Reads an unsigned field. + /// The width in bits, 0 to 32. + /// The value, or 0 once . + public long Read(int width) + { + if (Failed || width is < 0 or > 32 || _bit + width > (long)_data.Length * 8) + { + Failed = true; + return 0; + } + + long value = 0; + for (int index = 0; index < width; index++, _bit++) + { + int bit = (_data[(int)(_bit >> 3)] >> (7 - (int)(_bit & 7))) & 1; + value = (value << 1) | (long)bit; + } + + return value; + } + + /// Reads a 16-bit "number of bits" header item, which shall be 0 to 32 (F.4.2). + /// The width; an out-of-range value sets . + public int ReadWidth() + { + long width = Read(16); + if (width > 32) + { + Failed = true; + return 0; + } + + return (int)width; + } + + /// Reads fields of bits, then moves to the next byte boundary. + /// The number of fields. + /// The width of each. + /// The values. + public long[] ReadColumn(int count, int width) + { + if (Failed || (long)count * width > ((long)_data.Length * 8) - _bit) + { + Failed = true; + return new long[count]; + } + + long[] values = new long[count]; + for (int index = 0; index < count; index++) + { + values[index] = Read(width); + } + + AlignToByte(); + return values; + } + + /// Skips bits. + /// How many. + public void Skip(int bits) + { + if (Failed || _bit + bits > (long)_data.Length * 8) + { + Failed = true; + return; + } + + _bit += bits; + } + + /// Moves to the next byte boundary, unless already on one. + public void AlignToByte() => _bit = (_bit + 7) & ~7L; +} diff --git a/src/Broadside/Parsing/HintTableLayout.cs b/src/Broadside/Parsing/HintTableLayout.cs new file mode 100644 index 00000000..e57dae6f --- /dev/null +++ b/src/Broadside/Parsing/HintTableLayout.cs @@ -0,0 +1,15 @@ +namespace Broadside.Parsing; + +/// What turning hint table positions into file offsets needs (F.4.1, F.4.2). +/// The absolute offset of the %PDF- header; hint positions count from it. +/// The primary hint stream's offset, H[0]. +/// The primary hint stream's length, H[1]. +/// The first page's object number, O. +/// The number of pages, N. +internal readonly record struct HintTableLayout(long HeaderOffset, long HintOffset, long HintLength, long FirstPageObjectNumber, long PageCount) +{ + /// Moves a position past the primary hint stream when it is at or after it (F.4.1), then makes it absolute. + /// A position as a hint table states it. + /// The absolute file offset. + public long Absolute(long position) => HeaderOffset + (position >= HintOffset ? position + HintLength : position); +} diff --git a/src/Broadside/Parsing/HintTableReader.cs b/src/Broadside/Parsing/HintTableReader.cs new file mode 100644 index 00000000..83274521 --- /dev/null +++ b/src/Broadside/Parsing/HintTableReader.cs @@ -0,0 +1,271 @@ +using Broadside.Diagnostics; +using Broadside.IO; +using Broadside.Objects; + +namespace Broadside.Parsing; + +/// Reads the page offset and shared object hint tables of a linearized file (F.4.2 and F.4.3). +/// +/// +/// ISO 32000-2 F.3.6 and F.4.1 to F.4.3. The primary hint stream is the object at H[0]; an overflow stream at H[2] is +/// appended to it. The page offset table starts at 0, the shared object table at the primary stream's S entry. The data is a +/// bit stream read most significant bit first. +/// +/// +/// Alignment follows qpdf, which is validated against Acrobat: every column of items (all pages' item 1, all pages' item 2, …) +/// starts on a byte boundary, where F.4.1 says only that each table does. Offsets at or past the hint stream are moved past it +/// (F.4.1 says "greater than"; a first page stored right after the hint stream needs "or equal"). +/// +/// +/// Hints are information only. A table that cannot be read yields and a +/// diagnostic; it never affects how the document reads. A hint stream with +/// a filter yields without a diagnostic until stream decoding (issue #38) is wired in here. +/// +/// +internal static class HintTableReader +{ + /// The most pages, shared references or shared groups a table may describe; more is treated as a malformed table. + private const int MaxEntries = 1 << 20; + + private static readonly CosName Filter = new("Filter"); + private static readonly CosName SharedObjectTable = new("S"); + + /// Reads the hint tables. + /// The file. + /// The object loader. + /// The linearization parameter dictionary, already validated. + /// The H array: offset and length of the primary hint stream, then of the overflow stream. + /// Where to report a malformed table. + /// The tables, or . + public static PdfLinearizationHints? Read(PdfSource source, ObjectLoader loader, CosDictionary parameters, long[] hintStreams, DiagnosticSink diagnostics) + { + CosStream? primary = LoadStream(source, loader, hintStreams[0]); + CosStream? overflow = null; + if (primary is null || (hintStreams.Length == 4 && (overflow = LoadStream(source, loader, hintStreams[2])) is null)) + { + return Invalid(diagnostics, "The H entry of the linearization parameter dictionary does not point at a hint stream."); + } + + if (primary.Dictionary.ContainsKey(Filter) || (overflow?.Dictionary.ContainsKey(Filter) ?? false)) + { + return null; + } + + byte[] data = [.. primary.EncodedData.Span, .. overflow is null ? [] : overflow.EncodedData.Span]; + if (!primary.Dictionary.TryGetValue(SharedObjectTable, out CosObject? sharedEntry) + || sharedEntry is not CosInteger { Value: >= 0 } shared + || shared.Value >= data.Length) + { + return Invalid(diagnostics, "The primary hint stream's S entry does not give the position of the shared object hint table."); + } + + var layout = new HintTableLayout( + loader.Header.Offset, + hintStreams[0], + hintStreams[1], + ReadInteger(parameters, PdfLinearization.Names.O), + ReadInteger(parameters, PdfLinearization.Names.N)); + PdfLinearizationHints? hints = Parse(data, (int)shared.Value, layout, out string? error); + return error is null ? hints : Invalid(diagnostics, error); + } + + /// Decodes the page offset table at the start of and the shared object table at . + /// The decoded, concatenated hint stream data. + /// The position of the shared object hint table in . + /// What turning table positions into file offsets needs. + /// Why the tables cannot be read, or . + /// The tables, or with set. + public static PdfLinearizationHints? Parse(ReadOnlySpan data, int sharedTable, HintTableLayout layout, out string? error) + { + error = null; + if (layout.PageCount is < 0 or > MaxEntries) + { + error = "The linearization parameter dictionary's N entry is too large for a hint table."; + return null; + } + + if (sharedTable < 0 || sharedTable >= data.Length) + { + error = "The primary hint stream's S entry does not give the position of the shared object hint table."; + return null; + } + + var pageReader = new HintBitReader(data); + if (!TryReadPages(ref pageReader, layout, out List pages, out long firstPageLocation)) + { + error = "The page offset hint table is truncated or malformed."; + return null; + } + + var sharedReader = new HintBitReader(data[sharedTable..]); + if (!TryReadSharedObjects(ref sharedReader, layout, firstPageLocation, out List groups)) + { + error = "The shared object hint table is truncated or malformed."; + return null; + } + + return new PdfLinearizationHints(pages, groups); + } + + /// Reads the page offset hint table (F.4.2, Tables F.3 and F.4). + private static bool TryReadPages(ref HintBitReader reader, HintTableLayout context, out List pages, out long firstPageLocation) + { + pages = []; + long minObjects = reader.Read(32); + firstPageLocation = reader.Read(32); + int bitsObjects = reader.ReadWidth(); + long minLength = reader.Read(32); + int bitsLength = reader.ReadWidth(); + _ = reader.Read(32); // 6: least content stream offset (Acrobat: placeholder) + _ = reader.ReadWidth(); // 7 + _ = reader.Read(32); // 8: least content stream length (Acrobat: placeholder) + _ = reader.ReadWidth(); // 9 + int bitsShared = reader.ReadWidth(); + int bitsIdentifier = reader.ReadWidth(); + _ = reader.ReadWidth(); // 12: numerator width; item 5 is not read + _ = reader.Read(16); // 13: denominator + if (reader.Failed) + { + return false; + } + + int count = (int)context.PageCount; + long[] objects = reader.ReadColumn(count, bitsObjects); + long[] lengths = reader.ReadColumn(count, bitsLength); + long[] sharedCounts = reader.ReadColumn(count, bitsShared); + if (reader.Failed || sharedCounts.Sum() > MaxEntries) + { + return false; + } + + // Item 4 of every page, page after page, then aligned (qpdf reads page 0's too when Acrobat writes them). + var identifiers = new int[count][]; + for (int page = 0; page < count; page++) + { + identifiers[page] = new int[sharedCounts[page]]; + for (int index = 0; index < identifiers[page].Length; index++) + { + identifiers[page][index] = (int)reader.Read(bitsIdentifier); + } + } + + reader.AlignToByte(); + if (reader.Failed) + { + return false; + } + + long location = firstPageLocation; + long objectNumber = context.FirstPageObjectNumber; + for (int page = 0; page < count; page++) + { + long objectCount = minObjects + objects[page]; + long length = minLength + lengths[page]; + if (objectCount > int.MaxValue || objectNumber + objectCount > int.MaxValue) + { + return false; + } + + pages.Add(new PdfPageHint((int)objectNumber, (int)objectCount, context.Absolute(location), length, identifiers[page])); + location += length; + objectNumber = page == 0 ? 1 : objectNumber + objectCount; + } + + return true; + } + + /// Reads the shared object hint table (F.4.3, Tables F.5 and F.6). + private static bool TryReadSharedObjects(ref HintBitReader reader, HintTableLayout context, long firstPageLocation, out List groups) + { + groups = []; + long firstSharedObject = reader.Read(32); + long firstSharedLocation = reader.Read(32); + long firstPageEntries = reader.Read(32); + long totalEntries = reader.Read(32); + int bitsObjects = reader.ReadWidth(); + long minLength = reader.Read(32); + int bitsLength = reader.ReadWidth(); + if (reader.Failed || firstPageEntries > totalEntries || totalEntries > MaxEntries) + { + return false; + } + + int count = (int)totalEntries; + long[] lengths = reader.ReadColumn(count, bitsLength); + long[] signed = reader.ReadColumn(count, 1); + if (reader.Failed) + { + return false; + } + + // Item 3, the 128-bit MD5 signature, for each group that has one (qpdf: no alignment needed, the column is aligned). + foreach (long flag in signed) + { + if (flag != 0) + { + reader.Skip(128); + } + } + + long[] objectCounts = reader.ReadColumn(count, bitsObjects); + if (reader.Failed) + { + return false; + } + + long location = firstPageLocation; + long objectNumber = context.FirstPageObjectNumber; + for (int index = 0; index < count; index++) + { + if (index == firstPageEntries) + { + location = firstSharedLocation; + objectNumber = firstSharedObject; + } + + long objectCount = objectCounts[index] + 1; + long length = minLength + lengths[index]; + if (objectNumber + objectCount > int.MaxValue) + { + return false; + } + + groups.Add(new PdfSharedObjectHint((int)objectNumber, (int)objectCount, context.Absolute(location), length)); + location += length; + objectNumber += objectCount; + } + + return true; + } + + /// Loads the stream whose N G obj header is at (relative to the header). + private static CosStream? LoadStream(PdfSource source, ObjectLoader loader, long offset) + { + if (offset > source.Length - loader.Header.Offset) + { + return null; + } + + ReadOnlySpan window = source.GetWindow(loader.Header.Offset + offset).Span; + var lexer = new CosLexer(window); + if (!StructureTokens.TryReadUnsigned(ref lexer, out long number) + || !StructureTokens.TryReadUnsigned(ref lexer, out long generation) + || !StructureTokens.TryReadKeyword(ref lexer, "obj"u8) + || number is 0 or > int.MaxValue + || generation > CosReference.MaxGeneration) + { + return null; + } + + return loader.Load(new CosReference((int)number, (int)generation)) as CosStream; + } + + private static PdfLinearizationHints? Invalid(DiagnosticSink diagnostics, string message) + { + diagnostics.Report(DiagnosticCodes.LinearizationHintsInvalid, DiagnosticSeverity.Warning, message + " The hints are ignored."); + return null; + } + + private static long ReadInteger(CosDictionary dictionary, CosName key) => + dictionary.TryGetValue(key, out CosObject? value) && value is CosInteger integer ? integer.Value : 0; +} diff --git a/src/Broadside/Parsing/LinearizationReader.cs b/src/Broadside/Parsing/LinearizationReader.cs new file mode 100644 index 00000000..10c8b44c --- /dev/null +++ b/src/Broadside/Parsing/LinearizationReader.cs @@ -0,0 +1,146 @@ +using Broadside.Diagnostics; +using Broadside.IO; +using Broadside.Objects; + +namespace Broadside.Parsing; + +/// Detects a linearized file: its first object is a linearization parameter dictionary (Annex F, F.3.3). +/// +/// +/// ISO 32000-2 F.3.3 and Table F.1. The first indirect object after the header is looked at only when the first 1024 bytes hold +/// the name /Linearized, so no other file pays for loading its first object. The object is loaded through the cross-reference +/// information like any other, so it is the instance returns. +/// +/// +/// A dictionary with a Linearized entry whose required entries are missing or of the wrong type is ignored with a +/// diagnostic (pdf.js and qpdf ignore it too). The L check +/// against the file length is the caller's: a mismatch is not a deviation, it is what appending an update does (G.7). +/// +/// +internal static class LinearizationReader +{ + /// The parameter dictionary shall be within the first 1024 bytes of the file (F.3.3). + private const int SearchLength = 1024; + + /// Reads the linearization information of the file, if it has any. + /// The file. + /// The object loader. + /// Where to report an invalid parameter dictionary or hint table. + /// The information, or when the file does not start with a valid parameter dictionary. + public static PdfLinearization? Read(PdfSource source, ObjectLoader loader, DiagnosticSink diagnostics) + { + long headerOffset = loader.Header.Offset; + Span buffer = stackalloc byte[SearchLength]; + ReadOnlySpan start = buffer[..source.Read(headerOffset, buffer)]; + if (start.IndexOf("/Linearized"u8) < 0) + { + return null; + } + + var lexer = new CosLexer(start); + if (!StructureTokens.TryReadUnsigned(ref lexer, out long number) + || !StructureTokens.TryReadUnsigned(ref lexer, out long generation) + || !StructureTokens.TryReadKeyword(ref lexer, "obj"u8) + || number is 0 or > int.MaxValue + || generation > CosReference.MaxGeneration) + { + return null; + } + + var reference = new CosReference((int)number, (int)generation); + if (loader.Load(reference) is not CosDictionary dictionary || !dictionary.ContainsKey(PdfLinearization.Names.Linearized)) + { + return null; + } + + if (!TryValidate(dictionary, out long[] hintStreams)) + { + diagnostics.Report( + DiagnosticCodes.LinearizationDictionaryInvalid, + DiagnosticSeverity.Warning, + "The linearization parameter dictionary lacks a required entry or has one of the wrong type (Linearized, L, H, O, E, N, T, P); the file is read as not linearized.", + objectReference: reference); + return null; + } + + IReadOnlyList firstPageObjects = FirstPageObjects(loader.CrossReference); + return new PdfLinearization( + dictionary, + reference, + firstPageObjects, + () => HintTableReader.Read(source, loader, dictionary, hintStreams, diagnostics)); + } + + /// Checks the entries of Table F.1: all required ones present, direct and of the right type and range. + private static bool TryValidate(CosDictionary dictionary, out long[] hintStreams) + { + hintStreams = []; + if (!dictionary.TryGetValue(PdfLinearization.Names.Linearized, out CosObject? version) || version is not CosNumber { } number || number.ToDouble() <= 0) + { + return false; + } + + if (!IsInteger(dictionary, PdfLinearization.Names.L, minimum: 1) + || !IsInteger(dictionary, PdfLinearization.Names.O, minimum: 1) + || !IsInteger(dictionary, PdfLinearization.Names.E, minimum: 1) + || !IsInteger(dictionary, PdfLinearization.Names.N, minimum: 1) + || !IsInteger(dictionary, PdfLinearization.Names.T, minimum: 1) + || (dictionary.ContainsKey(PdfLinearization.Names.P) && !IsInteger(dictionary, PdfLinearization.Names.P, minimum: 0))) + { + return false; + } + + if (!dictionary.TryGetValue(PdfLinearization.Names.H, out CosObject? h) || h is not CosArray { Count: 2 or 4 } array) + { + return false; + } + + hintStreams = new long[array.Count]; + for (int index = 0; index < array.Count; index++) + { + if (array[index] is not CosInteger { Value: > 0 } item) + { + return false; + } + + hintStreams[index] = item.Value; + } + + return true; + } + + private static bool IsInteger(CosDictionary dictionary, CosName key, long minimum) => + dictionary.TryGetValue(key, out CosObject? value) && value is CosInteger integer && integer.Value >= minimum; + + /// + /// The in-use objects of the first-page cross-reference section (F.3.4): the section the original revision's chain reaches first, + /// whose Prev points forward to the main section. + /// + private static List FirstPageObjects(CrossReference crossReference) + { + var objects = new List(); + XrefRevision original = crossReference.Revisions[0]; + if (!original.IsLinearizedPair) + { + return objects; + } + + foreach ((int number, XrefEntry entry) in original.Newest.Entries) + { + switch (entry.Kind) + { + case XrefEntryKind.InUse: + objects.Add(new CosReference(number, entry.Generation)); + break; + case XrefEntryKind.Compressed: + objects.Add(new CosReference(number, 0)); + break; + default: + break; + } + } + + objects.Sort((left, right) => left.ObjectNumber.CompareTo(right.ObjectNumber)); + return objects; + } +} diff --git a/src/Broadside/Parsing/RevisionReader.cs b/src/Broadside/Parsing/RevisionReader.cs new file mode 100644 index 00000000..4c0c59bc --- /dev/null +++ b/src/Broadside/Parsing/RevisionReader.cs @@ -0,0 +1,97 @@ +using Broadside.Diagnostics; +using Broadside.IO; + +namespace Broadside.Parsing; + +/// Finds where each revision of a file ends: just past the %%EOF marker that terminates its trailer. +/// +/// +/// ISO 32000-2 §7.5.5 and §7.5.6: "Each trailer shall be terminated by its own end-of-file (%%EOF) marker." Revision k is the bytes +/// from the start of the file to the end of that marker, including the end-of-line marker after it when there is one, which is +/// what a signature's byte range covers (§12.8.1). +/// +/// +/// The marker is looked for right after the trailer of the revision's last section in the file: startxref, its offset, then +/// %%EOF. A revision whose marker is missing ends after the startxref offset (or after the trailer when that is +/// missing too) with a diagnostic; for the newest revision the reader of startxref has already reported it. +/// +/// +internal static class RevisionReader +{ + /// Returns the absolute end offset of each revision of , oldest first. + /// The file. + /// The cross-reference information. + /// Where to report a missing marker. + /// One exclusive end offset per revision. + public static long[] ReadEnds(PdfSource source, CrossReference crossReference, DiagnosticSink diagnostics) + { + IReadOnlyList revisions = crossReference.Revisions; + long[] ends = new long[revisions.Count]; + for (int index = 0; index < revisions.Count; index++) + { + bool newest = index == revisions.Count - 1; + ends[index] = FindEnd(source, revisions[index].LastInFile.End, reportMissing: !newest, diagnostics); + } + + return ends; + } + + private static long FindEnd(PdfSource source, long trailerEnd, bool reportMissing, DiagnosticSink diagnostics) + { + ReadOnlySpan window = source.GetWindow(trailerEnd).Span; + int position = SkipWhiteSpace(window, 0); + if (window[position..].StartsWith("startxref"u8)) + { + position = SkipWhiteSpace(window, position + "startxref"u8.Length); + int digits = position; + while (position < window.Length && char.IsAsciiDigit((char)window[position])) + { + position++; + } + + int afterOffset = position; + position = SkipWhiteSpace(window, position); + if (position > digits && window[position..].StartsWith("%%EOF"u8)) + { + position += "%%EOF"u8.Length; + if (window[position..].StartsWith("\r\n"u8)) + { + position += 2; + } + else if (position < window.Length && window[position] is (byte)'\r' or (byte)'\n') + { + position++; + } + + return trailerEnd + position; + } + + position = afterOffset; + } + else + { + position = 0; + } + + if (reportMissing) + { + diagnostics.Report( + DiagnosticCodes.EndOfFileMarkerMissing, + DiagnosticSeverity.Warning, + "The trailer of an earlier revision is not followed by startxref, its offset and the %%EOF marker; the revision ends here.", + trailerEnd + position); + } + + return trailerEnd + position; + } + + private static int SkipWhiteSpace(ReadOnlySpan window, int position) + { + while (position < window.Length && window[position] is 0 or (byte)'\t' or (byte)'\n' or (byte)'\f' or (byte)'\r' or (byte)' ') + { + position++; + } + + return position; + } +} diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 7d8beeba..6357eb31 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -26,12 +26,20 @@ public sealed class PdfDocument : IDisposable private readonly DiagnosticSink _diagnostics; private readonly ObjectLoader _loader; - private PdfDocument(PdfSource source, DiagnosticSink diagnostics, ObjectLoader loader, CosDictionary catalog) + private PdfDocument( + PdfSource source, + DiagnosticSink diagnostics, + ObjectLoader loader, + CosDictionary catalog, + IReadOnlyList revisions, + PdfLinearization? linearization) { _source = source; _diagnostics = diagnostics; _loader = loader; Catalog = catalog; + Revisions = revisions; + Linearization = linearization; Pages = new PdfPageCollection(() => PageTreeReader.Read(this, diagnostics)); } @@ -70,6 +78,32 @@ public PdfVersion Version /// ISO 32000-2 §7.7.3. public PdfPageCollection Pages { get; } + /// Gets the revisions of the file, oldest first: the original file, then one per incremental update. + /// + /// ISO 32000-2 §7.5.6. The document itself always shows the newest revision: for every object number the most recent + /// cross-reference section that lists it decides, and a number it marks free is deleted even when an older section has the + /// object. A linearized file without updates has one revision. + /// + public IReadOnlyList Revisions { get; } + + /// + /// Gets a value indicating whether the file is linearized: it starts with a linearization parameter dictionary whose file + /// length (L) is the length of the file. + /// + /// + /// ISO 32000-2 Annex F, Table F.1: a file whose length does not match "shall be treated as ordinary PDF file, ignoring + /// linearization information", which is what appending an update to a linearized file produces (G.7). Lengths count from the + /// %PDF- header. + /// + public bool IsLinearized => Linearization is { } linearization && linearization.FileLength == _source.Length - _loader.Header.Offset; + + /// + /// Gets the linearization information when the file starts with a valid linearization parameter dictionary, whether or not the + /// file is still linearized (); otherwise . + /// + /// ISO 32000-2 Annex F, F.3.3. + public PdfLinearization? Linearization { get; } + /// Gets the deviations found so far, in the order they were found. Empty for a well-formed file. /// /// ADR 0005. A snapshot: objects load lazily, so reading more of the document can add diagnostics, which a later call returns. @@ -156,8 +190,10 @@ internal static PdfDocument Read(PdfSource source, EngineConfiguration configura FileHeader header = FileHeader.Locate(source, diagnostics); CrossReference crossReference = CrossReferenceReader.Read(source, header, diagnostics) ?? Reconstruct(diagnostics); var loader = new ObjectLoader(source, header, crossReference, diagnostics, new ObjectLoaderHooks()); + IReadOnlyList revisions = ReadRevisions(source, crossReference, diagnostics); CosDictionary catalog = ReadCatalog(loader, diagnostics); - return new PdfDocument(source, diagnostics, loader, catalog); + PdfLinearization? linearization = LinearizationReader.Read(source, loader, diagnostics); + return new PdfDocument(source, diagnostics, loader, catalog, revisions, linearization); } catch { @@ -166,6 +202,19 @@ internal static PdfDocument Read(PdfSource source, EngineConfiguration configura } } + /// Describes each revision: its byte range and its own trailer (§7.5.6). + private static PdfRevision[] ReadRevisions(PdfSource source, CrossReference crossReference, DiagnosticSink diagnostics) + { + long[] ends = RevisionReader.ReadEnds(source, crossReference, diagnostics); + var revisions = new PdfRevision[ends.Length]; + for (int index = 0; index < ends.Length; index++) + { + revisions[index] = new PdfRevision(index, ends[index], crossReference.Revisions[index].Newest.Trailer); + } + + return revisions; + } + /// Rebuilds the cross-reference information by scanning the file when it cannot be read (§7.5.4). Issue #41. private static CrossReference Reconstruct(DiagnosticSink diagnostics) => throw new DiagnosticException(diagnostics.Snapshot() is [.., var last] diff --git a/src/Broadside/PdfLinearization.cs b/src/Broadside/PdfLinearization.cs new file mode 100644 index 00000000..85219ef2 --- /dev/null +++ b/src/Broadside/PdfLinearization.cs @@ -0,0 +1,87 @@ +using Broadside.Objects; + +namespace Broadside; + +/// +/// The linearization information of a file that begins with a linearization parameter dictionary: the dictionary, the objects the +/// first page needs, and the hint tables. +/// +/// +/// +/// ISO 32000-2 Annex F, F.3.3 and Table F.1. A linearized file is organized so that its first page can be displayed before the +/// rest of the file has arrived. Reading never relies on linearization: objects are located through the cross-reference +/// sections as in any file. This view exists for consumers that fetch byte ranges progressively. +/// +/// +/// A file keeps its parameter dictionary when an update is appended, but its L entry then no longer matches the file +/// length and the file is no longer linearized (Table F.1, G.7); tells the two apart. The +/// hints may then be stale. +/// +/// The typed properties read on every call; an entry that is not an integer reads as 0. +/// +public sealed class PdfLinearization +{ + private readonly Lazy _hints; + + internal PdfLinearization(CosDictionary dictionary, CosReference reference, IReadOnlyList firstPageObjects, Func readHints) + { + Dictionary = dictionary; + Reference = reference; + FirstPageObjects = firstPageObjects; + _hints = new Lazy(readHints, LazyThreadSafetyMode.ExecutionAndPublication); + } + + /// Gets the linearization parameter dictionary, the first object in the file. + /// ISO 32000-2 F.3.3, Table F.1. + public CosDictionary Dictionary { get; } + + /// Gets the indirect reference to the linearization parameter dictionary. + /// ISO 32000-2 F.3.3: nothing in the document refers to it, but the first-page cross-reference section lists it. + public CosReference Reference { get; } + + /// Gets the file length the dictionary states (L), in bytes from the %PDF- header. + /// ISO 32000-2 Table F.1. When it differs from the actual length, the file is not linearized. + public long FileLength => ReadInteger(Names.L); + + /// Gets the number of pages the dictionary states (N). + /// ISO 32000-2 Table F.1. + public int PageCount => (int)Math.Clamp(ReadInteger(Names.N), 0, int.MaxValue); + + /// Gets the object number of the first page's page object (O). + /// ISO 32000-2 Table F.1. + public int FirstPageObjectNumber => (int)Math.Clamp(ReadInteger(Names.O), 0, int.MaxValue); + + /// Gets the zero-based page number of the first page (P); 0 when absent. + /// ISO 32000-2 Table F.1 and F.3.4. + public int FirstPageNumber => (int)Math.Clamp(ReadInteger(Names.P), 0, int.MaxValue); + + /// + /// Gets the objects the first-page cross-reference section lists, in object number order: the linearization parameter + /// dictionary, the catalog and the other document-level objects needed at open, the first page's objects and the primary hint + /// stream. Empty when the file's original revision has no separate first-page section. + /// + /// ISO 32000-2 F.3.4, F.3.5 and F.3.6 (parts 2 to 6 of a linearized file). + public IReadOnlyList FirstPageObjects { get; } + + /// + /// Gets the page offset and shared object hint tables, read on first use; when the hint stream cannot be + /// read (a diagnostic says why) or uses a filter. + /// + /// ISO 32000-2 F.3.6, F.4.1, F.4.2 and F.4.3. + public PdfLinearizationHints? Hints => _hints.Value; + + private long ReadInteger(CosName key) => Dictionary.TryGetValue(key, out CosObject? value) && value is CosInteger integer ? integer.Value : 0; + + /// The parameter dictionary's keys (Table F.1). + internal static class Names + { + public static readonly CosName Linearized = new("Linearized"); + public static readonly CosName L = new("L"); + public static readonly CosName H = new("H"); + public static readonly CosName O = new("O"); + public static readonly CosName E = new("E"); + public static readonly CosName N = new("N"); + public static readonly CosName T = new("T"); + public static readonly CosName P = new("P"); + } +} diff --git a/src/Broadside/PdfLinearizationHints.cs b/src/Broadside/PdfLinearizationHints.cs new file mode 100644 index 00000000..aa0987bc --- /dev/null +++ b/src/Broadside/PdfLinearizationHints.cs @@ -0,0 +1,36 @@ +namespace Broadside; + +/// The page offset and shared object hint tables of a linearized file, decoded. +/// +/// +/// ISO 32000-2 F.4.1 to F.4.3. Offsets are absolute byte offsets from the start of the file (the same base as +/// ), already corrected for the primary hint stream, which the tables' own positions +/// leave out (F.4.1). Following qpdf, which is validated against Acrobat, an offset equal to the hint stream's is corrected too: +/// otherwise a first page stored right after the hint stream would be placed on it. +/// +/// +/// The content-stream offset and length items of the page offset table (Table F.4 items 6 and 7) and the fractional positions of +/// shared object references (item 5) are not exposed: Acrobat writes placeholder values there. The thumbnail, outline, thread, +/// named destination, interactive form, information dictionary, logical structure, page label, renditions and embedded file hint +/// tables (F.4.4 to F.4.7) are not read. +/// +/// +public sealed class PdfLinearizationHints +{ + internal PdfLinearizationHints(IReadOnlyList pages, IReadOnlyList sharedObjects) + { + Pages = pages; + SharedObjects = sharedObjects; + } + + /// Gets one entry per page, in the order of the page offset hint table: the first page (the linearization dictionary's O) first. + /// ISO 32000-2 F.4.2, Tables F.3 and F.4. + public IReadOnlyList Pages { get; } + + /// + /// Gets the shared object groups, in table order: the groups stored with the first page, then those in the shared objects + /// section. holds indexes into this list. + /// + /// ISO 32000-2 F.4.3, Tables F.5 and F.6. + public IReadOnlyList SharedObjects { get; } +} diff --git a/src/Broadside/PdfPageHint.cs b/src/Broadside/PdfPageHint.cs new file mode 100644 index 00000000..83e96e7e --- /dev/null +++ b/src/Broadside/PdfPageHint.cs @@ -0,0 +1,38 @@ +namespace Broadside; + +/// One page's entry in the page offset hint table: where the page's objects are and which shared objects it needs. +/// ISO 32000-2 F.4.2, Table F.4. +public sealed class PdfPageHint +{ + internal PdfPageHint(int firstObjectNumber, int objectCount, long offset, long length, IReadOnlyList sharedObjects) + { + FirstObjectNumber = firstObjectNumber; + ObjectCount = objectCount; + Offset = offset; + Length = length; + SharedObjects = sharedObjects; + } + + /// + /// Gets the object number of the page's first object: the linearization dictionary's O for the first page, 1 for the + /// second, then accumulated over the object counts of the pages before. + /// + /// ISO 32000-2 Table F.4, item 1. + public int FirstObjectNumber { get; } + + /// Gets the number of objects of the page, the page object included. + /// ISO 32000-2 Table F.4, item 1. + public int ObjectCount { get; } + + /// Gets the absolute offset of the page's page object in the file. + /// ISO 32000-2 Table F.3, item 2, and Table F.4, item 2: the first page's location, then accumulated page lengths. + public long Offset { get; } + + /// Gets the length of the page in bytes, from its page object to the last byte of its last object. + /// ISO 32000-2 Table F.4, item 2. + public long Length { get; } + + /// Gets the shared object identifiers the page references: indexes into . + /// ISO 32000-2 Table F.4, items 3 and 4. Empty for the first page in a conforming file. + public IReadOnlyList SharedObjects { get; } +} diff --git a/src/Broadside/PdfRevision.cs b/src/Broadside/PdfRevision.cs new file mode 100644 index 00000000..8a186443 --- /dev/null +++ b/src/Broadside/PdfRevision.cs @@ -0,0 +1,42 @@ +using Broadside.Objects; + +namespace Broadside; + +/// +/// One revision of a document: the original file or one incremental update appended to it, as the bytes from the start of the file +/// to that revision's end-of-file marker. +/// +/// +/// +/// ISO 32000-2 §7.5.6. Updates are appended and leave earlier bytes intact, so revision k is exactly the first +/// bytes of the file: that prefix is the complete file as it was after the k-th save. The range ends just past the %%EOF +/// marker that terminates the revision's trailer, including the end-of-line marker after it when there is one. +/// +/// +/// A linearized file's first-page and main cross-reference sections (Annex F, F.3.4) form one revision, the original; a hybrid +/// file's cross-reference stream belongs to the revision of the table that names it (§7.5.8.4). +/// +/// +public sealed class PdfRevision +{ + internal PdfRevision(int index, long length, CosDictionary trailer) + { + Index = index; + Length = length; + Trailer = trailer; + } + + /// Gets the zero-based position of the revision: 0 for the original file, 1 for the first update, and so on. + public int Index { get; } + + /// + /// Gets the length of the revision in bytes. The revision is the bytes from offset 0 of the file (not of the %PDF- header) + /// up to, not including, this offset. + /// + /// ISO 32000-2 §7.5.5 and §7.5.6: each trailer is terminated by its own %%EOF marker. + public long Length { get; } + + /// Gets the revision's own trailer dictionary, as stored in the file (for a linearized original, the first-page trailer). + /// ISO 32000-2 §7.5.5, Table 15, and §7.5.6. + public CosDictionary Trailer { get; } +} diff --git a/src/Broadside/PdfSharedObjectHint.cs b/src/Broadside/PdfSharedObjectHint.cs new file mode 100644 index 00000000..8c83155e --- /dev/null +++ b/src/Broadside/PdfSharedObjectHint.cs @@ -0,0 +1,30 @@ +namespace Broadside; + +/// One group of adjacent objects in the shared object hint table. +/// ISO 32000-2 F.4.3, Table F.6. +public sealed class PdfSharedObjectHint +{ + internal PdfSharedObjectHint(int firstObjectNumber, int objectCount, long offset, long length) + { + FirstObjectNumber = firstObjectNumber; + ObjectCount = objectCount; + Offset = offset; + Length = length; + } + + /// Gets the object number of the group's first object; the others follow it in number order. + /// ISO 32000-2 Table F.5, item 1, and Table F.6, item 4. + public int FirstObjectNumber { get; } + + /// Gets the number of objects in the group. + /// ISO 32000-2 Table F.6, item 4. + public int ObjectCount { get; } + + /// Gets the absolute offset of the group's first object in the file. + /// ISO 32000-2 Table F.5, item 2, and Table F.6, item 1 (accumulated group lengths). + public long Offset { get; } + + /// Gets the length of the group in bytes. + /// ISO 32000-2 Table F.6, item 1. + public long Length { get; } +} diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index 6b193443..dd9a7abc 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -111,8 +111,11 @@ Broadside.PdfDocument Broadside.PdfDocument.Catalog.get -> Broadside.Objects.CosDictionary! Broadside.PdfDocument.Diagnostics.get -> System.Collections.Generic.IReadOnlyList! Broadside.PdfDocument.Dispose() -> void +Broadside.PdfDocument.IsLinearized.get -> bool +Broadside.PdfDocument.Linearization.get -> Broadside.PdfLinearization? Broadside.PdfDocument.Pages.get -> Broadside.PdfPageCollection! Broadside.PdfDocument.Resolve(Broadside.Objects.CosObject? value) -> Broadside.Objects.CosObject! +Broadside.PdfDocument.Revisions.get -> System.Collections.Generic.IReadOnlyList! Broadside.PdfDocument.Trailer.get -> Broadside.Objects.CosDictionary! Broadside.PdfDocument.Version.get -> Broadside.PdfVersion Broadside.PdfEngine @@ -122,6 +125,18 @@ Broadside.PdfEngine.Open(System.IO.Stream! stream) -> Broadside.PdfDocument! Broadside.PdfEngine.Open(System.ReadOnlyMemory bytes) -> Broadside.PdfDocument! Broadside.PdfEngine.PdfEngine() -> void Broadside.PdfEngine.PdfEngine(Broadside.PdfOptions! options) -> void +Broadside.PdfLinearization +Broadside.PdfLinearization.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfLinearization.FileLength.get -> long +Broadside.PdfLinearization.FirstPageNumber.get -> int +Broadside.PdfLinearization.FirstPageObjectNumber.get -> int +Broadside.PdfLinearization.FirstPageObjects.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfLinearization.Hints.get -> Broadside.PdfLinearizationHints? +Broadside.PdfLinearization.PageCount.get -> int +Broadside.PdfLinearization.Reference.get -> Broadside.Objects.CosReference! +Broadside.PdfLinearizationHints +Broadside.PdfLinearizationHints.Pages.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfLinearizationHints.SharedObjects.get -> System.Collections.Generic.IReadOnlyList! Broadside.PdfOptions Broadside.PdfOptions.PdfOptions() -> void Broadside.PdfOptions.ReadingMode.get -> Broadside.PdfReadingMode @@ -143,6 +158,12 @@ Broadside.PdfPageCollection Broadside.PdfPageCollection.Count.get -> int Broadside.PdfPageCollection.GetEnumerator() -> System.Collections.Generic.IEnumerator! Broadside.PdfPageCollection.this[int index].get -> Broadside.PdfPage! +Broadside.PdfPageHint +Broadside.PdfPageHint.FirstObjectNumber.get -> int +Broadside.PdfPageHint.Length.get -> long +Broadside.PdfPageHint.ObjectCount.get -> int +Broadside.PdfPageHint.Offset.get -> long +Broadside.PdfPageHint.SharedObjects.get -> System.Collections.Generic.IReadOnlyList! Broadside.PdfReadingMode Broadside.PdfReadingMode.Lenient = 0 -> Broadside.PdfReadingMode Broadside.PdfReadingMode.Strict = 1 -> Broadside.PdfReadingMode @@ -156,6 +177,15 @@ Broadside.PdfRectangle.PdfRectangle(double x1, double y1, double x2, double y2) Broadside.PdfRectangle.Right.get -> double Broadside.PdfRectangle.Top.get -> double Broadside.PdfRectangle.Width.get -> double +Broadside.PdfRevision +Broadside.PdfRevision.Index.get -> int +Broadside.PdfRevision.Length.get -> long +Broadside.PdfRevision.Trailer.get -> Broadside.Objects.CosDictionary! +Broadside.PdfSharedObjectHint +Broadside.PdfSharedObjectHint.FirstObjectNumber.get -> int +Broadside.PdfSharedObjectHint.Length.get -> long +Broadside.PdfSharedObjectHint.ObjectCount.get -> int +Broadside.PdfSharedObjectHint.Offset.get -> long Broadside.PdfVersion Broadside.PdfVersion.CompareTo(Broadside.PdfVersion other) -> int Broadside.PdfVersion.Equals(Broadside.PdfVersion other) -> bool diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index ee0219ec..3c5d7939 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -1,5 +1,6 @@ using Broadside.Diagnostics; using Broadside.Objects; +using Broadside.Parsing; using SharpFuzz; namespace Broadside.Fuzz; @@ -16,15 +17,17 @@ internal static class FuzzTargets ["lexer"] = Lexer, ["object-parser"] = ObjectParser, ["document"] = Document, + ["hint-tables"] = HintTables, }; /// /// Opens the input as a whole file in lenient mode and reads everything the document model exposes: version, trailer, every - /// page's boxes, rotation, user unit and resources. A is the one documented outcome for a file + /// page's boxes, rotation, user unit and resources, the revisions, and the linearization dictionary and hint tables. A is the one documented outcome for a file /// whose cross-reference information cannot be read at all (until issue #41 reconstructs it); any other exception is a finding. - /// Every box must be normalized and every rotation one of 0, 90, 180, 270. + /// Every box must be normalized and every rotation one of 0, 90, 180, 270; every revision must be a non-empty prefix of the input + /// at its own index. /// - /// ISO 32000-2 §7.5.1 to §7.5.5, §7.7.2, §7.7.3. + /// ISO 32000-2 §7.5.1 to §7.5.6, §7.7.2, §7.7.3, Annex F. private static void Document(ReadOnlySpan data) { using PdfDocument? document = OpenOrNull(data); @@ -35,6 +38,22 @@ private static void Document(ReadOnlySpan data) _ = document.Version; _ = document.Trailer.Count; + for (int index = 0; index < document.Revisions.Count; index++) + { + PdfRevision revision = document.Revisions[index]; + if (revision.Index != index || revision.Length <= 0 || revision.Length > data.Length) + { + throw new InvalidOperationException($"Revision {revision.Index} at position {index} has length {revision.Length} in a file of {data.Length} bytes."); + } + } + + _ = document.IsLinearized; + if (document.Linearization is { } linearization) + { + _ = (linearization.FileLength, linearization.PageCount, linearization.FirstPageObjects.Count); + _ = linearization.Hints?.Pages.Count; + } + foreach (PdfPage page in document.Pages) { foreach (PdfRectangle box in (ReadOnlySpan)[page.MediaBox, page.CropBox, page.BleedBox, page.TrimBox, page.ArtBox]) @@ -54,6 +73,40 @@ private static void Document(ReadOnlySpan data) } } + /// + /// Decodes the input as linearization hint data: byte 0 gives the page count (1 to 16), bytes 1 and 2 the position of the shared + /// object table, the rest is the hint stream. Decoding either fails with a reason or yields one entry per page, groups of at + /// least one object, and never throws. + /// + /// ISO 32000-2 F.4.1 to F.4.3. + private static void HintTables(ReadOnlySpan data) + { + if (data.Length < 4) + { + return; + } + + int pages = (data[0] & 15) + 1; + ReadOnlySpan hints = data[3..]; + int shared = ((data[1] << 8) | data[2]) % hints.Length; + var layout = new HintTableLayout(HeaderOffset: 0, HintOffset: 100, HintLength: 50, FirstPageObjectNumber: 1, PageCount: pages); + + PdfLinearizationHints? decoded = HintTableReader.Parse(hints, shared, layout, out string? error); + + if ((decoded is null) == (error is null)) + { + throw new InvalidOperationException("Hint decoding must yield either tables or a reason, not both or neither."); + } + + if (decoded is not null + && (decoded.Pages.Count != pages + || decoded.SharedObjects.Any(group => group.ObjectCount < 1) + || decoded.Pages.Any(page => page.ObjectCount < 0 || page.Length < 0))) + { + throw new InvalidOperationException("Decoded hint tables are inconsistent with the layout."); + } + } + private static PdfDocument? OpenOrNull(ReadOnlySpan data) { try diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index ce3d0824..ad6b3059 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources; a `DiagnosticException` for a file whose cross-reference information cannot be read is the one allowed outcome until #41 reconstructs it). Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources; a `DiagnosticException` for a file whose cross-reference information cannot be read is the one allowed outcome until #41 reconstructs it; it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. @@ -25,7 +25,12 @@ dotnet run -c Release --project tests/Broadside.Fuzz -- --run object-parser arti `--run ` executes the target once on one input, which is also how to replay a crash found by libFuzzer or AFL. -Whole corpus files are the right seeds for `lexer` and `object-parser`, which read any bytes as a file body, and for `document`, which reads whole files. +Whole corpus files are the right seeds for `lexer` and `object-parser`, which read any bytes as a file body, and for `document`, which reads whole files. `hint-tables` reads raw hint stream data, for which whole files are a weak seed; for libFuzzer and AFL seed it with the hint stream of `linearized.pdf` behind its three control bytes (two pages, shared table at 44): + +```sh +mkdir -p artifacts/fuzz/seeds-hints +{ printf '\001\000\054'; qpdf --show-object=7 --raw-stream-data tests/Corpus/linearized.pdf; } > artifacts/fuzz/seeds-hints/linearized.bin +``` Smoke mode is a regression net, not a fuzzer: it has no coverage feedback and finds only shallow bugs. Use a real fuzzer for anything that parses. diff --git a/tests/Broadside.TestSupport/Corpus.cs b/tests/Broadside.TestSupport/Corpus.cs index 1f4e8c6a..f2904deb 100644 --- a/tests/Broadside.TestSupport/Corpus.cs +++ b/tests/Broadside.TestSupport/Corpus.cs @@ -16,6 +16,7 @@ public static class Corpus "object-stream.pdf", "incremental-update.pdf", "hybrid-xref.pdf", + "linearized.pdf", "flate-stream.pdf", "lzw-stream.pdf", "ascii85-stream.pdf", diff --git a/tests/Broadside.Tests/Document/IncrementalUpdateTests.cs b/tests/Broadside.Tests/Document/IncrementalUpdateTests.cs new file mode 100644 index 00000000..49415a23 --- /dev/null +++ b/tests/Broadside.Tests/Document/IncrementalUpdateTests.cs @@ -0,0 +1,153 @@ +using System.Text; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// Incremental updates: revisions, their byte ranges and the newest copy of each object. ISO 32000-2 §7.5.6, §7.5.4, H.7. +public class IncrementalUpdateTests +{ + [Fact] + public void An_updated_file_has_one_revision_per_update_and_the_first_is_the_original_file() + { + // incremental-update.pdf is empty-page.pdf with one update appended (tests/Corpus/README.md). + long original = Corpus.Bytes("empty-page.pdf").LongLength; + long updated = Corpus.Bytes("incremental-update.pdf").LongLength; + + using PdfDocument document = PdfDocument.Open(Corpus.Path("incremental-update.pdf")); + + Assert.Collection( + document.Revisions, + first => Assert.Equal((0, original), (first.Index, first.Length)), + second => Assert.Equal((1, updated), (second.Index, second.Length))); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_hybrid_file_has_its_main_section_and_its_update_section_as_two_revisions() + { + // §7.5.8.4: the update section's XRefStm stream is stored after the main section's %%EOF, so it belongs to the update. + byte[] file = Corpus.Bytes("hybrid-xref.pdf"); + int mainEnd = file.AsSpan().IndexOf("%%EOF\n"u8) + "%%EOF\n"u8.Length; + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal([mainEnd, file.Length], document.Revisions.Select(revision => (int)revision.Length)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation() + { + // The stages of ISO 32000-2 H.7: change an annotation, delete two, reuse one deleted number with generation 1. + byte[][] saves = UpdatingExample(); + + using PdfDocument document = PdfDocument.Open(saves[^1]); + + Assert.Same(CosNull.Instance, document.Resolve(new CosReference(5, 0))); + Assert.Equal("New Text #1", Contents(document, new CosReference(5, 1))); + Assert.Same(CosNull.Instance, document.Resolve(new CosReference(6, 0))); + Assert.Same(CosNull.Instance, document.Resolve(new CosReference(6, 1))); + Assert.Equal("Third", Contents(document, new CosReference(7, 0))); + CosArray annotations = Assert.IsType(document.Resolve(new CosReference(4, 0))); + Assert.Equal([new CosReference(5, 1), new CosReference(7, 0)], annotations.Cast()); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Each_revision_is_the_file_as_it_was_after_that_save() + { + byte[][] saves = UpdatingExample(); + + using PdfDocument document = PdfDocument.Open(saves[^1]); + + Assert.Equal(saves.Select(save => save.LongLength), document.Revisions.Select(revision => revision.Length)); + using PdfDocument afterFirstUpdate = PdfDocument.Open(saves[^1].AsMemory(0, (int)document.Revisions[1].Length)); + Assert.Equal("Changed", Contents(afterFirstUpdate, new CosReference(5, 0))); + Assert.Equal("Second", Contents(afterFirstUpdate, new CosReference(6, 0))); + Assert.Empty(afterFirstUpdate.Diagnostics); + } + + [Fact] + public void Each_revision_has_its_own_trailer() + { + byte[][] saves = UpdatingExample(); + + using PdfDocument document = PdfDocument.Open(saves[^1]); + + Assert.False(document.Revisions[0].Trailer.ContainsKey(new CosName("Prev"))); + Assert.All(document.Revisions.Skip(1), revision => Assert.IsType(revision.Trailer[new CosName("Prev")])); + Assert.Equal(new CosInteger(8), document.Revisions[^1].Trailer[new CosName("Size")]); + Assert.Equal(new CosInteger(7), document.Revisions[0].Trailer[new CosName("Size")]); + } + + [Fact] + public void An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic() + { + byte[] file = TestPdf.AppendUpdate(Corpus.Bytes("empty-page.pdf"), "/Size 4", (3, 0, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] >>")); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal(new PdfRectangle(0, 0, 595, 842), Assert.Single(document.Pages).MediaBox); + Assert.Equal(new CosReference(1, 0), document.Trailer[new CosName("Root")]); + Diagnostic diagnostic = Assert.Single(document.Diagnostics, d => d.Code == "TrailerEntryFromOlderRevision"); + Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); + Assert.Contains("Root", diagnostic.Message, StringComparison.Ordinal); + } + + [Fact] + public void An_update_trailer_that_drops_root_throws_in_strict_mode() + { + byte[] file = TestPdf.AppendUpdate(Corpus.Bytes("empty-page.pdf"), "/Size 4", (3, 0, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] >>")); + + DiagnosticException error = Assert.Throws(() => PdfDocument.Open(file, new PdfOptions().UseStrict())); + + Assert.Equal("TrailerEntryFromOlderRevision", error.Diagnostic.Code); + } + + [Fact] + public void An_earlier_revision_without_its_end_of_file_marker_ends_after_its_startxref_offset_with_a_diagnostic() + { + string original = Encoding.Latin1.GetString(Corpus.Bytes("empty-page.pdf")); + string truncated = original[..original.LastIndexOf("%%EOF", StringComparison.Ordinal)]; + byte[] file = TestPdf.AppendUpdate(Encoding.Latin1.GetBytes(truncated), "/Size 4 /Root 1 0 R", (3, 0, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] >>")); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal([truncated.TrimEnd().Length, file.Length], document.Revisions.Select(revision => (int)revision.Length)); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("EndOfFileMarkerMissing", diagnostic.Code); + Assert.Equal(truncated.TrimEnd().Length, diagnostic.Offset); + } + + private static string Contents(PdfDocument document, CosReference annotation) + { + CosDictionary dictionary = Assert.IsType(document.Resolve(annotation)); + return Assert.IsType(dictionary[new CosName("Contents")]).DecodeText(); + } + + /// The original file and the file after each of three updates, after ISO 32000-2 H.7. + private static byte[][] UpdatingExample() + { + byte[] original = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] /Annots 4 0 R >>", + "[5 0 R 6 0 R]", + "<< /Type /Annot /Subtype /Text /Rect [0 0 10 10] /Contents (First) >>", + "<< /Type /Annot /Subtype /Text /Rect [0 0 10 10] /Contents (Second) >>"); + byte[] changed = TestPdf.AppendUpdate( + original, + "/Size 7 /Root 1 0 R", + (5, 0, "<< /Type /Annot /Subtype /Text /Rect [0 0 10 10] /Contents (Changed) >>")); + byte[] deleted = TestPdf.AppendUpdate(changed, "/Size 7 /Root 1 0 R", (4, 0, "[]"), (5, 1, null), (6, 1, null)); + byte[] reused = TestPdf.AppendUpdate( + deleted, + "/Size 8 /Root 1 0 R", + (4, 0, "[5 1 R 7 0 R]"), + (5, 1, "<< /Type /Annot /Subtype /Text /Rect [0 0 10 10] /Contents (New Text #1) >>"), + (7, 0, "<< /Type /Annot /Subtype /Text /Rect [0 0 10 10] /Contents (Third) >>")); + return [original, changed, deleted, reused]; + } +} diff --git a/tests/Broadside.Tests/Document/LinearizationTests.cs b/tests/Broadside.Tests/Document/LinearizationTests.cs new file mode 100644 index 00000000..e44c4715 --- /dev/null +++ b/tests/Broadside.Tests/Document/LinearizationTests.cs @@ -0,0 +1,162 @@ +using System.Text; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// +/// Linearized files: detection, the parameter dictionary, the first-page objects and the hint tables. ISO 32000-2 Annex F. Expected +/// values come from qpdf --show-linearization tests/Corpus/linearized.pdf (qpdf 12.4.2), recorded in the corpus README. +/// +public class LinearizationTests +{ + [Fact] + public void A_linearized_file_is_detected_and_exposes_its_parameter_dictionary() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("linearized.pdf")); + + Assert.True(document.IsLinearized); + PdfLinearization linearization = Assert.IsType(document.Linearization); + Assert.Equal(new CosReference(5, 0), linearization.Reference); + Assert.Same(document.Resolve(new CosReference(5, 0)), linearization.Dictionary); + Assert.Equal(new CosInteger(1627), linearization.Dictionary[new CosName("L")]); + Assert.Equal(1627, linearization.FileLength); + Assert.Equal(2, linearization.PageCount); + Assert.Equal(8, linearization.FirstPageObjectNumber); + Assert.Equal(0, linearization.FirstPageNumber); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void The_first_page_objects_are_those_in_the_first_page_cross_reference_section() + { + // F.3.4: the linearization dictionary (5), the catalog (6), the primary hint stream (7) and the first page's objects (8-12). + using PdfDocument document = PdfDocument.Open(Corpus.Path("linearized.pdf")); + + IReadOnlyList objects = document.Linearization!.FirstPageObjects; + + Assert.Equal(Enumerable.Range(5, 8).Select(number => new CosReference(number, 0)), objects); + } + + [Fact] + public void A_linearized_file_is_one_revision() + { + byte[] file = Corpus.Bytes("linearized.pdf"); + + using PdfDocument document = PdfDocument.Open(file); + + PdfRevision revision = Assert.Single(document.Revisions); + Assert.Equal(file.LongLength, revision.Length); + Assert.Equal(new CosReference(6, 0), revision.Trailer[new CosName("Root")]); + Assert.Equal(2, document.Pages.Count); + } + + [Fact] + public void The_page_offset_hint_table_locates_each_page() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("linearized.pdf")); + + PdfLinearizationHints hints = Assert.IsType(document.Linearization!.Hints); + + Assert.Collection( + hints.Pages, + first => + { + Assert.Equal((8, 5, 720L, 359L), (first.FirstObjectNumber, first.ObjectCount, first.Offset, first.Length)); + Assert.Empty(first.SharedObjects); + }, + second => + { + Assert.Equal((1, 2, 1079L, 184L), (second.FirstObjectNumber, second.ObjectCount, second.Offset, second.Length)); + Assert.Equal([2, 3, 4], second.SharedObjects); + }); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void The_shared_object_hint_table_locates_each_group() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("linearized.pdf")); + + PdfLinearizationHints hints = document.Linearization!.Hints!; + + Assert.Equal( + [(8, 1, 720L, 98L), (9, 1, 818L, 86L), (10, 1, 904L, 98L), (11, 1, 1002L, 32L), (12, 1, 1034L, 45L)], + hints.SharedObjects.Select(group => (group.FirstObjectNumber, group.ObjectCount, group.Offset, group.Length))); + } + + [Fact] + public void Hint_offsets_count_from_byte_0_of_the_file_when_bytes_precede_the_header() + { + byte[] file = [.. "Junk\n"u8, .. Corpus.Bytes("linearized.pdf")]; + + using PdfDocument document = PdfDocument.Open(file); + + Assert.True(document.IsLinearized); + Assert.Equal([725L, 1084L], document.Linearization!.Hints!.Pages.Select(page => page.Offset)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_file_that_is_not_linearized_reports_false() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("page-tree-inherited.pdf")); + + Assert.False(document.IsLinearized); + Assert.Null(document.Linearization); + } + + [Fact] + public void An_update_appended_to_a_linearized_file_makes_it_an_ordinary_two_revision_file() + { + // Table F.1, L: a length mismatch means the file shall be treated as an ordinary file; G.7: hints may be stale. + byte[] original = Corpus.Bytes("linearized.pdf"); + string text = Encoding.Latin1.GetString(original); + int id = text.IndexOf("/ID ", StringComparison.Ordinal); + string idEntry = text[id..text.IndexOf(">>", id, StringComparison.Ordinal)]; + byte[] file = TestPdf.AppendUpdate(original, $"/Size 13 /Root 6 0 R {idEntry}", (11, 0, "[0 0 595 842]")); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.False(document.IsLinearized); + Assert.NotNull(document.Linearization); + Assert.Equal([original.LongLength, file.LongLength], document.Revisions.Select(revision => revision.Length)); + Assert.All(document.Pages, page => Assert.Equal(new PdfRectangle(0, 0, 595, 842), page.MediaBox)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_malformed_linearization_dictionary_is_ignored_with_a_diagnostic() + { + byte[] file = Replace(Corpus.Bytes("linearized.pdf"), "/N 2 ", "/N() "); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.False(document.IsLinearized); + Assert.Null(document.Linearization); + Assert.Equal(2, document.Pages.Count); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("LinearizationDictionaryInvalid", diagnostic.Code); + Assert.Equal(new CosReference(5, 0), diagnostic.ObjectReference); + } + + [Fact] + public void A_malformed_hint_table_leaves_the_file_linearized_without_hints_and_with_a_diagnostic() + { + byte[] file = Replace(Corpus.Bytes("linearized.pdf"), "/S 44 ", "/S 99 "); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.True(document.IsLinearized); + Assert.Null(document.Linearization!.Hints); + Assert.Equal("LinearizationHintsInvalid", Assert.Single(document.Diagnostics).Code); + } + + private static byte[] Replace(byte[] file, string oldValue, string newValue) + { + string text = Encoding.Latin1.GetString(file); + Assert.Contains(oldValue, text, StringComparison.Ordinal); + return Encoding.Latin1.GetBytes(text.Replace(oldValue, newValue, StringComparison.Ordinal)); + } +} diff --git a/tests/Broadside.Tests/Document/TestPdf.cs b/tests/Broadside.Tests/Document/TestPdf.cs index 19616348..c4ac74ee 100644 --- a/tests/Broadside.Tests/Document/TestPdf.cs +++ b/tests/Broadside.Tests/Document/TestPdf.cs @@ -26,6 +26,40 @@ public static byte[] OnePage(string pageEntries, string catalogEntries = "", str "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", $"<< /Type /Page /Parent 2 0 R /Resources << >> {pageEntries} >>"); + /// + /// Appends an incremental update (ISO 32000-2 §7.5.6) to : the objects, a cross-reference section with one + /// subsection per object, and a trailer with and a Prev entry pointing at the + /// section the file's last startxref names. An object whose body is is written as a free entry + /// carrying Generation, the generation a reuse of the number takes. + /// + public static byte[] AppendUpdate(byte[] file, string trailerEntries, params (int Number, int Generation, string? Body)[] objects) + { + string existing = Encoding.Latin1.GetString(file); + int startxref = existing.LastIndexOf("startxref", StringComparison.Ordinal); + string prev = existing[(startxref + "startxref".Length)..].Trim().Split('\n')[0].Trim(); + var text = new StringBuilder(existing); + var offsets = new Dictionary(); + foreach ((int number, int generation, string? body) in objects) + { + if (body is not null) + { + offsets[number] = text.Length; + text.Append(CultureInfo.InvariantCulture, $"{number} {generation} obj\n{body}\nendobj\n"); + } + } + + int xref = text.Length; + text.Append("xref\n"); + foreach ((int number, int generation, string? body) in objects.OrderBy(o => o.Number)) + { + string entry = body is null ? $"0000000000 {generation:D5} f" : $"{offsets[number]:D10} {generation:D5} n"; + text.Append(CultureInfo.InvariantCulture, $"{number} 1\n{entry} \n"); + } + + text.Append(CultureInfo.InvariantCulture, $"trailer\n<< {trailerEntries} /Prev {prev} >>\nstartxref\n{xref}\n%%EOF\n"); + return Encoding.Latin1.GetBytes(text.ToString()); + } + /// Writes the file. public byte[] Build(params string[] objects) { diff --git a/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs b/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs index fe69dc73..2ff2a840 100644 --- a/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs +++ b/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs @@ -22,7 +22,7 @@ public void A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics(str using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName)); - int expectedPages = fileName == "page-tree-inherited.pdf" ? 2 : 1; + int expectedPages = fileName is "page-tree-inherited.pdf" or "linearized.pdf" ? 2 : 1; Assert.Equal(expectedPages, document.Pages.Count); foreach (PdfPage page in document.Pages) { diff --git a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt index 419d0e00..26965c93 100644 --- a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt +++ b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt @@ -13,6 +13,7 @@ hybrid-xref.pdf, incremental-update.pdf, inline-image.pdf, + linearized.pdf, lzw-stream.pdf, metadata-xmp.pdf, missing-endobj.pdf, diff --git a/tests/Corpus/README.md b/tests/Corpus/README.md index 73a0378c..690e53a2 100644 --- a/tests/Corpus/README.md +++ b/tests/Corpus/README.md @@ -2,7 +2,7 @@ Hand-written PDF files, one feature per file, for the Phase 1 unit tests. Every file is as small as it can be while remaining a complete document: a catalog, a page tree and one page (two in `page-tree-inherited.pdf`), plus only the objects the feature needs. -All files are produced by `generate.py`: +All files but one are produced by `generate.py`: ```sh python3 -I tests/Corpus/generate.py # rewrites every PDF in place @@ -11,6 +11,15 @@ python3 -I tests/Corpus/generate.py /tmp/out # or into another directory The script uses only the standard library. It computes cross-reference offsets and stream lengths, and it implements the codecs and ciphers the corpus needs (LZW, ASCII85, ASCIIHex, RunLength, PNG predictor, RC4, AES-128/256, the standard security handler algorithms of ISO 32000-2 clause 7.6.4). It is deterministic: the values the specification asks a writer to draw from a random source (file identifiers, AES initialization vectors, R6 salts and file key) are fixed constants derived from the file name, so regenerating the corpus produces byte-identical files and `git diff` shows exactly what a change to the script did. A real writer must use a cryptographically secure random source for those values; the corpus trades that for reproducibility. +The exception is `linearized.pdf`: writing hint tables by hand is a project of its own, so the file is qpdf's output, checked in as a binary. It is regenerated, byte for byte with the same qpdf version, from `page-tree-inherited.pdf`: + +```sh +qpdf --linearize --deterministic-id --object-streams=disable --compress-streams=n \ + tests/Corpus/page-tree-inherited.pdf tests/Corpus/linearized.pdf # qpdf 12.4.2 +``` + +`--object-streams=disable` keeps classic cross-reference tables (no cross-reference streams) and `--compress-streams=n` leaves the hint stream unfiltered, so the file reads without either. `generate.py` does not write or delete it. + `generate.py` self-tests its codecs against known answers before writing anything (the LZW example in clause 7.4.4.2, FIPS-197 AES vectors, an RC4 vector). Clause numbers below refer to ISO 32000-2:2020. @@ -28,7 +37,8 @@ Verification was run with qpdf 12.4.2 (`qpdf --check`), poppler (`pdfinfo`, `pdf | `xref-stream.pdf` | Cross-reference stream (`/Type /XRef`, `/W [1 2 1]`, uncompressed), no classic table, no `trailer` keyword. | 7.5.8.2, 7.5.8.3 | `qpdf --check`; `qpdf --qdf --object-streams=disable` | clean | | `object-stream.pdf` | Catalog, page tree and page stored in an object stream (`/Type /ObjStm`, `/N 3`, `/First`), located through type 2 entries in a cross-reference stream. | 7.5.7, 7.5.8.3 Table 18 | `qpdf --qdf --object-streams=disable` lists objects 1-3 as ordinary objects | clean | | `incremental-update.pdf` | `empty-page.pdf` followed by one update section that replaces object 3 with an A4 `/MediaBox`; update trailer carries `/Prev`. | 7.5.6 | `pdfinfo` shows `595 x 842 pts (A4)` | clean | -| `hybrid-xref.pdf` | Classic table for objects 1-3 (4-6 listed free), then an object stream (5) holding the `/Info` dictionary (4), a cross-reference stream (6, `/Index [4 3]`) describing it, and an empty update section whose trailer has `/Prev` and `/XRefStm`. Mirrors the example in 7.5.8.4. A reader that follows `/XRefStm` sees the title; one that does not sees no `/Info`. | 7.5.8.4 Table 19 | `pdfinfo` shows `Title: hybrid` | clean | +| `hybrid-xref.pdf` | Classic table for objects 1-3 (4-6 listed free), then an object stream (5) holding the `/Info` dictionary (4), a cross-reference stream (6, `/Index [4 3]`) describing it, and an empty update section whose trailer has `/Prev` and `/XRefStm`. Each section ends with `startxref` and `%%EOF` (7.5.6), so the file has two revisions. Mirrors the example in 7.5.8.4. A reader that follows `/XRefStm` sees the title; one that does not sees no `/Info`. | 7.5.8.4 Table 19 | `pdfinfo` shows `Title: hybrid` | clean | +| `linearized.pdf` | `page-tree-inherited.pdf` linearized by qpdf 12.4.2 (command above): linearization parameter dictionary (object 5, `/L 1627 /H [590 130] /O 8 /E 1079 /N 2 /T 1409`), first-page cross-reference section for objects 5-12 whose trailer `/Prev` points forward to the main section (objects 0-4), unfiltered primary hint stream (object 7, `/S 44`), inherited attributes pushed down to the pages. Two Letter pages. | F.3, F.3.3, F.3.4, F.4.1-F.4.3 | `qpdf --check` (`File is linearized`), `qpdf --check-linearization` (`no linearization errors`), `qpdf --show-linearization`; `pdfinfo` shows `Optimized: yes`, 2 Letter pages; `pdftotext` prints `Page 1` and `Page 2` | clean; hint tables per `qpdf --show-linearization`: page 0 = 5 objects from 8, 359 bytes at 720, no shared references; page 1 = 2 objects from 1, 184 bytes at 1079, shared groups 2, 3, 4; shared groups 0-4 = objects 8-12, one each, lengths 98, 86, 98, 32, 45 from 720 | | `flate-stream.pdf` | Content stream with `/Filter /FlateDecode`. | 7.4.4 | `pdftotext` prints `FlateDecode` | clean | | `lzw-stream.pdf` | Content stream with `/Filter /LZWDecode`, `EarlyChange` 1 (default), clear code first, EOD last. | 7.4.4.2, Table 8 | `pdftotext` prints `LZWDecode` | clean | | `ascii85-stream.pdf` | Content stream with `/Filter /ASCII85Decode`, `~>` terminator. | 7.4.3 | `pdftotext` prints `ASCII85Decode` | clean | diff --git a/tests/Corpus/generate.py b/tests/Corpus/generate.py index 6e62fbf4..bc82c8ff 100644 --- a/tests/Corpus/generate.py +++ b/tests/Corpus/generate.py @@ -626,13 +626,16 @@ def gen_incremental_update() -> bytes: def gen_hybrid_xref() -> bytes: """7.5.8.4: objects 1-3 in the classic table; the /Info dictionary (4) lives in an object stream (5) that only the cross-reference stream (6) knows about. - The main table lists 4-6 as free, as in the example in 7.5.8.4.""" + The main table lists 4-6 as free, as in the example in 7.5.8.4. The main + section and the update section each end with startxref and %%EOF (7.5.6).""" f = File("1.5", binary=True) f.add(1, catalog()) f.add(2, pages()) f.add(3, page()) main = f.pos() f.raw(xref_table(f.offsets, 7, b"<< /Size 7 /Root 1 0 R >>")) + # 7.5.6: each trailer is terminated by its own %%EOF; the example in 7.5.8.4 ends the main section so too. + f.raw(b"startxref\n%d\n%%%%EOF\n" % main) f.add(5, object_stream([(4, b"<< /Title (hybrid) >>")])) xs = f.pos() rows = xref_stream_rows([(2, 5, 0), (1, f.offsets[5], 0), (1, xs, 0)]) diff --git a/tests/Corpus/hybrid-xref.pdf b/tests/Corpus/hybrid-xref.pdf index dffc77750502a350d0fb2f4350423b3300b1a842..254fd8e944aaf9f28be37e60b2716f7c3553c352 100644 GIT binary patch delta 69 zcmdnPdVzIA2cvLtNn%k+MNw)Rmyv-bm#V6(zuV+?#@(!Q7#NvYCc865Nt+s)DcIR@ NArzV!89@|s0RZH)6KMbd delta 49 zcmcb>x`%Z`2jk>9jJsGn7#JBpOpa!Xk~Xn4Q?Rq+DlSPZDyb++P2(~%Fyc~Gb@g}S F0sxlE4x|78 diff --git a/tests/Corpus/linearized.pdf b/tests/Corpus/linearized.pdf new file mode 100644 index 0000000000000000000000000000000000000000..a5330f72341ed2a97d6a5d81d2a9fed00499f64a GIT binary patch literal 1627 zcmc&!%Wl&^6g33|@`_J5n@F&LdH5AeRVDg}KtLO%mRM9>IPoO7Dt2YNRbkDCAby}* zcJLki2s^~Rel#Xgg^)mul1b*y%$;;7pE%}pl~r6+ zHE+@$4E7F2Hiyzx!#G};5>69b^zO_+?8H@knlE~(4tf_3;kr~dCRozU!e7&;dzID~@@bBIBYgw@Fefaj^)<=s=tgLFMZLv{S zu0!6*v&v*uiLihBaso{D@wX@CjrPY8-cMT7&L@)pxlh z2}vE=gb?;fU;?|d*EF}R{T-UwS@*&p)2wfznd`Unx|5$1#Tw#8nv|q!O&O4;Ez@51 zAoKQ3SGnpYq>?<7gSM`IX_lscmg#634PGZkEKR=WIUeSnK-HqUB1TFD)MPxCLZ-A& ZPp#M--4mX^$kf8(;a_QoR(`7 Date: Fri, 9 Oct 2026 13:40:31 -0500 Subject: [PATCH 007/152] feat(filters): decode streams through filters (#38) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the filter extension point and the managed non-image filters of ISO 32000-2 §7.4. - Contract: IStreamFilter (Name, Decode(ReadOnlyMemory, IBufferWriter, FilterContext)) and FilterContext (parameters, stream dictionary, Resolve, DecodeStream for auxiliary streams such as JBIG2Globals, Report, reading mode, decoded-length limit), sized for the Phase 2B image codecs. - Registry per engine, built from the options: PdfOptions.UseFilter replaces or adds a filter; no static registry. PdfOptions.WithMaxDecodedStreamLength bounds decompression bombs. - Defaults: ASCIIHexDecode, ASCII85Decode, LZWDecode (EarlyChange), FlateDecode (BCL DeflateStream, zlib header checked, raw-deflate fallback, truncation detected), RunLengthDecode. TIFF predictor 2 and PNG predictors 10-15 run in the pipeline after LZW and Flate, so a replacement gets them too. - PdfDocument.DecodeStream (array and IBufferWriter overloads). Table 5 deviations, abbreviations, unknown filters, external files and over-long output are repaired with diagnostics; strict mode throws. - Crypt filter slot (Identity only) for the security handler (#42). - Fuzz targets filter-asciihex, filter-ascii85, filter-lzw, filter-flate, filter-runlength, filter-predictor; document target decodes contents. - Benchmarks per filter and for the predictors; allocation tests prove no per-byte or per-row allocation. - Conformance rows 7.4.1-7.4.10; adding-a-filter skill carries the real contract. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/adding-a-filter/SKILL.md | 63 ++- .../Broadside.Benchmarks.csproj | 3 +- .../Broadside.Benchmarks/FilterBenchmarks.cs | 153 +++++++ docs/conformance/iso-32000-2.md | 13 +- src/Broadside/EngineConfiguration.cs | 14 +- src/Broadside/Filters/Ascii85DecodeFilter.cs | 116 ++++++ src/Broadside/Filters/AsciiHexDecodeFilter.cs | 100 +++++ src/Broadside/Filters/FilterContext.cs | 131 ++++++ src/Broadside/Filters/FilterNames.cs | 105 +++++ src/Broadside/Filters/FilterOutput.cs | 106 +++++ src/Broadside/Filters/FilterRegistry.cs | 47 +++ src/Broadside/Filters/FlateDecodeFilter.cs | 181 +++++++++ src/Broadside/Filters/ICryptFilterHandler.cs | 43 ++ src/Broadside/Filters/IStreamFilter.cs | 44 ++ src/Broadside/Filters/LzwDecodeFilter.cs | 205 ++++++++++ src/Broadside/Filters/PooledBufferWriter.cs | 141 +++++++ src/Broadside/Filters/Predictor.cs | 229 +++++++++++ .../Filters/RunLengthDecodeFilter.cs | 76 ++++ src/Broadside/Filters/StreamDecoder.cs | 381 ++++++++++++++++++ src/Broadside/Parsing/DiagnosticCodes.cs | 15 + src/Broadside/PdfDocument.cs | 36 +- src/Broadside/PdfOptions.cs | 63 +++ src/Broadside/PublicAPI.Unshipped.txt | 45 +++ tests/Broadside.Fuzz/FuzzTargets.cs | 83 ++++ tests/Broadside.Fuzz/README.md | 4 +- tests/Broadside.TestSupport/FilterEncoders.cs | 181 +++++++++ .../Filters/AsciiFilterTests.cs | 113 ++++++ .../Filters/CorpusFilterTests.cs | 79 ++++ .../Filters/FilterAllocationTests.cs | 126 ++++++ .../Filters/FilterExtensionPointTests.cs | 206 ++++++++++ .../Filters/FilterPipelineTests.cs | 205 ++++++++++ .../Broadside.Tests/Filters/FilterTesting.cs | 58 +++ .../Filters/FlateDecodeFilterTests.cs | 96 +++++ .../Filters/LzwDecodeFilterTests.cs | 118 ++++++ .../Broadside.Tests/Filters/PredictorTests.cs | 126 ++++++ .../Filters/RunLengthDecodeFilterTests.cs | 65 +++ 36 files changed, 3748 insertions(+), 22 deletions(-) create mode 100644 bench/Broadside.Benchmarks/FilterBenchmarks.cs create mode 100644 src/Broadside/Filters/Ascii85DecodeFilter.cs create mode 100644 src/Broadside/Filters/AsciiHexDecodeFilter.cs create mode 100644 src/Broadside/Filters/FilterContext.cs create mode 100644 src/Broadside/Filters/FilterNames.cs create mode 100644 src/Broadside/Filters/FilterOutput.cs create mode 100644 src/Broadside/Filters/FilterRegistry.cs create mode 100644 src/Broadside/Filters/FlateDecodeFilter.cs create mode 100644 src/Broadside/Filters/ICryptFilterHandler.cs create mode 100644 src/Broadside/Filters/IStreamFilter.cs create mode 100644 src/Broadside/Filters/LzwDecodeFilter.cs create mode 100644 src/Broadside/Filters/PooledBufferWriter.cs create mode 100644 src/Broadside/Filters/Predictor.cs create mode 100644 src/Broadside/Filters/RunLengthDecodeFilter.cs create mode 100644 src/Broadside/Filters/StreamDecoder.cs create mode 100644 tests/Broadside.TestSupport/FilterEncoders.cs create mode 100644 tests/Broadside.Tests/Filters/AsciiFilterTests.cs create mode 100644 tests/Broadside.Tests/Filters/CorpusFilterTests.cs create mode 100644 tests/Broadside.Tests/Filters/FilterAllocationTests.cs create mode 100644 tests/Broadside.Tests/Filters/FilterExtensionPointTests.cs create mode 100644 tests/Broadside.Tests/Filters/FilterPipelineTests.cs create mode 100644 tests/Broadside.Tests/Filters/FilterTesting.cs create mode 100644 tests/Broadside.Tests/Filters/FlateDecodeFilterTests.cs create mode 100644 tests/Broadside.Tests/Filters/LzwDecodeFilterTests.cs create mode 100644 tests/Broadside.Tests/Filters/PredictorTests.cs create mode 100644 tests/Broadside.Tests/Filters/RunLengthDecodeFilterTests.cs diff --git a/.claude/skills/adding-a-filter/SKILL.md b/.claude/skills/adding-a-filter/SKILL.md index 22b37049..82f96a3b 100644 --- a/.claude/skills/adding-a-filter/SKILL.md +++ b/.claude/skills/adding-a-filter/SKILL.md @@ -5,8 +5,6 @@ description: "Use when implementing a stream filter or image codec (FlateDecode, # Adding a filter -> **The filter contract is defined by issue #38 (Decode streams through filters). When it lands, replace the "Contract" section of this skill with the real signatures from `src/Broadside/Filters/` and `src/Broadside/PublicAPI.Unshipped.txt`.** Until then this is a design brief: it says what the contract must provide and what a filter PR must deliver. It does not spell the methods. - A filter is "a stream encoding named in a stream's `/Filter` entry, and the codec that decodes or encodes it. Image codecs are filters." (`CONTEXT.md`). Filters are an extension point: a public contract in the core with a fully managed default (`CLAUDE.md`, "Hard rules"; ADR 0001). ## Where it lives @@ -14,20 +12,58 @@ A filter is "a stream encoding named in a stream's `/Filter` entry, and the code - Contract and standard filters: namespace `Broadside.Filters` in `src/Broadside/`. Image codecs (DCT, CCITT, JBIG2, JPX; Phase 2B) implement the same contract, in the same namespace or a sub-namespace per codec. - Tests: `tests/Broadside.Tests/Filters/`, namespace `Broadside.Tests.Filters`, one class per filter. - Corpus: `tests/Corpus/-stream.pdf` (`flate-stream.pdf`, `lzw-stream.pdf`, `ascii85-stream.pdf`, `asciihex-stream.pdf`, `runlength-stream.pdf`, `filter-chain.pdf`, `png-predictor.pdf` exist); the encoder side of each lives in `tests/Corpus/generate.py` (`lzw_encode`, `ascii85_encode`, `png_up_predict`, ...). -- Benchmarks: `bench/Broadside.Benchmarks/Benchmarks.cs`. Fuzz: `tests/Broadside.Fuzz/FuzzTargets.cs`, target `filter-`. +- Benchmarks: a `Benchmarks` class deriving from `FilterBenchmark` in `bench/Broadside.Benchmarks/FilterBenchmarks.cs` (256 KB of `FilterEncoders.SampleData`, encoded in setup with `tests/Broadside.TestSupport/FilterEncoders.cs`). Allocation proof: `tests/Broadside.Tests/Filters/FilterAllocationTests.cs`. Fuzz: `tests/Broadside.Fuzz/FuzzTargets.cs`, target `filter-`. + +## Contract + +The contract landed with #38 in `src/Broadside/Filters/` (public surface in `src/Broadside/PublicAPI.Unshipped.txt`): + +```csharp +namespace Broadside.Filters; + +public interface IStreamFilter +{ + CosName Name { get; } // full /Filter name (Table 6), the registry key; never an abbreviation + void Decode(ReadOnlyMemory encoded, // never empty: the pipeline short-circuits empty data without a diagnostic + IBufferWriter output, + FilterContext context); +} + +public sealed class FilterContext +{ + public FilterContext(); // stand-alone: default filters, no document, own diagnostics + public CosDictionary? Parameters { get; init; } // this filter's DecodeParms (values may be references: Resolve them) + public CosDictionary StreamDictionary { get; init; } // the stream's dictionary: Width, Height, BitsPerComponent, ColorSpace, Decode... + public PdfReadingMode ReadingMode { get; init; } // Strict => Report throws + public long MaxDecodedLength { get; init; } // check header-declared sizes against this before allocating + public IReadOnlyList Diagnostics { get; }// what was reported through this context + public void Report(string code, DiagnosticSeverity severity, string message); // lenient: record; strict: throw DiagnosticException + public CosObject Resolve(CosObject? value); // indirect references of the document (CosNull outside one) + public ReadOnlyMemory DecodeStream(CosStream stream); // another stream through the same pipeline (JBIG2Globals) +} + +// Registration, per engine (no static registry): +new PdfOptions().UseFilter(IStreamFilter filter); // replaces the default of filter.Name or adds a name; later wins +new PdfOptions().WithMaxDecodedStreamLength(long); // decompression-bomb limit, default PdfOptions.DefaultMaxDecodedStreamLength (1 GiB) + +// Consumption: +ReadOnlyMemory PdfDocument.DecodeStream(CosStream stream); +void PdfDocument.DecodeStream(CosStream stream, IBufferWriter output); +``` + +Managed defaults (`sealed`, stateless): `AsciiHexDecodeFilter`, `Ascii85DecodeFilter`, `LzwDecodeFilter`, `FlateDecodeFilter`, `RunLengthDecodeFilter`, listed in internal `FilterRegistry.Defaults`. A Phase 2B codec adds its instance there (one line; registration lines conflict trivially). -## Contract (responsibilities, not signatures) +What the pipeline (internal `StreamDecoder`, one per document) does so a filter does not: -An implementation must be able to: +- reads `Filter`/`DecodeParms` (resolving references), repairs Table 5 deviations with `DecodeParmsInvalid`/`FilterInvalid`, expands the §8.9.7 Table 92 abbreviations (with `FilterAbbreviationNotAllowed` outside inline images), and runs the chain in order; +- applies the §7.4.4.4 predictors (internal `Predictor`) after any filter named `LZWDecode` or `FlateDecode`, including a replacement: a replacement must not apply them itself; +- routes `Crypt` (§7.4.10) to the internal `ICryptFilterHandler` slot (`StreamDecoder.CryptFilter`, set by #42); `Crypt` and abbreviations cannot be registered; +- buffers between stages in pooled memory, truncates at `MaxDecodedLength` with `StreamDecodedLengthExceeded`, stops the chain at an unregistered name with `FilterUnsupported` and returns the data decoded so far; +- converts any exception a filter throws (other than a strict-mode `DiagnosticException`) into `FilterFailed`, keeping what it wrote. -- name the filter as it appears in `/Filter` (§7.4 Table 6) and its inline-image abbreviation (§8.9.7 Table 92: `/Fl`, `/LZW`, `/A85`, `/AHx`, `/RL`, `/CCF`, `/DCT`); -- decode a stream body given its `/DecodeParms` dictionary (§7.4.1; predictor parameters in §7.4.4.4 Table 10, CCITT in Table 11, JBIG2 in Table 12, DCT in Table 13, JPX in §7.4.9, Crypt in §7.4.10) into a caller-provided or pooled buffer, without per-byte or per-row allocation (codecs are a hot path); -- participate in a chain: the `/Filter` array is applied in order on decode (`filter-chain.pdf` is `[/ASCII85Decode /FlateDecode]`), each stage consuming the previous stage's output; -- repair and record in lenient mode: truncated data, a missing EOD marker, a wrong predictor row length produce a `Diagnostic` and the bytes decoded so far; strict mode throws (ADR 0005); -- for image codecs, deliver samples as a planar or interleaved buffer with a declared colour space and bit depth (plan, Track 2B), including the DCT Adobe-marker CMYK/YCCK and JPX colour-space and SMask-in-data cases; -- encode, for the filters the writer uses (Flate, DCT baseline, PNG predictors; Phase 4A). Decode-only filters say so. +Rules for an implementation: keep no state between calls (one instance serves every thread of every document of the engine); write through `IBufferWriter` in chunks (internal `FilterOutput` ref struct does this for the defaults); report each kind of deviation once per call with the codes in `Parsing/DiagnosticCodes.cs` ("Stream filters" group: `FilterDataInvalid`, `FilterDataTruncated`, ...); in lenient mode write what can be decoded and return. -Registration goes through the options object: `PdfOptions.UseFilter(...)` (plan row 1.12; `Use*` selects an implementation, `CLAUDE.md` "Code conventions") replaces or adds a filter for one engine instance. There is no static registry: a consumer must be able to run two engines with different filter sets in one process, and tests must be able to inject a fake. +Image codecs (Phase 2B): read the image entries from `StreamDictionary`, resolve auxiliary streams with `Resolve` and decode them with `DecodeStream`, size-check against `MaxDecodedLength` before allocating, and write the §8.9.3 sample layout so a codec behaves like any filter in a chain. Codec metadata (DCT transform, JPX components and colour, alpha) is #60's optional image facet: a second interface the four codecs implement in addition to `IStreamFilter`, used when the codec is last in the chain. Encoding (Flate, DCT baseline, PNG predictors; Phase 4A) will be a separate interface, so decode-only filters need not change. ## Managed default @@ -46,11 +82,10 @@ Every filter the PDF file format depends on ships in the core, written in C#. Al ## Worked example: LZWDecode -`tests/Corpus/lzw-stream.pdf` holds a content stream encoded by `lzw_encode` in `generate.py` (9–12-bit codes, clear code 256 first, EOD 257 last, `EarlyChange` 1). The decoder lives in `Broadside.Filters`, cites `ISO 32000-2 §7.4.4.2.`, handles `/EarlyChange 0` from `/DecodeParms` (Table 8), and then the TIFF and PNG predictors from §7.4.4.4 run as a second stage shared with Flate. Tests: the Table 7 sequence `45 45 45 45 45 65 45 45 45 66` decodes from `80 0B 60 50 22 0C 0C 85 01` (the known answer `self_test()` in `generate.py` already checks for the encoder); `lzw-stream.pdf` decodes to the bytes `pdftotext` shows (`LZWDecode`); a truncated body yields a diagnostic in lenient mode and throws in strict mode. Fuzz target `filter-lzw`, benchmark `LzwBenchmarks.Decode` over the corpus stream, row `7.4.4` done with those tests named. +`tests/Corpus/lzw-stream.pdf` holds a content stream encoded by `lzw_encode` in `generate.py` (9–12-bit codes, clear code 256 first, EOD 257 last, `EarlyChange` 1). The decoder lives in `Broadside.Filters`, cites `ISO 32000-2 §7.4.4.2.`, handles `/EarlyChange 0` from `/DecodeParms` (Table 8), and then the TIFF and PNG predictors from §7.4.4.4 run as a second stage shared with Flate. Tests: the Table 7 sequence `45 45 45 45 45 65 45 45 45 66` decodes from `80 0B 60 50 22 0C 0C 85 01` (the known answer `self_test()` in `generate.py` already checks for the encoder); `lzw-stream.pdf` decodes to the bytes `pdftotext` shows (`LZWDecode`); a truncated body yields a diagnostic in lenient mode and throws in strict mode. Fuzz target `filter-lzw`, benchmark `LzwBenchmarks.Decode`, row `7.4.4` done with those tests named. ## Checklist -- [ ] Contract section of this skill replaced with the real signatures once #38 has landed - [ ] Implementation in `Broadside.Filters`, managed only, `sealed`, clause-cited XML docs - [ ] Registered through `PdfOptions`, not a static registry - [ ] Lenient repairs recorded as `Diagnostic`; strict mode throws diff --git a/bench/Broadside.Benchmarks/Broadside.Benchmarks.csproj b/bench/Broadside.Benchmarks/Broadside.Benchmarks.csproj index b072a2bc..72543caf 100644 --- a/bench/Broadside.Benchmarks/Broadside.Benchmarks.csproj +++ b/bench/Broadside.Benchmarks/Broadside.Benchmarks.csproj @@ -10,8 +10,9 @@ - + + diff --git a/bench/Broadside.Benchmarks/FilterBenchmarks.cs b/bench/Broadside.Benchmarks/FilterBenchmarks.cs new file mode 100644 index 00000000..f10e9b31 --- /dev/null +++ b/bench/Broadside.Benchmarks/FilterBenchmarks.cs @@ -0,0 +1,153 @@ +using System.Buffers; +using System.Text; +using BenchmarkDotNet.Attributes; +using Broadside.Filters; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Benchmarks; + +/// +/// Shared shape of the filter benchmarks: decode 256 KB of sample data, encoded in setup, through the filter contract into a +/// reused buffer (ISO 32000-2 §7.4). Filters are a hot path: Allocated must read - for every filter except Flate, +/// whose BCL inflater costs a constant per call; Broadside.Tests.Filters.FilterAllocationTests fails the build otherwise. +/// +public abstract class FilterBenchmark +{ + /// The size of the decoded data. + protected const int DecodedLength = 256 * 1024; + + private readonly ArrayBufferWriter _output = new(DecodedLength * 2); + private readonly FilterContext _context; + private byte[] _encoded = []; + + /// Initializes a new instance of the class. + /// The filter's DecodeParms, or . + protected FilterBenchmark(CosDictionary? parameters = null) => _context = new FilterContext { Parameters = parameters }; + + /// Gets the filter under test. + protected abstract IStreamFilter Filter { get; } + + [GlobalSetup] + public void Setup() + { + _encoded = Encode(FilterEncoders.SampleData(DecodedLength)); + Decode(); + if (_output.WrittenCount != DecodedLength) + { + throw new InvalidOperationException($"{Filter.Name.Value} decoded {_output.WrittenCount} bytes, not {DecodedLength}."); + } + } + + [Benchmark] + public int Decode() + { + _output.ResetWrittenCount(); + Filter.Decode(_encoded, _output, _context); + return _output.WrittenCount; + } + + /// Encodes the sample data the way the filter expects it. + /// The data. + /// The encoded data. + protected abstract byte[] Encode(byte[] data); +} + +/// ASCIIHexDecode (§7.4.2). +[MemoryDiagnoser] +public class AsciiHexBenchmarks : FilterBenchmark +{ + protected override IStreamFilter Filter { get; } = new AsciiHexDecodeFilter(); + + protected override byte[] Encode(byte[] data) => Encoding.ASCII.GetBytes(Convert.ToHexString(data) + ">"); +} + +/// ASCII85Decode (§7.4.3). +[MemoryDiagnoser] +public class Ascii85Benchmarks : FilterBenchmark +{ + protected override IStreamFilter Filter { get; } = new Ascii85DecodeFilter(); + + protected override byte[] Encode(byte[] data) => FilterEncoders.Ascii85Encode(data); +} + +/// LZWDecode with EarlyChange 1 (§7.4.4.2). +[MemoryDiagnoser] +public class LzwBenchmarks : FilterBenchmark +{ + protected override IStreamFilter Filter { get; } = new LzwDecodeFilter(); + + protected override byte[] Encode(byte[] data) => FilterEncoders.LzwEncode(data); +} + +/// FlateDecode through the BCL (§7.4.4.1): allocation is the inflater, once per call. +[MemoryDiagnoser] +public class FlateBenchmarks : FilterBenchmark +{ + protected override IStreamFilter Filter { get; } = new FlateDecodeFilter(); + + protected override byte[] Encode(byte[] data) => FilterEncoders.Zlib(data); +} + +/// RunLengthDecode (§7.4.5). +[MemoryDiagnoser] +public class RunLengthBenchmarks : FilterBenchmark +{ + protected override IStreamFilter Filter { get; } = new RunLengthDecodeFilter(); + + protected override byte[] Encode(byte[] data) => FilterEncoders.RunLengthEncode(data); +} + +/// +/// The PNG and TIFF predictors (§7.4.4.4) over 256 KB of rows of 256 RGB samples, undone as the pipeline does after LZW or Flate. +/// +[MemoryDiagnoser] +public class PredictorBenchmarks +{ + private const int Columns = 256; + private const int Rows = 341; + + private readonly ArrayBufferWriter _output = new(Columns * 3 * (Rows + 1)); + private FilterContext _context = new(); + private byte[] _predicted = []; + + /// The Predictor value: 2 (TIFF) or 15 (PNG, rows cycling through the five algorithms). + [Params(2, 15)] + public int Predictor { get; set; } + + [GlobalSetup] + public void Setup() + { + _context = new FilterContext + { + Parameters = new CosDictionary + { + [new CosName("Predictor")] = new CosInteger(Predictor), + [new CosName("Colors")] = new CosInteger(3), + [new CosName("Columns")] = new CosInteger(Columns), + }, + }; + int row = Columns * 3; + byte[] samples = FilterEncoders.SampleData(row * Rows, alphabet: 200); + if (Predictor == 2) + { + _predicted = samples; + return; + } + + _predicted = new byte[(row + 1) * Rows]; + for (int index = 0; index < Rows; index++) + { + _predicted[index * (row + 1)] = (byte)(index % 5); + samples.AsSpan(index * row, row).CopyTo(_predicted.AsSpan((index * (row + 1)) + 1)); + } + } + + [Benchmark] + public int Decode() + { + _output.ResetWrittenCount(); + Filters.Predictor.Decode(_predicted, _output, _context); + return _output.WrittenCount; + } +} diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index 655fac59..0eaae2b7 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -16,10 +16,19 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.3.5 | Name objects | done | `CosName` | `Broadside.Tests.Objects.StringAndNameParsingTests.Names_from_table_4_expand_number_sign_escapes`, `Broadside.Tests.Objects.StringAndNameParsingTests.Names_are_equal_when_their_expanded_bytes_are_equal`, `Broadside.Tests.Objects.SerializationTests.Names_escape_delimiters_white_space_number_signs_and_non_ascii_bytes` | | | 7.3.6 | Array objects | done | `CosArray` | `Broadside.Tests.Objects.ContainerParsingTests.Parses_the_array_example`, `Broadside.Tests.Objects.ContainerParsingTests.Arrays_nest_hold_references_and_keep_null_elements` | | | 7.3.7 | Dictionary objects | done | `CosDictionary` | `Broadside.Tests.Objects.ContainerParsingTests.Parses_the_dictionary_example`, `Broadside.Tests.Objects.ContainerParsingTests.A_null_valued_entry_is_the_same_as_an_absent_one` | Null-valued entries are never stored | -| 7.3.8 | Stream objects | partial | `CosStream` | `Broadside.Tests.Objects.ContainerParsingTests.A_stream_takes_its_data_from_its_length_or_from_endstream`, `Broadside.Tests.Objects.ContainerParsingTests.Streams_with_a_wrong_length_or_no_endstream_are_rejected`, `Broadside.Tests.Objects.CorpusObjectTests.The_metadata_stream_of_metadata_xmp_pdf_holds_its_declared_length` | Extent from a direct or indirect Length (`Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length`), else from endstream; external stream files (F, FFilter, FDecodeParms) and filters (#38) pending | +| 7.3.8 | Stream objects | partial | `CosStream` | `Broadside.Tests.Objects.ContainerParsingTests.A_stream_takes_its_data_from_its_length_or_from_endstream`, `Broadside.Tests.Objects.ContainerParsingTests.Streams_with_a_wrong_length_or_no_endstream_are_rejected`, `Broadside.Tests.Objects.CorpusObjectTests.The_metadata_stream_of_metadata_xmp_pdf_holds_its_declared_length` | Extent from a direct or indirect Length (`Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length`), else from endstream; filters decode through `PdfDocument.DecodeStream` (7.4) with DL as a capacity hint; external stream files (F, FFilter, FDecodeParms) are not read: `StreamExternalFileUnsupported` and the embedded bytes decode instead (`Broadside.Tests.Filters.FilterPipelineTests.Data_in_an_external_file_is_not_read_and_the_stream_bytes_decode_instead_with_a_diagnostic`) | | 7.3.9 | Null object | done | `CosNull` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_null_as_the_single_null_object`, `Broadside.Tests.Objects.ContainerParsingTests.A_null_valued_entry_is_the_same_as_an_absent_one` | | | 7.3.10 | Indirect objects | done | `CosReference`, `PdfDocument` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_indirect_references`, `Broadside.Tests.Document.FileStructureTests.References_to_missing_free_or_other_generation_objects_resolve_to_null_without_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.An_object_without_endobj_is_read_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_reads_as_null_with_a_diagnostic` | `PdfDocument.Resolve`; references to missing, free or other-generation objects are null with no diagnostic; loading goes through the internal `ObjectLoader` (hooks for #41, #42, #45); a misplaced object reads as null until #41 searches for it | -| 7.4 | Filters | not started | | | | +| 7.4.1 | General | done | `IStreamFilter`, `FilterContext`, `StreamDecoder`, `FilterRegistry`, `PdfDocument`, `PdfOptions` | `Broadside.Tests.Filters.CorpusFilterTests.A_filtered_content_stream_decodes_to_the_bytes_that_were_encoded`, `Broadside.Tests.Filters.CorpusFilterTests.Every_page_content_stream_of_a_well_formed_file_decodes_with_no_diagnostics`, `Broadside.Tests.Filters.FilterPipelineTests.Filters_apply_in_array_order_and_the_same_filter_may_appear_twice`, `Broadside.Tests.Filters.FilterPipelineTests.Decode_parameters_align_with_the_filter_array_and_null_means_defaults`, `Broadside.Tests.Filters.FilterPipelineTests.Deviations_from_table_5_are_repaired_with_one_diagnostic`, `Broadside.Tests.Filters.FilterPipelineTests.An_unknown_filter_leaves_the_stream_readable_as_raw_bytes_with_a_diagnostic`, `Broadside.Tests.Filters.FilterPipelineTests.Output_beyond_the_decoded_length_limit_is_truncated_with_a_diagnostic`, `Broadside.Tests.Filters.FilterExtensionPointTests.A_decorator_registered_through_the_options_replaces_the_default_flate_filter`, `Broadside.Tests.Filters.FilterExtensionPointTests.Two_engines_in_one_process_keep_their_own_filters` | `PdfDocument.DecodeStream`; filter extension point `PdfOptions.UseFilter` (per engine, no static registry); unknown or not-yet-implemented filters stop the chain with `FilterUnsupported`; decoded-length limit `PdfOptions.WithMaxDecodedStreamLength`; fuzz targets `filter-*`, `document` decodes page contents; Table 92 abbreviations outside inline images read with a diagnostic | +| 7.4.2 | ASCIIHexDecode filter | done | `AsciiHexDecodeFilter` | `Broadside.Tests.Filters.AsciiFilterTests.Ascii_hex_decodes_digit_pairs_ignores_white_space_and_pads_an_odd_final_digit`, `Broadside.Tests.Filters.AsciiFilterTests.Ascii_hex_skips_invalid_characters_with_one_diagnostic`, `Broadside.Tests.Filters.AsciiFilterTests.Ascii_hex_without_the_end_marker_decodes_to_its_end_with_a_diagnostic`, `Broadside.Tests.Filters.AsciiFilterTests.Both_filters_round_trip_the_encoders_of_the_corpus_generator` | Decode; `asciihex-stream.pdf`; `AsciiHexBenchmarks`; fuzz `filter-asciihex`; encoding is Phase 4 | +| 7.4.3 | ASCII85Decode filter | done | `Ascii85DecodeFilter` | `Broadside.Tests.Filters.AsciiFilterTests.Ascii85_decodes_groups_z_partial_groups_and_ignores_white_space`, `Broadside.Tests.Filters.AsciiFilterTests.Ascii85_repairs_impossible_sequences_with_a_diagnostic`, `Broadside.Tests.Filters.AsciiFilterTests.Ascii85_without_the_end_marker_decodes_the_partial_group_with_a_diagnostic`, `Broadside.Tests.Filters.AsciiFilterTests.Strict_mode_throws_for_an_invalid_character` | Decode; `ascii85-stream.pdf`, `filter-chain.pdf`; `Ascii85Benchmarks`; fuzz `filter-ascii85`; encoding is Phase 4 | +| 7.4.4 | LZWDecode and FlateDecode filters | done | `LzwDecodeFilter`, `FlateDecodeFilter`, `Predictor` | `Broadside.Tests.Filters.LzwDecodeFilterTests.Decodes_the_packed_example_after_table_7`, `Broadside.Tests.Filters.LzwDecodeFilterTests.Round_trips_data_that_grows_the_code_length_to_12_bits_and_clears_the_table`, `Broadside.Tests.Filters.LzwDecodeFilterTests.Data_without_the_end_of_data_code_decodes_to_its_end_with_a_diagnostic`, `Broadside.Tests.Filters.FlateDecodeFilterTests.Inflates_zlib_data`, `Broadside.Tests.Filters.FlateDecodeFilterTests.Truncated_data_keeps_everything_inflated_with_a_diagnostic`, `Broadside.Tests.Filters.PredictorTests.Png_predicted_rows_decode_to_the_samples_whatever_predictor_10_to_15_is_declared`, `Broadside.Tests.Filters.PredictorTests.Tiff_predictor_2_adds_each_component_to_the_same_component_to_its_left`, `Broadside.Tests.Filters.PredictorTests.Malformed_predictor_data_or_parameters_are_repaired_with_a_diagnostic`, `Broadside.Tests.Filters.FilterAllocationTests.Decoding_through_the_contract_allocates_nothing` | 7.4.4.1 to 7.4.4.4. Flate through the BCL `DeflateStream` (zlib header checked, Adler-32 not read); LZW honors EarlyChange; predictors 2 and 10 to 15 applied by the pipeline after any LZWDecode/FlateDecode filter; `lzw-stream.pdf`, `flate-stream.pdf`; `LzwBenchmarks`, `FlateBenchmarks`, `PredictorBenchmarks`; fuzz `filter-lzw`, `filter-flate`, `filter-predictor`; encoding (Flate, PNG predictors) is Phase 4A | +| 7.4.5 | RunLengthDecode filter | done | `RunLengthDecodeFilter` | `Broadside.Tests.Filters.RunLengthDecodeFilterTests.Decodes_literal_and_repeated_runs_up_to_the_end_of_data_byte`, `Broadside.Tests.Filters.RunLengthDecodeFilterTests.Data_that_ends_early_keeps_what_is_available_with_a_diagnostic`, `Broadside.Tests.Filters.RunLengthDecodeFilterTests.Round_trips_the_encoder_of_the_corpus_generator` | Decode; `runlength-stream.pdf`; `RunLengthBenchmarks`; fuzz `filter-runlength`; encoding is Phase 4 | +| 7.4.6 | CCITTFaxDecode filter | not started | | | Phase 2B (#63); until then the chain stops before it with `FilterUnsupported` | +| 7.4.7 | JBIG2Decode filter | not started | | | Phase 2B (#64, #65); `FilterContext.DecodeStream` and `Resolve` serve JBIG2Globals | +| 7.4.8 | DCTDecode filter | not started | | | Phase 2B (#61, #62) | +| 7.4.9 | JPXDecode filter | not started | | | Phase 2B (#67, #68) | +| 7.4.10 | Crypt filter | partial | `StreamDecoder`, `ICryptFilterHandler` | `Broadside.Tests.Filters.FilterPipelineTests.The_identity_crypt_filter_passes_the_data_through`, `Broadside.Tests.Filters.FilterPipelineTests.A_crypt_filter_the_security_handler_does_not_know_leaves_the_data_encrypted_with_a_diagnostic`, `Broadside.Tests.Filters.FilterPipelineTests.A_crypt_filter_that_is_not_first_is_applied_where_it_is_with_a_diagnostic` | Slot only: Identity passes through, other crypt filter names are `CryptFilterUnsupported` until the security handler (#42) sets `StreamDecoder.CryptFilter` | | 7.5.1 | General | done | `PdfDocument`, `CrossReferenceReader` | `Broadside.Tests.Document.OpenDocumentTests.A_file_opens_identically_from_a_path_a_stream_and_bytes_with_no_diagnostics`, `Broadside.Tests.Document.WellFormedCorpusTests.A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics` | Read from the end through startxref, the cross-reference table and the trailer, never serially; linearized files (Annex F) are #40 | | 7.5.2 | File header | done | `FileHeader`, `PdfVersion`, `PdfDocument` | `Broadside.Tests.Document.FileStructureTests.Offsets_count_from_the_header_so_bytes_before_it_do_not_matter`, `Broadside.Tests.Document.FileStructureTests.A_file_without_a_header_opens_from_byte_0_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_header_without_a_valid_version_takes_the_catalog_version_with_a_diagnostic` | Header searched in the first 1024 bytes; every stated offset is relative to it; missing header: offsets from byte 0, version 1.4 unless the catalog says otherwise; the unshifted-offset retry is #41 | | 7.5.3 | File body | done | `ObjectLoader` | `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length` | Objects load lazily by cross-reference entry; object streams are #39 | diff --git a/src/Broadside/EngineConfiguration.cs b/src/Broadside/EngineConfiguration.cs index c03f38e0..59f69227 100644 --- a/src/Broadside/EngineConfiguration.cs +++ b/src/Broadside/EngineConfiguration.cs @@ -1,3 +1,5 @@ +using Broadside.Filters; + namespace Broadside; /// @@ -14,8 +16,18 @@ internal sealed class EngineConfiguration /// Gets how deviations are treated. public PdfReadingMode ReadingMode { get; } + /// Gets the filters by name: the managed defaults with the options' registrations applied (issue #38). + public FilterRegistry Filters { get; private init; } = FilterRegistry.Create([]); + + /// Gets the most bytes one stream may decode to (issue #38). + public long MaxDecodedStreamLength { get; private init; } = PdfOptions.DefaultMaxDecodedStreamLength; + /// Copies the current values of . /// The options. /// The snapshot. - public static EngineConfiguration From(PdfOptions options) => new(options.ReadingMode); + public static EngineConfiguration From(PdfOptions options) => new(options.ReadingMode) + { + Filters = FilterRegistry.Create(options.Filters), + MaxDecodedStreamLength = options.MaxDecodedStreamLength, + }; } diff --git a/src/Broadside/Filters/Ascii85DecodeFilter.cs b/src/Broadside/Filters/Ascii85DecodeFilter.cs new file mode 100644 index 00000000..c8b6a322 --- /dev/null +++ b/src/Broadside/Filters/Ascii85DecodeFilter.cs @@ -0,0 +1,116 @@ +using System.Buffers; +using System.Buffers.Binary; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Filters; + +/// The ASCII85Decode filter: groups of five base-85 digits to four bytes. Decode only. +/// +/// +/// ISO 32000-2 §7.4.3. Digits are ! to u; z stands for a whole group of four zero bytes; ~> ends the +/// data; white-space (§7.2.3) is ignored; a final partial group of n digits (2 to 4) decodes to n - 1 bytes. Takes no parameters. +/// +/// +/// Lenient repairs, one diagnostic per kind: other characters and a z inside a group are skipped, a group above +/// 232 - 1 keeps its low 32 bits, a final group of one digit is dropped (FilterDataInvalid); data without +/// ~> decodes to its end (FilterDataTruncated). A ~ not followed by > also ends the data, and a +/// leading PostScript-style <~ is skipped, as other readers do. +/// +/// +public sealed class Ascii85DecodeFilter : IStreamFilter +{ + /// + /// ISO 32000-2 §7.4.3: ASCII85Decode; abbreviated A85 in inline images (§8.9.7). + public CosName Name => FilterNames.Ascii85Decode; + + /// + /// ISO 32000-2 §7.4.3. + public void Decode(ReadOnlyMemory encoded, IBufferWriter output, FilterContext context) + { + ArgumentNullException.ThrowIfNull(output); + ArgumentNullException.ThrowIfNull(context); + ReadOnlySpan input = SkipPostScriptPrefix(encoded.Span); + var writer = new FilterOutput(output); + ulong value = 0; + int digits = 0; + bool ended = false; + bool invalidCharacter = false; + bool misplacedZ = false; + bool overflow = false; + foreach (byte character in input) + { + if (character is >= (byte)'!' and <= (byte)'u') + { + value = (value * 85) + (ulong)(character - '!'); + if (++digits == 5) + { + overflow |= value > uint.MaxValue; + BinaryPrimitives.WriteUInt32BigEndian(writer.Reserve(4), (uint)value); + value = 0; + digits = 0; + } + } + else if (character == (byte)'z' && digits == 0) + { + writer.Reserve(4).Clear(); + } + else if (character == (byte)'~') + { + ended = true; + break; + } + else if (character == (byte)'z') + { + misplacedZ = true; + } + else if (!CosLexer.IsWhitespace(character)) + { + invalidCharacter = true; + } + } + + bool loneDigit = digits == 1; + if (digits > 1) + { + for (int padding = digits; padding < 5; padding++) + { + value = (value * 85) + 84; + } + + Span group = stackalloc byte[4]; + BinaryPrimitives.WriteUInt32BigEndian(group, (uint)value); + writer.Write(group[..(digits - 1)]); + } + + writer.Flush(); + ReportIf(context, invalidCharacter, "ASCII85Decode data holds a character outside ! to u, z, ~ and white-space; such characters are skipped."); + ReportIf(context, misplacedZ, "ASCII85Decode data has a z inside a group; it is skipped."); + ReportIf(context, overflow, "ASCII85Decode data has a group greater than 2^32 - 1; its low 32 bits are kept."); + ReportIf(context, loneDigit, "ASCII85Decode data ends with a partial group of one character, which cannot occur; it is dropped."); + if (!ended) + { + context.Report(DiagnosticCodes.FilterDataTruncated, DiagnosticSeverity.Warning, "ASCII85Decode data ends without the ~> end-of-data marker; it is decoded to its end."); + } + } + + private static void ReportIf(FilterContext context, bool condition, string message) + { + if (condition) + { + context.Report(DiagnosticCodes.FilterDataInvalid, DiagnosticSeverity.Warning, message); + } + } + + private static ReadOnlySpan SkipPostScriptPrefix(ReadOnlySpan input) + { + int start = 0; + while (start < input.Length && CosLexer.IsWhitespace(input[start])) + { + start++; + } + + return input[start..].StartsWith("<~"u8) ? input[(start + 2)..] : input; + } +} diff --git a/src/Broadside/Filters/AsciiHexDecodeFilter.cs b/src/Broadside/Filters/AsciiHexDecodeFilter.cs new file mode 100644 index 00000000..6000df8f --- /dev/null +++ b/src/Broadside/Filters/AsciiHexDecodeFilter.cs @@ -0,0 +1,100 @@ +using System.Buffers; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Filters; + +/// The ASCIIHexDecode filter: pairs of hexadecimal digits to bytes. Decode only. +/// +/// +/// ISO 32000-2 §7.4.2. White-space (§7.2.3: NUL, TAB, LF, FF, CR, SP) is ignored, > ends the data, and an odd final +/// digit decodes as if a 0 followed it. Takes no parameters. +/// +/// +/// Lenient repairs: any other character is skipped (FilterDataInvalid); data without the > marker decodes to +/// its end (FilterDataTruncated). +/// +/// +public sealed class AsciiHexDecodeFilter : IStreamFilter +{ + private const sbyte Invalid = -2; + + /// + /// ISO 32000-2 §7.4.2: ASCIIHexDecode; abbreviated AHx in inline images (§8.9.7). + public CosName Name => FilterNames.AsciiHexDecode; + + /// + /// ISO 32000-2 §7.4.2. + public void Decode(ReadOnlyMemory encoded, IBufferWriter output, FilterContext context) + { + ArgumentNullException.ThrowIfNull(output); + ArgumentNullException.ThrowIfNull(context); + ReadOnlySpan input = encoded.Span; + ReadOnlySpan values = DigitValues; + var writer = new FilterOutput(output); + int high = -1; + bool invalidReported = false; + bool ended = false; + foreach (byte character in input) + { + if (character == (byte)'>') + { + ended = true; + break; + } + + int value = values[character]; + if (value >= 0) + { + if (high < 0) + { + high = value; + } + else + { + writer.Write((byte)((high << 4) | value)); + high = -1; + } + } + else if (value == Invalid && !invalidReported) + { + invalidReported = true; + writer.Flush(); + context.Report(DiagnosticCodes.FilterDataInvalid, DiagnosticSeverity.Warning, "ASCIIHexDecode data holds a character that is neither a hexadecimal digit nor white-space; such characters are skipped."); + } + } + + if (high >= 0) + { + writer.Write((byte)(high << 4)); + } + + writer.Flush(); + if (!ended) + { + context.Report(DiagnosticCodes.FilterDataTruncated, DiagnosticSeverity.Warning, "ASCIIHexDecode data ends without the > end-of-data marker; it is decoded to its end."); + } + } + + /// The value of each byte as a hexadecimal digit; -1 for white-space (§7.2.3), otherwise. + private static ReadOnlySpan DigitValues => + [ + -1, -2, -2, -2, -2, -2, -2, -2, -2, -1, -1, -2, -1, -1, -2, -2, + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + -1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -2, -2, -2, -2, -2, -2, + -2, 10, 11, 12, 13, 14, 15, -2, -2, -2, -2, -2, -2, -2, -2, -2, + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + -2, 10, 11, 12, 13, 14, 15, -2, -2, -2, -2, -2, -2, -2, -2, -2, + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, + ]; +} diff --git a/src/Broadside/Filters/FilterContext.cs b/src/Broadside/Filters/FilterContext.cs new file mode 100644 index 00000000..e574c865 --- /dev/null +++ b/src/Broadside/Filters/FilterContext.cs @@ -0,0 +1,131 @@ +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Filters; + +/// +/// Everything a may need beyond the bytes it decodes: its parameters, the stream it decodes, the means +/// to resolve references and decode other streams of the same document, the limits, and the diagnostics sink. +/// +/// +/// +/// ISO 32000-2 §7.3.8.2 (Table 5) and §7.4. A document creates one context per filter in a stream's chain. A context created with +/// the public constructor stands alone: it decodes other streams with the default filters, resolves no references, and keeps its +/// diagnostics in only, which is how a filter is tested or used outside a document. +/// +/// +/// Image codecs read the image's entries (Width, Height, BitsPerComponent, ColorSpace, Decode) +/// from and decode auxiliary streams such as JBIG2Globals with . +/// +/// A context belongs to one decode call on one thread. +/// +public sealed class FilterContext +{ + private StreamDecoder? _decoder; + private readonly int _depth; + private List? _diagnostics; + + /// Initializes a new instance of the class that stands alone, outside any document. + public FilterContext() + { + } + + /// Initializes a new instance of the class for one filter of a document's chain. + internal FilterContext(StreamDecoder decoder, int depth) + { + _decoder = decoder; + _depth = depth; + ReadingMode = decoder.ReadingMode; + MaxDecodedLength = decoder.MaxDecodedLength; + } + + /// Gets the filter's parameter dictionary, or when it has none and every parameter takes its default. + /// + /// ISO 32000-2 §7.3.8.2, Table 5: the stream's DecodeParms entry, or the element of its array that belongs to this filter. + /// Values may be indirect references; read them through . + /// + public CosDictionary? Parameters { get; init; } + + /// Gets the dictionary of the stream being decoded; for an inline image, its dictionary with abbreviations expanded. + /// ISO 32000-2 §7.3.8.2, Table 5; for an image, §8.9.5 Table 87. + public CosDictionary StreamDictionary { get; init; } = new(); + + /// Gets how deviations are treated: in mode, throws. + /// ADR 0005. + public PdfReadingMode ReadingMode { get; init; } = PdfReadingMode.Lenient; + + /// Gets the most bytes one stream may decode to; the pipeline truncates longer output with a diagnostic. + /// + /// Guards against decompression bombs. A filter that must allocate for its output up front (an image codec sizing a buffer from + /// its header) checks the size against this first. + /// + public long MaxDecodedLength { get; init; } = PdfOptions.DefaultMaxDecodedStreamLength; + + /// Gets the diagnostics reported through this context, in order. + public IReadOnlyList Diagnostics => (IReadOnlyList?)_diagnostics ?? []; + + /// Records a deviation the filter found in its data and what it did about it. + /// A stable PascalCase identifier of the kind of deviation, such as FilterDataTruncated. + /// Whether the repair kept all content () or probably lost some. + /// What was wrong and what the filter did. + /// In strict mode, always: the decode ends here. + /// ADR 0005. Inside a document the diagnostic is also recorded on the document. + public void Report(string code, DiagnosticSeverity severity, string message) + { + var diagnostic = new Diagnostic(code, severity, message); + (_diagnostics ??= []).Add(diagnostic); + Decoder.Report(diagnostic); + } + + /// Returns , or the object it refers to when it is an indirect reference. + /// A value from or , or . + /// The direct object; for , and, outside a document, for any reference. + /// ISO 32000-2 §7.3.10. + public CosObject Resolve(CosObject? value) => Decoder.Resolve(value); + + /// Decodes another stream of the same document through the same filters, such as a JBIG2 JBIG2Globals stream. + /// The stream. + /// The decoded data. + /// In strict mode, for the first deviation. + /// ISO 32000-2 §7.4. + public ReadOnlyMemory DecodeStream(CosStream stream) + { + ArgumentNullException.ThrowIfNull(stream); + return Decoder.Decode(stream, _depth + 1); + } + + /// Gets the document's decoder, or, for a context that stands alone, one with the default filters created on first use. + private StreamDecoder Decoder => _decoder ??= StreamDecoder.Standalone(ReadingMode, MaxDecodedLength); + + /// Reads an integer parameter; reports and returns the default when it is not an integer in range. + /// The parameter. + /// The value when absent or invalid. + /// The least valid value. + /// The greatest valid value. + /// The value. + internal long ReadInteger(CosName key, long defaultValue, long minimum, long maximum) + { + if (Parameters is null || !Parameters.TryGetValue(key, out CosObject? entry)) + { + return defaultValue; + } + + switch (Resolve(entry)) + { + case CosNull: + return defaultValue; + case CosInteger { Value: var value } when value >= minimum && value <= maximum: + return value; + default: + Report( + DiagnosticCodes.DecodeParmsInvalid, + DiagnosticSeverity.Warning, + string.Create( + CultureInfo.InvariantCulture, + $"The {key.Value} parameter shall be an integer from {minimum} to {maximum}; the default {defaultValue} is used.")); + return defaultValue; + } + } +} diff --git a/src/Broadside/Filters/FilterNames.cs b/src/Broadside/Filters/FilterNames.cs new file mode 100644 index 00000000..8d90be45 --- /dev/null +++ b/src/Broadside/Filters/FilterNames.cs @@ -0,0 +1,105 @@ +using Broadside.Objects; + +namespace Broadside.Filters; + +/// The names the filter pipeline looks up: stream dictionary entries, filter names and their parameters, created once. +internal static class FilterNames +{ + /// /Filter, the stream dictionary entry naming the filters to decode with (ISO 32000-2 §7.3.8.2, Table 5). + public static readonly CosName Filter = new("Filter"); + + /// /DecodeParms, the parameters of the filters (§7.3.8.2, Table 5). + public static readonly CosName DecodeParms = new("DecodeParms"); + + /// /F, the file specification of an external stream's data (§7.3.8.2, Table 5). + public static readonly CosName F = new("F"); + + /// /DL, the decoded length hint (§7.3.8.2, Table 5). + public static readonly CosName DL = new("DL"); + + /// /ASCIIHexDecode (§7.4.2). + public static readonly CosName AsciiHexDecode = new("ASCIIHexDecode"); + + /// /ASCII85Decode (§7.4.3). + public static readonly CosName Ascii85Decode = new("ASCII85Decode"); + + /// /LZWDecode (§7.4.4). + public static readonly CosName LzwDecode = new("LZWDecode"); + + /// /FlateDecode (§7.4.4). + public static readonly CosName FlateDecode = new("FlateDecode"); + + /// /RunLengthDecode (§7.4.5). + public static readonly CosName RunLengthDecode = new("RunLengthDecode"); + + /// /CCITTFaxDecode (§7.4.6). + public static readonly CosName CcittFaxDecode = new("CCITTFaxDecode"); + + /// /JBIG2Decode (§7.4.7). + public static readonly CosName Jbig2Decode = new("JBIG2Decode"); + + /// /DCTDecode (§7.4.8). + public static readonly CosName DctDecode = new("DCTDecode"); + + /// /JPXDecode (§7.4.9). + public static readonly CosName JpxDecode = new("JPXDecode"); + + /// /Crypt (§7.4.10). + public static readonly CosName Crypt = new("Crypt"); + + /// /Name, the Crypt filter parameter naming the crypt filter (§7.4.10, Table 14). + public static readonly CosName Name = new("Name"); + + /// /Identity, the crypt filter that leaves data unchanged (§7.4.10, §7.6.6 Table 26). + public static readonly CosName Identity = new("Identity"); + + /// /Predictor (§7.4.4.3, Table 8). + public static readonly CosName Predictor = new("Predictor"); + + /// /Colors (§7.4.4.3, Table 8). + public static readonly CosName Colors = new("Colors"); + + /// /BitsPerComponent (§7.4.4.3, Table 8). + public static readonly CosName BitsPerComponent = new("BitsPerComponent"); + + /// /Columns (§7.4.4.3, Table 8). + public static readonly CosName Columns = new("Columns"); + + /// /EarlyChange (§7.4.4.3, Table 8). + public static readonly CosName EarlyChange = new("EarlyChange"); + + /// + /// The filter name abbreviations of §8.9.7, Table 92, which are valid only in inline images, and the full names they stand for. + /// + private static readonly Dictionary Abbreviations = new() + { + [new CosName("AHx")] = AsciiHexDecode, + [new CosName("A85")] = Ascii85Decode, + [new CosName("LZW")] = LzwDecode, + [new CosName("Fl")] = FlateDecode, + [new CosName("RL")] = RunLengthDecode, + [new CosName("CCF")] = CcittFaxDecode, + [new CosName("DCT")] = DctDecode, + }; + + /// The standard filters of §7.4.1, Table 6. + private static readonly HashSet Standard = + [AsciiHexDecode, Ascii85Decode, LzwDecode, FlateDecode, RunLengthDecode, CcittFaxDecode, Jbig2Decode, DctDecode, JpxDecode, Crypt]; + + /// Returns the full filter name an inline-image abbreviation stands for (§8.9.7, Table 92). + /// A filter name. + /// The full name, when is an abbreviation. + /// when is an abbreviation. + public static bool TryExpandAbbreviation(CosName name, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out CosName? fullName) => + Abbreviations.TryGetValue(name, out fullName); + + /// Returns whether is one of the standard filters of Table 6. + /// A full filter name. + /// for a standard filter. + public static bool IsStandard(CosName name) => Standard.Contains(name); + + /// Returns whether the predictor functions of §7.4.4.4 apply after the filter named . + /// A full filter name. + /// for LZWDecode and FlateDecode. + public static bool TakesPredictor(CosName name) => name.Equals(LzwDecode) || name.Equals(FlateDecode); +} diff --git a/src/Broadside/Filters/FilterOutput.cs b/src/Broadside/Filters/FilterOutput.cs new file mode 100644 index 00000000..c66cad94 --- /dev/null +++ b/src/Broadside/Filters/FilterOutput.cs @@ -0,0 +1,106 @@ +using System.Buffers; + +namespace Broadside.Filters; + +/// +/// Writes a filter's output into an in chunks, so the decode loop pays a span store per byte and a +/// writer call per chunk. Call before returning. +/// +internal ref struct FilterOutput +{ + private const int ChunkSize = 4096; + private readonly IBufferWriter _writer; + private Span _span; + private int _position; + + /// Initializes a new instance of the struct. + /// The destination. + public FilterOutput(IBufferWriter writer) + { + _writer = writer; + _span = default; + _position = 0; + } + + /// Writes one byte. + /// The byte. + public void Write(byte value) + { + if (_position == _span.Length) + { + Grow(1); + } + + _span[_position++] = value; + } + + /// Writes bytes. + /// The bytes. + public void Write(scoped ReadOnlySpan bytes) + { + while (!bytes.IsEmpty) + { + if (_position == _span.Length) + { + Grow(1); + } + + int count = Math.Min(bytes.Length, _span.Length - _position); + bytes[..count].CopyTo(_span[_position..]); + _position += count; + bytes = bytes[count..]; + } + } + + /// Writes times. + /// The byte. + /// How many times. + public void WriteRepeated(byte value, int count) + { + while (count > 0) + { + if (_position == _span.Length) + { + Grow(1); + } + + int run = Math.Min(count, _span.Length - _position); + _span.Slice(_position, run).Fill(value); + _position += run; + count -= run; + } + } + + /// Returns the next bytes of output to be filled in, in any order. + /// How many bytes. + /// The bytes, now part of the output. + public Span Reserve(int count) + { + if (_span.Length - _position < count) + { + Grow(count); + } + + Span reserved = _span.Slice(_position, count); + _position += count; + return reserved; + } + + /// Commits everything written to the underlying writer. + public void Flush() + { + if (_position > 0) + { + _writer.Advance(_position); + } + + _span = default; + _position = 0; + } + + private void Grow(int minimum) + { + Flush(); + _span = _writer.GetSpan(Math.Max(minimum, ChunkSize)); + } +} diff --git a/src/Broadside/Filters/FilterRegistry.cs b/src/Broadside/Filters/FilterRegistry.cs new file mode 100644 index 00000000..1bc72380 --- /dev/null +++ b/src/Broadside/Filters/FilterRegistry.cs @@ -0,0 +1,47 @@ +using System.Collections.Frozen; +using System.Diagnostics.CodeAnalysis; +using Broadside.Objects; + +namespace Broadside.Filters; + +/// +/// One engine's filters by name: the managed defaults, with the replacements and additions its options registered. Immutable; built +/// once when the engine is constructed and shared by every document it opens. There is no static or global registry. +/// +/// ISO 32000-2 §7.4.1, Table 6. The image codecs of §7.4.6 to §7.4.9 join the defaults as Phase 2B implements them. +internal sealed class FilterRegistry +{ + private readonly FrozenDictionary _filters; + + private FilterRegistry(FrozenDictionary filters) => _filters = filters; + + /// Gets the managed default filters, one stateless instance each. + public static IReadOnlyList Defaults { get; } = + [ + new AsciiHexDecodeFilter(), + new Ascii85DecodeFilter(), + new LzwDecodeFilter(), + new FlateDecodeFilter(), + new RunLengthDecodeFilter(), + ]; + + /// Builds a registry of the defaults with applied in order; a later one replaces an earlier one of the same name. + /// The filters registered through the options. + /// The registry. + public static FilterRegistry Create(IEnumerable registrations) + { + var filters = new Dictionary(); + foreach (IStreamFilter filter in Defaults.Concat(registrations)) + { + filters[filter.Name] = filter; + } + + return new FilterRegistry(filters.ToFrozenDictionary()); + } + + /// Finds the filter registered under a full filter name. + /// The name. + /// The filter. + /// when one is registered. + public bool TryGet(CosName name, [NotNullWhen(true)] out IStreamFilter? filter) => _filters.TryGetValue(name, out filter); +} diff --git a/src/Broadside/Filters/FlateDecodeFilter.cs b/src/Broadside/Filters/FlateDecodeFilter.cs new file mode 100644 index 00000000..ba2ed42d --- /dev/null +++ b/src/Broadside/Filters/FlateDecodeFilter.cs @@ -0,0 +1,181 @@ +using System.Buffers; +using System.IO.Compression; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Filters; + +/// The FlateDecode filter: zlib/deflate decompression through the BCL's . Decode only for now. +/// +/// +/// ISO 32000-2 §7.4.4.1 (RFC 1950 zlib wrapper around RFC 1951 deflate) and §7.4.4.3. The two-byte zlib header is checked here and +/// the deflate data after it is inflated; the Adler-32 checksum and anything after the final block are not read, as other readers +/// do. The predictor parameters of Table 8 are applied after this filter by the pipeline (§7.4.4.4). +/// +/// +/// Lenient repairs, one diagnostic each: data without a valid zlib header is inflated as raw deflate data from its first byte +/// (FilterDataInvalid); corrupt data keeps the bytes inflated before the error, but for at most the last one (FilterDataInvalid); data that ends +/// before the final deflate block keeps everything inflated (FilterDataTruncated). +/// +/// Allocates the BCL inflater once per call, never per byte. +/// +public sealed class FlateDecodeFilter : IStreamFilter +{ + private const int ChunkSize = 16384; + + /// + /// ISO 32000-2 §7.4.4: FlateDecode; abbreviated Fl in inline images (§8.9.7). + public CosName Name => FilterNames.FlateDecode; + + /// + /// ISO 32000-2 §7.4.4.1; RFC 1950; RFC 1951. + public void Decode(ReadOnlyMemory encoded, IBufferWriter output, FilterContext context) + { + ArgumentNullException.ThrowIfNull(output); + ArgumentNullException.ThrowIfNull(context); + ReadOnlyMemory deflate = encoded; + if (HasZlibHeader(encoded.Span)) + { + deflate = encoded[2..]; + } + else + { + context.Report(DiagnosticCodes.FilterDataInvalid, DiagnosticSeverity.Warning, "FlateDecode data does not start with a zlib header (RFC 1950); it is read as raw deflate data."); + } + + using var source = new MemorySource(deflate); + long inflated = 0; + try + { + using var inflater = new DeflateStream(source, CompressionMode.Decompress); + while (true) + { + Span chunk = output.GetSpan(ChunkSize); + int count = inflater.Read(chunk); + if (count == 0) + { + break; + } + + output.Advance(count); + inflated += count; + } + } + catch (InvalidDataException) + { + RecoverBeforeError(deflate, inflated, output); + context.Report(DiagnosticCodes.FilterDataInvalid, DiagnosticSeverity.Error, "FlateDecode data is corrupt; the bytes inflated before the error are kept."); + return; + } + + if (source.ReadPastEnd) + { + context.Report(DiagnosticCodes.FilterDataTruncated, DiagnosticSeverity.Warning, "FlateDecode data ends before its final deflate block; everything inflated is kept."); + } + } + + /// + /// After an error, inflates again one byte at a time from where the first pass stopped committing output: the BCL discards the + /// bytes a read produced before the error, so this recovers everything before the error except, at most, the last byte, which + /// zlib produces in the same call that finds the error. Runs only on corrupt data. + /// + private static void RecoverBeforeError(ReadOnlyMemory deflate, long alreadyWritten, IBufferWriter output) + { + byte[] scratch = ArrayPool.Shared.Rent(ChunkSize); + try + { + using var source = new MemorySource(deflate); + using var inflater = new DeflateStream(source, CompressionMode.Decompress); + long skipped = 0; + while (skipped < alreadyWritten) + { + int count = inflater.Read(scratch, 0, (int)Math.Min(scratch.Length, alreadyWritten - skipped)); + if (count == 0) + { + return; + } + + skipped += count; + } + + while (inflater.Read(scratch, 0, 1) == 1) + { + output.Write(scratch.AsSpan(0, 1)); + } + } + catch (InvalidDataException) + { + // The error itself: everything before it has been written. + } + finally + { + ArrayPool.Shared.Return(scratch); + } + } + + /// Checks the RFC 1950 header: method 8 (deflate), window of at most 32 KB, check bits, no preset dictionary. + private static bool HasZlibHeader(ReadOnlySpan data) => + data.Length >= 2 + && (data[0] & 0x0F) == 8 + && (data[0] >> 4) <= 7 + && ((data[0] << 8) | data[1]) % 31 == 0 + && (data[1] & 0x20) == 0; + + /// + /// A read-only stream over memory that records whether the inflater asked for data past the end: + /// stops asking once it has inflated the final block, so asking past the end means the deflate data is truncated. + /// + private sealed class MemorySource(ReadOnlyMemory data) : Stream + { + private int _position; + + public bool ReadPastEnd { get; private set; } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => data.Length; + + public override long Position + { + get => _position; + set => throw new NotSupportedException(); + } + + public override int Read(Span buffer) + { + int count = Math.Min(buffer.Length, data.Length - _position); + if (count == 0 && buffer.Length > 0) + { + ReadPastEnd = true; + return 0; + } + + data.Span.Slice(_position, count).CopyTo(buffer); + _position += count; + return count; + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int ReadByte() + { + Span one = stackalloc byte[1]; + return Read(one) == 1 ? one[0] : -1; + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } +} diff --git a/src/Broadside/Filters/ICryptFilterHandler.cs b/src/Broadside/Filters/ICryptFilterHandler.cs new file mode 100644 index 00000000..0bdc9b08 --- /dev/null +++ b/src/Broadside/Filters/ICryptFilterHandler.cs @@ -0,0 +1,43 @@ +using System.Buffers; +using Broadside.Objects; + +namespace Broadside.Filters; + +/// +/// The slot the pipeline decodes a Crypt filter through (ISO 32000-2 §7.4.10). Issue #42 supplies the security handler's +/// implementation, set on when the document's Encrypt dictionary is read; until then +/// decodes only the Identity crypt filter. +/// +/// +/// A stream whose chain starts with Crypt is decrypted here with the named crypt filter's key used as is (§7.4.10), so the +/// object decryptor (hook 2 of the object loader) must leave such a stream's data alone. +/// +internal interface ICryptFilterHandler +{ + /// Decrypts with the crypt filter named . + /// The Name parameter, Identity when absent (Table 14). + /// The stream's data. + /// Where to write the decrypted data. + /// The Crypt filter's context; its parameters may hold entries private to the security handler. + /// when no crypt filter of that name is known; nothing was written. + bool TryDecrypt(CosName cryptFilterName, ReadOnlySpan data, IBufferWriter output, FilterContext context); +} + +/// The of an unencrypted document: only Identity, which copies the data (§7.6.6 Table 26). +internal sealed class IdentityCryptFilterHandler : ICryptFilterHandler +{ + /// Gets the shared instance; it holds no state. + public static IdentityCryptFilterHandler Instance { get; } = new(); + + /// + public bool TryDecrypt(CosName cryptFilterName, ReadOnlySpan data, IBufferWriter output, FilterContext context) + { + if (!cryptFilterName.Equals(FilterNames.Identity)) + { + return false; + } + + output.Write(data); + return true; + } +} diff --git a/src/Broadside/Filters/IStreamFilter.cs b/src/Broadside/Filters/IStreamFilter.cs new file mode 100644 index 00000000..a9c39ff4 --- /dev/null +++ b/src/Broadside/Filters/IStreamFilter.cs @@ -0,0 +1,44 @@ +using System.Buffers; +using Broadside.Objects; + +namespace Broadside.Filters; + +/// +/// A stream filter: the codec for one encoding a stream's Filter entry can name. The filter extension point: every engine +/// holds one filter per name, the managed defaults unless replaced or added one. +/// +/// +/// +/// ISO 32000-2 §7.4.1. A document decodes a stream by running the filters its Filter entry names, in order, each one over the +/// previous one's output (§7.3.8.2, Table 5). The pipeline around the filters, not the filters, handles everything shared: +/// reading Filter and DecodeParms, the inline-image abbreviations of §8.9.7 Table 92, the predictor functions of +/// §7.4.4.4 after any filter named LZWDecode or FlateDecode (a replacement for either gets them too and must not apply +/// them itself), the Crypt filter of §7.4.10 (handled by the security handler, never by a registered filter), the +/// decoded-length limit (), and converting any exception other than a strict-mode +/// into a diagnostic. +/// +/// +/// Thread safety: one instance serves every document of every thread of the engines it is registered with. An implementation +/// keeps no state between calls; everything a decode needs lives in locals, pooled buffers or the . +/// +/// +/// Leniency (ADR 0005): on malformed data a filter writes what it can decode, reports one diagnostic per kind of deviation through +/// , and returns. In strict mode throws, which ends the decode. +/// +/// +public interface IStreamFilter +{ + /// Gets the name the filter has in a Filter entry, such as FlateDecode: the key it is registered under. + /// ISO 32000-2 §7.4.1, Table 6. Always the full name; the pipeline expands the abbreviations of §8.9.7 Table 92. + CosName Name { get; } + + /// Decodes and writes the result to . + /// The data to decode: the stream's data, or the previous filter's output in a chain. Never empty. + /// Where to write the decoded bytes. + /// + /// The filter's parameters (its DecodeParms dictionary), the stream's dictionary, the means to resolve references and + /// decode other streams, and the diagnostics sink. + /// + /// ISO 32000-2 §7.4. + void Decode(ReadOnlyMemory encoded, IBufferWriter output, FilterContext context); +} diff --git a/src/Broadside/Filters/LzwDecodeFilter.cs b/src/Broadside/Filters/LzwDecodeFilter.cs new file mode 100644 index 00000000..1b532b14 --- /dev/null +++ b/src/Broadside/Filters/LzwDecodeFilter.cs @@ -0,0 +1,205 @@ +using System.Buffers; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Filters; + +/// The LZWDecode filter: Lempel-Ziv-Welch with 9- to 12-bit codes. Decode only. +/// +/// +/// ISO 32000-2 §7.4.4.1 to §7.4.4.3. Codes are read high-order bit first; 256 clears the table, 257 ends the data, 258 and up are +/// table entries. The code length grows to 10, 11 and 12 bits as the table reaches 512, 1024 and 2048 entries, one code early when +/// the EarlyChange parameter is 1 (the default) and only when necessary when it is 0 (Table 8). The predictor parameters of +/// Table 8 are applied after this filter by the pipeline (§7.4.4.4). +/// +/// +/// Lenient repairs, one diagnostic each: data that ends without the end-of-data code decodes to its end +/// (FilterDataTruncated); a code that is not yet in the table ends the data, and a full table without a clear code stops +/// growing (FilterDataInvalid); an EarlyChange other than 0 or 1 is read as 1 (DecodeParmsInvalid). +/// +/// The table lives in arrays rented from the shared pool: no allocation per code. +/// +public sealed class LzwDecodeFilter : IStreamFilter +{ + private const int ClearTable = 256; + private const int EndOfData = 257; + private const int FirstEntry = 258; + private const int TableSize = 4096; + + /// + /// ISO 32000-2 §7.4.4: LZWDecode; abbreviated LZW in inline images (§8.9.7). + public CosName Name => FilterNames.LzwDecode; + + /// + /// ISO 32000-2 §7.4.4.2 and §7.4.4.3 Table 8 (EarlyChange). + public void Decode(ReadOnlyMemory encoded, IBufferWriter output, FilterContext context) + { + ArgumentNullException.ThrowIfNull(output); + ArgumentNullException.ThrowIfNull(context); + int earlyChange = ReadEarlyChange(context); + ushort[] prefixes = ArrayPool.Shared.Rent(TableSize); + ushort[] lengths = ArrayPool.Shared.Rent(TableSize); + byte[] suffixes = ArrayPool.Shared.Rent(TableSize); + byte[] firsts = ArrayPool.Shared.Rent(TableSize); + try + { + Outcome outcome = Decode(encoded.Span, output, earlyChange, prefixes, lengths, suffixes, firsts); + if ((outcome & Outcome.InvalidCode) != 0) + { + context.Report(DiagnosticCodes.FilterDataInvalid, DiagnosticSeverity.Error, "LZWDecode data holds a code that is not in the table; the data ends there."); + } + + if ((outcome & Outcome.TableFull) != 0) + { + context.Report(DiagnosticCodes.FilterDataInvalid, DiagnosticSeverity.Warning, "LZWDecode data fills the table without a clear-table code; no more entries are added."); + } + + if ((outcome & Outcome.Truncated) != 0) + { + context.Report(DiagnosticCodes.FilterDataTruncated, DiagnosticSeverity.Warning, "LZWDecode data ends without the end-of-data code 257; it is decoded to its end."); + } + } + finally + { + ArrayPool.Shared.Return(prefixes); + ArrayPool.Shared.Return(lengths); + ArrayPool.Shared.Return(suffixes); + ArrayPool.Shared.Return(firsts); + } + } + + private static int ReadEarlyChange(FilterContext context) + { + long value = context.ReadInteger(FilterNames.EarlyChange, defaultValue: 1, long.MinValue, long.MaxValue); + if (value is 0 or 1) + { + return (int)value; + } + + context.Report(DiagnosticCodes.DecodeParmsInvalid, DiagnosticSeverity.Warning, "The EarlyChange parameter shall be 0 or 1; it is read as 1."); + return 1; + } + + private static Outcome Decode( + ReadOnlySpan input, + IBufferWriter output, + int earlyChange, + Span prefixes, + Span lengths, + Span suffixes, + Span firsts) + { + for (int code = 0; code < 256; code++) + { + lengths[code] = 1; + suffixes[code] = (byte)code; + firsts[code] = (byte)code; + } + + var writer = new FilterOutput(output); + Outcome outcome = Outcome.Truncated; + int position = 0; + uint bits = 0; + int bitCount = 0; + int nextCode = FirstEntry; + int previous = -1; + while (true) + { + int width = CodeWidth(nextCode + earlyChange); + while (bitCount < width && position < input.Length) + { + bits = (bits << 8) | input[position++]; + bitCount += 8; + } + + if (bitCount < width) + { + break; + } + + bitCount -= width; + int code = (int)(bits >> bitCount) & ((1 << width) - 1); + if (code == ClearTable) + { + nextCode = FirstEntry; + previous = -1; + continue; + } + + if (code == EndOfData) + { + outcome &= ~Outcome.Truncated; + break; + } + + byte first; + if (code < 256 || (code >= FirstEntry && code < nextCode && previous >= 0)) + { + WriteEntry(ref writer, code, prefixes, lengths, suffixes); + first = firsts[code]; + } + else if (code == nextCode && previous >= 0) + { + // The entry being defined by this very code: the previous string followed by its own first byte (§7.4.4.2). + first = firsts[previous]; + WriteEntry(ref writer, previous, prefixes, lengths, suffixes); + writer.Write(first); + } + else + { + outcome = (outcome & ~Outcome.Truncated) | Outcome.InvalidCode; + break; + } + + if (previous >= 0) + { + if (nextCode < TableSize) + { + prefixes[nextCode] = (ushort)previous; + suffixes[nextCode] = first; + firsts[nextCode] = firsts[previous]; + lengths[nextCode] = (ushort)(lengths[previous] + 1); + nextCode++; + } + else + { + outcome |= Outcome.TableFull; + } + } + + previous = code; + } + + writer.Flush(); + return outcome; + } + + /// The code length once the table holds entries counting the early change: 9 to 12 bits. + private static int CodeWidth(int entries) => entries switch + { + < 512 => 9, + < 1024 => 10, + < 2048 => 11, + _ => 12, + }; + + private static void WriteEntry(ref FilterOutput writer, int code, ReadOnlySpan prefixes, ReadOnlySpan lengths, ReadOnlySpan suffixes) + { + Span target = writer.Reserve(lengths[code]); + for (int index = target.Length - 1; index >= 0; index--) + { + target[index] = suffixes[code]; + code = prefixes[code]; + } + } + + [Flags] + private enum Outcome + { + None = 0, + Truncated = 1, + InvalidCode = 2, + TableFull = 4, + } +} diff --git a/src/Broadside/Filters/PooledBufferWriter.cs b/src/Broadside/Filters/PooledBufferWriter.cs new file mode 100644 index 00000000..3d10392c --- /dev/null +++ b/src/Broadside/Filters/PooledBufferWriter.cs @@ -0,0 +1,141 @@ +using System.Buffers; + +namespace Broadside.Filters; + +/// +/// A growable over arrays rented from , with a length limit: the +/// buffer between the stages of a filter chain. Writing past the limit keeps the first bytes and throws +/// , which the pipeline turns into a diagnostic. +/// +internal sealed class PooledBufferWriter : IBufferWriter, IDisposable +{ + private const int MinimumCapacity = 256; + private byte[] _buffer; + private int _written; + + /// Initializes a new instance of the class. + /// The capacity to start with, such as the stream's DL hint. + /// The most bytes the writer accepts. + public PooledBufferWriter(long initialCapacity, long limit) + { + Limit = (int)Math.Clamp(limit, 0, Array.MaxLength); + _buffer = ArrayPool.Shared.Rent((int)Math.Clamp(initialCapacity, MinimumCapacity, Math.Max(MinimumCapacity, Math.Min(Limit, 1 << 24)))); + } + + /// Gets the most bytes the writer accepts. + public int Limit { get; } + + /// Gets a value indicating whether a write went past . + public bool Exceeded { get; private set; } + + /// Gets the bytes written so far. + public ReadOnlySpan WrittenSpan => _buffer.AsSpan(0, _written); + + /// Gets the bytes written so far. + public ReadOnlyMemory WrittenMemory => _buffer.AsMemory(0, _written); + + /// Forgets what was written, keeping the buffer. + public void Clear() + { + _written = 0; + Exceeded = false; + } + + /// + public void Advance(int count) + { + ArgumentOutOfRangeException.ThrowIfNegative(count); + if (count > _buffer.Length - _written) + { + throw new InvalidOperationException("Cannot advance past the end of the buffer."); + } + + if (count > Limit - _written) + { + _written = Limit; + Exceeded = true; + throw new DecodedLengthExceededException(); + } + + _written += count; + } + + /// + public Memory GetMemory(int sizeHint = 0) + { + Reserve(sizeHint); + return _buffer.AsMemory(_written); + } + + /// + public Span GetSpan(int sizeHint = 0) + { + Reserve(sizeHint); + return _buffer.AsSpan(_written); + } + + /// + public void Dispose() + { + byte[] buffer = _buffer; + _buffer = []; + _written = 0; + if (buffer.Length > 0) + { + ArrayPool.Shared.Return(buffer); + } + } + + private void Reserve(int sizeHint) + { + if (Exceeded) + { + throw new DecodedLengthExceededException(); + } + + int needed = Math.Max(sizeHint, 1); + if (_buffer.Length - _written >= needed) + { + return; + } + + long capacity = Math.Max((long)_buffer.Length * 2, (long)_written + needed); + capacity = Math.Min(capacity, Math.Max((long)Limit + needed, _written + needed)); + if (capacity > Array.MaxLength) + { + capacity = Array.MaxLength; + } + + byte[] larger = ArrayPool.Shared.Rent((int)capacity); + _buffer.AsSpan(0, _written).CopyTo(larger); + ArrayPool.Shared.Return(_buffer); + _buffer = larger; + } +} + +/// Thrown by when a filter writes past the decoded-length limit; never escapes the pipeline. +#pragma warning disable CA1064 // Internal control flow between the writer and the pipeline; never public. +internal sealed class DecodedLengthExceededException : Exception +#pragma warning restore CA1064 +{ + /// Initializes a new instance of the class. + public DecodedLengthExceededException() + : base("The decoded data exceeds the configured limit.") + { + } + + /// Initializes a new instance of the class. + /// The message. + public DecodedLengthExceededException(string message) + : base(message) + { + } + + /// Initializes a new instance of the class. + /// The message. + /// The cause. + public DecodedLengthExceededException(string message, Exception innerException) + : base(message, innerException) + { + } +} diff --git a/src/Broadside/Filters/Predictor.cs b/src/Broadside/Filters/Predictor.cs new file mode 100644 index 00000000..22d328ca --- /dev/null +++ b/src/Broadside/Filters/Predictor.cs @@ -0,0 +1,229 @@ +using System.Buffers; +using Broadside.Diagnostics; +using Broadside.Parsing; + +namespace Broadside.Filters; + +/// +/// The predictor functions of LZWDecode and FlateDecode: TIFF Predictor 2 and the PNG predictors, undone after the filter by the +/// pipeline. Not a filter of its own. +/// +/// +/// +/// ISO 32000-2 §7.4.4.3 (Table 8: Predictor, Colors, BitsPerComponent, Columns) and §7.4.4.4 (Tables 9 and 10). Rows are +/// ceil(Colors × BitsPerComponent × Columns / 8) bytes. TIFF Predictor 2 adds each colour component to the same component of the +/// sample to its left, modulo 2BitsPerComponent (16-bit components big-endian). Predictor 10 to 15 means PNG: each row +/// starts with its own algorithm tag (0 None, 1 Sub, 2 Up, 3 Average, 4 Paeth), whatever value of 10 to 15 is declared, and bytes +/// are predicted from the byte max(1, ceil(Colors × BitsPerComponent / 8)) to the left. Samples outside the image are 0. +/// +/// +/// Lenient repairs, one PredictorInvalid diagnostic each: an unknown Predictor passes the data through unchanged; a PNG tag +/// above 4 is read as None; a final partial row is padded with zeros. Parameters out of range take their defaults +/// (DecodeParmsInvalid); a row longer than the decoded-length limit passes the data through. +/// +/// +internal static class Predictor +{ + /// Undoes the predictor the context's parameters name; with Predictor 1 or absent, copies the data. + /// The filter's output. + /// Where to write the samples. + /// The filter's context; its parameters are the filter's DecodeParms. + public static void Decode(ReadOnlySpan data, IBufferWriter output, FilterContext context) + { + long predictor = context.ReadInteger(FilterNames.Predictor, 1, long.MinValue, long.MaxValue); + if (predictor == 1) + { + output.Write(data); + return; + } + + if (predictor is not (2 or (>= 10 and <= 15))) + { + context.Report(DiagnosticCodes.PredictorInvalid, DiagnosticSeverity.Error, "The Predictor parameter shall be 1, 2 or 10 to 15; the data is passed through unpredicted."); + output.Write(data); + return; + } + + int colors = (int)context.ReadInteger(FilterNames.Colors, 1, 1, 256); + int bitsPerComponent = (int)context.ReadInteger(FilterNames.BitsPerComponent, 8, 1, 16); + if (bitsPerComponent is not (1 or 2 or 4 or 8 or 16)) + { + context.Report(DiagnosticCodes.DecodeParmsInvalid, DiagnosticSeverity.Warning, "The BitsPerComponent parameter shall be 1, 2, 4, 8 or 16; the default 8 is used."); + bitsPerComponent = 8; + } + + long columns = context.ReadInteger(FilterNames.Columns, 1, 1, int.MaxValue); + long rowLength = ((colors * bitsPerComponent * columns) + 7) / 8; + if (rowLength > Math.Min(context.MaxDecodedLength, Array.MaxLength - 1)) + { + context.Report(DiagnosticCodes.PredictorInvalid, DiagnosticSeverity.Error, "The predictor's rows are longer than the decoded-length limit; the data is passed through unpredicted."); + output.Write(data); + return; + } + + int bytesPerPixel = Math.Max(1, ((colors * bitsPerComponent) + 7) / 8); + byte[] previous = ArrayPool.Shared.Rent((int)rowLength); + byte[] current = ArrayPool.Shared.Rent((int)rowLength); + try + { + if (predictor == 2) + { + DecodeTiff(data, output, context, current.AsSpan(0, (int)rowLength), colors, bitsPerComponent, (int)columns); + } + else + { + DecodePng(data, output, context, previous.AsSpan(0, (int)rowLength), current.AsSpan(0, (int)rowLength), bytesPerPixel); + } + } + finally + { + ArrayPool.Shared.Return(previous); + ArrayPool.Shared.Return(current); + } + } + + private static void DecodePng(ReadOnlySpan data, IBufferWriter output, FilterContext context, Span previous, Span current, int bytesPerPixel) + { + previous.Clear(); + bool unknownTag = false; + bool partialRow = false; + int rowLength = current.Length; + while (!data.IsEmpty) + { + byte tag = data[0]; + int available = Math.Min(rowLength, data.Length - 1); + partialRow |= available < rowLength; + current.Clear(); + data.Slice(1, available).CopyTo(current); + data = data[(1 + available)..]; + switch (tag) + { + case 0: + break; + case 1: + for (int index = bytesPerPixel; index < rowLength; index++) + { + current[index] += current[index - bytesPerPixel]; + } + + break; + case 2: + for (int index = 0; index < rowLength; index++) + { + current[index] += previous[index]; + } + + break; + case 3: + for (int index = 0; index < rowLength; index++) + { + int left = index >= bytesPerPixel ? current[index - bytesPerPixel] : 0; + current[index] += (byte)((left + previous[index]) >> 1); + } + + break; + case 4: + for (int index = 0; index < rowLength; index++) + { + int left = index >= bytesPerPixel ? current[index - bytesPerPixel] : 0; + int upperLeft = index >= bytesPerPixel ? previous[index - bytesPerPixel] : 0; + current[index] += Paeth(left, previous[index], upperLeft); + } + + break; + default: + unknownTag = true; + break; + } + + output.Write(current); + current.CopyTo(previous); + } + + if (unknownTag) + { + context.Report(DiagnosticCodes.PredictorInvalid, DiagnosticSeverity.Warning, "A PNG predictor row has an algorithm tag above 4; such rows are read unpredicted."); + } + + if (partialRow) + { + context.Report(DiagnosticCodes.PredictorInvalid, DiagnosticSeverity.Warning, "The predicted data ends in the middle of a row; the row is padded with zeros."); + } + } + + /// The Paeth predictor of ISO/IEC 15948 §9.4: whichever of left, above and upper-left is closest to left + above - upper-left. + private static byte Paeth(int left, int above, int upperLeft) + { + int estimate = left + above - upperLeft; + int toLeft = Math.Abs(estimate - left); + int toAbove = Math.Abs(estimate - above); + int toUpperLeft = Math.Abs(estimate - upperLeft); + if (toLeft <= toAbove && toLeft <= toUpperLeft) + { + return (byte)left; + } + + return toAbove <= toUpperLeft ? (byte)above : (byte)upperLeft; + } + + private static void DecodeTiff(ReadOnlySpan data, IBufferWriter output, FilterContext context, Span row, int colors, int bitsPerComponent, int columns) + { + bool partialRow = false; + int rowLength = row.Length; + while (!data.IsEmpty) + { + int available = Math.Min(rowLength, data.Length); + partialRow |= available < rowLength; + row.Clear(); + data[..available].CopyTo(row); + data = data[available..]; + switch (bitsPerComponent) + { + case 8: + for (int index = colors; index < rowLength; index++) + { + row[index] += row[index - colors]; + } + + break; + case 16: + int stride = colors * 2; + for (int index = stride; index + 1 < rowLength; index += 2) + { + int sum = ((row[index] << 8) | row[index + 1]) + ((row[index - stride] << 8) | row[index - stride + 1]); + row[index] = (byte)(sum >> 8); + row[index + 1] = (byte)sum; + } + + break; + default: + UndoSubByteDifferences(row, colors, bitsPerComponent, colors * columns); + break; + } + + output.Write(row); + } + + if (partialRow) + { + context.Report(DiagnosticCodes.PredictorInvalid, DiagnosticSeverity.Warning, "The predicted data ends in the middle of a row; the row is padded with zeros."); + } + } + + /// TIFF Predictor 2 for 1, 2 and 4 bits per component: components packed high-order bit first. + private static void UndoSubByteDifferences(Span row, int colors, int bitsPerComponent, int components) + { + int mask = (1 << bitsPerComponent) - 1; + for (int component = colors; component < components; component++) + { + int bit = component * bitsPerComponent; + int leftBit = bit - (colors * bitsPerComponent); + int shift = 8 - bitsPerComponent - (bit & 7); + int leftShift = 8 - bitsPerComponent - (leftBit & 7); + int value = (row[bit >> 3] >> shift) & mask; + int left = (row[leftBit >> 3] >> leftShift) & mask; + int sum = (value + left) & mask; + row[bit >> 3] = (byte)((row[bit >> 3] & ~(mask << shift)) | (sum << shift)); + } + } +} diff --git a/src/Broadside/Filters/RunLengthDecodeFilter.cs b/src/Broadside/Filters/RunLengthDecodeFilter.cs new file mode 100644 index 00000000..e91efac9 --- /dev/null +++ b/src/Broadside/Filters/RunLengthDecodeFilter.cs @@ -0,0 +1,76 @@ +using System.Buffers; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Filters; + +/// The RunLengthDecode filter: byte-oriented run-length encoding. Decode only. +/// +/// +/// ISO 32000-2 §7.4.5. A length byte of 0 to 127 copies the next length + 1 bytes; 129 to 255 repeats the next byte 257 - length +/// times; 128 ends the data. Takes no parameters. +/// +/// +/// Lenient repair: data that ends without the 128 marker, or in the middle of a run, decodes to its end, keeping the bytes of a +/// partial literal run (FilterDataTruncated). +/// +/// +public sealed class RunLengthDecodeFilter : IStreamFilter +{ + private const byte EndOfData = 128; + + /// + /// ISO 32000-2 §7.4.5: RunLengthDecode; abbreviated RL in inline images (§8.9.7). + public CosName Name => FilterNames.RunLengthDecode; + + /// + /// ISO 32000-2 §7.4.5. + public void Decode(ReadOnlyMemory encoded, IBufferWriter output, FilterContext context) + { + ArgumentNullException.ThrowIfNull(output); + ArgumentNullException.ThrowIfNull(context); + ReadOnlySpan input = encoded.Span; + var writer = new FilterOutput(output); + int position = 0; + bool ended = false; + bool truncated = false; + while (position < input.Length) + { + byte length = input[position++]; + if (length == EndOfData) + { + ended = true; + break; + } + + if (length < EndOfData) + { + int count = length + 1; + int available = Math.Min(count, input.Length - position); + writer.Write(input.Slice(position, available)); + position += available; + truncated = available < count; + } + else if (position < input.Length) + { + writer.WriteRepeated(input[position++], 257 - length); + } + else + { + truncated = true; + } + } + + writer.Flush(); + if (!ended) + { + context.Report( + DiagnosticCodes.FilterDataTruncated, + DiagnosticSeverity.Warning, + truncated + ? "RunLengthDecode data ends in the middle of a run; the bytes available are kept." + : "RunLengthDecode data ends without the end-of-data byte 128; it is decoded to its end."); + } + } +} diff --git a/src/Broadside/Filters/StreamDecoder.cs b/src/Broadside/Filters/StreamDecoder.cs new file mode 100644 index 00000000..41f5d281 --- /dev/null +++ b/src/Broadside/Filters/StreamDecoder.cs @@ -0,0 +1,381 @@ +using System.Buffers; +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Filters; + +/// +/// The filter pipeline of one document: reads a stream's Filter and DecodeParms, runs the filters in order with the +/// predictor stage after LZW and Flate, routes Crypt to the security handler, enforces the decoded-length limit, and turns +/// every failure into a diagnostic (or, in strict mode, a ). +/// +/// +/// +/// ISO 32000-2 §7.3.8.2 (Table 5), §7.4.1, §7.4.4.4, §7.4.10. Deviations from Table 5 are repaired the way most readers do: a +/// DecodeParms array for a single filter uses its first element; a single dictionary for several filters is ignored; an +/// element that is not a dictionary means defaults; an abbreviation of §8.9.7 Table 92 outside an inline image is expanded; a chain +/// stops at the first filter it cannot run and the data decoded so far is the result. A stream with no data decodes to nothing, +/// with no diagnostic, whatever its filters. +/// +/// Thread-safe: stateless apart from , which is set once during open. +/// +internal sealed class StreamDecoder +{ + /// How many streams may decode one inside another (a JBIG2 stream decoding its globals) before the inner one is empty. + public const int MaxDepth = 8; + + private readonly FilterRegistry _filters; + private readonly DiagnosticSink _diagnostics; + private readonly Func _resolve; + private volatile ICryptFilterHandler _cryptFilter = IdentityCryptFilterHandler.Instance; + + /// Initializes a new instance of the class. + /// The engine's filters. + /// The most bytes one stream may decode to. + /// Where to report deviations; its strictness is the reading mode. + /// Resolves indirect references of the document. + public StreamDecoder(FilterRegistry filters, long maxDecodedLength, DiagnosticSink diagnostics, Func resolve) + { + _filters = filters; + _diagnostics = diagnostics; + _resolve = resolve; + MaxDecodedLength = maxDecodedLength; + } + + /// Gets the reading mode the diagnostics sink applies. + public PdfReadingMode ReadingMode => _diagnostics.IsStrict ? PdfReadingMode.Strict : PdfReadingMode.Lenient; + + /// Gets the most bytes one stream may decode to. + public long MaxDecodedLength { get; } + + /// + /// Gets or sets the security handler's crypt filters (issue #42). Set once during open, after the Encrypt dictionary is read. + /// + public ICryptFilterHandler CryptFilter + { + get => _cryptFilter; + set => _cryptFilter = value; + } + + /// Creates the decoder a stand-alone uses: default filters, no document, its own diagnostics. + /// The reading mode. + /// The decoded-length limit. + /// The decoder. + public static StreamDecoder Standalone(PdfReadingMode readingMode, long maxDecodedLength) => + new( + FilterRegistry.Create([]), + maxDecodedLength, + new DiagnosticSink(readingMode == PdfReadingMode.Strict), + static value => value is null or CosReference ? CosNull.Instance : value); + + /// Resolves an indirect reference of the document. + /// The value. + /// The direct object. + public CosObject Resolve(CosObject? value) => _resolve(value); + + /// Records a diagnostic; throws it in strict mode. + /// The diagnostic. + public void Report(Diagnostic diagnostic) => + _diagnostics.Report(diagnostic.Code, diagnostic.Severity, diagnostic.Message, diagnostic.Offset, diagnostic.ObjectReference); + + /// Decodes a stream into a new array. + /// The stream. + /// How many decodes are in progress beneath this one. + /// The decoded data; for a stream without filters, its encoded data itself. + public ReadOnlyMemory Decode(CosStream stream, int depth = 0) + { + if (!HasFilters(stream)) + { + CheckExternalFile(stream); + return stream.EncodedData; + } + + using var output = new PooledBufferWriter(InitialCapacity(stream), MaxDecodedLength); + Decode(stream, output, depth); + return output.WrittenSpan.ToArray(); + } + + /// Decodes a stream into . + /// The stream. + /// Where to write the decoded data. + /// How many decodes are in progress beneath this one. + public void Decode(CosStream stream, IBufferWriter output, int depth = 0) + { + CheckExternalFile(stream); + if (depth > MaxDepth) + { + Report(DiagnosticCodes.StreamDecodingTooDeep, DiagnosticSeverity.Error, string.Create( + CultureInfo.InvariantCulture, + $"Decoding the stream needs more than {MaxDepth} nested stream decodes; it decodes to nothing.")); + return; + } + + List chain = ReadChain(stream.Dictionary); + ReadOnlyMemory data = stream.EncodedData; + PooledBufferWriter? current = null; + PooledBufferWriter? next = null; + try + { + for (int index = 0; index < chain.Count && !data.IsEmpty; index++) + { + next ??= new PooledBufferWriter(InitialCapacity(stream), MaxDecodedLength); + next.Clear(); + FilterStage stage = chain[index]; + var context = new FilterContext(this, depth) { Parameters = stage.Parameters, StreamDictionary = stream.Dictionary }; + bool stop = !RunStage(stage, index, data, next, context); + if (!stop && FilterNames.TakesPredictor(stage.Name)) + { + current ??= new PooledBufferWriter(next.WrittenSpan.Length, MaxDecodedLength); + current.Clear(); + stop = !RunPredictor(next.WrittenMemory, current, context); + } + else + { + (current, next) = (next, current); + } + + data = current!.WrittenMemory; + if (stop) + { + break; + } + } + + output.Write(data.Span); + } + finally + { + current?.Dispose(); + next?.Dispose(); + } + } + + private static bool HasFilters(CosStream stream) => stream.Dictionary.ContainsKey(FilterNames.Filter); + + private static long InitialCapacity(CosStream stream) => + stream.Dictionary.TryGetValue(FilterNames.DL, out CosObject? hint) && hint is CosInteger { Value: > 0 } length + ? length.Value + : (long)stream.EncodedData.Length * 4; + + /// Runs one filter; returns when the chain cannot continue past it. + private bool RunStage(FilterStage stage, int index, ReadOnlyMemory data, PooledBufferWriter output, FilterContext context) + { + CosName name = stage.Name; + if (name.Equals(FilterNames.Crypt)) + { + return RunCryptFilter(index, data, output, context); + } + + if (!_filters.TryGet(name, out IStreamFilter? filter)) + { + string kind = FilterNames.IsStandard(name) ? "is a standard filter this version does not implement" : "is not a filter this engine knows"; + Report(DiagnosticCodes.FilterUnsupported, DiagnosticSeverity.Error, $"The filter /{name.Value} {kind}; the stream is left encoded from that filter on."); + output.Write(data.Span); + return false; + } + + return Guard(output, name, () => filter.Decode(data, output, context)); + } + + private bool RunPredictor(ReadOnlyMemory data, PooledBufferWriter output, FilterContext context) => + Guard(output, filterName: null, () => Predictor.Decode(data.Span, output, context)); + + private bool RunCryptFilter(int index, ReadOnlyMemory data, PooledBufferWriter output, FilterContext context) + { + if (index != 0) + { + Report(DiagnosticCodes.CryptFilterNotFirst, DiagnosticSeverity.Warning, "The Crypt filter shall be the first filter in the Filter array; it is applied where it is."); + } + + CosName cryptFilterName = context.Resolve(context.Parameters?.TryGetValue(FilterNames.Name, out CosObject? named) == true ? named : null) as CosName + ?? FilterNames.Identity; + bool decrypted = false; + bool completed = Guard(output, FilterNames.Crypt, () => decrypted = CryptFilter.TryDecrypt(cryptFilterName, data.Span, output, context)); + if (completed && !decrypted) + { + Report( + DiagnosticCodes.CryptFilterUnsupported, + DiagnosticSeverity.Error, + $"The crypt filter /{cryptFilterName.Value} is not known to the document's security handler; the stream is left encrypted."); + output.Clear(); + output.Write(data.Span); + return false; + } + + return completed; + } + + /// Runs a stage, converting its failures into diagnostics; returns when the chain should stop. + /// The stage's output. + /// The filter the stage runs, or for the predictor stage. + /// The stage. + private bool Guard(PooledBufferWriter output, CosName? filterName, Action action) + { + try + { + action(); + return !output.Exceeded; + } + catch (DiagnosticException) when (_diagnostics.IsStrict) + { + throw; + } + catch (DecodedLengthExceededException) + { + ReportLengthExceeded(); + return false; + } +#pragma warning disable CA1031 // A filter is an extension point; whatever it throws becomes a diagnostic, never a crash (ADR 0005). + catch (Exception exception) when (exception is not OutOfMemoryException) +#pragma warning restore CA1031 + { + if (output.Exceeded) + { + ReportLengthExceeded(); + return false; + } + + Report( + DiagnosticCodes.FilterFailed, + DiagnosticSeverity.Error, + $"{(filterName is null ? "The predictor" : $"The filter /{filterName.Value}")} failed ({exception.GetType().Name}: {exception.Message}); the bytes it decoded before failing are kept."); + return true; + } + } + + private void ReportLengthExceeded() => + Report(DiagnosticCodes.StreamDecodedLengthExceeded, DiagnosticSeverity.Error, string.Create( + CultureInfo.InvariantCulture, + $"The stream decodes to more than the limit of {MaxDecodedLength} bytes; it is truncated there.")); + + private void CheckExternalFile(CosStream stream) + { + if (stream.Dictionary.ContainsKey(FilterNames.F)) + { + Report( + DiagnosticCodes.StreamExternalFileUnsupported, + DiagnosticSeverity.Error, + "The stream's data is in an external file (F), which is not read; the bytes in the stream itself are decoded instead."); + } + } + + /// Reads Filter and DecodeParms into the chain of filters to run, repairing deviations from Table 5. + private List ReadChain(CosDictionary dictionary) + { + var chain = new List(); + CosObject filterEntry = Resolve(dictionary.TryGetValue(FilterNames.Filter, out CosObject? filter) ? filter : null); + CosObject parametersEntry = Resolve(dictionary.TryGetValue(FilterNames.DecodeParms, out CosObject? parameters) ? parameters : null); + switch (filterEntry) + { + case CosNull: + return chain; + case CosName name: + chain.Add(new FilterStage(Expand(name), SingleParameters(parametersEntry))); + return chain; + case CosArray names: + ReadArrayChain(names, parametersEntry, chain); + return chain; + default: + Report(DiagnosticCodes.FilterInvalid, DiagnosticSeverity.Error, "The Filter entry shall be a name or an array of names; the stream is left encoded."); + return chain; + } + } + + private void ReadArrayChain(CosArray names, CosObject parametersEntry, List chain) + { + CosArray? parameterArray = parametersEntry as CosArray; + switch (parametersEntry) + { + case CosNull or CosArray: + break; + case CosDictionary when names.Count == 1: + break; + case CosDictionary: + Report( + DiagnosticCodes.DecodeParmsInvalid, + DiagnosticSeverity.Warning, + "DecodeParms shall be an array with one entry per filter when Filter is an array of several; the dictionary is ignored."); + break; + default: + Report(DiagnosticCodes.DecodeParmsInvalid, DiagnosticSeverity.Warning, "DecodeParms shall be a dictionary or an array; it is ignored."); + break; + } + + if (parameterArray is not null && parameterArray.Count != names.Count) + { + Report( + DiagnosticCodes.DecodeParmsInvalid, + DiagnosticSeverity.Warning, + "The DecodeParms array shall have one entry per filter; missing entries take the defaults."); + } + + for (int index = 0; index < names.Count; index++) + { + if (Resolve(names[index]) is not CosName name) + { + Report(DiagnosticCodes.FilterInvalid, DiagnosticSeverity.Error, "Every element of the Filter array shall be a name; the chain stops before the first that is not."); + return; + } + + CosDictionary? stageParameters = parameterArray is not null + ? index < parameterArray.Count ? ParametersElement(Resolve(parameterArray[index])) : null + : names.Count == 1 ? parametersEntry as CosDictionary : null; + chain.Add(new FilterStage(Expand(name), stageParameters)); + } + } + + private CosDictionary? SingleParameters(CosObject parametersEntry) + { + switch (parametersEntry) + { + case CosNull: + return null; + case CosDictionary dictionary: + return dictionary; + case CosArray array: + Report( + DiagnosticCodes.DecodeParmsInvalid, + DiagnosticSeverity.Warning, + "DecodeParms shall be a dictionary when Filter is a single name; the first element of the array is used."); + return array.Count > 0 ? Resolve(array[0]) as CosDictionary : null; + default: + Report(DiagnosticCodes.DecodeParmsInvalid, DiagnosticSeverity.Warning, "DecodeParms shall be a dictionary; it is ignored."); + return null; + } + } + + private CosDictionary? ParametersElement(CosObject element) + { + switch (element) + { + case CosNull: + return null; + case CosDictionary dictionary: + return dictionary; + default: + Report(DiagnosticCodes.DecodeParmsInvalid, DiagnosticSeverity.Warning, "Each element of the DecodeParms array shall be a dictionary or null; this one is ignored."); + return null; + } + } + + private CosName Expand(CosName name) + { + if (!FilterNames.TryExpandAbbreviation(name, out CosName? fullName)) + { + return name; + } + + Report( + DiagnosticCodes.FilterAbbreviationNotAllowed, + DiagnosticSeverity.Warning, + $"The abbreviation /{name.Value} is valid only in inline images; it is read as /{fullName.Value}."); + return fullName; + } + + private void Report(string code, DiagnosticSeverity severity, string message) => _diagnostics.Report(code, severity, message); + + /// One filter of a chain and its parameters. + private readonly record struct FilterStage(CosName Name, CosDictionary? Parameters); +} diff --git a/src/Broadside/Parsing/DiagnosticCodes.cs b/src/Broadside/Parsing/DiagnosticCodes.cs index 910077f7..c20079b1 100644 --- a/src/Broadside/Parsing/DiagnosticCodes.cs +++ b/src/Broadside/Parsing/DiagnosticCodes.cs @@ -31,6 +31,21 @@ internal static class DiagnosticCodes public const string MissingEndobj = nameof(MissingEndobj); public const string ReferenceChainTooDeep = nameof(ReferenceChainTooDeep); + // Stream filters (§7.3.8.2 Table 5, §7.4). + public const string FilterInvalid = nameof(FilterInvalid); + public const string FilterUnsupported = nameof(FilterUnsupported); + public const string FilterAbbreviationNotAllowed = nameof(FilterAbbreviationNotAllowed); + public const string FilterDataInvalid = nameof(FilterDataInvalid); + public const string FilterDataTruncated = nameof(FilterDataTruncated); + public const string FilterFailed = nameof(FilterFailed); + public const string DecodeParmsInvalid = nameof(DecodeParmsInvalid); + public const string PredictorInvalid = nameof(PredictorInvalid); + public const string CryptFilterNotFirst = nameof(CryptFilterNotFirst); + public const string CryptFilterUnsupported = nameof(CryptFilterUnsupported); + public const string StreamExternalFileUnsupported = nameof(StreamExternalFileUnsupported); + public const string StreamDecodedLengthExceeded = nameof(StreamDecodedLengthExceeded); + public const string StreamDecodingTooDeep = nameof(StreamDecodingTooDeep); + // Document catalog (§7.7.2). public const string CatalogTypeInvalid = nameof(CatalogTypeInvalid); public const string CatalogVersionNotName = nameof(CatalogVersionNotName); diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 7d8beeba..313517de 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -1,4 +1,6 @@ +using System.Buffers; using Broadside.Diagnostics; +using Broadside.Filters; using Broadside.IO; using Broadside.Objects; using Broadside.Parsing; @@ -25,12 +27,14 @@ public sealed class PdfDocument : IDisposable private readonly PdfSource _source; private readonly DiagnosticSink _diagnostics; private readonly ObjectLoader _loader; + private readonly StreamDecoder _streams; - private PdfDocument(PdfSource source, DiagnosticSink diagnostics, ObjectLoader loader, CosDictionary catalog) + private PdfDocument(PdfSource source, DiagnosticSink diagnostics, ObjectLoader loader, StreamDecoder streams, CosDictionary catalog) { _source = source; _diagnostics = diagnostics; _loader = loader; + _streams = streams; Catalog = catalog; Pages = new PdfPageCollection(() => PageTreeReader.Read(this, diagnostics)); } @@ -141,6 +145,33 @@ public PdfVersion Version /// ISO 32000-2 §7.3.10. public CosObject Resolve(CosObject? value) => _loader.Resolve(value); + /// Returns the data of decoded through the filters its Filter entry names. + /// A stream of this document. + /// The decoded data; for a stream without filters, its itself. + /// In strict mode, for the first deviation found while decoding. + /// + /// ISO 32000-2 §7.3.8.2 and §7.4. Filters come from the engine's options (). In lenient mode a + /// filter that is unknown or not implemented yet leaves the data as decoded up to it, with a diagnostic; damaged data decodes as + /// far as it can. Decodes on every call; nothing is cached. + /// + public ReadOnlyMemory DecodeStream(CosStream stream) + { + ArgumentNullException.ThrowIfNull(stream); + return _streams.Decode(stream); + } + + /// Decodes the data of through the filters its Filter entry names into . + /// A stream of this document. + /// Where to write the decoded data. + /// In strict mode, for the first deviation found while decoding. + /// ISO 32000-2 §7.3.8.2 and §7.4. As , into a caller-provided or pooled buffer. + public void DecodeStream(CosStream stream, IBufferWriter output) + { + ArgumentNullException.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(output); + _streams.Decode(stream, output); + } + /// public void Dispose() => _source.Dispose(); @@ -156,8 +187,9 @@ internal static PdfDocument Read(PdfSource source, EngineConfiguration configura FileHeader header = FileHeader.Locate(source, diagnostics); CrossReference crossReference = CrossReferenceReader.Read(source, header, diagnostics) ?? Reconstruct(diagnostics); var loader = new ObjectLoader(source, header, crossReference, diagnostics, new ObjectLoaderHooks()); + var streams = new StreamDecoder(configuration.Filters, configuration.MaxDecodedStreamLength, diagnostics, loader.Resolve); CosDictionary catalog = ReadCatalog(loader, diagnostics); - return new PdfDocument(source, diagnostics, loader, catalog); + return new PdfDocument(source, diagnostics, loader, streams, catalog); } catch { diff --git a/src/Broadside/PdfOptions.cs b/src/Broadside/PdfOptions.cs index f78cc55c..916975e8 100644 --- a/src/Broadside/PdfOptions.cs +++ b/src/Broadside/PdfOptions.cs @@ -1,3 +1,6 @@ +using Broadside.Filters; +using Broadside.Objects; + namespace Broadside; /// @@ -10,6 +13,12 @@ namespace Broadside; /// public sealed class PdfOptions { + /// The default of : 1 GiB. + public const long DefaultMaxDecodedStreamLength = 1L << 30; + + private readonly List _filters = []; + private long _maxDecodedStreamLength = DefaultMaxDecodedStreamLength; + /// Gets or sets how deviations from the specification are treated. The default is . /// ADR 0005. public PdfReadingMode ReadingMode { get; set; } = PdfReadingMode.Lenient; @@ -29,4 +38,58 @@ public PdfOptions UseStrict() ReadingMode = PdfReadingMode.Strict; return this; } + + /// Gets or sets the most bytes one stream may decode to; longer output is truncated with a diagnostic. Default 1 GiB. + /// ISO 32000-2 §7.4. Guards against decompression bombs; a stream's DL entry is only a hint (§7.3.8.2, Table 5). + /// The value is not positive. + public long MaxDecodedStreamLength + { + get => _maxDecodedStreamLength; + set + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); + _maxDecodedStreamLength = value; + } + } + + /// Gets the filters registered with , in registration order. + /// ISO 32000-2 §7.4.1. + public IReadOnlyList Filters => _filters; + + /// + /// Uses for every stream whose Filter entry names , replacing the + /// managed default of that name or adding a filter the defaults lack. A later registration of the same name wins. + /// + /// The filter. Shared by every document and thread of the engine: it must keep no state between calls. + /// These options. + /// + /// The filter's name is Crypt, which the security handler decodes (§7.4.10), or an inline-image abbreviation such as + /// Fl (§8.9.7, Table 92), which is always read as the full name it stands for. + /// + /// ISO 32000-2 §7.4.1. The filter extension point (ADR 0001). + public PdfOptions UseFilter(IStreamFilter filter) + { + ArgumentNullException.ThrowIfNull(filter); + CosName name = filter.Name ?? throw new ArgumentException("The filter has no name.", nameof(filter)); + if (name.Equals(FilterNames.Crypt) || FilterNames.TryExpandAbbreviation(name, out _)) + { + throw new ArgumentException( + $"A filter cannot be registered under /{name.Value}: Crypt belongs to the security handler and abbreviations are read as full names.", + nameof(filter)); + } + + _filters.Add(filter); + return this; + } + + /// Sets . + /// The most bytes one stream may decode to. + /// These options. + /// is not positive. + /// ISO 32000-2 §7.4. + public PdfOptions WithMaxDecodedStreamLength(long maxLength) + { + MaxDecodedStreamLength = maxLength; + return this; + } } diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index 6b193443..b33f4867 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -107,8 +107,47 @@ Broadside.Diagnostics.DiagnosticException.DiagnosticException(string? message, S Broadside.Diagnostics.DiagnosticSeverity Broadside.Diagnostics.DiagnosticSeverity.Error = 1 -> Broadside.Diagnostics.DiagnosticSeverity Broadside.Diagnostics.DiagnosticSeverity.Warning = 0 -> Broadside.Diagnostics.DiagnosticSeverity +Broadside.Filters.Ascii85DecodeFilter +Broadside.Filters.Ascii85DecodeFilter.Ascii85DecodeFilter() -> void +Broadside.Filters.Ascii85DecodeFilter.Decode(System.ReadOnlyMemory encoded, System.Buffers.IBufferWriter! output, Broadside.Filters.FilterContext! context) -> void +Broadside.Filters.Ascii85DecodeFilter.Name.get -> Broadside.Objects.CosName! +Broadside.Filters.AsciiHexDecodeFilter +Broadside.Filters.AsciiHexDecodeFilter.AsciiHexDecodeFilter() -> void +Broadside.Filters.AsciiHexDecodeFilter.Decode(System.ReadOnlyMemory encoded, System.Buffers.IBufferWriter! output, Broadside.Filters.FilterContext! context) -> void +Broadside.Filters.AsciiHexDecodeFilter.Name.get -> Broadside.Objects.CosName! +Broadside.Filters.FilterContext +Broadside.Filters.FilterContext.DecodeStream(Broadside.Objects.CosStream! stream) -> System.ReadOnlyMemory +Broadside.Filters.FilterContext.Diagnostics.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Filters.FilterContext.FilterContext() -> void +Broadside.Filters.FilterContext.MaxDecodedLength.get -> long +Broadside.Filters.FilterContext.MaxDecodedLength.init -> void +Broadside.Filters.FilterContext.Parameters.get -> Broadside.Objects.CosDictionary? +Broadside.Filters.FilterContext.Parameters.init -> void +Broadside.Filters.FilterContext.ReadingMode.get -> Broadside.PdfReadingMode +Broadside.Filters.FilterContext.ReadingMode.init -> void +Broadside.Filters.FilterContext.Report(string! code, Broadside.Diagnostics.DiagnosticSeverity severity, string! message) -> void +Broadside.Filters.FilterContext.Resolve(Broadside.Objects.CosObject? value) -> Broadside.Objects.CosObject! +Broadside.Filters.FilterContext.StreamDictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Filters.FilterContext.StreamDictionary.init -> void +Broadside.Filters.FlateDecodeFilter +Broadside.Filters.FlateDecodeFilter.Decode(System.ReadOnlyMemory encoded, System.Buffers.IBufferWriter! output, Broadside.Filters.FilterContext! context) -> void +Broadside.Filters.FlateDecodeFilter.FlateDecodeFilter() -> void +Broadside.Filters.FlateDecodeFilter.Name.get -> Broadside.Objects.CosName! +Broadside.Filters.IStreamFilter +Broadside.Filters.IStreamFilter.Decode(System.ReadOnlyMemory encoded, System.Buffers.IBufferWriter! output, Broadside.Filters.FilterContext! context) -> void +Broadside.Filters.IStreamFilter.Name.get -> Broadside.Objects.CosName! +Broadside.Filters.LzwDecodeFilter +Broadside.Filters.LzwDecodeFilter.Decode(System.ReadOnlyMemory encoded, System.Buffers.IBufferWriter! output, Broadside.Filters.FilterContext! context) -> void +Broadside.Filters.LzwDecodeFilter.LzwDecodeFilter() -> void +Broadside.Filters.LzwDecodeFilter.Name.get -> Broadside.Objects.CosName! +Broadside.Filters.RunLengthDecodeFilter +Broadside.Filters.RunLengthDecodeFilter.Decode(System.ReadOnlyMemory encoded, System.Buffers.IBufferWriter! output, Broadside.Filters.FilterContext! context) -> void +Broadside.Filters.RunLengthDecodeFilter.Name.get -> Broadside.Objects.CosName! +Broadside.Filters.RunLengthDecodeFilter.RunLengthDecodeFilter() -> void Broadside.PdfDocument Broadside.PdfDocument.Catalog.get -> Broadside.Objects.CosDictionary! +Broadside.PdfDocument.DecodeStream(Broadside.Objects.CosStream! stream) -> System.ReadOnlyMemory +Broadside.PdfDocument.DecodeStream(Broadside.Objects.CosStream! stream, System.Buffers.IBufferWriter! output) -> void Broadside.PdfDocument.Diagnostics.get -> System.Collections.Generic.IReadOnlyList! Broadside.PdfDocument.Dispose() -> void Broadside.PdfDocument.Pages.get -> Broadside.PdfPageCollection! @@ -123,11 +162,16 @@ Broadside.PdfEngine.Open(System.ReadOnlyMemory bytes) -> Broadside.PdfDocu Broadside.PdfEngine.PdfEngine() -> void Broadside.PdfEngine.PdfEngine(Broadside.PdfOptions! options) -> void Broadside.PdfOptions +Broadside.PdfOptions.Filters.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfOptions.MaxDecodedStreamLength.get -> long +Broadside.PdfOptions.MaxDecodedStreamLength.set -> void Broadside.PdfOptions.PdfOptions() -> void Broadside.PdfOptions.ReadingMode.get -> Broadside.PdfReadingMode Broadside.PdfOptions.ReadingMode.set -> void +Broadside.PdfOptions.UseFilter(Broadside.Filters.IStreamFilter! filter) -> Broadside.PdfOptions! Broadside.PdfOptions.UseLenient() -> Broadside.PdfOptions! Broadside.PdfOptions.UseStrict() -> Broadside.PdfOptions! +Broadside.PdfOptions.WithMaxDecodedStreamLength(long maxLength) -> Broadside.PdfOptions! Broadside.PdfPage Broadside.PdfPage.ArtBox.get -> Broadside.PdfRectangle Broadside.PdfPage.BleedBox.get -> Broadside.PdfRectangle @@ -163,6 +207,7 @@ Broadside.PdfVersion.Major.get -> int Broadside.PdfVersion.Minor.get -> int Broadside.PdfVersion.PdfVersion() -> void Broadside.PdfVersion.PdfVersion(int major, int minor) -> void +const Broadside.PdfOptions.DefaultMaxDecodedStreamLength = 1073741824 -> long override Broadside.Diagnostics.Diagnostic.ToString() -> string! override Broadside.PdfRectangle.Equals(object? obj) -> bool override Broadside.PdfRectangle.GetHashCode() -> int diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index ee0219ec..28b1ce77 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -1,4 +1,6 @@ +using System.Buffers; using Broadside.Diagnostics; +using Broadside.Filters; using Broadside.Objects; using SharpFuzz; @@ -16,8 +18,16 @@ internal static class FuzzTargets ["lexer"] = Lexer, ["object-parser"] = ObjectParser, ["document"] = Document, + ["filter-asciihex"] = data => Filter(new AsciiHexDecodeFilter(), data, parameters: null, maxRatio: 1), + ["filter-ascii85"] = data => Filter(new Ascii85DecodeFilter(), data, parameters: null, maxRatio: 4), + ["filter-lzw"] = Lzw, + ["filter-flate"] = data => Filter(new FlateDecodeFilter(), data, parameters: null, maxRatio: 1100), + ["filter-runlength"] = data => Filter(new RunLengthDecodeFilter(), data, parameters: null, maxRatio: 128), + ["filter-predictor"] = PredictorTarget, }; + private static readonly CosName ContentsKey = new("Contents"); + /// /// Opens the input as a whole file in lenient mode and reads everything the document model exposes: version, trailer, every /// page's boxes, rotation, user unit and resources. A is the one documented outcome for a file @@ -51,6 +61,79 @@ private static void Document(ReadOnlySpan data) } _ = page.Resources; + if (page.Dictionary.TryGetValue(ContentsKey, out CosObject? contents) && document.Resolve(contents) is CosStream stream) + { + _ = document.DecodeStream(stream); + } + } + } + + /// + /// Decodes the input as a raw stream body with one filter in lenient mode. The output must stay within + /// bytes per input byte (plus one group), the most any encoding of that filter can expand. + /// + /// ISO 32000-2 §7.4.2 to §7.4.5. + private static void Filter(IStreamFilter filter, ReadOnlySpan data, CosDictionary? parameters, long maxRatio) + { + var output = new ArrayBufferWriter(); + filter.Decode(data.ToArray(), output, new FilterContext { Parameters = parameters }); + if (output.WrittenCount > (data.Length * maxRatio) + 8) + { + throw new InvalidOperationException($"{filter.Name.Value} decoded {data.Length} bytes to {output.WrittenCount}, more than the encoding allows."); + } + } + + /// LZWDecode: the first byte's low bit selects EarlyChange (Table 8); the rest is the stream body. + /// ISO 32000-2 §7.4.4.2 and §7.4.4.3. + private static void Lzw(ReadOnlySpan data) + { + if (data.IsEmpty) + { + return; + } + + var parameters = new CosDictionary { [new CosName("EarlyChange")] = new CosInteger(data[0] & 1) }; + + // One code (at least 9 bits) expands to at most 4096 bytes. + Filter(new LzwDecodeFilter(), data[1..], parameters, maxRatio: 4096); + } + + /// + /// The LZW and Flate predictor functions over the input: the first four bytes select Predictor (1, 2, 10 to 15, or an invalid 3), + /// Colors (1 to 4), BitsPerComponent (1, 2, 4, 8, 16) and Columns (1 to 64); the rest is the filter's output to undo. The result + /// must be whole rows, and no more rows than the input holds. + /// + /// ISO 32000-2 §7.4.4.3 Table 8 and §7.4.4.4. + private static void PredictorTarget(ReadOnlySpan data) + { + if (data.Length < 4) + { + return; + } + + ReadOnlySpan predictors = [1, 2, 10, 11, 12, 13, 14, 15, 3]; + ReadOnlySpan depths = [1, 2, 4, 8, 16]; + int predictor = predictors[data[0] % predictors.Length]; + int colors = 1 + (data[1] % 4); + int bitsPerComponent = depths[data[2] % depths.Length]; + int columns = 1 + (data[3] % 64); + var parameters = new CosDictionary + { + [new CosName("Predictor")] = new CosInteger(predictor), + [new CosName("Colors")] = new CosInteger(colors), + [new CosName("BitsPerComponent")] = new CosInteger(bitsPerComponent), + [new CosName("Columns")] = new CosInteger(columns), + }; + ReadOnlySpan body = data[4..]; + var output = new ArrayBufferWriter(); + Predictor.Decode(body, output, new FilterContext { Parameters = parameters }); + + int row = ((colors * bitsPerComponent * columns) + 7) / 8; + int rowsIn = predictor >= 10 ? (body.Length + row) / (row + 1) : (body.Length + row - 1) / row; + bool passedThrough = predictor is 1 or 3; + if (!passedThrough && (output.WrittenCount % row != 0 || output.WrittenCount > rowsIn * row)) + { + throw new InvalidOperationException($"Predictor {predictor} turned {body.Length} bytes into {output.WrittenCount}, not whole rows of {row}."); } } diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index ce3d0824..21e418d5 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources; a `DiagnosticException` for a file whose cross-reference information cannot be read is the one allowed outcome until #41 reconstructs it). Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` for a file whose cross-reference information cannot be read is the one allowed outcome until #41 reconstructs it). The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. @@ -25,7 +25,7 @@ dotnet run -c Release --project tests/Broadside.Fuzz -- --run object-parser arti `--run ` executes the target once on one input, which is also how to replay a crash found by libFuzzer or AFL. -Whole corpus files are the right seeds for `lexer` and `object-parser`, which read any bytes as a file body, and for `document`, which reads whole files. +Whole corpus files are the right seeds for `lexer` and `object-parser`, which read any bytes as a file body, and for `document`, which reads whole files. For the `filter-*` targets they are weak seeds (a whole PDF as a stream body); for real fuzzing extract stream bodies into `artifacts/fuzz/seeds/`, for example `qpdf --show-object=4 --raw-stream-data tests/Corpus/lzw-stream.pdf > artifacts/fuzz/seeds/lzw.bin`. Smoke mode is a regression net, not a fuzzer: it has no coverage feedback and finds only shallow bugs. Use a real fuzzer for anything that parses. diff --git a/tests/Broadside.TestSupport/FilterEncoders.cs b/tests/Broadside.TestSupport/FilterEncoders.cs new file mode 100644 index 00000000..4221f2ab --- /dev/null +++ b/tests/Broadside.TestSupport/FilterEncoders.cs @@ -0,0 +1,181 @@ +using System.IO.Compression; + +namespace Broadside.TestSupport; + +/// +/// Encoders for the standard filters, the counterparts of the decoders under test: ports of the encoders in +/// tests/Corpus/generate.py (lzw_encode, ascii85_encode, runlength_encode) and the BCL's zlib. Shared by +/// the filter tests and the filter benchmarks (linked as source there, as is). ISO 32000-2 §7.4. +/// +public static class FilterEncoders +{ + /// Deterministic bytes from a small alphabet of letters: compressible, so LZW tables fill and clear several times. + /// How many bytes. + /// How many distinct letters. + /// The generator's seed. + /// The bytes. + public static byte[] SampleData(int length, int alphabet = 7, int seed = 38) + { + // A linear congruential generator: deterministic across runtimes, and not mistaken for a security use of Random. + uint state = (uint)seed; + byte[] data = new byte[length]; + for (int index = 0; index < length; index++) + { + state = (state * 1664525) + 1013904223; + data[index] = (byte)('a' + ((state >> 16) % (uint)alphabet)); + } + + return data; + } + + /// Compresses with the BCL's zlib (RFC 1950): what FlateDecode decodes. + /// The data. + /// The zlib stream. + public static byte[] Zlib(ReadOnlySpan data) + { + var buffer = new MemoryStream(); + using (var zlib = new ZLibStream(buffer, CompressionLevel.Optimal, leaveOpen: true)) + { + zlib.Write(data); + } + + return buffer.ToArray(); + } + + /// + /// lzw_encode of generate.py, ported: 9 to 12-bit codes, clear first, EOD last, a clear code whenever the table + /// fills, the code length growing one code early when is 1 (§7.4.4.2, Table 8). + /// + /// The data. + /// The EarlyChange parameter, 0 or 1. + /// The LZW codes, packed high-order bit first. + public static byte[] LzwEncode(ReadOnlySpan data, int earlyChange = 1) + { + var codes = new List<(int Code, int Width)>(); + Dictionary table = NewTable(); + int nextCode = 258; + int width = 9; + codes.Add((256, width)); + string pending = string.Empty; + foreach (byte value in data) + { + string extended = pending + (char)value; + if (table.ContainsKey(extended)) + { + pending = extended; + continue; + } + + codes.Add((table[pending], width)); + table[extended] = nextCode++; + if (nextCode + earlyChange > (1 << width) && width < 12) + { + width++; + } + + if (nextCode + earlyChange >= 4096) + { + codes.Add((256, width)); + table = NewTable(); + nextCode = 258; + width = 9; + } + + pending = ((char)value).ToString(); + } + + if (pending.Length > 0) + { + codes.Add((table[pending], width)); + } + + codes.Add((257, width)); + var output = new List(); + long accumulator = 0; + int bits = 0; + foreach ((int code, int codeWidth) in codes) + { + accumulator = (accumulator << codeWidth) | (uint)code; + bits += codeWidth; + while (bits >= 8) + { + output.Add((byte)(accumulator >> (bits - 8))); + bits -= 8; + } + } + + if (bits > 0) + { + output.Add((byte)(accumulator << (8 - bits))); + } + + return [.. output]; + + static Dictionary NewTable() => Enumerable.Range(0, 256).ToDictionary(index => ((char)index).ToString(), index => index); + } + + /// ascii85_encode of generate.py: groups of five digits, a final partial group, ~> (§7.4.3). + /// The data. + /// The ASCII base-85 text. + public static byte[] Ascii85Encode(ReadOnlySpan data) + { + var output = new List(); + byte[] group = new byte[5]; + for (int index = 0; index < data.Length; index += 4) + { + int count = Math.Min(4, data.Length - index); + uint value = 0; + for (int offset = 0; offset < 4; offset++) + { + value = (value << 8) | (offset < count ? data[index + offset] : 0u); + } + + for (int digit = 4; digit >= 0; digit--) + { + group[digit] = (byte)('!' + (value % 85)); + value /= 85; + } + + output.AddRange(group.AsSpan(0, count + 1)); + } + + return [.. output, (byte)'~', (byte)'>']; + } + + /// runlength_encode of generate.py: repeated runs of 2 to 128, literal runs of up to 128, EOD 128 (§7.4.5). + /// The data. + /// The run-length encoded data. + public static byte[] RunLengthEncode(ReadOnlySpan data) + { + var output = new List(); + int index = 0; + while (index < data.Length) + { + int run = 1; + while (index + run < data.Length && run < 128 && data[index + run] == data[index]) + { + run++; + } + + if (run >= 2) + { + output.Add((byte)(257 - run)); + output.Add(data[index]); + index += run; + continue; + } + + int start = index; + while (index < data.Length && index - start < 128 && !(index + 1 < data.Length && data[index + 1] == data[index])) + { + index++; + } + + output.Add((byte)(index - start - 1)); + output.AddRange(data[start..index]); + } + + output.Add(0x80); + return [.. output]; + } +} diff --git a/tests/Broadside.Tests/Filters/AsciiFilterTests.cs b/tests/Broadside.Tests/Filters/AsciiFilterTests.cs new file mode 100644 index 00000000..bb5c40f1 --- /dev/null +++ b/tests/Broadside.Tests/Filters/AsciiFilterTests.cs @@ -0,0 +1,113 @@ +using System.Text; +using Broadside.Diagnostics; +using Broadside.Filters; +using Broadside.TestSupport; + +namespace Broadside.Tests.Filters; + +/// ASCIIHexDecode and ASCII85Decode through the filter contract. ISO 32000-2 §7.4.2 and §7.4.3. +public class AsciiFilterTests +{ + [Theory] + [InlineData("48656C6C6F>", "Hello")] + [InlineData("48 65\n6c\t6C\r6F\f\0>", "Hello")] + [InlineData("4>", "@")] + [InlineData("486>", "H`")] + [InlineData(">", "")] + [InlineData("41>42", "A")] + public void Ascii_hex_decodes_digit_pairs_ignores_white_space_and_pads_an_odd_final_digit(string encoded, string expected) + { + (byte[] decoded, string[] codes) = FilterTesting.Run(new AsciiHexDecodeFilter(), Encoding.Latin1.GetBytes(encoded)); + + Assert.Equal(expected, Encoding.Latin1.GetString(decoded)); + Assert.Empty(codes); + } + + [Fact] + public void Ascii_hex_skips_invalid_characters_with_one_diagnostic() + { + (byte[] decoded, string[] codes) = FilterTesting.Run(new AsciiHexDecodeFilter(), "4G1x42>"u8); + + Assert.Equal("AB", Encoding.Latin1.GetString(decoded)); + Assert.Equal(["FilterDataInvalid"], codes); + } + + [Fact] + public void Ascii_hex_without_the_end_marker_decodes_to_its_end_with_a_diagnostic() + { + (byte[] decoded, string[] codes) = FilterTesting.Run(new AsciiHexDecodeFilter(), "414"u8); + + Assert.Equal([0x41, 0x40], decoded); + Assert.Equal(["FilterDataTruncated"], codes); + } + + [Theory] + [InlineData("9jqo^~>", "Man ")] + [InlineData("9jqo^BlbD-BleB1DJ+*+F(f,q~>", "Man is distinguished")] + [InlineData("z~>", "\0\0\0\0")] + [InlineData("zz9jqo^~>", "\0\0\0\0\0\0\0\0Man ")] + [InlineData("9jqo~>", "Man")] + [InlineData("9jn~>", "Ma")] + [InlineData("9`~>", "M")] + [InlineData(" 9j\nqo^\t\0\r\f~>", "Man ")] + [InlineData("~>", "")] + [InlineData("s8W-!~>", "\xff\xff\xff\xff")] + [InlineData("9jqo^~", "Man ")] + [InlineData("<~9jqo^~>", "Man ")] + public void Ascii85_decodes_groups_z_partial_groups_and_ignores_white_space(string encoded, string expected) + { + (byte[] decoded, string[] codes) = FilterTesting.Run(new Ascii85DecodeFilter(), Encoding.Latin1.GetBytes(encoded)); + + Assert.Equal(expected, Encoding.Latin1.GetString(decoded)); + Assert.Empty(codes); + } + + [Theory] + [InlineData("9jqo^{~>", "Man ")] + [InlineData("9jzqo^~>", "Man ")] + [InlineData("s8W-\"~>", "\0\0\0\0")] + [InlineData("9jqo^9~>", "Man ")] + public void Ascii85_repairs_impossible_sequences_with_a_diagnostic(string encoded, string expected) + { + (byte[] decoded, string[] codes) = FilterTesting.Run(new Ascii85DecodeFilter(), Encoding.Latin1.GetBytes(encoded)); + + Assert.Equal(expected, Encoding.Latin1.GetString(decoded)); + Assert.Equal(["FilterDataInvalid"], codes); + } + + [Fact] + public void Ascii85_without_the_end_marker_decodes_the_partial_group_with_a_diagnostic() + { + (byte[] decoded, string[] codes) = FilterTesting.Run(new Ascii85DecodeFilter(), "9jqo^9jqo"u8); + + Assert.Equal("Man Man", Encoding.Latin1.GetString(decoded)); + Assert.Equal(["FilterDataTruncated"], codes); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + public void Both_filters_round_trip_the_encoders_of_the_corpus_generator(int extra) + { + byte[] data = [.. FilterEncoders.SampleData(10_000, alphabet: 200), .. new byte[extra]]; + + (byte[] fromHex, string[] hexCodes) = FilterTesting.Run(new AsciiHexDecodeFilter(), Encoding.ASCII.GetBytes(Convert.ToHexString(data) + ">")); + (byte[] from85, string[] codes85) = FilterTesting.Run(new Ascii85DecodeFilter(), FilterEncoders.Ascii85Encode(data)); + + Assert.Equal(data, fromHex); + Assert.Equal(data, from85); + Assert.Empty(hexCodes); + Assert.Empty(codes85); + } + + [Fact] + public void Strict_mode_throws_for_an_invalid_character() + { + DiagnosticException error = Assert.Throws( + () => FilterTesting.Run(new Ascii85DecodeFilter(), "9jqo^v~>"u8, mode: PdfReadingMode.Strict)); + + Assert.Equal("FilterDataInvalid", error.Diagnostic.Code); + } +} diff --git a/tests/Broadside.Tests/Filters/CorpusFilterTests.cs b/tests/Broadside.Tests/Filters/CorpusFilterTests.cs new file mode 100644 index 00000000..fa075eca --- /dev/null +++ b/tests/Broadside.Tests/Filters/CorpusFilterTests.cs @@ -0,0 +1,79 @@ +using System.Text; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Filters; + +/// +/// The filter corpus files decode, through the public document API, to exactly the content stream tests/Corpus/generate.py +/// encoded (its gen_* functions; pdftotext prints the text each one shows). ISO 32000-2 §7.4. +/// +public class CorpusFilterTests +{ + public static TheoryData FilteredContentStreams => new() + { + { "flate-stream.pdf", "BT /F1 24 Tf 72 700 Td (FlateDecode) Tj ET" }, + { "lzw-stream.pdf", "BT /F1 24 Tf 72 700 Td (LZWDecode) Tj ET" }, + { "ascii85-stream.pdf", "BT /F1 24 Tf 72 700 Td (ASCII85Decode) Tj ET" }, + { "asciihex-stream.pdf", "BT /F1 24 Tf 72 700 Td (ASCIIHexDecode) Tj ET" }, + { "runlength-stream.pdf", "BT /F1 24 Tf 72 700 Td (RunLengthDecode) Tj ET " }, + { "filter-chain.pdf", "BT /F1 24 Tf 72 700 Td (ASCII85 then Flate) Tj ET" }, + }; + + [Theory] + [MemberData(nameof(FilteredContentStreams))] + public void A_filtered_content_stream_decodes_to_the_bytes_that_were_encoded(string fileName, string expected) + { + using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName)); + CosStream contents = ContentStream(document); + + ReadOnlyMemory decoded = document.DecodeStream(contents); + + Assert.Equal(expected, Encoding.Latin1.GetString(decoded.Span)); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [MemberData(nameof(FilteredContentStreams))] + public void Decoding_into_a_buffer_writer_gives_the_same_bytes(string fileName, string expected) + { + using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName)); + var output = new System.Buffers.ArrayBufferWriter(); + + document.DecodeStream(ContentStream(document), output); + + Assert.Equal(expected, Encoding.Latin1.GetString(output.WrittenSpan)); + } + + [Theory] + [MemberData(nameof(Corpus.WellFormedFiles), MemberType = typeof(Corpus))] + public void Every_page_content_stream_of_a_well_formed_file_decodes_with_no_diagnostics(string fileName) + { + Assert.SkipWhen(Document.WellFormedCorpusTests.NeedsCrossReferenceStreams(fileName), "Needs cross-reference streams (#39)."); + Assert.SkipWhen(fileName.StartsWith("encrypted-", StringComparison.Ordinal), "Needs decryption (#42)."); + + using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName)); + foreach (PdfPage page in document.Pages) + { + if (document.Resolve(page.Dictionary.TryGetValue(new CosName("Contents"), out CosObject? contents) ? contents : null) is CosStream stream) + { + Assert.False(document.DecodeStream(stream).IsEmpty); + } + } + + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void An_unfiltered_stream_decodes_to_its_encoded_data() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("text-standard14.pdf")); + + ReadOnlyMemory decoded = document.DecodeStream(ContentStream(document)); + + Assert.Equal("BT /F1 24 Tf 72 700 Td (Hello, Broadside) Tj ET", Encoding.Latin1.GetString(decoded.Span)); + } + + internal static CosStream ContentStream(PdfDocument document) => + Assert.IsType(document.Resolve(document.Pages[0].Dictionary[new CosName("Contents")])); +} diff --git a/tests/Broadside.Tests/Filters/FilterAllocationTests.cs b/tests/Broadside.Tests/Filters/FilterAllocationTests.cs new file mode 100644 index 00000000..ba4fec35 --- /dev/null +++ b/tests/Broadside.Tests/Filters/FilterAllocationTests.cs @@ -0,0 +1,126 @@ +using System.Buffers; +using System.Text; +using Broadside.Filters; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Filters; + +/// +/// Filters are a hot path and allocate nothing per byte, code or row (CLAUDE.md, "Code conventions"). This is the build-breaking +/// half of that rule; the *Benchmarks classes in bench/Broadside.Benchmarks are the measuring half. ISO 32000-2 §7.4. +/// +public class FilterAllocationTests +{ + public static TheoryData AllocationFreeFilters => new() { "ASCIIHexDecode", "ASCII85Decode", "LZWDecode", "RunLengthDecode" }; + + [Theory] + [MemberData(nameof(AllocationFreeFilters))] + public void Decoding_through_the_contract_allocates_nothing(string name) + { + (IStreamFilter filter, byte[] encoded) = Encoded(name, FilterEncoders.SampleData(200_000)); + var context = new FilterContext(); + var output = new ArrayBufferWriter(400_000); + + // Past tiered compilation's call-count threshold first, so the runtime's own bookkeeping is not counted. + for (int warmUp = 0; warmUp < 40; warmUp++) + { + Decode(filter, encoded, output, context); + } + + long allocated = Decode(filter, encoded, output, context); + + Assert.True(output.WrittenCount >= 200_000); + Assert.Equal(0, allocated); + } + + [Fact] + public void Flate_allocates_the_inflater_once_per_call_and_nothing_per_byte() + { + var filter = new FlateDecodeFilter(); + var context = new FilterContext(); + var output = new ArrayBufferWriter(1_000_000); + byte[] small = FilterEncoders.Zlib(FilterEncoders.SampleData(1_000)); + byte[] large = FilterEncoders.Zlib(FilterEncoders.SampleData(900_000)); + for (int warmUp = 0; warmUp < 40; warmUp++) + { + Decode(filter, small, output, context); + Decode(filter, large, output, context); + } + + long forSmall = Decode(filter, small, output, context); + long forLarge = Decode(filter, large, output, context); + + Assert.InRange(forLarge, 0, forSmall + 64); + } + + [Fact] + public void Decoding_a_predicted_stream_through_a_document_allocates_per_stream_not_per_row() + { + long forSmall = PredictedStreamAllocation(rows: 10); + long forLarge = PredictedStreamAllocation(rows: 20_000); + + Assert.InRange(forLarge, 0, forSmall + 64); + } + + private static long PredictedStreamAllocation(int rows) + { + byte[] predicted = new byte[rows * 5]; + for (int row = 0; row < rows; row++) + { + predicted[row * 5] = (byte)(row % 5); + predicted[(row * 5) + 1] = (byte)row; + } + + byte[] file = FilterTesting.FileWithStream("/Filter /FlateDecode /DecodeParms << /Predictor 15 /Columns 4 >>", FilterEncoders.Zlib(predicted)); + using PdfDocument document = PdfDocument.Open(file); + var stream = (CosStream)document.Resolve(FilterTesting.StreamReference); + var output = new ArrayBufferWriter(rows * 4); + for (int warmUp = 0; warmUp < 40; warmUp++) + { + output.ResetWrittenCount(); + document.DecodeStream(stream, output); + } + + output.ResetWrittenCount(); + + long before = GC.GetAllocatedBytesForCurrentThread(); + document.DecodeStream(stream, output); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.Equal(rows * 4, output.WrittenCount); + return allocated; + } + + private static long Decode(IStreamFilter filter, byte[] encoded, ArrayBufferWriter output, FilterContext context) + { + output.ResetWrittenCount(); + long before = GC.GetAllocatedBytesForCurrentThread(); + filter.Decode(encoded, output, context); + return GC.GetAllocatedBytesForCurrentThread() - before; + } + + private static (IStreamFilter Filter, byte[] Encoded) Encoded(string name, byte[] data) => name switch + { + "ASCIIHexDecode" => (new AsciiHexDecodeFilter(), Encoding.ASCII.GetBytes(Convert.ToHexString(data) + ">")), + "ASCII85Decode" => (new Ascii85DecodeFilter(), FilterEncoders.Ascii85Encode(data)), + "LZWDecode" => (new LzwDecodeFilter(), FilterEncoders.LzwEncode(data)), + "RunLengthDecode" => (new RunLengthDecodeFilter(), RunLength(data)), + _ => throw new ArgumentOutOfRangeException(nameof(name)), + }; + + private static byte[] RunLength(byte[] data) + { + var output = new List(); + for (int index = 0; index < data.Length; index += 64) + { + int count = Math.Min(64, data.Length - index); + output.Add((byte)(count - 1)); + output.AddRange(data.AsSpan(index, count)); + output.Add(0xFD); + output.Add(data[index]); + } + + output.Add(0x80); + return [.. output]; + } +} diff --git a/tests/Broadside.Tests/Filters/FilterExtensionPointTests.cs b/tests/Broadside.Tests/Filters/FilterExtensionPointTests.cs new file mode 100644 index 00000000..fc41de45 --- /dev/null +++ b/tests/Broadside.Tests/Filters/FilterExtensionPointTests.cs @@ -0,0 +1,206 @@ +using System.Buffers; +using System.Text; +using Broadside.Diagnostics; +using Broadside.Filters; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Filters; + +/// +/// The filter extension point: filters are registered per engine through the options, never in a static registry, and a +/// registered filter replaces the managed default of its name or adds a new one. ISO 32000-2 §7.4.1; ADR 0001. +/// +public class FilterExtensionPointTests +{ + [Fact] + public void A_decorator_registered_through_the_options_replaces_the_default_flate_filter() + { + var counting = new CountingFilter(new FlateDecodeFilter()); + var engine = new PdfEngine(new PdfOptions().UseFilter(counting)); + using PdfDocument document = engine.Open(Corpus.Bytes("flate-stream.pdf")); + + ReadOnlyMemory decoded = document.DecodeStream(CorpusFilterTests.ContentStream(document)); + + Assert.Equal(1, counting.Calls); + Assert.Equal("BT /F1 24 Tf 72 700 Td (FlateDecode) Tj ET", Encoding.Latin1.GetString(decoded.Span)); + } + + [Fact] + public void Two_engines_in_one_process_keep_their_own_filters() + { + var counting = new CountingFilter(new FlateDecodeFilter()); + var withDecorator = new PdfEngine(new PdfOptions().UseFilter(counting)); + var withDefaults = new PdfEngine(); + + using (PdfDocument document = withDefaults.Open(Corpus.Bytes("flate-stream.pdf"))) + { + _ = document.DecodeStream(CorpusFilterTests.ContentStream(document)); + } + + using (PdfDocument document = PdfDocument.Open(Corpus.Bytes("filter-chain.pdf"))) + { + _ = document.DecodeStream(CorpusFilterTests.ContentStream(document)); + } + + Assert.Equal(0, counting.Calls); + using PdfDocument decorated = withDecorator.Open(Corpus.Bytes("filter-chain.pdf")); + _ = decorated.DecodeStream(CorpusFilterTests.ContentStream(decorated)); + Assert.Equal(1, counting.Calls); + } + + [Fact] + public void Options_changed_after_the_engine_is_built_do_not_change_its_filters() + { + var options = new PdfOptions(); + var engine = new PdfEngine(options); + var counting = new CountingFilter(new FlateDecodeFilter()); + options.UseFilter(counting); + + using PdfDocument document = engine.Open(Corpus.Bytes("flate-stream.pdf")); + _ = document.DecodeStream(CorpusFilterTests.ContentStream(document)); + + Assert.Equal(0, counting.Calls); + Assert.Same(counting, Assert.Single(options.Filters)); + } + + [Fact] + public void A_registered_filter_can_add_a_name_the_defaults_lack() + { + byte[] file = FilterTesting.FileWithStream("/Filter /ROT13Decode", "Uryyb"u8); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file, new PdfOptions().UseFilter(new Rot13Filter())); + + Assert.Equal("Hello", Encoding.Latin1.GetString(decoded)); + Assert.Empty(codes); + } + + [Fact] + public void A_replacement_flate_filter_still_gets_the_predictor_applied_by_the_pipeline() + { + var counting = new CountingFilter(new FlateDecodeFilter()); + byte[] file = FilterTesting.FileWithStream( + "/Filter /FlateDecode /DecodeParms << /Predictor 12 /Columns 2 >>", + FilterEncoders.Zlib([2, 1, 2, 2, 1, 1])); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file, new PdfOptions().UseFilter(counting)); + + Assert.Equal([1, 2, 2, 3], decoded); + Assert.Empty(codes); + Assert.Equal(1, counting.Calls); + } + + [Fact] + public void A_filter_sees_its_parameters_and_the_stream_dictionary_and_can_decode_a_referenced_stream() + { + // The shape a JBIG2 codec needs: parameters naming a globals stream, decoded through the same pipeline (§7.4.7). + var probe = new ProbeFilter(); + byte[] file = FilterTesting.FileWithStream( + "/Filter /ProbeDecode /DecodeParms << /Globals 5 0 R >> /Width 7", + "x"u8, + "<< /Length 13 /Filter /ASCIIHexDecode >>\nstream\n676C6F62616C>\nendstream"); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file, new PdfOptions().UseFilter(probe)); + + Assert.Equal("global|7", Encoding.Latin1.GetString(decoded)); + Assert.Empty(codes); + } + + [Fact] + public void An_exception_thrown_by_a_filter_becomes_a_diagnostic_and_keeps_what_it_wrote() + { + byte[] file = FilterTesting.FileWithStream("/Filter /ThrowingDecode", "abc"u8); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file, new PdfOptions().UseFilter(new ThrowingFilter())); + + Assert.Equal("partial", Encoding.Latin1.GetString(decoded)); + Assert.Equal(["FilterFailed"], codes); + } + + [Fact] + public void Crypt_and_abbreviations_cannot_be_registered() + { + Assert.Throws(() => new PdfOptions().UseFilter(new NamedFilter("Crypt"))); + Assert.Throws(() => new PdfOptions().UseFilter(new NamedFilter("Fl"))); + } + + [Fact] + public void A_stand_alone_context_reports_resolves_and_decodes_with_the_default_filters() + { + var context = new FilterContext(); + var stream = new CosStream(new CosDictionary { [new CosName("Filter")] = new CosName("ASCIIHexDecode") }, "414>"u8.ToArray()); + + Assert.Equal("A@", Encoding.Latin1.GetString(context.DecodeStream(stream).Span)); + Assert.Same(CosNull.Instance, context.Resolve(new CosReference(1, 0))); + context.Report("Custom", DiagnosticSeverity.Warning, "Recorded."); + Assert.Equal("Custom", Assert.Single(context.Diagnostics).Code); + + var strict = new FilterContext { ReadingMode = PdfReadingMode.Strict }; + Assert.Throws(() => strict.Report("Custom", DiagnosticSeverity.Warning, "Thrown.")); + } + + private sealed class CountingFilter(IStreamFilter inner) : IStreamFilter + { + private int _calls; + + public int Calls => _calls; + + public CosName Name => inner.Name; + + public void Decode(ReadOnlyMemory encoded, IBufferWriter output, FilterContext context) + { + Interlocked.Increment(ref _calls); + inner.Decode(encoded, output, context); + } + } + + private sealed class Rot13Filter : IStreamFilter + { + public CosName Name { get; } = new("ROT13Decode"); + + public void Decode(ReadOnlyMemory encoded, IBufferWriter output, FilterContext context) + { + foreach (byte value in encoded.Span) + { + byte rotated = value switch + { + >= (byte)'a' and <= (byte)'z' => (byte)('a' + ((value - 'a' + 13) % 26)), + >= (byte)'A' and <= (byte)'Z' => (byte)('A' + ((value - 'A' + 13) % 26)), + _ => value, + }; + output.Write([rotated]); + } + } + } + + private sealed class ProbeFilter : IStreamFilter + { + public CosName Name { get; } = new("ProbeDecode"); + + public void Decode(ReadOnlyMemory encoded, IBufferWriter output, FilterContext context) + { + var globals = (CosStream)context.Resolve(context.Parameters![new CosName("Globals")]); + var width = (CosInteger)context.Resolve(context.StreamDictionary[new CosName("Width")]); + output.Write(context.DecodeStream(globals).Span); + output.Write(Encoding.Latin1.GetBytes($"|{width.Value}")); + } + } + + private sealed class ThrowingFilter : IStreamFilter + { + public CosName Name { get; } = new("ThrowingDecode"); + + public void Decode(ReadOnlyMemory encoded, IBufferWriter output, FilterContext context) + { + output.Write("partial"u8); + throw new InvalidOperationException("Broken on purpose."); + } + } + + private sealed class NamedFilter(string name) : IStreamFilter + { + public CosName Name { get; } = new(name); + + public void Decode(ReadOnlyMemory encoded, IBufferWriter output, FilterContext context) => output.Write(encoded.Span); + } +} diff --git a/tests/Broadside.Tests/Filters/FilterPipelineTests.cs b/tests/Broadside.Tests/Filters/FilterPipelineTests.cs new file mode 100644 index 00000000..f65be2d4 --- /dev/null +++ b/tests/Broadside.Tests/Filters/FilterPipelineTests.cs @@ -0,0 +1,205 @@ +using System.Text; +using Broadside.Diagnostics; +using Broadside.TestSupport; + +namespace Broadside.Tests.Filters; + +/// +/// How a document reads Filter and DecodeParms and runs the chain, including the repairs of deviations from Table 5. +/// ISO 32000-2 §7.3.8.2 Table 5, §7.4.1, §7.4.10, §8.9.7 Table 92. +/// +public class FilterPipelineTests +{ + [Fact] + public void An_unknown_filter_leaves_the_stream_readable_as_raw_bytes_with_a_diagnostic() + { + byte[] file = FilterTesting.FileWithStream("/Filter /NoSuchDecode", "raw bytes"u8); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); + + Assert.Equal("raw bytes", Encoding.Latin1.GetString(decoded)); + Assert.Equal(["FilterUnsupported"], codes); + } + + [Fact] + public void A_chain_stops_at_the_first_filter_it_cannot_run_keeping_what_was_decoded() + { + // ASCIIHex decodes to the bytes of a JPEG marker; DCTDecode is a Phase 2B filter not registered yet. + byte[] file = FilterTesting.FileWithStream("/Filter [/ASCIIHexDecode /DCTDecode]", "FFD8FFE0>"u8); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); + + Assert.Equal([0xFF, 0xD8, 0xFF, 0xE0], decoded); + Assert.Equal(["FilterUnsupported"], codes); + } + + [Fact] + public void Strict_mode_throws_for_an_unknown_filter() + { + byte[] file = FilterTesting.FileWithStream("/Filter /NoSuchDecode", "raw"u8); + + DiagnosticException error = Assert.Throws(() => FilterTesting.Decode(file, new PdfOptions().UseStrict())); + + Assert.Equal("FilterUnsupported", error.Diagnostic.Code); + } + + [Fact] + public void Filters_apply_in_array_order_and_the_same_filter_may_appear_twice() + { + // "3431>" hex-decodes to "41>", which hex-decodes to "A". + byte[] file = FilterTesting.FileWithStream("/Filter [/ASCIIHexDecode /ASCIIHexDecode]", "34313E>"u8); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); + + Assert.Equal("A", Encoding.Latin1.GetString(decoded)); + Assert.Empty(codes); + } + + [Fact] + public void Decode_parameters_align_with_the_filter_array_and_null_means_defaults() + { + byte[] predicted = FilterEncoders.Zlib([2, 1, 2, 2, 1, 1]); + byte[] hex = Encoding.ASCII.GetBytes(Convert.ToHexString(predicted) + ">"); + byte[] file = FilterTesting.FileWithStream("/Filter [/ASCIIHexDecode /FlateDecode] /DecodeParms [null << /Predictor 12 /Columns 2 >>]", hex); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); + + Assert.Equal([1, 2, 2, 3], decoded); + Assert.Empty(codes); + } + + [Fact] + public void Indirect_filter_and_parameters_are_resolved() + { + byte[] file = FilterTesting.FileWithStream("/Filter 5 0 R /DecodeParms 6 0 R", FilterEncoders.Zlib([2, 1, 2, 2, 1, 1]), "[/FlateDecode]", "[<< /Predictor 12 /Columns 2 >>]"); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); + + Assert.Equal([1, 2, 2, 3], decoded); + Assert.Empty(codes); + } + + public static TheoryData TableFiveDeviations => new() + { + // A single filter with a parameter array: the first element is used. + { "/Filter /FlateDecode /DecodeParms [<< /Predictor 12 /Columns 2 >>]", [1, 2, 2, 3], "DecodeParmsInvalid" }, + // Two filters with one parameter dictionary: the dictionary is ignored, so Flate runs without the predictor. + { "/Filter [/ASCIIHexDecode /FlateDecode] /DecodeParms << /Predictor 12 /Columns 2 >>", [2, 1, 2, 2, 1, 1], "DecodeParmsInvalid" }, + // An abbreviation outside an inline image: read as the full name. + { "/Filter /Fl /DecodeParms << /Predictor 12 /Columns 2 >>", [1, 2, 2, 3], "FilterAbbreviationNotAllowed" }, + // A parameter array element that is not a dictionary: defaults. + { "/Filter [/FlateDecode] /DecodeParms [42]", [2, 1, 2, 2, 1, 1], "DecodeParmsInvalid" }, + }; + + [Theory] + [MemberData(nameof(TableFiveDeviations))] + public void Deviations_from_table_5_are_repaired_with_one_diagnostic(string entries, byte[] expected, string code) + { + byte[] flate = FilterEncoders.Zlib([2, 1, 2, 2, 1, 1]); + byte[] data = entries.Contains("ASCIIHexDecode", StringComparison.Ordinal) ? Encoding.ASCII.GetBytes(Convert.ToHexString(flate) + ">") : flate; + byte[] file = FilterTesting.FileWithStream(entries, data); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); + + Assert.Equal(expected, decoded); + Assert.Equal([code], codes); + } + + // Member data, not inline data: the conformance checker cannot read inline strings that hold a closing bracket. + public static TheoryData NotNames => new() { "/Filter 42", "/Filter [42]" }; + + public static TheoryData EmptyStreams => new() { "/Filter /FlateDecode", "/Filter [/ASCII85Decode /LZWDecode]" }; + + public static TheoryData IdentityCryptFilters => new() + { + "/Filter /Crypt", + "/Filter [/Crypt /ASCIIHexDecode] /DecodeParms [<< /Type /CryptFilterDecodeParms /Name /Identity >> null]", + }; + + [Theory] + [MemberData(nameof(NotNames))] + public void A_filter_entry_that_is_not_a_name_leaves_the_data_raw_with_a_diagnostic(string entries) + { + byte[] file = FilterTesting.FileWithStream(entries, "raw"u8); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); + + Assert.Equal("raw", Encoding.Latin1.GetString(decoded)); + Assert.Equal(["FilterInvalid"], codes); + } + + [Theory] + [MemberData(nameof(EmptyStreams))] + public void A_stream_with_no_data_decodes_to_nothing_without_a_diagnostic(string entries) + { + byte[] file = FilterTesting.FileWithStream(entries, []); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); + + Assert.Empty(decoded); + Assert.Empty(codes); + } + + [Theory] + [MemberData(nameof(IdentityCryptFilters))] + public void The_identity_crypt_filter_passes_the_data_through(string entries) + { + byte[] file = FilterTesting.FileWithStream(entries, entries.Contains("ASCIIHex", StringComparison.Ordinal) ? "41>"u8 : "A"u8); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); + + Assert.Equal("A", Encoding.Latin1.GetString(decoded)); + Assert.Empty(codes); + } + + [Fact] + public void A_crypt_filter_the_security_handler_does_not_know_leaves_the_data_encrypted_with_a_diagnostic() + { + byte[] file = FilterTesting.FileWithStream("/Filter /Crypt /DecodeParms << /Name /StdCF >>", "secret"u8); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); + + Assert.Equal("secret", Encoding.Latin1.GetString(decoded)); + Assert.Equal(["CryptFilterUnsupported"], codes); + } + + [Fact] + public void A_crypt_filter_that_is_not_first_is_applied_where_it_is_with_a_diagnostic() + { + byte[] file = FilterTesting.FileWithStream("/Filter [/ASCIIHexDecode /Crypt]", "41>"u8); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); + + Assert.Equal("A", Encoding.Latin1.GetString(decoded)); + Assert.Equal(["CryptFilterNotFirst"], codes); + } + + [Fact] + public void Output_beyond_the_decoded_length_limit_is_truncated_with_a_diagnostic() + { + byte[] file = FilterTesting.FileWithStream("/Filter /FlateDecode", FilterEncoders.Zlib(new byte[100_000])); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file, new PdfOptions().WithMaxDecodedStreamLength(1000)); + + Assert.Equal(new byte[1000], decoded); + Assert.Equal(["StreamDecodedLengthExceeded"], codes); + } + + [Fact] + public void Data_in_an_external_file_is_not_read_and_the_stream_bytes_decode_instead_with_a_diagnostic() + { + byte[] file = FilterTesting.FileWithStream("/F (data.bin) /Filter /ASCIIHexDecode", "41>"u8); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); + + Assert.Equal("A", Encoding.Latin1.GetString(decoded)); + Assert.Equal(["StreamExternalFileUnsupported"], codes); + } + + [Fact] + public void The_maximum_decoded_length_must_be_positive() + { + Assert.Throws(() => new PdfOptions().WithMaxDecodedStreamLength(0)); + Assert.Equal(PdfOptions.DefaultMaxDecodedStreamLength, new PdfOptions().MaxDecodedStreamLength); + } +} diff --git a/tests/Broadside.Tests/Filters/FilterTesting.cs b/tests/Broadside.Tests/Filters/FilterTesting.cs new file mode 100644 index 00000000..e4aa2312 --- /dev/null +++ b/tests/Broadside.Tests/Filters/FilterTesting.cs @@ -0,0 +1,58 @@ +using System.Buffers; +using System.Text; +using Broadside.Filters; +using Broadside.Objects; +using Broadside.Tests.Document; +using Broadside.TestSupport; + +namespace Broadside.Tests.Filters; + +/// Helpers shared by the filter tests: one-stream files and direct filter calls. Encoders are in . +internal static class FilterTesting +{ + /// The stream object number in files built by . + public static readonly CosReference StreamReference = new(4, 0); + + /// A one-page file whose object 4 is a stream with the given dictionary entries (besides Length) and data. + public static byte[] FileWithStream(string dictionaryEntries, ReadOnlySpan data, params string[] moreObjects) + { + string stream = $"<< /Length {data.Length} {dictionaryEntries} >>\nstream\n{Encoding.Latin1.GetString(data)}\nendstream"; + return new TestPdf().Build( + ["<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>", + stream, + .. moreObjects]); + } + + /// Opens a file built by and decodes its stream. + public static (byte[] Decoded, PdfDocument Document) Decode(byte[] file, PdfOptions? options = null) + { + PdfDocument document = PdfDocument.Open(file, options ?? new PdfOptions()); + var stream = (CosStream)document.Resolve(StreamReference); + return (document.DecodeStream(stream).ToArray(), document); + } + + /// Opens a file built by , decodes its stream, and returns the bytes and diagnostic codes. + public static (byte[] Decoded, string[] Codes) DecodeWithCodes(byte[] file, PdfOptions? options = null) + { + (byte[] decoded, PdfDocument document) = Decode(file, options); + using (document) + { + return (decoded, [.. document.Diagnostics.Select(diagnostic => diagnostic.Code)]); + } + } + + /// Calls a filter directly through its contract with a stand-alone context. + public static (byte[] Decoded, string[] Codes) Run(IStreamFilter filter, ReadOnlySpan encoded, string? parameters = null, PdfReadingMode mode = PdfReadingMode.Lenient) + { + var context = new FilterContext + { + Parameters = parameters is null ? null : (CosDictionary)CosObject.Parse(Encoding.Latin1.GetBytes(parameters)), + ReadingMode = mode, + }; + var output = new ArrayBufferWriter(); + filter.Decode(encoded.ToArray(), output, context); + return (output.WrittenSpan.ToArray(), [.. context.Diagnostics.Select(diagnostic => diagnostic.Code)]); + } +} diff --git a/tests/Broadside.Tests/Filters/FlateDecodeFilterTests.cs b/tests/Broadside.Tests/Filters/FlateDecodeFilterTests.cs new file mode 100644 index 00000000..8da1d7e2 --- /dev/null +++ b/tests/Broadside.Tests/Filters/FlateDecodeFilterTests.cs @@ -0,0 +1,96 @@ +using System.IO.Compression; +using Broadside.Diagnostics; +using Broadside.Filters; +using Broadside.TestSupport; + +namespace Broadside.Tests.Filters; + +/// FlateDecode through the filter contract. ISO 32000-2 §7.4.4.1; RFC 1950 and RFC 1951. +public class FlateDecodeFilterTests +{ + private static readonly byte[] Data = FilterEncoders.SampleData(100_000, alphabet: 4); + + [Fact] + public void Inflates_zlib_data() + { + (byte[] decoded, string[] codes) = FilterTesting.Run(new FlateDecodeFilter(), FilterEncoders.Zlib(Data)); + + Assert.Equal(Data, decoded); + Assert.Empty(codes); + } + + [Fact] + public void Ignores_a_wrong_checksum_and_bytes_after_the_final_block() + { + byte[] encoded = [.. FilterEncoders.Zlib(Data), 0x0D, 0x0A]; + encoded[^3] ^= 0xFF; + + (byte[] decoded, string[] codes) = FilterTesting.Run(new FlateDecodeFilter(), encoded); + + Assert.Equal(Data, decoded); + Assert.Empty(codes); + } + + [Fact] + public void A_missing_checksum_is_not_a_deviation_worth_reporting() + { + byte[] encoded = FilterEncoders.Zlib(Data)[..^4]; + + (byte[] decoded, string[] codes) = FilterTesting.Run(new FlateDecodeFilter(), encoded); + + Assert.Equal(Data, decoded); + Assert.Empty(codes); + } + + [Fact] + public void Raw_deflate_data_without_a_zlib_header_is_inflated_with_a_diagnostic() + { + var buffer = new MemoryStream(); + using (var deflate = new DeflateStream(buffer, CompressionLevel.Optimal, leaveOpen: true)) + { + deflate.Write(Data); + } + + (byte[] decoded, string[] codes) = FilterTesting.Run(new FlateDecodeFilter(), buffer.ToArray()); + + Assert.Equal(Data, decoded); + Assert.Equal(["FilterDataInvalid"], codes); + } + + [Fact] + public void Truncated_data_keeps_everything_inflated_with_a_diagnostic() + { + byte[] encoded = FilterEncoders.Zlib(Data); + + (byte[] decoded, string[] codes) = FilterTesting.Run(new FlateDecodeFilter(), encoded.AsSpan(0, encoded.Length / 2)); + + Assert.InRange(decoded.Length, 10_000, Data.Length - 1); + Assert.Equal(Data[..decoded.Length], decoded); + Assert.Equal(["FilterDataTruncated"], codes); + } + + [Fact] + public void Corrupt_data_keeps_the_bytes_inflated_before_the_error_with_a_diagnostic() + { + // zlib header 78 01; a non-final stored block of 5 bytes (RFC 1951 §3.2.4); then a final block of the reserved type 11. + byte[] encoded = [0x78, 0x01, 0x00, 0x05, 0x00, 0xFA, 0xFF, .. "hello"u8, 0x07]; + + (byte[] decoded, string[] codes) = FilterTesting.Run(new FlateDecodeFilter(), encoded); + + // zlib reports the error in the same call that produced the last byte, which the BCL then withholds: at most one is lost. + Assert.Equal("hell"u8.ToArray(), decoded[..4]); + Assert.InRange(decoded.Length, 4, 5); + Assert.Equal(["FilterDataInvalid"], codes); + } + + [Fact] + public void Strict_mode_throws_for_truncated_data() + { + byte[] encoded = FilterEncoders.Zlib(Data); + + DiagnosticException error = Assert.Throws( + () => FilterTesting.Run(new FlateDecodeFilter(), encoded.AsSpan(0, 100).ToArray(), mode: PdfReadingMode.Strict)); + + Assert.Equal("FilterDataTruncated", error.Diagnostic.Code); + } +} diff --git a/tests/Broadside.Tests/Filters/LzwDecodeFilterTests.cs b/tests/Broadside.Tests/Filters/LzwDecodeFilterTests.cs new file mode 100644 index 00000000..bb58d006 --- /dev/null +++ b/tests/Broadside.Tests/Filters/LzwDecodeFilterTests.cs @@ -0,0 +1,118 @@ +using Broadside.Diagnostics; +using Broadside.Filters; +using Broadside.TestSupport; + +namespace Broadside.Tests.Filters; + +/// LZWDecode through the filter contract. ISO 32000-2 §7.4.4.2 and §7.4.4.3 Table 8. +public class LzwDecodeFilterTests +{ + [Fact] + public void Decodes_the_packed_example_after_table_7() + { + // §7.4.4.2 Example 1 and Example 2: the codes of Table 7, 9 bits each, packed high-order bit first. + byte[] encoded = Convert.FromHexString("800B6050220C0C8501"); + + (byte[] decoded, string[] codes) = FilterTesting.Run(new LzwDecodeFilter(), encoded); + + Assert.Equal([45, 45, 45, 45, 45, 65, 45, 45, 45, 66], decoded); + Assert.Empty(codes); + } + + [Theory] + [InlineData(1, null)] + [InlineData(1, "<< /EarlyChange 1 >>")] + [InlineData(0, "<< /EarlyChange 0 >>")] + public void Round_trips_data_that_grows_the_code_length_to_12_bits_and_clears_the_table(int earlyChange, string? parameters) + { + byte[] data = FilterEncoders.SampleData(60_000); + + (byte[] decoded, string[] codes) = FilterTesting.Run(new LzwDecodeFilter(), FilterEncoders.LzwEncode(data, earlyChange), parameters); + + Assert.Equal(data, decoded); + Assert.Empty(codes); + } + + [Fact] + public void Early_change_matters_once_the_table_reaches_511_entries() + { + byte[] data = FilterEncoders.SampleData(5_000); + byte[] encodedLate = FilterEncoders.LzwEncode(data, earlyChange: 0); + + (byte[] decoded, _) = FilterTesting.Run(new LzwDecodeFilter(), encodedLate); + + Assert.NotEqual(data, decoded); + } + + [Fact] + public void Data_without_the_end_of_data_code_decodes_to_its_end_with_a_diagnostic() + { + byte[] data = FilterEncoders.SampleData(2_000); + byte[] encoded = FilterEncoders.LzwEncode(data); + byte[] truncated = encoded[..(encoded.Length / 2)]; + + (byte[] decoded, string[] codes) = FilterTesting.Run(new LzwDecodeFilter(), truncated); + + Assert.True(decoded.Length > 500); + Assert.Equal(data[..decoded.Length], decoded); + Assert.Equal(["FilterDataTruncated"], codes); + } + + [Fact] + public void A_code_not_yet_in_the_table_ends_the_data_with_a_diagnostic() + { + // Clear, 'A' (65), then code 300 while the next free entry is 258 (9-bit codes: 256, 65, 300, 257). + byte[] encoded = Pack9(256, 65, 300, 257); + + (byte[] decoded, string[] codes) = FilterTesting.Run(new LzwDecodeFilter(), encoded); + + Assert.Equal([65], decoded); + Assert.Equal(["FilterDataInvalid"], codes); + } + + [Fact] + public void An_early_change_other_than_0_or_1_is_read_as_1_with_a_diagnostic() + { + byte[] data = FilterEncoders.SampleData(3_000); + + (byte[] decoded, string[] codes) = FilterTesting.Run(new LzwDecodeFilter(), FilterEncoders.LzwEncode(data), "<< /EarlyChange 5 >>"); + + Assert.Equal(data, decoded); + Assert.Equal(["DecodeParmsInvalid"], codes); + } + + [Fact] + public void Strict_mode_throws_for_truncated_data() + { + byte[] encoded = FilterEncoders.LzwEncode(FilterEncoders.SampleData(100)); + + DiagnosticException error = Assert.Throws( + () => FilterTesting.Run(new LzwDecodeFilter(), encoded.AsSpan(0, encoded.Length - 2).ToArray(), mode: PdfReadingMode.Strict)); + + Assert.Equal("FilterDataTruncated", error.Diagnostic.Code); + } + + private static byte[] Pack9(params int[] codes) + { + var output = new List(); + int accumulator = 0; + int bits = 0; + foreach (int code in codes) + { + accumulator = (accumulator << 9) | code; + bits += 9; + while (bits >= 8) + { + output.Add((byte)(accumulator >> (bits - 8))); + bits -= 8; + } + } + + if (bits > 0) + { + output.Add((byte)(accumulator << (8 - bits))); + } + + return [.. output]; + } +} diff --git a/tests/Broadside.Tests/Filters/PredictorTests.cs b/tests/Broadside.Tests/Filters/PredictorTests.cs new file mode 100644 index 00000000..4c880d48 --- /dev/null +++ b/tests/Broadside.Tests/Filters/PredictorTests.cs @@ -0,0 +1,126 @@ +using Broadside.Diagnostics; +using Broadside.TestSupport; + +namespace Broadside.Tests.Filters; + +/// +/// The LZW and Flate predictor functions, through the document API: hand-computed vectors for TIFF Predictor 2 and each PNG +/// algorithm. ISO 32000-2 §7.4.4.3 Table 8 and §7.4.4.4 Tables 9 and 10; PNG algorithms per ISO/IEC 15948 §9. +/// +public class PredictorTests +{ + /// Two rows of three 8-bit gray samples: 10 20 30 / 15 25 40. + private static readonly byte[] Samples = [10, 20, 30, 15, 25, 40]; + + public static TheoryData PngRows => new() + { + { [0, 10, 20, 30, 0, 15, 25, 40] }, // None + { [1, 10, 10, 10, 1, 15, 10, 15] }, // Sub: minus the byte to the left + { [2, 10, 20, 30, 2, 5, 5, 10] }, // Up: minus the byte above (0 above the first row) + { [3, 10, 15, 20, 3, 10, 8, 13] }, // Average: minus floor((left + above) / 2) + { [4, 10, 10, 10, 4, 5, 5, 10] }, // Paeth: minus the closest of left, above, upper-left to left + above - upper-left + { [1, 10, 10, 10, 4, 5, 5, 10] }, // Each row carries its own tag + }; + + [Theory] + [MemberData(nameof(PngRows))] + public void Png_predicted_rows_decode_to_the_samples_whatever_predictor_10_to_15_is_declared(byte[] predicted) + { + foreach (int declared in (int[])[10, 12, 15]) + { + byte[] file = FilterTesting.FileWithStream( + $"/Filter /FlateDecode /DecodeParms << /Predictor {declared} /Columns 3 >>", + FilterEncoders.Zlib(predicted)); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); + + Assert.Equal(Samples, decoded); + Assert.Empty(codes); + } + } + + [Fact] + public void Png_sub_predicts_from_the_whole_pixel_to_the_left_when_a_pixel_is_several_bytes() + { + // Colors 2, 8 bits: the left neighbour of byte 2 is byte 0. + byte[] file = FilterTesting.FileWithStream( + "/Filter /FlateDecode /DecodeParms << /Predictor 11 /Colors 2 /Columns 2 >>", + FilterEncoders.Zlib([1, 1, 2, 2, 2])); + + (byte[] decoded, _) = FilterTesting.DecodeWithCodes(file); + + Assert.Equal([1, 2, 3, 4], decoded); + } + + public static TheoryData TiffRows => new() + { + // 8 bits, 2 colors, 3 columns: each component minus the same component of the sample to its left, modulo 256. + { "/Colors 2 /Columns 3", [10, 100, 2, 1, 3, 254], [10, 100, 12, 101, 15, 99] }, + // 16 bits, big-endian: 0100 0203 0001 differenced to 0100 0103 FDFE. + { "/BitsPerComponent 16 /Columns 3", [0x01, 0x00, 0x01, 0x03, 0xFD, 0xFE], [0x01, 0x00, 0x02, 0x03, 0x00, 0x01] }, + // 1 bit, 8 columns: 1 1 0 0 1 0 1 1 differenced (XOR with the left bit) to 1 0 1 0 1 1 1 0. + { "/BitsPerComponent 1 /Columns 8", [0xAE], [0xCB] }, + // 2 bits, 4 columns: 3 1 2 0 differenced modulo 4 to 3 2 1 2; two rows, each predicted on its own. + { "/BitsPerComponent 2 /Columns 4", [0xE6, 0xE6], [0xD8, 0xD8] }, + // 4 bits, 3 columns: 15 1 8 differenced modulo 16 to 15 2 7; the padding nibble is left alone. + { "/BitsPerComponent 4 /Columns 3", [0xF2, 0x75], [0xF1, 0x85] }, + }; + + [Theory] + [MemberData(nameof(TiffRows))] + public void Tiff_predictor_2_adds_each_component_to_the_same_component_to_its_left(string parameters, byte[] predicted, byte[] expected) + { + byte[] file = FilterTesting.FileWithStream( + $"/Filter /FlateDecode /DecodeParms << /Predictor 2 {parameters} >>", + FilterEncoders.Zlib(predicted)); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); + + Assert.Equal(expected, decoded); + Assert.Empty(codes); + } + + [Fact] + public void Predictors_apply_after_lzw_too() + { + byte[] file = FilterTesting.FileWithStream( + "/Filter /LZWDecode /DecodeParms << /Predictor 12 /Columns 3 /EarlyChange 0 >>", + FilterEncoders.LzwEncode([2, 10, 20, 30, 2, 5, 5, 10], earlyChange: 0)); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); + + Assert.Equal(Samples, decoded); + Assert.Empty(codes); + } + + public static TheoryData MalformedPredictions => new() + { + { "/Predictor 7 /Columns 3", [2, 10, 20, 30], [2, 10, 20, 30], "PredictorInvalid" }, + { "/Predictor 12 /Columns 3", [9, 10, 20, 30], [10, 20, 30], "PredictorInvalid" }, + { "/Predictor 12 /Columns 3", [2, 10, 20, 30, 0, 5], [10, 20, 30, 5, 0, 0], "PredictorInvalid" }, + { "/Predictor 12 /Columns 0", [2, 10, 2, 5], [10, 15], "DecodeParmsInvalid" }, + { "/Predictor 12 /Columns 1 /BitsPerComponent 3", [2, 10, 2, 5], [10, 15], "DecodeParmsInvalid" }, + }; + + [Theory] + [MemberData(nameof(MalformedPredictions))] + public void Malformed_predictor_data_or_parameters_are_repaired_with_a_diagnostic(string parameters, byte[] predicted, byte[] expected, string code) + { + byte[] file = FilterTesting.FileWithStream($"/Filter /FlateDecode /DecodeParms << {parameters} >>", FilterEncoders.Zlib(predicted)); + + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); + + Assert.Equal(expected, decoded); + Assert.Equal([code], codes); + } + + [Fact] + public void Strict_mode_throws_for_an_unknown_predictor() + { + byte[] file = FilterTesting.FileWithStream("/Filter /FlateDecode /DecodeParms << /Predictor 3 >>", FilterEncoders.Zlib([1, 2, 3])); + + DiagnosticException error = Assert.Throws(() => FilterTesting.Decode(file, new PdfOptions().UseStrict())); + + Assert.Equal("PredictorInvalid", error.Diagnostic.Code); + } +} diff --git a/tests/Broadside.Tests/Filters/RunLengthDecodeFilterTests.cs b/tests/Broadside.Tests/Filters/RunLengthDecodeFilterTests.cs new file mode 100644 index 00000000..a14609d9 --- /dev/null +++ b/tests/Broadside.Tests/Filters/RunLengthDecodeFilterTests.cs @@ -0,0 +1,65 @@ +using System.Text; +using Broadside.Diagnostics; +using Broadside.Filters; +using Broadside.TestSupport; + +namespace Broadside.Tests.Filters; + +/// RunLengthDecode through the filter contract. ISO 32000-2 §7.4.5. +public class RunLengthDecodeFilterTests +{ + public static TheoryData WellFormed => new() + { + { [0xFD, (byte)'a', 0x00, (byte)'b', 0x80], "aaaab" }, + { [0x02, (byte)'x', (byte)'y', (byte)'z', 0x81, (byte)'-', 0x80], "xyz" + new string('-', 128) }, + { [0x80], string.Empty }, + { [0x00, (byte)'q', 0x80, 0x00, (byte)'r'], "q" }, + }; + + [Theory] + [MemberData(nameof(WellFormed))] + public void Decodes_literal_and_repeated_runs_up_to_the_end_of_data_byte(byte[] encoded, string expected) + { + (byte[] decoded, string[] codes) = FilterTesting.Run(new RunLengthDecodeFilter(), encoded); + + Assert.Equal(expected, Encoding.Latin1.GetString(decoded)); + Assert.Empty(codes); + } + + [Fact] + public void Round_trips_the_encoder_of_the_corpus_generator() + { + byte[] data = [.. FilterEncoders.SampleData(5_000, alphabet: 3), .. new byte[300], .. FilterEncoders.SampleData(5_000, alphabet: 250)]; + + (byte[] decoded, string[] codes) = FilterTesting.Run(new RunLengthDecodeFilter(), FilterEncoders.RunLengthEncode(data)); + + Assert.Equal(data, decoded); + Assert.Empty(codes); + } + + public static TheoryData EndingEarly => new() + { + { [0x00, (byte)'a'], "a" }, + { [0x03, (byte)'a', (byte)'b'], "ab" }, + { [0x00, (byte)'a', 0xFE], "a" }, + }; + + [Theory] + [MemberData(nameof(EndingEarly))] + public void Data_that_ends_early_keeps_what_is_available_with_a_diagnostic(byte[] encoded, string expected) + { + (byte[] decoded, string[] codes) = FilterTesting.Run(new RunLengthDecodeFilter(), encoded); + + Assert.Equal(expected, Encoding.Latin1.GetString(decoded)); + Assert.Equal(["FilterDataTruncated"], codes); + } + + [Fact] + public void Strict_mode_throws_when_the_end_of_data_byte_is_missing() + { + DiagnosticException error = Assert.Throws( + () => FilterTesting.Run(new RunLengthDecodeFilter(), [0x00, (byte)'a'], mode: PdfReadingMode.Strict)); + + Assert.Equal("FilterDataTruncated", error.Diagnostic.Code); + } +} From 2fdfb3338ca914fdf271ac7718f55f316c473312 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:07:49 -0500 Subject: [PATCH 008/152] feat(cos): cross-reference streams, object streams and hybrid files (#39) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Files that use the PDF 1.5 compressed structures now open and read like classic files (ISO 32000-2 §7.5.7, §7.5.8). - XrefStreamReader reads a cross-reference stream section: W (0 to 8 bytes per field, W[0] = 0 means type 1), Index (default [0 Size]), Size, big-endian fields, type 0/1/2 entries, other types as the null object. Data is decoded through the filter pipeline, which PdfDocument.Read now builds before the cross-reference information; the stream is never decrypted. The trailer is the stream dictionary without its stream-only keys. - Hybrid files: a table's XRefStm stream is inserted right after the table in CrossReference.Sections (XRefStreamOffset set to its absolute offset), so lookup is table, then XRefStm, then Prev; the stream's own Prev is not followed and its dictionary is not a trailer. Stream sections end past endobj, so revisions still find each %%EOF. - ObjectLoader.LoadCompressed loads type 2 entries: the container is an ordinary object (hooks included, so decrypted as a whole), decoded once per document into an ObjectStream; each member is parsed over exactly the bytes up to the next offset; wrong indexes, unordered offsets, nested containers and self-referencing containers are repaired or end with a diagnostic. - New corpus file linearized-xref-stream.pdf (qpdf --object-streams=generate). - Removes every "Needs cross-reference streams (#39)" skip and the not-readable-yet boundary test. - Fuzz targets xref-stream and object-stream; DocumentOpenBenchmarks covers the compressed-structure files. Conformance rows 7.5.7 and 7.5.8 done. Co-Authored-By: Claude Opus 5.5 --- .../DocumentOpenBenchmarks.cs | 8 +- docs/conformance/iso-32000-2.md | 10 +- src/Broadside/Parsing/CrossReference.cs | 26 +- src/Broadside/Parsing/CrossReferenceReader.cs | 112 +++++- src/Broadside/Parsing/DiagnosticCodes.cs | 19 +- src/Broadside/Parsing/ObjectLoader.cs | 117 +++++- src/Broadside/Parsing/ObjectLoaderHooks.cs | 10 +- src/Broadside/Parsing/ObjectStream.cs | 210 +++++++++++ src/Broadside/Parsing/XrefStreamReader.cs | 345 ++++++++++++++++++ src/Broadside/PdfDocument.cs | 14 +- tests/Broadside.Fuzz/FuzzTargets.cs | 68 ++++ tests/Broadside.Fuzz/README.md | 10 +- tests/Broadside.TestSupport/Corpus.cs | 1 + .../Document/CrossReferenceStreamTests.cs | 207 +++++++++++ tests/Broadside.Tests/Document/EngineTests.cs | 4 - .../Document/HybridFileTests.cs | 107 ++++++ .../Document/LinearizationTests.cs | 20 + .../Document/ObjectStreamTests.cs | 214 +++++++++++ .../Document/WellFormedCorpusTests.cs | 22 +- .../Broadside.Tests/Document/XrefStreamPdf.cs | 117 ++++++ .../Filters/CorpusFilterTests.cs | 1 - .../Hosting/DependencyInjectionTests.cs | 1 - ...pus_file_names_match_snapshot.verified.txt | 1 + tests/Corpus/README.md | 9 +- tests/Corpus/linearized-xref-stream.pdf | Bin 0 -> 1661 bytes 25 files changed, 1575 insertions(+), 78 deletions(-) create mode 100644 src/Broadside/Parsing/ObjectStream.cs create mode 100644 src/Broadside/Parsing/XrefStreamReader.cs create mode 100644 tests/Broadside.Tests/Document/CrossReferenceStreamTests.cs create mode 100644 tests/Broadside.Tests/Document/HybridFileTests.cs create mode 100644 tests/Broadside.Tests/Document/ObjectStreamTests.cs create mode 100644 tests/Broadside.Tests/Document/XrefStreamPdf.cs create mode 100644 tests/Corpus/linearized-xref-stream.pdf diff --git a/bench/Broadside.Benchmarks/DocumentOpenBenchmarks.cs b/bench/Broadside.Benchmarks/DocumentOpenBenchmarks.cs index ad6f6d34..f54d09ec 100644 --- a/bench/Broadside.Benchmarks/DocumentOpenBenchmarks.cs +++ b/bench/Broadside.Benchmarks/DocumentOpenBenchmarks.cs @@ -13,8 +13,12 @@ public class DocumentOpenBenchmarks { private byte[] _bytes = []; - /// The corpus file to open: one page, a two-level page tree with inheritance, an updated file and a linearized file. - [Params("empty-page.pdf", "page-tree-inherited.pdf", "incremental-update.pdf", "linearized.pdf")] + /// + /// The corpus file to open: one page, a two-level page tree with inheritance, an updated file, a linearized file, and the + /// compressed structures of §7.5.7 and §7.5.8 (a cross-reference stream, an object stream, a Flate and PNG-predicted + /// cross-reference stream, a hybrid file). + /// + [Params("empty-page.pdf", "page-tree-inherited.pdf", "incremental-update.pdf", "linearized.pdf", "xref-stream.pdf", "object-stream.pdf", "png-predictor.pdf", "hybrid-xref.pdf")] public string File { get; set; } = ""; [GlobalSetup] diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index 2da5fec4..fb3f59f9 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -31,12 +31,12 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.4.10 | Crypt filter | partial | `StreamDecoder`, `ICryptFilterHandler` | `Broadside.Tests.Filters.FilterPipelineTests.The_identity_crypt_filter_passes_the_data_through`, `Broadside.Tests.Filters.FilterPipelineTests.A_crypt_filter_the_security_handler_does_not_know_leaves_the_data_encrypted_with_a_diagnostic`, `Broadside.Tests.Filters.FilterPipelineTests.A_crypt_filter_that_is_not_first_is_applied_where_it_is_with_a_diagnostic` | Slot only: Identity passes through, other crypt filter names are `CryptFilterUnsupported` until the security handler (#42) sets `StreamDecoder.CryptFilter` | | 7.5.1 | General | done | `PdfDocument`, `CrossReferenceReader` | `Broadside.Tests.Document.OpenDocumentTests.A_file_opens_identically_from_a_path_a_stream_and_bytes_with_no_diagnostics`, `Broadside.Tests.Document.WellFormedCorpusTests.A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics` | Read from the end through startxref, the cross-reference table and the trailer, never serially; linearized files read through the same path (Annex F) | | 7.5.2 | File header | done | `FileHeader`, `PdfVersion`, `PdfDocument` | `Broadside.Tests.Document.FileStructureTests.Offsets_count_from_the_header_so_bytes_before_it_do_not_matter`, `Broadside.Tests.Document.FileStructureTests.A_file_without_a_header_opens_from_byte_0_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_header_without_a_valid_version_takes_the_catalog_version_with_a_diagnostic` | Header searched in the first 1024 bytes; every stated offset is relative to it; missing header: offsets from byte 0, version 1.4 unless the catalog says otherwise; the unshifted-offset retry is #41 | -| 7.5.3 | File body | done | `ObjectLoader` | `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length` | Objects load lazily by cross-reference entry; object streams are #39 | +| 7.5.3 | File body | done | `ObjectLoader` | `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length` | Objects load lazily by cross-reference entry, from the file body or an object stream (7.5.7) | | 7.5.4 | Cross-reference table | partial | `XrefTableReader`, `CrossReference` | `Broadside.Tests.Document.FileStructureTests.Entries_are_read_as_tokens_not_fixed_width_records`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_reads_as_null_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation` | Subsections and n/f entries read as tokens; offset-0 in-use entries read as free; reconstruction by scanning when the table is wrong, and diagnostics for non-20-byte entries and comments, are #41 | | 7.5.5 | File trailer | partial | `CrossReferenceReader`, `CrossReference`, `PdfDocument` | `Broadside.Tests.Document.FileStructureTests.A_startxref_offset_on_the_white_space_before_xref_is_repaired_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_file_with_no_startxref_cannot_be_read_even_leniently`, `Broadside.Tests.Document.FileStructureTests.A_trailer_without_root_cannot_be_read`, `Broadside.Tests.Document.FileStructureTests.A_prev_chain_that_loops_ends_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic` | Last startxref, Prev chain with loop guard, Root; trailer merged newest-first; ignoring entries beyond Size, startxref recovery and trailer reconstruction are #41; Encrypt is #42 | -| 7.5.6 | Incremental updates | done | `CrossReference`, `RevisionReader`, `PdfRevision`, `PdfDocument` | `Broadside.Tests.Document.IncrementalUpdateTests.An_updated_file_has_one_revision_per_update_and_the_first_is_the_original_file`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_is_the_file_as_it_was_after_that_save`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_has_its_own_trailer`, `Broadside.Tests.Document.IncrementalUpdateTests.A_hybrid_file_has_its_main_section_and_its_update_section_as_two_revisions`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_earlier_revision_without_its_end_of_file_marker_ends_after_its_startxref_offset_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev` | Revisions oldest first, each the byte prefix up to its %%EOF and end-of-line; newest section decides per object number, free hides older copies, a reference must match the live generation; Root, Info, Encrypt and ID missing from the newest trailer are taken from an older one with TrailerEntryFromOlderRevision; a linearized pair is one revision; a hybrid XRefStm joins its table's revision (#39 re-verifies); writing updates is #44 | -| 7.5.7 | Object streams | not started | | | #39 | -| 7.5.8 | Cross-reference streams | not started | | | #39; files with only a cross-reference stream fail to open with XrefStreamUnsupported until then | +| 7.5.6 | Incremental updates | done | `CrossReference`, `RevisionReader`, `PdfRevision`, `PdfDocument` | `Broadside.Tests.Document.IncrementalUpdateTests.An_updated_file_has_one_revision_per_update_and_the_first_is_the_original_file`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_is_the_file_as_it_was_after_that_save`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_has_its_own_trailer`, `Broadside.Tests.Document.IncrementalUpdateTests.A_hybrid_file_has_its_main_section_and_its_update_section_as_two_revisions`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_earlier_revision_without_its_end_of_file_marker_ends_after_its_startxref_offset_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev` | Revisions oldest first, each the byte prefix up to its %%EOF and end-of-line; newest section decides per object number, free hides older copies, a reference must match the live generation; Root, Info, Encrypt and ID missing from the newest trailer are taken from an older one with TrailerEntryFromOlderRevision; a linearized pair is one revision; a hybrid XRefStm stream joins its table's revision; writing updates is #44 | +| 7.5.7 | Object streams | done | `ObjectStream`, `ObjectLoader` | `Broadside.Tests.Document.ObjectStreamTests.The_catalog_page_tree_and_page_resolve_from_an_object_stream`, `Broadside.Tests.Document.ObjectStreamTests.A_reference_to_a_member_with_a_generation_other_than_0_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.Members_need_no_white_space_between_them`, `Broadside.Tests.Document.ObjectStreamTests.A_member_at_another_index_than_its_entry_says_is_found_by_its_object_number`, `Broadside.Tests.Document.ObjectStreamTests.Offsets_out_of_order_bound_each_member_by_the_next_offset_in_sorted_order`, `Broadside.Tests.Document.ObjectStreamTests.A_member_the_object_stream_does_not_hold_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_whose_N_is_one_of_its_own_members_resolves_its_members_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_listed_as_compressed_itself_is_not_read`, `Broadside.Tests.Document.ObjectStreamTests.A_type_2_entry_naming_an_object_that_is_not_a_stream_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.A_flate_encoded_object_stream_is_decoded_through_the_filters`, `Broadside.Tests.Document.ObjectStreamTests.Members_of_one_object_stream_resolve_to_the_same_instances_from_concurrent_threads`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file` | Members located by type 2 entries (index checked against the header, searched by number when wrong, with ObjectStreamIndexMismatch); each member parsed over exactly the bytes up to the next offset (NOTE 7); out-of-order offsets sorted; container decoded once per document and shared, decrypted as a whole (members skip hooks 1 and 2); nested containers and self-referencing N/First/Filter end with ObjectStreamNested/ObjectStreamCycle; /Extends ignored (grouping only); object-stream.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `object-stream`; writing is #44 | +| 7.5.8 | Cross-reference streams | done | `XrefStreamReader`, `CrossReferenceReader`, `CrossReference` | `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file`, `Broadside.Tests.Document.CrossReferenceStreamTests.Strict_mode_opens_a_file_with_compressed_structures`, `Broadside.Tests.Document.CrossReferenceStreamTests.The_trailer_of_a_cross_reference_stream_is_its_dictionary_without_the_entries_that_describe_the_stream`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_type_field_makes_every_entry_type_1`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_generation_field_defaults_to_generation_0`, `Broadside.Tests.Document.CrossReferenceStreamTests.Index_with_two_subsections_numbers_the_entries_of_each_from_its_first_object_number`, `Broadside.Tests.Document.CrossReferenceStreamTests.Wide_fields_are_read_big_endian`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_entry_of_an_unknown_type_is_a_reference_to_the_null_object`, `Broadside.Tests.Document.CrossReferenceStreamTests.Data_shorter_than_the_entries_ends_the_section_where_the_data_ends`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_without_type_XRef_is_read_with_a_diagnostic`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_whose_W_cannot_be_read_is_not_a_cross_reference_section`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_update_written_as_a_cross_reference_stream_overrides_the_original_section`, `Broadside.Tests.Document.HybridFileTests.An_object_only_the_XRefStm_stream_lists_is_found`, `Broadside.Tests.Document.HybridFileTests.The_table_of_a_section_takes_precedence_over_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.The_XRefStm_streams_dictionary_is_not_the_trailer_and_its_Prev_is_not_followed`, `Broadside.Tests.Document.HybridFileTests.An_XRefStm_offset_that_names_no_stream_is_reported_and_the_table_is_still_read`, `Broadside.Tests.Document.LinearizationTests.A_linearized_file_with_cross_reference_streams_has_its_first_page_and_main_streams_as_one_revision` | 7.5.8.1 to 7.5.8.4. W (0 to 8 bytes per field, W[0] = 0 means type 1), Index (default [0 Size]), Size, Prev; entries big-endian into long; type 0/1/2, other types are the null object; dictionary minus Type, Length, W, Index, Filter, DecodeParms, DL, F, FFilter, FDecodeParms is the trailer; data decoded through the filter pipeline under the engine's decoded-length limit, never decrypted; hybrid XRefStm read after its table and before Prev, its own Prev not followed and its dictionary not a trailer; xref-stream.pdf, object-stream.pdf, png-predictor.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `xref-stream`; writing is #44 | | 7.6 | Encryption | not started | | | | | 7.7.1 | General | n/a | | | Introductory text | | 7.7.2 | Document catalog dictionary | partial | `PdfDocument`, `PdfVersion` | `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_catalog_version_written_as_a_number_is_read_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.A_malformed_catalog_version_is_ignored_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_catalog_without_its_type_is_read_with_a_diagnostic` | Type, Version (effective version = later of header and catalog) and Pages; the other Table 29 entries arrive with their features (outlines, names, AcroForm, ...) | @@ -133,7 +133,7 @@ Clause numbers at the second level; split rows to the third level as clauses are | Annex E | Extending PDF | not started | | | | | F.1 | General | n/a | | | Introductory text | | F.2 | Background and assumptions | n/a | | | Informative background | -| F.3 | Linearized PDF document structure | partial | `LinearizationReader`, `PdfLinearization`, `CrossReference`, `PdfDocument` | `Broadside.Tests.Document.LinearizationTests.A_linearized_file_is_detected_and_exposes_its_parameter_dictionary`, `Broadside.Tests.Document.LinearizationTests.The_first_page_objects_are_those_in_the_first_page_cross_reference_section`, `Broadside.Tests.Document.LinearizationTests.A_linearized_file_is_one_revision`, `Broadside.Tests.Document.LinearizationTests.A_file_that_is_not_linearized_reports_false`, `Broadside.Tests.Document.LinearizationTests.An_update_appended_to_a_linearized_file_makes_it_an_ordinary_two_revision_file`, `Broadside.Tests.Document.LinearizationTests.A_malformed_linearization_dictionary_is_ignored_with_a_diagnostic` | Reading: detection by the first object in the first 1024 bytes, Table F.1 validation, L against the file length (G.7), first-page objects from the first-page section, first-page and main sections as one revision; part ordering is not validated and writing linearized files is not started; linearized.pdf (qpdf) | +| F.3 | Linearized PDF document structure | partial | `LinearizationReader`, `PdfLinearization`, `CrossReference`, `PdfDocument` | `Broadside.Tests.Document.LinearizationTests.A_linearized_file_is_detected_and_exposes_its_parameter_dictionary`, `Broadside.Tests.Document.LinearizationTests.The_first_page_objects_are_those_in_the_first_page_cross_reference_section`, `Broadside.Tests.Document.LinearizationTests.A_linearized_file_is_one_revision`, `Broadside.Tests.Document.LinearizationTests.A_linearized_file_with_cross_reference_streams_has_its_first_page_and_main_streams_as_one_revision`, `Broadside.Tests.Document.LinearizationTests.A_file_that_is_not_linearized_reports_false`, `Broadside.Tests.Document.LinearizationTests.An_update_appended_to_a_linearized_file_makes_it_an_ordinary_two_revision_file`, `Broadside.Tests.Document.LinearizationTests.A_malformed_linearization_dictionary_is_ignored_with_a_diagnostic` | Reading: detection by the first object in the first 1024 bytes, Table F.1 validation, L against the file length (G.7), first-page objects from the first-page section, first-page and main sections as one revision, tables or cross-reference streams; part ordering is not validated and writing linearized files is not started; linearized.pdf, linearized-xref-stream.pdf (qpdf) | | F.4.1 | General | done | `HintTableReader`, `HintBitReader`, `PdfLinearizationHints` | `Broadside.Tests.Document.LinearizationTests.The_page_offset_hint_table_locates_each_page`, `Broadside.Tests.Document.LinearizationTests.Hint_offsets_count_from_byte_0_of_the_file_when_bytes_precede_the_header`, `Broadside.Tests.Document.LinearizationTests.A_malformed_hint_table_leaves_the_file_linearized_without_hints_and_with_a_diagnostic` | MSB-first bit stream, each item column byte-aligned (qpdf, Acrobat); positions at or after H[0] moved by H[1]; overflow stream appended; a filtered hint stream yields no hints until #38 decodes it | | F.4.2 | Page offset hint table | partial | `HintTableReader`, `PdfPageHint` | `Broadside.Tests.Document.LinearizationTests.The_page_offset_hint_table_locates_each_page` | Items 1 to 4 per page; item 5 (numerators) and items 6 and 7 (content stream offset and length, Acrobat placeholders) are not exposed | | F.4.3 | Shared object hint table | done | `HintTableReader`, `PdfSharedObjectHint` | `Broadside.Tests.Document.LinearizationTests.The_shared_object_hint_table_locates_each_group` | MD5 signatures skipped; Table F.6 item 1 cites Table F.3 item 4 for the first page location, read as item 2 (qpdf) | diff --git a/src/Broadside/Parsing/CrossReference.cs b/src/Broadside/Parsing/CrossReference.cs index fd7440ac..c1cbca9f 100644 --- a/src/Broadside/Parsing/CrossReference.cs +++ b/src/Broadside/Parsing/CrossReference.cs @@ -12,7 +12,7 @@ internal enum XrefEntryKind : byte /// An object stored in the file body at a byte offset. InUse, - /// An object stored inside an object stream (§7.5.7). Read by issue #39. + /// An object stored inside an object stream (§7.5.7), type 2 in a cross-reference stream (§7.5.8.3, Table 18). Compressed, } @@ -39,21 +39,33 @@ internal enum XrefSectionKind : byte /// A classic xref table followed by trailer. Table, - /// A cross-reference stream (issue #39). + /// A cross-reference stream (§7.5.8). Stream, } /// One cross-reference section as read from the file: its entries and its trailer. /// ISO 32000-2 §7.5.4 and §7.5.5. Kept per section, never only merged, for incremental updates (#40) and repair (#41). /// The absolute byte offset of the section (the xref keyword, or the stream object). -/// The absolute byte offset just past the section's trailer dictionary. +/// +/// The absolute byte offset just past the section's trailer dictionary; for a stream, just past the stream object's endobj. +/// /// Table or stream. /// The entries, by object number. Object number 0 is never present. -/// The section's trailer dictionary (for a stream, the stream dictionary). +/// +/// The section's trailer dictionary. For a cross-reference stream, its dictionary without the entries that describe the stream +/// itself (Type, Length, W, Index, Filter, DecodeParms, DL, F, FFilter, FDecodeParms); for the stream a hybrid file's table names +/// through XRefStm, an empty dictionary, since the table's trailer is the trailer (§7.5.8.4). +/// internal sealed record XrefSection(long Offset, long End, XrefSectionKind Kind, IReadOnlyDictionary Entries, CosDictionary Trailer) { - /// Gets the offset of the hybrid-file cross-reference stream this table's trailer names (§7.5.8.4), when issue #39 follows it. + /// + /// Gets the absolute offset of the cross-reference stream this table's trailer names through XRefStm (§7.5.8.4), when it + /// was read; that stream is the next section in . + /// public long? XRefStreamOffset { get; init; } + + /// Gets the cross-reference stream object of a section, as parsed. + public CosStream? Stream { get; init; } } /// @@ -108,8 +120,8 @@ public CrossReference(IReadOnlyList sections) /// /// Each update appends one revision. A revision usually has one section; it has more when the file is linearized (the /// first-page section and the main section, F.3.4, form the original revision: the first-page section's Prev points - /// forward, to a higher offset, which an appended update never does) or, with issue #39, when a hybrid file's table names a - /// cross-reference stream through XRefStm (§7.5.8.4: the stream belongs to its table's revision). + /// forward, to a higher offset, which an appended update never does) or when a hybrid file's table names a cross-reference + /// stream through XRefStm (§7.5.8.4: the stream belongs to its table's revision). /// /// public IReadOnlyList Revisions { get; } diff --git a/src/Broadside/Parsing/CrossReferenceReader.cs b/src/Broadside/Parsing/CrossReferenceReader.cs index 25efda67..5550d247 100644 --- a/src/Broadside/Parsing/CrossReferenceReader.cs +++ b/src/Broadside/Parsing/CrossReferenceReader.cs @@ -1,4 +1,5 @@ using Broadside.Diagnostics; +using Broadside.Filters; using Broadside.IO; using Broadside.Objects; @@ -10,13 +11,18 @@ namespace Broadside.Parsing; /// /// /// -/// ISO 32000-2 §7.5.4, §7.5.5 and §7.5.6. Every offset the file states is relative to the %PDF- header (§7.5.2). The -/// Prev chain is guarded by a set of visited offsets, so a loop ends the chain with a diagnostic instead of hanging. +/// ISO 32000-2 §7.5.4, §7.5.5, §7.5.6 and §7.5.8. Every offset the file states is relative to the %PDF- header (§7.5.2). A +/// section is a classic table or a cross-reference stream (). The Prev chain is guarded by a +/// set of visited offsets, so a loop ends the chain with a diagnostic instead of hanging. /// /// -/// Extension: issue #39 reads cross-reference streams in and follows a hybrid file's -/// XRefStm before Prev; issue #41 locates startxref when it is wrong and reconstructs the table when nothing -/// here can be read ( returns ). +/// Hybrid files (§7.5.8.4): a table whose trailer has XRefStm is followed, in , by the +/// cross-reference stream it names, so lookup consults the table, then that stream, then the older sections. The stream's own +/// Prev is not followed ("not meaningful in hybrid-reference files", Table 17) and its dictionary is not a trailer. +/// +/// +/// Extension: issue #41 locates startxref when it is wrong and reconstructs the table when nothing here can be read +/// ( returns ). /// /// internal static class CrossReferenceReader @@ -24,12 +30,15 @@ internal static class CrossReferenceReader /// How many bytes the backward search for startxref reads at a time. private const int TailWindow = 1024; + private static readonly CosName XRefStm = new("XRefStm"); + /// Reads the cross-reference sections of . /// The file. /// The header, whose offset every stated offset is relative to. + /// The filter pipeline cross-reference streams are decoded with. /// Where to report deviations. /// The cross-reference information, or when no section could be read. - public static CrossReference? Read(PdfSource source, FileHeader header, DiagnosticSink diagnostics) + public static CrossReference? Read(PdfSource source, FileHeader header, StreamDecoder streams, DiagnosticSink diagnostics) { if (!TryReadStartxref(source, header, diagnostics, out long first)) { @@ -51,13 +60,25 @@ internal static class CrossReferenceReader break; } - XrefSection? section = ReadSection(source, offset, isFirst: sections.Count == 0, diagnostics); + XrefSection? section = ReadSection(source, offset, isFirst: sections.Count == 0, streams, diagnostics); if (section is null) { break; } - sections.Add(section); + XrefSection? hybridStream = section.Kind == XrefSectionKind.Table + ? ReadHybridStream(source, header, section, visited, streams, diagnostics) + : null; + if (hybridStream is not null) + { + sections.Add(section with { XRefStreamOffset = hybridStream.Offset }); + sections.Add(hybridStream); + } + else + { + sections.Add(section); + } + next = PreviousSectionOffset(section, header, diagnostics); } @@ -128,7 +149,7 @@ private static bool TryReadStartxref(PdfSource source, FileHeader header, Diagno } /// Reads the section at : a table when it starts with xref, else a stream. - private static XrefSection? ReadSection(PdfSource source, long offset, bool isFirst, DiagnosticSink diagnostics) + private static XrefSection? ReadSection(PdfSource source, long offset, bool isFirst, StreamDecoder streams, DiagnosticSink diagnostics) { ReadOnlySpan window = source.GetWindow(offset).Span; var lexer = new CosLexer(window); @@ -148,7 +169,7 @@ private static bool TryReadStartxref(PdfSource source, FileHeader header, Diagno window = window[first.Start..]; } - return isTable ? XrefTableReader.Read(window, offset, diagnostics) : ReadStreamSection(source, offset, diagnostics); + return isTable ? XrefTableReader.Read(window, offset, diagnostics) : XrefStreamReader.Read(source, offset, streams, diagnostics); } diagnostics.Report( @@ -161,16 +182,69 @@ private static bool TryReadStartxref(PdfSource source, FileHeader header, Diagno return null; } - /// Reads a cross-reference stream section (§7.5.8). Issue #39. - private static XrefSection? ReadStreamSection(PdfSource source, long offset, DiagnosticSink diagnostics) + /// + /// Reads the cross-reference stream a hybrid file's table names through its trailer's XRefStm entry (§7.5.8.4, Table 19). + /// + /// The stream section, whose trailer is empty, or when there is none or it cannot be read. + private static XrefSection? ReadHybridStream( + PdfSource source, + FileHeader header, + XrefSection table, + HashSet visited, + StreamDecoder streams, + DiagnosticSink diagnostics) { - _ = source; - diagnostics.Report( - DiagnosticCodes.XrefStreamUnsupported, - DiagnosticSeverity.Error, - "The cross-reference section is a cross-reference stream, which this version cannot read yet.", - offset); - return null; + if (!table.Trailer.TryGetValue(XRefStm, out CosObject? entry)) + { + return null; + } + + if (entry is not CosInteger { Value: >= 0 } stated || stated.Value > long.MaxValue - header.Offset) + { + diagnostics.Report( + DiagnosticCodes.TrailerXRefStmInvalid, + DiagnosticSeverity.Error, + "The trailer's XRefStm entry is not a direct, non-negative integer; the cross-reference stream it names is not read.", + table.Offset); + return null; + } + + long offset = header.Offset + stated.Value; + if (!visited.Add(offset)) + { + diagnostics.Report( + DiagnosticCodes.XrefPrevLoop, + DiagnosticSeverity.Error, + "The trailer's XRefStm entry names a cross-reference section already read; it is not read again.", + offset); + return null; + } + + ReadOnlySpan window = source.GetWindow(offset).Span; + CosToken first = new CosLexer(window).Next(); + if (first.Kind != CosTokenKind.Integer) + { + diagnostics.Report( + DiagnosticCodes.TrailerXRefStmInvalid, + DiagnosticSeverity.Error, + "The trailer's XRefStm offset does not point at a cross-reference stream; it is not read.", + offset); + return null; + } + + if (first.Start != 0) + { + diagnostics.Report( + DiagnosticCodes.TrailerXRefStmInvalid, + DiagnosticSeverity.Warning, + "The XRefStm offset points before the cross-reference stream rather than at it.", + offset); + offset += first.Start; + } + + return XrefStreamReader.Read(source, offset, streams, diagnostics) is { } section + ? section with { Trailer = new CosDictionary() } + : null; } /// Returns the absolute offset of the section before , from its trailer's Prev entry. diff --git a/src/Broadside/Parsing/DiagnosticCodes.cs b/src/Broadside/Parsing/DiagnosticCodes.cs index 672972dc..bd32f737 100644 --- a/src/Broadside/Parsing/DiagnosticCodes.cs +++ b/src/Broadside/Parsing/DiagnosticCodes.cs @@ -24,7 +24,24 @@ internal static class DiagnosticCodes public const string XrefSectionInvalid = nameof(XrefSectionInvalid); public const string XrefEntryInvalid = nameof(XrefEntryInvalid); public const string XrefPrevLoop = nameof(XrefPrevLoop); - public const string XrefStreamUnsupported = nameof(XrefStreamUnsupported); + + // Cross-reference streams and hybrid files (§7.5.8). + public const string XrefStreamTypeInvalid = nameof(XrefStreamTypeInvalid); + public const string XrefStreamWidthsInvalid = nameof(XrefStreamWidthsInvalid); + public const string XrefStreamIndexInvalid = nameof(XrefStreamIndexInvalid); + public const string XrefStreamSizeInvalid = nameof(XrefStreamSizeInvalid); + public const string XrefStreamDataTruncated = nameof(XrefStreamDataTruncated); + public const string TrailerXRefStmInvalid = nameof(TrailerXRefStmInvalid); + + // Object streams (§7.5.7). + public const string ObjectStreamInvalid = nameof(ObjectStreamInvalid); + public const string ObjectStreamTypeInvalid = nameof(ObjectStreamTypeInvalid); + public const string ObjectStreamHeaderInvalid = nameof(ObjectStreamHeaderInvalid); + public const string ObjectStreamIndexMismatch = nameof(ObjectStreamIndexMismatch); + public const string ObjectStreamMemberMissing = nameof(ObjectStreamMemberMissing); + public const string ObjectStreamMemberInvalid = nameof(ObjectStreamMemberInvalid); + public const string ObjectStreamNested = nameof(ObjectStreamNested); + public const string ObjectStreamCycle = nameof(ObjectStreamCycle); // Incremental updates (§7.5.6). public const string TrailerEntryFromOlderRevision = nameof(TrailerEntryFromOlderRevision); diff --git a/src/Broadside/Parsing/ObjectLoader.cs b/src/Broadside/Parsing/ObjectLoader.cs index 8dbec034..1fd3f24b 100644 --- a/src/Broadside/Parsing/ObjectLoader.cs +++ b/src/Broadside/Parsing/ObjectLoader.cs @@ -1,5 +1,7 @@ +using System.Collections.Concurrent; using System.Globalization; using Broadside.Diagnostics; +using Broadside.Filters; using Broadside.IO; using Broadside.Objects; @@ -16,8 +18,15 @@ namespace Broadside.Parsing; /// /// /// Order for every object (see ): cache lookup; locate; parse, with hook 1 resolving stream extents; -/// hook 2 decryption; hook 3 cache publication. Issue #39 adds entries in -/// ; issue #41 adds recovery when the header at an offset does not match in . +/// hook 2 decryption; hook 3 cache publication. Issue #41 adds recovery when the header at an offset does not match in +/// . +/// +/// +/// An object stored in an object stream (§7.5.7, a entry) is parsed from its container's +/// decoded data, which is decoded once per container and shared (). The container is an ordinary object +/// loaded through this loader, hooks included, so it is decrypted as a whole; its members are never decrypted on their own and skip +/// hooks 1 and 2 (§7.6.2: strings in an object stream are not separately encrypted). Members publish to the cache like any object. +/// A member reference with a generation other than 0 resolves to null (§7.5.7: members have generation 0). /// /// internal sealed class ObjectLoader @@ -25,8 +34,18 @@ internal sealed class ObjectLoader /// How many loads may nest (an indirect Length loads while its stream loads) before the inner one reads null. public const int MaxDepth = 32; + private static readonly CosName ObjStm = new("ObjStm"); + private static readonly CosName N = new("N"); + private static readonly CosName First = new("First"); + + /// The object streams this thread is decoding, across loaders, so a container that needs its own member ends. + [ThreadStatic] + private static List<(ObjectLoader Loader, int Number)>? _decoding; + private readonly PdfSource _source; private readonly DiagnosticSink _diagnostics; + private readonly StreamDecoder _streams; + private ConcurrentDictionary? _objectStreams; /// Initializes a new instance of the class. /// The file. @@ -34,9 +53,17 @@ internal sealed class ObjectLoader /// The cross-reference information. /// Where to report deviations. /// The hooks. - public ObjectLoader(PdfSource source, FileHeader header, CrossReference crossReference, DiagnosticSink diagnostics, ObjectLoaderHooks hooks) + /// The filter pipeline object streams are decoded with. + public ObjectLoader( + PdfSource source, + FileHeader header, + CrossReference crossReference, + DiagnosticSink diagnostics, + ObjectLoaderHooks hooks, + StreamDecoder streams) { _source = source; + _streams = streams; Header = header; CrossReference = crossReference; _diagnostics = diagnostics; @@ -111,13 +138,89 @@ public CosObject Load(CosReference reference, int depth) return Hooks.Cache.Publish(reference, loaded); } - /// Loads an object stored in an object stream (§7.5.7). Issue #39. - private static CosNull LoadCompressed(CosReference reference, XrefEntry entry, int depth) + /// Loads an object stored in an object stream (§7.5.7): container, then the member at the entry's index. + private CosObject LoadCompressed(CosReference reference, XrefEntry entry, int depth) { - _ = (reference, entry, depth); - return CosNull.Instance; + int containerNumber = (int)entry.Offset; + if (IsDecoding(containerNumber)) + { + _diagnostics.Report( + DiagnosticCodes.ObjectStreamCycle, + DiagnosticSeverity.Error, + string.Create(CultureInfo.InvariantCulture, $"Object stream {containerNumber} needs this object, which it holds, to be decoded; read as null."), + objectReference: reference); + return CosNull.Instance; + } + + ConcurrentDictionary objectStreams = ObjectStreams; + ObjectStream container = objectStreams.TryGetValue(containerNumber, out ObjectStream? cached) + ? cached + : objectStreams.GetOrAdd(containerNumber, ReadObjectStream(containerNumber, reference, depth)); + CosObject loaded = container.Parse(reference, entry.Generation, _diagnostics); + return Hooks.Cache.Publish(reference, loaded); + } + + /// Loads and decodes object stream and reads its header (§7.5.7, Table 16). + private ObjectStream ReadObjectStream(int number, CosReference member, int depth) + { + var reference = new CosReference(number, 0); + if (CrossReference.TryGetEntry(number, out XrefEntry entry) && entry.Kind == XrefEntryKind.Compressed) + { + _diagnostics.Report( + DiagnosticCodes.ObjectStreamNested, + DiagnosticSeverity.Error, + "The object stream holding this object is itself listed as stored in an object stream, which a stream cannot be; read as null.", + objectReference: member); + return ObjectStream.Unreadable(reference); + } + + List<(ObjectLoader Loader, int Number)> decoding = _decoding ??= []; + decoding.Add((this, number)); + try + { + if (Load(reference, depth + 1) is not CosStream stream) + { + _diagnostics.Report( + DiagnosticCodes.ObjectStreamInvalid, + DiagnosticSeverity.Error, + string.Create(CultureInfo.InvariantCulture, $"The cross-reference entry places the object in object {number}, which is not a stream; read as null."), + objectReference: member); + return ObjectStream.Unreadable(reference); + } + + if (!stream.Dictionary.TryGetValue(KnownNames.Type, out CosObject? type) || !ObjStm.Equals(type)) + { + _diagnostics.Report( + DiagnosticCodes.ObjectStreamTypeInvalid, + DiagnosticSeverity.Warning, + "The object stream's Type entry shall be /ObjStm; the stream is read as one.", + objectReference: reference); + } + + CosObject count = Resolve(stream.Dictionary.TryGetValue(N, out CosObject? n) ? n : null, depth + 1); + CosObject first = Resolve(stream.Dictionary.TryGetValue(First, out CosObject? f) ? f : null, depth + 1); + return ObjectStream.Read(reference, _streams.Decode(stream), count, first, _diagnostics); + } + finally + { + decoding.Remove((this, number)); + } + } + + /// Gets the decoded object streams by object number, created on first use so a file without them pays nothing. + private ConcurrentDictionary ObjectStreams + { + get + { + ConcurrentDictionary? objectStreams = Volatile.Read(ref _objectStreams); + return objectStreams ?? Interlocked.CompareExchange(ref _objectStreams, new(), null) ?? _objectStreams; + } } + private bool IsDecoding(int containerNumber) => _decoding is { Count: > 0 } decoding && decoding.Contains((this, containerNumber)); + + private CosObject Resolve(CosObject? value, int depth) => value is CosReference reference ? Load(reference, depth) : value ?? CosNull.Instance; + /// Handles an entry whose offset does not hold the expected N G obj header. Issue #41 searches for the object. private CosNull LoadMisplaced(in ObjectLoadContext context) { diff --git a/src/Broadside/Parsing/ObjectLoaderHooks.cs b/src/Broadside/Parsing/ObjectLoaderHooks.cs index 1fa11d03..32658b9a 100644 --- a/src/Broadside/Parsing/ObjectLoaderHooks.cs +++ b/src/Broadside/Parsing/ObjectLoaderHooks.cs @@ -10,7 +10,10 @@ internal enum ObjectOrigin : byte /// An indirect object in the file body, located by a cross-reference entry (§7.3.10). FileBody, - /// An object inside an object stream (§7.5.7; issue #39). Never decrypted on its own (§7.6.2). + /// + /// An object inside an object stream (§7.5.7). Never decrypted on its own (§7.6.2): its container is decrypted as a whole, and the + /// loader does not run hooks 1 and 2 for members. + /// ObjectStream, } @@ -41,8 +44,9 @@ internal interface IStreamExtentResolver /// dictionary has been read the loader uses . /// /// -/// Must not decrypt cross-reference streams, objects inside object streams (, already decrypted -/// with their container), or the Encrypt dictionary itself (§7.6.2). Must not mark anything dirty (ADR 0004). +/// Must not decrypt cross-reference streams (they never pass through the loader: reads them), objects +/// inside object streams (never passed to it: they are decrypted with their container, an ordinary +/// stream), or the Encrypt dictionary itself (§7.6.2). Must not mark anything dirty (ADR 0004). /// internal interface IObjectDecryptor { diff --git a/src/Broadside/Parsing/ObjectStream.cs b/src/Broadside/Parsing/ObjectStream.cs new file mode 100644 index 00000000..036f9eb1 --- /dev/null +++ b/src/Broadside/Parsing/ObjectStream.cs @@ -0,0 +1,210 @@ +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Objects; + +namespace Broadside.Parsing; + +/// +/// The decoded contents of one object stream: its data and, for each member, the object number and the byte range it occupies. +/// Built once per object stream and shared by every member load. +/// +/// +/// +/// ISO 32000-2 §7.5.7, Table 16. The data starts with N pairs of integers, an object number and the offset of the object +/// relative to First; the objects follow. Objects need not be separated by white-space (NOTE 7), so each member is parsed +/// over exactly the bytes up to the next member's offset (the last one up to the end of the data). +/// +/// +/// Deviations repaired: fewer pairs than N (the pairs present are used); offsets out of order (members are bounded by the +/// next offset in sorted order); offsets past the end of the data (the member is dropped). A First or N that is not a +/// non-negative integer, or a First past the end of the data, makes every member unreadable. +/// +/// +internal sealed class ObjectStream +{ + private readonly ReadOnlyMemory _data; + private readonly int[] _numbers; + private readonly int[] _starts; + private readonly int[] _ends; + + private ObjectStream(CosReference reference, ReadOnlyMemory data, int[] numbers, int[] starts, int[] ends) + { + Reference = reference; + _data = data; + _numbers = numbers; + _starts = starts; + _ends = ends; + } + + /// Gets the object stream's own reference. + public CosReference Reference { get; } + + /// Gets the object numbers of the members, in header order. + public IReadOnlyList ObjectNumbers => _numbers; + + /// Gets a value indicating whether the object stream could be read; its members read as null, silently, when not. + public bool IsReadable { get; private init; } = true; + + /// Creates the contents of an object stream that cannot be read, already reported: it has no members. + /// The object stream's reference. + /// The empty contents. + public static ObjectStream Unreadable(CosReference reference) => new(reference, ReadOnlyMemory.Empty, [], [], []) { IsReadable = false }; + + /// Reads the header of a decoded object stream. + /// The object stream's reference, for diagnostics. + /// The decoded stream data. + /// The resolved N entry. + /// The resolved First entry. + /// Where to report deviations. + /// The contents; when N or First cannot be used. + public static ObjectStream Read(CosReference reference, ReadOnlyMemory data, CosObject count, CosObject first, DiagnosticSink diagnostics) + { + if (count is not CosInteger { Value: >= 0 } n || first is not CosInteger { Value: >= 0 } firstOffset || firstOffset.Value > data.Length) + { + diagnostics.Report( + DiagnosticCodes.ObjectStreamInvalid, + DiagnosticSeverity.Error, + "The object stream's N and First entries shall be non-negative integers, First within the data; its objects read as null.", + objectReference: reference); + return Unreadable(reference); + } + + int dataStart = (int)firstOffset.Value; + ReadOnlySpan header = data.Span[..dataStart]; + var lexer = new CosLexer(header); + + // Each pair takes at least four bytes ("1 0 "), so a hostile N cannot make the capacity exceed the header's size. + int capacity = (int)Math.Min(n.Value, (header.Length / 4) + 1); + var numbers = new List(capacity); + var starts = new List(capacity); + bool dropped = false; + for (long index = 0; index < n.Value; index++) + { + if (!StructureTokens.TryReadUnsigned(ref lexer, out long number) || !StructureTokens.TryReadUnsigned(ref lexer, out long offset)) + { + diagnostics.Report( + DiagnosticCodes.ObjectStreamHeaderInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The object stream's header holds {index} pairs of object number and offset where N says {n.Value}; the pairs present are used."), + objectReference: reference); + break; + } + + if (number is 0 or > int.MaxValue || offset > data.Length - dataStart) + { + dropped = true; + continue; + } + + numbers.Add((int)number); + starts.Add(dataStart + (int)offset); + } + + if (dropped) + { + diagnostics.Report( + DiagnosticCodes.ObjectStreamHeaderInvalid, + DiagnosticSeverity.Warning, + "A pair in the object stream's header has an invalid object number or an offset past the end of the data; that object is not read.", + objectReference: reference); + } + + int[] ends = Ends(starts, data.Length, out bool ordered); + if (!ordered) + { + diagnostics.Report( + DiagnosticCodes.ObjectStreamHeaderInvalid, + DiagnosticSeverity.Warning, + "The offsets in the object stream's header shall increase; each object is read up to the next offset in sorted order.", + objectReference: reference); + } + + return new ObjectStream(reference, data, [.. numbers], [.. starts], ends); + } + + /// Parses the member the cross-reference stream places at . + /// The member's reference (generation 0). + /// The index from the type 2 cross-reference entry (Table 18). + /// Where to report deviations. + /// The object, or when the object stream does not hold it. + public CosObject Parse(CosReference member, int index, DiagnosticSink diagnostics) + { + if (!IsReadable) + { + return CosNull.Instance; + } + + int position = index < _numbers.Length && _numbers[index] == member.ObjectNumber ? index : Array.IndexOf(_numbers, member.ObjectNumber); + if (position < 0) + { + diagnostics.Report( + DiagnosticCodes.ObjectStreamMemberMissing, + DiagnosticSeverity.Error, + string.Create(CultureInfo.InvariantCulture, $"The cross-reference entry places the object in object stream {Reference.ObjectNumber}, which does not hold it; read as null."), + objectReference: member); + return CosNull.Instance; + } + + if (position != index) + { + diagnostics.Report( + DiagnosticCodes.ObjectStreamIndexMismatch, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The cross-reference entry gives index {index} in object stream {Reference.ObjectNumber}, but the object is at index {position}; it is read from there."), + objectReference: member); + } + + ReadOnlySpan bytes = _data.Span[_starts[position].._ends[position]]; + var repairs = new CosRepairLog(keepAll: true); + var parser = new CosParser(bytes, repairs); + CosObject value = parser.ParseObject(); + foreach (CosRepair repair in repairs.All) + { + diagnostics.Report(repair.Code, DiagnosticSeverity.Warning, repair.Message, objectReference: member); + } + + if (value is CosStream) + { + diagnostics.Report( + DiagnosticCodes.ObjectStreamMemberInvalid, + DiagnosticSeverity.Warning, + "A stream shall not be stored in an object stream (§7.5.7); it is read anyway.", + objectReference: member); + } + + return value; + } + + /// Returns, for each start, the nearest greater start of another member, or the end of the data. + private static int[] Ends(List starts, int dataLength, out bool ordered) + { + ordered = true; + for (int index = 1; index < starts.Count; index++) + { + ordered &= starts[index] >= starts[index - 1]; + } + + int[] ends = new int[starts.Count]; + int[] sorted = [.. starts]; + Array.Sort(sorted); + for (int index = 0; index < starts.Count; index++) + { + int next = Array.BinarySearch(sorted, starts[index] + 1); + next = next < 0 ? ~next : FirstAtOrAbove(sorted, next); + ends[index] = next < sorted.Length ? sorted[next] : dataLength; + } + + return ends; + } + + /// Moves a binary-search hit back to the first element with the same value. + private static int FirstAtOrAbove(int[] sorted, int found) + { + while (found > 0 && sorted[found - 1] == sorted[found]) + { + found--; + } + + return found; + } +} diff --git a/src/Broadside/Parsing/XrefStreamReader.cs b/src/Broadside/Parsing/XrefStreamReader.cs new file mode 100644 index 00000000..8abd8d7f --- /dev/null +++ b/src/Broadside/Parsing/XrefStreamReader.cs @@ -0,0 +1,345 @@ +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Filters; +using Broadside.IO; +using Broadside.Objects; + +namespace Broadside.Parsing; + +/// Reads one cross-reference stream section: the stream object at an offset, its dictionary and its binary entries. +/// +/// +/// ISO 32000-2 §7.5.8. The stream is read before any object can be loaded, so its Length is used only when direct (an +/// indirect one makes the parser find the data end at endstream), its Filter and DecodeParms shall be direct +/// (§7.5.8.2), and it is never decrypted (§7.6.2). The data is decoded under the engine's decoded-length limit; entries are read +/// only as far as the data goes, so a hostile Index or Size cannot make the reader allocate more than the data holds. +/// +/// +/// Deviations repaired: a missing or wrong Type is read anyway; a malformed Index is replaced by its default +/// [0 Size]; data shorter than the entries ends the section where the data ends; entries for numbers at or beyond +/// Size are kept (Table 15 says they "shall be ignored", which would lose objects real files have); a type 1 entry with +/// offset 0 reads as free, as in a classic table. A W entry that cannot be read makes the section unreadable. +/// +/// +internal static class XrefStreamReader +{ + /// The widest field this reader accepts, in bytes: offsets and object numbers fit in a . + public const int MaxFieldWidth = 8; + + private static readonly CosName XRef = new("XRef"); + private static readonly CosName W = new("W"); + private static readonly CosName Index = new("Index"); + + /// The keys of a cross-reference stream's dictionary that describe the stream, not the file (Table 5 and Table 17). + private static readonly CosName[] StreamOnlyKeys = + [ + KnownNames.Type, KnownNames.Length, W, Index, FilterNames.Filter, FilterNames.DecodeParms, FilterNames.DL, FilterNames.F, + new("FFilter"), new("FDecodeParms"), + ]; + + /// Reads the cross-reference stream whose N G obj header is at . + /// The file. + /// The absolute offset of the stream object. + /// The document's filter pipeline. + /// Where to report deviations. + /// + /// The section, whose is the stream dictionary without the entries that describe the stream + /// itself; when no cross-reference stream can be read there. + /// + public static XrefSection? Read(PdfSource source, long offset, StreamDecoder streams, DiagnosticSink diagnostics) + { + if (!TryParseStreamObject(source, offset, diagnostics, out CosStream? stream, out CosReference? reference, out long end)) + { + return null; + } + + CosDictionary dictionary = stream.Dictionary; + if (!dictionary.TryGetValue(KnownNames.Type, out CosObject? type) || !XRef.Equals(type)) + { + Report(diagnostics, DiagnosticCodes.XrefStreamTypeInvalid, DiagnosticSeverity.Warning, "The cross-reference stream's Type entry shall be /XRef; the stream is read as one.", offset, reference); + } + + if (!TryReadWidths(dictionary, out int[] widths)) + { + Report( + diagnostics, + DiagnosticCodes.XrefStreamWidthsInvalid, + DiagnosticSeverity.Error, + $"The cross-reference stream's W entry shall be an array of three direct integers from 0 to {MaxFieldWidth} with a positive sum; the section cannot be read.", + offset, + reference); + return null; + } + + ReadOnlySpan data = streams.Decode(stream).Span; + int entryWidth = widths[0] + widths[1] + widths[2]; + long? size = ReadSize(dictionary, offset, reference, diagnostics); + List<(long First, long Count)> subsections = ReadIndex(dictionary, size ?? (data.Length / entryWidth), offset, reference, diagnostics); + var entries = new Dictionary(); + ReadEntries(data, widths, subsections, size, entries, offset, reference, diagnostics); + return new XrefSection(offset, end, XrefSectionKind.Stream, entries, Trailer(dictionary)) { Stream = stream }; + } + + /// Returns the trailer a cross-reference stream stands for: its dictionary without the stream-only entries. + private static CosDictionary Trailer(CosDictionary dictionary) + { + var trailer = new OrderedDictionary(); + foreach (KeyValuePair entry in dictionary) + { + if (Array.IndexOf(StreamOnlyKeys, entry.Key) < 0) + { + trailer.Add(entry.Key, entry.Value); + } + } + + return CosDictionary.FromOwnedEntries(trailer); + } + + /// Parses N G obj stream endobj at (§7.3.10). + private static bool TryParseStreamObject( + PdfSource source, + long offset, + DiagnosticSink diagnostics, + [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out CosStream? stream, + out CosReference? reference, + out long end) + { + stream = null; + reference = null; + end = offset; + ReadOnlySpan window = source.GetWindow(offset).Span; + var lexer = new CosLexer(window); + if (!StructureTokens.TryReadUnsigned(ref lexer, out long number) + || !StructureTokens.TryReadUnsigned(ref lexer, out long generation) + || !StructureTokens.TryReadKeyword(ref lexer, "obj"u8) + || number is 0 or > int.MaxValue + || generation > CosReference.MaxGeneration) + { + Report(diagnostics, DiagnosticCodes.XrefSectionInvalid, DiagnosticSeverity.Error, "Expected the xref keyword or the header of a cross-reference stream object.", offset, null); + return false; + } + + reference = new CosReference((int)number, (int)generation); + var repairs = new CosRepairLog(keepAll: true); + var parser = new CosParser(window, repairs, lexer.Position); + CosObject value = parser.ParseObject(); + foreach (CosRepair repair in repairs.All) + { + diagnostics.Report(repair.Code, DiagnosticSeverity.Warning, repair.Message, offset + repair.Offset, reference); + } + + if (value is not CosStream parsed) + { + Report(diagnostics, DiagnosticCodes.XrefSectionInvalid, DiagnosticSeverity.Error, "The object at the cross-reference offset is not a stream.", offset, reference); + return false; + } + + lexer.Position = parser.Position; + CosToken endobj = lexer.Next(); + if (StructureTokens.IsKeyword(window, endobj, "endobj"u8)) + { + end = offset + endobj.End; + } + else + { + diagnostics.Report(DiagnosticCodes.MissingEndobj, DiagnosticSeverity.Warning, "The object is not followed by the endobj keyword; it ends here.", offset + endobj.Start, reference); + end = offset + parser.Position; + } + + stream = parsed; + return true; + } + + /// Reads W (Table 17): three direct integers, each 0 to , at least one positive. + private static bool TryReadWidths(CosDictionary dictionary, out int[] widths) + { + widths = new int[3]; + if (!dictionary.TryGetValue(W, out CosObject? entry) || entry is not CosArray { Count: 3 } array) + { + return false; + } + + for (int index = 0; index < 3; index++) + { + if (array[index] is not CosInteger { Value: >= 0 and <= MaxFieldWidth } width) + { + return false; + } + + widths[index] = (int)width.Value; + } + + return widths[0] + widths[1] + widths[2] > 0; + } + + /// Reads Size (Table 15 and Table 17): a direct, non-negative integer. + private static long? ReadSize(CosDictionary dictionary, long offset, CosReference? reference, DiagnosticSink diagnostics) + { + if (dictionary.TryGetValue(KnownNames.Size, out CosObject? entry) && entry is CosInteger { Value: >= 0 } size) + { + return size.Value; + } + + Report( + diagnostics, + DiagnosticCodes.XrefStreamSizeInvalid, + DiagnosticSeverity.Warning, + "The cross-reference stream's Size entry shall be a direct, non-negative integer; the entries are read as far as the data goes.", + offset, + reference); + return null; + } + + /// Reads Index (Table 17): pairs of first object number and count; default [0 Size]. + private static List<(long First, long Count)> ReadIndex(CosDictionary dictionary, long defaultCount, long offset, CosReference? reference, DiagnosticSink diagnostics) + { + var subsections = new List<(long First, long Count)>(); + if (!dictionary.TryGetValue(Index, out CosObject? entry)) + { + subsections.Add((0, defaultCount)); + return subsections; + } + + if (entry is CosArray array && array.Count % 2 == 0) + { + for (int index = 0; index < array.Count; index += 2) + { + if (array[index] is not CosInteger { Value: >= 0 } first || array[index + 1] is not CosInteger { Value: >= 0 } count) + { + subsections.Clear(); + break; + } + + subsections.Add((first.Value, count.Value)); + } + + if (subsections.Count > 0 || array.Count == 0) + { + return subsections; + } + } + + Report( + diagnostics, + DiagnosticCodes.XrefStreamIndexInvalid, + DiagnosticSeverity.Warning, + "The cross-reference stream's Index entry shall be an array of pairs of direct, non-negative integers; the default [0 Size] is used.", + offset, + reference); + subsections.Add((0, defaultCount)); + return subsections; + } + + /// Reads the entries (Table 18), one per object number of each subsection, until the data ends. + private static void ReadEntries( + ReadOnlySpan data, + int[] widths, + List<(long First, long Count)> subsections, + long? size, + Dictionary entries, + long offset, + CosReference? reference, + DiagnosticSink diagnostics) + { + int entryWidth = widths[0] + widths[1] + widths[2]; + int position = 0; + bool beyondSize = false; + foreach ((long first, long count) in subsections) + { + for (long index = 0; index < count; index++) + { + if (data.Length - position < entryWidth) + { + Report( + diagnostics, + DiagnosticCodes.XrefStreamDataTruncated, + DiagnosticSeverity.Warning, + "The cross-reference stream's data ends before the last entry its Index and W entries describe; the entries after it are missing.", + offset, + reference); + return; + } + + ReadOnlySpan row = data.Slice(position, entryWidth); + position += entryWidth; + long number = first + index; + if (number is 0 or > int.MaxValue) + { + // §7.5.4: object number 0 is the head of the free list and never names an object. + continue; + } + + beyondSize |= number >= size; + string? problem = DecodeEntry(row, widths, out XrefEntry entry); + if (problem is not null) + { + string what = problem == DiagnosticCodes.XrefEntryOffsetInvalid ? "is in use at offset 0, where the header is" : "has a field out of range"; + Report( + diagnostics, + problem, + DiagnosticSeverity.Error, + string.Create(CultureInfo.InvariantCulture, $"The cross-reference stream entry for object {number} {what}; the object is read as free."), + offset, + reference); + } + + entries.TryAdd((int)number, entry); + } + } + + if (beyondSize) + { + Report( + diagnostics, + DiagnosticCodes.XrefStreamSizeInvalid, + DiagnosticSeverity.Warning, + "The cross-reference stream has entries for object numbers at or beyond its Size entry; they are kept.", + offset, + reference); + } + } + + /// Decodes one row (Table 18): fields big-endian, absent fields take their defaults, an unknown type is the null object. + /// The diagnostic code of the problem when the row is unusable (the entry is then free), else . + private static string? DecodeEntry(ReadOnlySpan row, int[] widths, out XrefEntry entry) + { + long type = widths[0] == 0 ? 1 : Field(row[..widths[0]]); + long field2 = Field(row.Slice(widths[0], widths[1])); + long field3 = Field(row.Slice(widths[0] + widths[1], widths[2])); + entry = XrefEntry.Free; + switch (type) + { + case 0: + entry = new XrefEntry(XrefEntryKind.Free, Math.Max(field2, 0), (int)Math.Clamp(field3, 0, CosReference.MaxGeneration)); + return null; + case 1 when field2 == 0: + return DiagnosticCodes.XrefEntryOffsetInvalid; + case 1 when field2 > 0 && field3 is >= 0 and <= CosReference.MaxGeneration: + entry = new XrefEntry(XrefEntryKind.InUse, field2, (int)field3); + return null; + case 2 when field2 is > 0 and <= int.MaxValue && field3 is >= 0 and <= int.MaxValue: + entry = new XrefEntry(XrefEntryKind.Compressed, field2, (int)field3); + return null; + case 1 or 2: + return DiagnosticCodes.XrefEntryInvalid; + default: + // Table 18: "Any other value shall be interpreted as a reference to the null object", which a free entry reads as. + return null; + } + } + + /// Reads a big-endian unsigned field; one wider than 63 bits reads as negative, which every caller rejects. + private static long Field(ReadOnlySpan bytes) + { + long value = 0; + foreach (byte b in bytes) + { + value = (value << 8) | b; + } + + return value; + } + + private static void Report(DiagnosticSink diagnostics, string code, DiagnosticSeverity severity, string message, long offset, CosReference? reference) => + diagnostics.Report(code, severity, message, offset, reference); +} diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 58d4cfbb..339aebd8 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -220,9 +220,17 @@ internal static PdfDocument Read(PdfSource source, EngineConfiguration configura { var diagnostics = new DiagnosticSink(configuration.ReadingMode == PdfReadingMode.Strict, configuration.DiagnosticObserver); FileHeader header = FileHeader.Locate(source, diagnostics); - CrossReference crossReference = CrossReferenceReader.Read(source, header, diagnostics) ?? Reconstruct(diagnostics); - var loader = new ObjectLoader(source, header, crossReference, diagnostics, new ObjectLoaderHooks()); - var streams = new StreamDecoder(configuration.Filters, configuration.MaxDecodedStreamLength, diagnostics, loader.Resolve); + + // Cross-reference streams are decoded before any object can be loaded; their Filter and DecodeParms are direct + // (§7.5.8.2), so until the loader exists a reference resolves to null. + ObjectLoader? loader = null; + var streams = new StreamDecoder( + configuration.Filters, + configuration.MaxDecodedStreamLength, + diagnostics, + value => loader is not null ? loader.Resolve(value) : value is null or CosReference ? CosNull.Instance : value); + CrossReference crossReference = CrossReferenceReader.Read(source, header, streams, diagnostics) ?? Reconstruct(diagnostics); + loader = new ObjectLoader(source, header, crossReference, diagnostics, new ObjectLoaderHooks(), streams); IReadOnlyList revisions = ReadRevisions(source, crossReference, diagnostics); CosDictionary catalog = ReadCatalog(loader, diagnostics); PdfLinearization? linearization = LinearizationReader.Read(source, loader, diagnostics); diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index a4f15690..332f7742 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -1,6 +1,7 @@ using System.Buffers; using Broadside.Diagnostics; using Broadside.Filters; +using Broadside.IO; using Broadside.Objects; using Broadside.Parsing; using SharpFuzz; @@ -20,6 +21,8 @@ internal static class FuzzTargets ["object-parser"] = ObjectParser, ["document"] = Document, ["hint-tables"] = HintTables, + ["xref-stream"] = XrefStream, + ["object-stream"] = ObjectStreamTarget, ["filter-asciihex"] = data => Filter(new AsciiHexDecodeFilter(), data, parameters: null, maxRatio: 1), ["filter-ascii85"] = data => Filter(new Ascii85DecodeFilter(), data, parameters: null, maxRatio: 4), ["filter-lzw"] = Lzw, @@ -190,6 +193,71 @@ private static void HintTables(ReadOnlySpan data) } } + /// + /// Reads the input as cross-reference stream data: bytes 0 to 2 are the field widths of W (0 to 9, so invalid widths are + /// tried too), byte 3 selects whether Index is [0 Size] by default or two subsections, the rest is the data. The + /// section must have at most one entry per whole row of data, never object number 0, and in-use offsets and compressed indexes + /// that are not negative. + /// + /// ISO 32000-2 §7.5.8.2 Table 17 and §7.5.8.3 Table 18. + private static void XrefStream(ReadOnlySpan data) + { + if (data.Length < 4) + { + return; + } + + int[] widths = [data[0] % 10, data[1] % 10, data[2] % 10]; + ReadOnlySpan rows = data[4..]; + string index = (data[3] & 1) == 0 ? string.Empty : "/Index [0 3 1000 1000000]"; + byte[] head = System.Text.Encoding.ASCII.GetBytes( + $"7 0 obj\n<< /Type /XRef /Size 1000 {index} /W [{widths[0]} {widths[1]} {widths[2]}] /Length {rows.Length} >>\nstream\n"); + byte[] file = [.. head, .. rows, .. "\nendstream\nendobj\n"u8]; + var diagnostics = new DiagnosticSink(strict: false); + var streams = new StreamDecoder(FilterRegistry.Create([]), PdfOptions.DefaultMaxDecodedStreamLength, diagnostics, static value => value ?? CosNull.Instance); + using PdfSource source = PdfSource.FromMemory(file); + + XrefSection? section = XrefStreamReader.Read(source, 0, streams, diagnostics); + + if (section is null) + { + return; + } + + int entryWidth = widths.Sum(); + if (section.Entries.Count > rows.Length / entryWidth + || section.Entries.ContainsKey(0) + || section.Entries.Values.Any(entry => entry.Offset < 0 || entry.Generation < 0) + || section.Trailer.ContainsKey(new CosName("W"))) + { + throw new InvalidOperationException("The cross-reference stream section is inconsistent with its data."); + } + } + + /// + /// Reads the input as decoded object stream data: byte 0 is N, byte 1 is First (both modulo the data length plus + /// one), the rest is the data. Every member the header names is then parsed, at its own index and at a wrong one; none may throw. + /// + /// ISO 32000-2 §7.5.7 Table 16. + private static void ObjectStreamTarget(ReadOnlySpan data) + { + if (data.Length < 2) + { + return; + } + + byte[] body = data[2..].ToArray(); + var diagnostics = new DiagnosticSink(strict: false); + var reference = new CosReference(1, 0); + ObjectStream contents = ObjectStream.Read(reference, body, new CosInteger(data[0]), new CosInteger(data[1] % (body.Length + 1)), diagnostics); + for (int index = 0; index < contents.ObjectNumbers.Count; index++) + { + var member = new CosReference(contents.ObjectNumbers[index], 0); + _ = contents.Parse(member, index, diagnostics); + _ = contents.Parse(member, index + 1, diagnostics); + } + } + private static PdfDocument? OpenOrNull(ReadOnlySpan data) { try diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index d3467f32..e62cdaf7 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` for a file whose cross-reference information cannot be read is the one allowed outcome until #41 reconstructs it; it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` for a file whose cross-reference information cannot be read is the one allowed outcome until #41 reconstructs it; it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. @@ -32,6 +32,14 @@ mkdir -p artifacts/fuzz/seeds-hints { printf '\001\000\054'; qpdf --show-object=7 --raw-stream-data tests/Corpus/linearized.pdf; } > artifacts/fuzz/seeds-hints/linearized.bin ``` +`xref-stream` and `object-stream` read raw stream data behind control bytes, so whole files are weak seeds for them too; for libFuzzer and AFL seed them from the corpus: + +```sh +mkdir -p artifacts/fuzz/seeds-xref-stream artifacts/fuzz/seeds-object-stream +{ printf '\001\002\001\000'; qpdf --show-object=4 --filtered-stream-data tests/Corpus/png-predictor.pdf; } > artifacts/fuzz/seeds-xref-stream/png-predictor.bin +{ printf '\003\016'; qpdf --show-object=4 --filtered-stream-data tests/Corpus/object-stream.pdf; } > artifacts/fuzz/seeds-object-stream/object-stream.bin +``` + For the `filter-*` targets whole files are weak seeds too (a whole PDF as a stream body); for real fuzzing extract stream bodies, for example `qpdf --show-object=4 --raw-stream-data tests/Corpus/lzw-stream.pdf > artifacts/fuzz/seeds/lzw.bin`. Smoke mode is a regression net, not a fuzzer: it has no coverage feedback and finds only shallow bugs. Use a real fuzzer for anything that parses. diff --git a/tests/Broadside.TestSupport/Corpus.cs b/tests/Broadside.TestSupport/Corpus.cs index f2904deb..8c9cb728 100644 --- a/tests/Broadside.TestSupport/Corpus.cs +++ b/tests/Broadside.TestSupport/Corpus.cs @@ -17,6 +17,7 @@ public static class Corpus "incremental-update.pdf", "hybrid-xref.pdf", "linearized.pdf", + "linearized-xref-stream.pdf", "flate-stream.pdf", "lzw-stream.pdf", "ascii85-stream.pdf", diff --git a/tests/Broadside.Tests/Document/CrossReferenceStreamTests.cs b/tests/Broadside.Tests/Document/CrossReferenceStreamTests.cs new file mode 100644 index 00000000..31f0fdfa --- /dev/null +++ b/tests/Broadside.Tests/Document/CrossReferenceStreamTests.cs @@ -0,0 +1,207 @@ +using System.Text; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// +/// Cross-reference streams read exactly like classic tables: their dictionary is the trailer, their binary entries locate objects. +/// ISO 32000-2 §7.5.8.1 to §7.5.8.3, Tables 17 and 18. +/// +public class CrossReferenceStreamTests +{ + private static readonly int[] W121 = [1, 2, 1]; + + public static TheoryData CompressedStructureFiles => new(["xref-stream.pdf", "object-stream.pdf", "png-predictor.pdf", "hybrid-xref.pdf"]); + + [Theory] + [MemberData(nameof(CompressedStructureFiles))] + public void A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file(string fileName) + { + // Every file holds the catalog (1), page tree (2) and page (3) of empty-page.pdf, the classic baseline (tests/Corpus/README.md). + using PdfDocument classic = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName)); + + Assert.Equal(DocumentProjection.Of(classic).Pages, DocumentProjection.Of(document).Pages); + for (int number = 1; number <= 3; number++) + { + var reference = new CosReference(number, 0); + Assert.True(CosObject.DeepEquals(classic.Resolve(reference), document.Resolve(reference)), $"object {number}"); + } + + Assert.Equal(new CosReference(1, 0), document.Trailer[new CosName("Root")]); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [MemberData(nameof(CompressedStructureFiles))] + public void Strict_mode_opens_a_file_with_compressed_structures(string fileName) + { + using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName), new PdfOptions().UseStrict()); + + Assert.Single(document.Pages); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void The_trailer_of_a_cross_reference_stream_is_its_dictionary_without_the_entries_that_describe_the_stream() + { + // §7.5.8.1: the stream's dictionary replaces the trailer; Type, W, Index, Length and the filter entries describe the stream itself. + using PdfDocument document = PdfDocument.Open(Corpus.Path("png-predictor.pdf")); + + Assert.Equal(["Size", "Root"], document.Trailer.Keys.Select(key => key.Value)); + Assert.Equal(new CosInteger(5), document.Trailer[new CosName("Size")]); + Assert.Equal(["Size", "Root"], Assert.Single(document.Revisions).Trailer.Keys.Select(key => key.Value)); + } + + [Fact] + public void A_missing_type_field_makes_every_entry_type_1() + { + // Table 17, W: "If the first element is zero, the type field shall not be present, and shall default to type 1." + var pdf = new XrefStreamPdf().AddOnePage(); + byte[] file = pdf.Finish(4, "/Size 4 /Index [1 3] /Root 1 0 R /W [0 2 1]", [0, 2, 1], (0, pdf.Offset(1), 0), (0, pdf.Offset(2), 0), (0, pdf.Offset(3), 0)); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Single(document.Pages); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_missing_generation_field_defaults_to_generation_0() + { + // Table 18: the generation number of a type 1 entry defaults to 0 when its field is absent (W[2] = 0). + var pdf = new XrefStreamPdf().AddOnePage(); + byte[] file = pdf.Finish(4, "/Size 4 /Root 1 0 R /W [1 4 0]", [1, 4, 0], (0, 0, 0), (1, pdf.Offset(1), 0), (1, pdf.Offset(2), 0), (1, pdf.Offset(3), 0)); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Single(document.Pages); + Assert.IsType(document.Resolve(new CosReference(3, 0))); + Assert.Same(CosNull.Instance, document.Resolve(new CosReference(3, 1))); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Index_with_two_subsections_numbers_the_entries_of_each_from_its_first_object_number() + { + var pdf = new XrefStreamPdf().AddOnePage().Add(10, "(ten)").Add(11, "(eleven)"); + byte[] file = pdf.Finish( + 12, + "/Size 12 /Index [1 3 10 2] /Root 1 0 R /W [1 2 1]", + W121, + (1, pdf.Offset(1), 0), + (1, pdf.Offset(2), 0), + (1, pdf.Offset(3), 0), + (1, pdf.Offset(10), 0), + (1, pdf.Offset(11), 0)); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal("ten", Text(document, 10)); + Assert.Equal("eleven", Text(document, 11)); + Assert.Same(CosNull.Instance, document.Resolve(new CosReference(4, 0))); + Assert.Single(document.Pages); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Wide_fields_are_read_big_endian() + { + var pdf = new XrefStreamPdf().AddOnePage().Add(4, "(four)"); + byte[] file = pdf.Finish( + 5, + "/Size 5 /Root 1 0 R /W [2 8 3]", + [2, 8, 3], + (0, 0, 65535), + (1, pdf.Offset(1), 0), + (1, pdf.Offset(2), 0), + (1, pdf.Offset(3), 0), + (1, pdf.Offset(4), 0)); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal("four", Text(document, 4)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void An_entry_of_an_unknown_type_is_a_reference_to_the_null_object() + { + // Table 18: "Any other value shall be interpreted as a reference to the null object", here hiding an object a classic reader would find. + var pdf = new XrefStreamPdf().AddOnePage().Add(4, "(hidden)"); + byte[] file = pdf.Finish(5, "/Size 5 /Root 1 0 R /W [1 2 1]", W121, (0, 0, 255), (1, pdf.Offset(1), 0), (1, pdf.Offset(2), 0), (1, pdf.Offset(3), 0), (7, pdf.Offset(4), 0)); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Same(CosNull.Instance, document.Resolve(new CosReference(4, 0))); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Data_shorter_than_the_entries_ends_the_section_where_the_data_ends() + { + var pdf = new XrefStreamPdf().AddOnePage().Add(4, "(four)"); + byte[] rows = XrefStreamPdf.Rows(W121, (0, 0, 255), (1, pdf.Offset(1), 0), (1, pdf.Offset(2), 0), (1, pdf.Offset(3), 0), (1, pdf.Offset(4), 0)); + byte[] file = pdf.Finish(5, "/Size 5 /Root 1 0 R /W [1 2 1]", rows[..^2]); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Single(document.Pages); + Assert.Same(CosNull.Instance, document.Resolve(new CosReference(4, 0))); + Assert.Equal("XrefStreamDataTruncated", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_stream_without_type_XRef_is_read_with_a_diagnostic() + { + var pdf = new XrefStreamPdf().AddOnePage(); + string text = Encoding.Latin1.GetString(pdf.Finish(4, "/Size 4 /Root 1 0 R /W [1 2 1]", W121, (0, 0, 255), (1, pdf.Offset(1), 0), (1, pdf.Offset(2), 0), (1, pdf.Offset(3), 0))); + byte[] file = Encoding.Latin1.GetBytes(text.Replace("/Type /XRef", "/Type /XRf", StringComparison.Ordinal)); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Single(document.Pages); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("XrefStreamTypeInvalid", diagnostic.Code); + Assert.Equal(new CosReference(4, 0), diagnostic.ObjectReference); + } + + [Fact] + public void A_stream_whose_W_cannot_be_read_is_not_a_cross_reference_section() + { + var pdf = new XrefStreamPdf().AddOnePage(); + byte[] file = pdf.Finish(4, "/Size 4 /Root 1 0 R /W [1 2]", W121, (0, 0, 255), (1, pdf.Offset(1), 0), (1, pdf.Offset(2), 0), (1, pdf.Offset(3), 0)); + + DiagnosticException error = Assert.Throws(() => PdfDocument.Open(file)); + + Assert.Equal("XrefStreamWidthsInvalid", error.Diagnostic.Code); + } + + [Fact] + public void An_update_written_as_a_cross_reference_stream_overrides_the_original_section() + { + // §7.5.6 and §7.5.8.1: an update's stream has Prev pointing at the previous section, a classic table here. + byte[] original = TestPdf.OnePage("/MediaBox [0 0 612 792]"); + string text = Encoding.Latin1.GetString(original); + int previous = int.Parse(text[(text.LastIndexOf("startxref", StringComparison.Ordinal) + 9)..].Trim().Split('\n')[0], System.Globalization.CultureInfo.InvariantCulture); + var update = new StringBuilder(text); + int pageOffset = update.Length; + update.Append("3 0 obj\n<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 595 842] >>\nendobj\n"); + int streamOffset = update.Length; + byte[] rows = XrefStreamPdf.Rows(W121, (1, pageOffset, 0), (1, streamOffset, 0)); + update.Append(System.Globalization.CultureInfo.InvariantCulture, $"4 0 obj\n<< /Type /XRef /Size 5 /Index [3 2] /W [1 2 1] /Root 1 0 R /Prev {previous} /Length {rows.Length} >>\nstream\n"); + update.Append(Encoding.Latin1.GetString(rows)).Append(System.Globalization.CultureInfo.InvariantCulture, $"\nendstream\nendobj\nstartxref\n{streamOffset}\n%%EOF\n"); + byte[] file = Encoding.Latin1.GetBytes(update.ToString()); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal(595, document.Pages[0].MediaBox.Width); + Assert.Equal([original.LongLength, file.LongLength], document.Revisions.Select(revision => revision.Length)); + Assert.Empty(document.Diagnostics); + } + + private static string Text(PdfDocument document, int number) => + Assert.IsType(document.Resolve(new CosReference(number, 0))).DecodeText(); +} diff --git a/tests/Broadside.Tests/Document/EngineTests.cs b/tests/Broadside.Tests/Document/EngineTests.cs index 96a8f0b6..bc4d1be2 100644 --- a/tests/Broadside.Tests/Document/EngineTests.cs +++ b/tests/Broadside.Tests/Document/EngineTests.cs @@ -11,8 +11,6 @@ public class EngineTests [MemberData(nameof(Corpus.WellFormedFiles), MemberType = typeof(Corpus))] public void The_static_entry_point_and_an_engine_instance_open_documents_identically(string fileName) { - Assert.SkipWhen(WellFormedCorpusTests.NeedsCrossReferenceStreams(fileName), "Needs cross-reference streams (#39)."); - var engine = new PdfEngine(new PdfOptions()); using PdfDocument fromEngine = engine.Open(Corpus.Bytes(fileName)); using PdfDocument fromStatic = PdfDocument.Open(Corpus.Bytes(fileName)); @@ -64,8 +62,6 @@ public void Strict_mode_throws_from_the_member_that_loads_a_deviating_object() [MemberData(nameof(Corpus.WellFormedFiles), MemberType = typeof(Corpus))] public void Strict_mode_opens_every_well_formed_file(string fileName) { - Assert.SkipWhen(WellFormedCorpusTests.NeedsCrossReferenceStreams(fileName), "Needs cross-reference streams (#39)."); - using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName), new PdfOptions().UseStrict()); Assert.NotEmpty(document.Pages); diff --git a/tests/Broadside.Tests/Document/HybridFileTests.cs b/tests/Broadside.Tests/Document/HybridFileTests.cs new file mode 100644 index 00000000..c1985bc1 --- /dev/null +++ b/tests/Broadside.Tests/Document/HybridFileTests.cs @@ -0,0 +1,107 @@ +using System.Globalization; +using System.Text; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// +/// Hybrid-reference files: a classic table whose trailer names a cross-reference stream through XRefStm, consulted after the +/// table and before older sections. ISO 32000-2 §7.5.8.4, Table 19. +/// +public class HybridFileTests +{ + [Fact] + public void An_object_only_the_XRefStm_stream_lists_is_found() + { + // hybrid-xref.pdf: the main table lists 4-6 free; the update's XRefStm stream puts the Info dictionary (4) in object stream 5. + using PdfDocument document = PdfDocument.Open(Corpus.Path("hybrid-xref.pdf")); + + CosDictionary info = Assert.IsType(document.Resolve(document.Trailer[new CosName("Info")])); + + Assert.Equal("hybrid", Assert.IsType(info[new CosName("Title")]).DecodeText()); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void The_table_of_a_section_takes_precedence_over_its_XRefStm_stream() + { + // §7.5.8.4: the stream is searched only for entries the table does not have. + byte[] file = Hybrid(tableHasObject4: true, streamEntries: string.Empty); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal("table", Assert.IsType(document.Resolve(new CosReference(4, 0))).DecodeText()); + Assert.Single(document.Pages); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void The_XRefStm_streams_dictionary_is_not_the_trailer_and_its_Prev_is_not_followed() + { + // Table 17: Prev in an XRefStm stream is "not meaningful in hybrid-reference files"; Root comes from the table's trailer. + byte[] file = Hybrid(tableHasObject4: false, streamEntries: "/Prev 999999 /Root 3 0 R /Info 4 0 R"); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal("stream", Assert.IsType(document.Resolve(new CosReference(4, 0))).DecodeText()); + Assert.Equal(new CosReference(1, 0), document.Trailer[new CosName("Root")]); + Assert.False(document.Trailer.ContainsKey(new CosName("Info"))); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void An_XRefStm_offset_that_names_no_stream_is_reported_and_the_table_is_still_read() + { + byte[] file = Hybrid(tableHasObject4: false, streamEntries: string.Empty, xrefStm: "13"); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Single(document.Pages); + Assert.Same(CosNull.Instance, document.Resolve(new CosReference(4, 0))); + Assert.Equal("TrailerXRefStmInvalid", Assert.Single(document.Diagnostics).Code); + } + + /// + /// One section: objects 1-3 (and 4, "(table)", when ) in the classic table, which lists nothing + /// else, object stream 5 + /// holding 4 as "(stream)", and cross-reference stream 6 for 4-6 named by the trailer's XRefStm (or by ). + /// + private static byte[] Hybrid(bool tableHasObject4, string streamEntries, string? xrefStm = null) + { + var text = new StringBuilder("%PDF-1.5\n"); + var offsets = new Dictionary(); + void Add(int number, string body) + { + offsets[number] = text.Length; + text.Append(CultureInfo.InvariantCulture, $"{number} 0 obj\n{body}\nendobj\n"); + } + + for (int index = 0; index < XrefStreamPdf.OnePage.Length; index++) + { + Add(index + 1, XrefStreamPdf.OnePage[index]); + } + + if (tableHasObject4) + { + Add(4, "(table)"); + } + + Add(5, "<< /Type /ObjStm /N 1 /First 4 /Length 12 >>\nstream\n4 0 (stream)\nendstream"); + int stream = text.Length; + byte[] rows = XrefStreamPdf.Rows([1, 2, 1], (2, 5, 0), (1, offsets[5], 0), (1, stream, 0)); + text.Append(CultureInfo.InvariantCulture, $"6 0 obj\n<< /Type /XRef /Size 7 /Index [4 3] /W [1 2 1] {streamEntries} /Length {rows.Length} >>\nstream\n"); + text.Append(Encoding.Latin1.GetString(rows)).Append("\nendstream\nendobj\n"); + int table = text.Length; + // The table lists only the objects it holds: a free entry for 4 would be found in the table and hide the stream's (§7.5.8.4). + int listed = tableHasObject4 ? 4 : 3; + text.Append(CultureInfo.InvariantCulture, $"xref\n0 {listed + 1}\n0000000000 65535 f \n"); + for (int number = 1; number <= listed; number++) + { + text.Append(CultureInfo.InvariantCulture, $"{offsets[number]:D10} 00000 n \n"); + } + + text.Append(CultureInfo.InvariantCulture, $"trailer\n<< /Size 7 /Root 1 0 R /XRefStm {xrefStm ?? stream.ToString(CultureInfo.InvariantCulture)} >>\nstartxref\n{table}\n%%EOF\n"); + return Encoding.Latin1.GetBytes(text.ToString()); + } +} diff --git a/tests/Broadside.Tests/Document/LinearizationTests.cs b/tests/Broadside.Tests/Document/LinearizationTests.cs index e44c4715..1d24874f 100644 --- a/tests/Broadside.Tests/Document/LinearizationTests.cs +++ b/tests/Broadside.Tests/Document/LinearizationTests.cs @@ -98,6 +98,26 @@ public void Hint_offsets_count_from_byte_0_of_the_file_when_bytes_precede_the_he Assert.Empty(document.Diagnostics); } + [Fact] + public void A_linearized_file_with_cross_reference_streams_has_its_first_page_and_main_streams_as_one_revision() + { + // linearized-xref-stream.pdf (qpdf --object-streams=generate): the first-page cross-reference stream (object 5, objects 4-15) + // has Prev pointing forward to the main one (object 3, objects 0-3); objects 13-15 are in object stream 10 (F.3.4, §7.5.8). + byte[] file = Corpus.Bytes("linearized-xref-stream.pdf"); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.True(document.IsLinearized); + PdfLinearization linearization = document.Linearization!; + Assert.Equal((new CosReference(4, 0), 1661L, 2, 8), (linearization.Reference, linearization.FileLength, linearization.PageCount, linearization.FirstPageObjectNumber)); + Assert.Equal(Enumerable.Range(4, 12).Select(number => new CosReference(number, 0)), linearization.FirstPageObjects); + PdfRevision revision = Assert.Single(document.Revisions); + Assert.Equal(file.LongLength, revision.Length); + Assert.Equal(new CosReference(6, 0), revision.Trailer[new CosName("Root")]); + Assert.Equal(2, document.Pages.Count); + Assert.Empty(document.Diagnostics); + } + [Fact] public void A_file_that_is_not_linearized_reports_false() { diff --git a/tests/Broadside.Tests/Document/ObjectStreamTests.cs b/tests/Broadside.Tests/Document/ObjectStreamTests.cs new file mode 100644 index 00000000..3831992e --- /dev/null +++ b/tests/Broadside.Tests/Document/ObjectStreamTests.cs @@ -0,0 +1,214 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// +/// Objects stored in object streams resolve like any other object, through the type 2 entries of a cross-reference stream. +/// ISO 32000-2 §7.5.7 (Table 16) and §7.5.8.3 (Table 18). +/// +public class ObjectStreamTests +{ + private static readonly int[] W121 = [1, 2, 1]; + + [Fact] + public void The_catalog_page_tree_and_page_resolve_from_an_object_stream() + { + // object-stream.pdf: objects 1-3 are members 0-2 of object stream 4 (tests/Corpus/README.md). + using PdfDocument document = PdfDocument.Open(Corpus.Path("object-stream.pdf")); + + CosDictionary page = Assert.IsType(document.Resolve(new CosReference(3, 0))); + + Assert.Equal(new CosName("Page"), page[new CosName("Type")]); + Assert.Same(page, document.Pages[0].Dictionary); + Assert.Same(page, document.Resolve(new CosReference(3, 0))); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_reference_to_a_member_with_a_generation_other_than_0_resolves_to_null() + { + // §7.5.7: "The generation number of an object stream and of any compressed object shall be zero." + using PdfDocument document = PdfDocument.Open(Corpus.Path("object-stream.pdf")); + + Assert.Same(CosNull.Instance, document.Resolve(new CosReference(3, 1))); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Members_need_no_white_space_between_them() + { + // §7.5.7 NOTE 7: each object is bounded by the next one's offset, so "(a)(b)12" holds three objects. + byte[] file = OneObjectStream([(4, "(a)"), (5, "(b)"), (6, "12"), (7, "<< /K 1 >>")], separator: string.Empty); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal("a", Assert.IsType(document.Resolve(new CosReference(4, 0))).DecodeText()); + Assert.Equal("b", Assert.IsType(document.Resolve(new CosReference(5, 0))).DecodeText()); + Assert.Equal(new CosInteger(12), document.Resolve(new CosReference(6, 0))); + Assert.IsType(document.Resolve(new CosReference(7, 0))); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_member_at_another_index_than_its_entry_says_is_found_by_its_object_number() + { + // The stream holds 4 then 5; the cross-reference stream says 4 is at index 1. + byte[] file = OneObjectStream([(4, "(four)"), (5, "(five)")], indexes: [1, 0]); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal("four", Assert.IsType(document.Resolve(new CosReference(4, 0))).DecodeText()); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("ObjectStreamIndexMismatch", diagnostic.Code); + Assert.Equal(new CosReference(4, 0), diagnostic.ObjectReference); + } + + [Fact] + public void Offsets_out_of_order_bound_each_member_by_the_next_offset_in_sorted_order() + { + // Header "5 6 4 0": object 5 is stored after object 4 although its pair comes first. + byte[] file = OneObjectStream([(4, "(four)"), (5, "(five)")], separator: string.Empty, header: "5 6 4 0 "); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal("four", Assert.IsType(document.Resolve(new CosReference(4, 0))).DecodeText()); + Assert.Equal("five", Assert.IsType(document.Resolve(new CosReference(5, 0))).DecodeText()); + Assert.Contains("ObjectStreamHeaderInvalid", document.Diagnostics.Select(diagnostic => diagnostic.Code)); + } + + [Fact] + public void A_member_the_object_stream_does_not_hold_resolves_to_null() + { + byte[] file = OneObjectStream([(4, "(four)")], extraEntries: [(5, 0)]); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Same(CosNull.Instance, document.Resolve(new CosReference(5, 0))); + Assert.Equal("ObjectStreamMemberMissing", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void An_object_stream_whose_N_is_one_of_its_own_members_resolves_its_members_to_null() + { + // A container cannot be decoded with a value it holds; the loader must end instead of recursing. + byte[] file = OneObjectStream([(4, "(four)"), (5, "2")], count: "5 0 R"); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Same(CosNull.Instance, document.Resolve(new CosReference(4, 0))); + Assert.Equal(["ObjectStreamCycle", "ObjectStreamInvalid"], document.Diagnostics.Select(diagnostic => diagnostic.Code)); + } + + [Fact] + public void An_object_stream_listed_as_compressed_itself_is_not_read() + { + // Streams cannot be stored in object streams (§7.5.7), so a container with a type 2 entry is invalid. + var pdf = new XrefStreamPdf().AddOnePage(); + byte[] file = pdf.Finish(4, "/Size 6 /Root 1 0 R /W [1 2 1]", W121, (0, 0, 255), (1, pdf.Offset(1), 0), (1, pdf.Offset(2), 0), (1, pdf.Offset(3), 0), (2, 4, 0), (2, 4, 0)); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Same(CosNull.Instance, document.Resolve(new CosReference(5, 0))); + Assert.Equal("ObjectStreamNested", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_type_2_entry_naming_an_object_that_is_not_a_stream_resolves_to_null() + { + var pdf = new XrefStreamPdf().AddOnePage(); + byte[] file = pdf.Finish(4, "/Size 5 /Root 1 0 R /W [1 2 1]", W121, (0, 0, 255), (1, pdf.Offset(1), 0), (1, pdf.Offset(2), 0), (1, pdf.Offset(3), 0), (2, 2, 0)); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Same(CosNull.Instance, document.Resolve(new CosReference(4, 0))); + Assert.Equal("ObjectStreamInvalid", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_flate_encoded_object_stream_is_decoded_through_the_filters() + { + byte[] data = FilterEncoders.Zlib("4 0 5 7 (four) (five)"u8.ToArray()); + var pdf = new XrefStreamPdf().AddOnePage(); + pdf.Add(6, $"<< /Type /ObjStm /N 2 /First 8 /Filter /FlateDecode /Length {data.Length} >>\nstream\n{System.Text.Encoding.Latin1.GetString(data)}\nendstream"); + byte[] file = pdf.Finish( + 7, + "/Size 7 /Root 1 0 R /W [1 2 1]", + W121, + (0, 0, 255), + (1, pdf.Offset(1), 0), + (1, pdf.Offset(2), 0), + (1, pdf.Offset(3), 0), + (2, 6, 0), + (2, 6, 1), + (1, pdf.Offset(6), 0)); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal("five", Assert.IsType(document.Resolve(new CosReference(5, 0))).DecodeText()); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Members_of_one_object_stream_resolve_to_the_same_instances_from_concurrent_threads() + { + // Thread-safety contract (CLAUDE.md): concurrent reads of an unmutated document are safe and see one instance per object. + (int, string)[] members = [.. Enumerable.Range(4, 50).Select(number => (number, $"<< /N {number} >>"))]; + byte[] file = OneObjectStream(members); + using PdfDocument document = PdfDocument.Open(file); + + CosObject[][] seen = new CosObject[8][]; + Parallel.For(0, seen.Length, thread => + seen[thread] = [.. Enumerable.Range(4, 50).Select(number => document.Resolve(new CosReference(number, 0)))]); + + for (int index = 0; index < 50; index++) + { + Assert.All(seen, objects => Assert.Same(seen[0][index], objects[index])); + } + + Assert.Equal(new CosInteger(53), ((CosDictionary)seen[0][49])[new CosName("N")]); + Assert.Empty(document.Diagnostics); + } + + /// + /// Objects 1-3 as plain objects, the given members in object stream 100, and a cross-reference stream (101) with a type 2 entry + /// per member (at when given) and the given extra type 2 entries (object number, index). + /// + private static byte[] OneObjectStream( + (int Number, string Body)[] members, + string separator = "\n", + string? header = null, + int[]? indexes = null, + (int Number, int Index)[]? extraEntries = null, + string? count = null) + { + var entries = new List<(long, long, long)>(); + var numbers = new List(); + XrefStreamPdf pdf = new XrefStreamPdf().AddOnePage().AddObjectStream(100, members, separator, header, count); + for (int index = 0; index < members.Length; index++) + { + numbers.Add(members[index].Number); + entries.Add((2, 100, indexes?[index] ?? index)); + } + + foreach ((int number, int index) in extraEntries ?? []) + { + numbers.Add(number); + entries.Add((2, 100, index)); + } + + // One subsection for objects 1-3, one per member, one for the object stream itself. + var subsections = new System.Text.StringBuilder("1 3"); + var rows = new List<(long, long, long)> { (1, pdf.Offset(1), 0), (1, pdf.Offset(2), 0), (1, pdf.Offset(3), 0) }; + foreach ((int number, (long, long, long) entry) in numbers.Zip(entries)) + { + subsections.Append(System.Globalization.CultureInfo.InvariantCulture, $" {number} 1"); + rows.Add(entry); + } + + subsections.Append(" 100 1"); + rows.Add((1, pdf.Offset(100), 0)); + return pdf.Finish(101, $"/Size 102 /Index [{subsections}] /Root 1 0 R /W [1 2 1]", W121, [.. rows]); + } +} diff --git a/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs b/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs index 2ff2a840..d633c4c6 100644 --- a/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs +++ b/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs @@ -1,4 +1,3 @@ -using Broadside.Diagnostics; using Broadside.TestSupport; namespace Broadside.Tests.Document; @@ -9,20 +8,13 @@ namespace Broadside.Tests.Document; /// public class WellFormedCorpusTests { - /// Files whose only cross-reference section is a stream; issue #39 reads them and removes this list. - private static readonly string[] CrossReferenceStreamFiles = ["xref-stream.pdf", "object-stream.pdf", "png-predictor.pdf"]; - - internal static bool NeedsCrossReferenceStreams(string fileName) => CrossReferenceStreamFiles.Contains(fileName); - [Theory] [MemberData(nameof(Corpus.WellFormedFiles), MemberType = typeof(Corpus))] public void A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics(string fileName) { - Assert.SkipWhen(NeedsCrossReferenceStreams(fileName), "Needs cross-reference streams (#39)."); - using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName)); - int expectedPages = fileName is "page-tree-inherited.pdf" or "linearized.pdf" ? 2 : 1; + int expectedPages = fileName is "page-tree-inherited.pdf" or "linearized.pdf" or "linearized-xref-stream.pdf" ? 2 : 1; Assert.Equal(expectedPages, document.Pages.Count); foreach (PdfPage page in document.Pages) { @@ -32,16 +24,4 @@ public void A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics(str Assert.Empty(document.Diagnostics); } - - [Theory] - [InlineData("xref-stream.pdf")] - [InlineData("object-stream.pdf")] - [InlineData("png-predictor.pdf")] - public void A_file_with_only_a_cross_reference_stream_is_not_readable_yet(string fileName) - { - // Pins the boundary of this version: issue #39 turns this into a successful open and deletes the test. - DiagnosticException error = Assert.Throws(() => PdfDocument.Open(Corpus.Path(fileName))); - - Assert.Equal("XrefStreamUnsupported", error.Diagnostic.Code); - } } diff --git a/tests/Broadside.Tests/Document/XrefStreamPdf.cs b/tests/Broadside.Tests/Document/XrefStreamPdf.cs new file mode 100644 index 00000000..c9343ec2 --- /dev/null +++ b/tests/Broadside.Tests/Document/XrefStreamPdf.cs @@ -0,0 +1,117 @@ +using System.Globalization; +using System.Text; + +namespace Broadside.Tests.Document; + +/// +/// Builds a PDF 1.5 file in memory whose cross-reference information is a cross-reference stream (ISO 32000-2 §7.5.8), for tests +/// that need a variation the corpus does not have. Objects are written in the order they are added; gives the +/// offset of each, and writes the cross-reference stream from rows the test states field by field. +/// +internal sealed class XrefStreamPdf +{ + private readonly StringBuilder _text = new("%PDF-1.5\n"); + private readonly Dictionary _offsets = []; + + /// The catalog, page tree root and page every test file needs, as objects 1, 2 and 3. + public static readonly string[] OnePage = + [ + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>", + ]; + + /// Gets the offset the next object will be written at. + public int Position => _text.Length; + + /// Gets the offset object was written at. + public int Offset(int number) => _offsets[number]; + + /// Writes number 0 obj body endobj. + public XrefStreamPdf Add(int number, string body, int generation = 0) + { + _offsets[number] = _text.Length; + _text.Append(CultureInfo.InvariantCulture, $"{number} {generation} obj\n{body}\nendobj\n"); + return this; + } + + /// Writes objects 1, 2 and 3 of . + public XrefStreamPdf AddOnePage() + { + for (int index = 0; index < OnePage.Length; index++) + { + Add(index + 1, OnePage[index]); + } + + return this; + } + + /// + /// Writes an object stream (§7.5.7) holding , each followed by . The header + /// pairs come from when given, else from the members in order; N is + /// when given, else the number of members. + /// + public XrefStreamPdf AddObjectStream(int number, (int Number, string Body)[] members, string separator = "\n", string? header = null, string? count = null) + { + var pairs = new StringBuilder(); + var data = new StringBuilder(); + foreach ((int member, string body) in members) + { + pairs.Append(CultureInfo.InvariantCulture, $"{member} {data.Length} "); + data.Append(body).Append(separator); + } + + string head = header ?? pairs.ToString(); + string content = head + data; + return Add(number, $"<< /Type /ObjStm /N {count ?? members.Length.ToString(CultureInfo.InvariantCulture)} /First {head.Length} /Length {content.Length} >>\nstream\n{content}\nendstream"); + } + + /// Writes raw text, such as a classic section. + public XrefStreamPdf Raw(string text) + { + _text.Append(text); + return this; + } + + /// + /// Writes the cross-reference stream as object with in its dictionary (which + /// must state W), its data the rows encoded big-endian with , then startxref and %%EOF. + /// + public byte[] Finish(int number, string entries, int[] widths, params (long Type, long Field2, long Field3)[] rows) + { + byte[] data = Rows(widths, rows); + return Finish(number, entries, data); + } + + /// Writes the cross-reference stream with the given raw data, then startxref and %%EOF. + public byte[] Finish(int number, string entries, byte[] data) + { + int start = _text.Length; + _text.Append(CultureInfo.InvariantCulture, $"{number} 0 obj\n<< /Type /XRef {entries} /Length {data.Length} >>\nstream\n"); + _text.Append(Encoding.Latin1.GetString(data)); + _text.Append(CultureInfo.InvariantCulture, $"\nendstream\nendobj\nstartxref\n{start}\n%%EOF\n"); + return Encoding.Latin1.GetBytes(_text.ToString()); + } + + /// Encodes rows of three fields big-endian, each field in its width; a width of 0 omits the field. + public static byte[] Rows(int[] widths, params (long Type, long Field2, long Field3)[] rows) + { + var bytes = new List(); + foreach ((long type, long field2, long field3) in rows) + { + Append(bytes, type, widths[0]); + Append(bytes, field2, widths[1]); + Append(bytes, field3, widths[2]); + } + + return [.. bytes]; + } + + private static void Append(List bytes, long value, int width) + { + for (int shift = (width - 1) * 8; shift >= 0; shift -= 8) + { + bytes.Add((byte)(value >> shift)); + } + } +} diff --git a/tests/Broadside.Tests/Filters/CorpusFilterTests.cs b/tests/Broadside.Tests/Filters/CorpusFilterTests.cs index fa075eca..d9d4f34e 100644 --- a/tests/Broadside.Tests/Filters/CorpusFilterTests.cs +++ b/tests/Broadside.Tests/Filters/CorpusFilterTests.cs @@ -49,7 +49,6 @@ public void Decoding_into_a_buffer_writer_gives_the_same_bytes(string fileName, [MemberData(nameof(Corpus.WellFormedFiles), MemberType = typeof(Corpus))] public void Every_page_content_stream_of_a_well_formed_file_decodes_with_no_diagnostics(string fileName) { - Assert.SkipWhen(Document.WellFormedCorpusTests.NeedsCrossReferenceStreams(fileName), "Needs cross-reference streams (#39)."); Assert.SkipWhen(fileName.StartsWith("encrypted-", StringComparison.Ordinal), "Needs decryption (#42)."); using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName)); diff --git a/tests/Broadside.Tests/Hosting/DependencyInjectionTests.cs b/tests/Broadside.Tests/Hosting/DependencyInjectionTests.cs index 9d14fcae..4e369c5a 100644 --- a/tests/Broadside.Tests/Hosting/DependencyInjectionTests.cs +++ b/tests/Broadside.Tests/Hosting/DependencyInjectionTests.cs @@ -20,7 +20,6 @@ public class DependencyInjectionTests [MemberData(nameof(Corpus.WellFormedFiles), MemberType = typeof(Corpus))] public void The_registered_engine_and_the_static_entry_point_open_documents_identically(string fileName) { - Assert.SkipWhen(WellFormedCorpusTests.NeedsCrossReferenceStreams(fileName), "Needs cross-reference streams (#39)."); using ServiceProvider services = new ServiceCollection().AddBroadside().BuildServiceProvider(); using PdfDocument fromContainer = services.GetRequiredService().Open(Corpus.Bytes(fileName)); diff --git a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt index 26965c93..9bdfc25e 100644 --- a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt +++ b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt @@ -13,6 +13,7 @@ hybrid-xref.pdf, incremental-update.pdf, inline-image.pdf, + linearized-xref-stream.pdf, linearized.pdf, lzw-stream.pdf, metadata-xmp.pdf, diff --git a/tests/Corpus/README.md b/tests/Corpus/README.md index 690e53a2..792a46b6 100644 --- a/tests/Corpus/README.md +++ b/tests/Corpus/README.md @@ -11,14 +11,16 @@ python3 -I tests/Corpus/generate.py /tmp/out # or into another directory The script uses only the standard library. It computes cross-reference offsets and stream lengths, and it implements the codecs and ciphers the corpus needs (LZW, ASCII85, ASCIIHex, RunLength, PNG predictor, RC4, AES-128/256, the standard security handler algorithms of ISO 32000-2 clause 7.6.4). It is deterministic: the values the specification asks a writer to draw from a random source (file identifiers, AES initialization vectors, R6 salts and file key) are fixed constants derived from the file name, so regenerating the corpus produces byte-identical files and `git diff` shows exactly what a change to the script did. A real writer must use a cryptographically secure random source for those values; the corpus trades that for reproducibility. -The exception is `linearized.pdf`: writing hint tables by hand is a project of its own, so the file is qpdf's output, checked in as a binary. It is regenerated, byte for byte with the same qpdf version, from `page-tree-inherited.pdf`: +The exceptions are the two linearized files: writing hint tables by hand is a project of its own, so each is qpdf's output, checked in as a binary. They are regenerated, byte for byte with the same qpdf version, from `page-tree-inherited.pdf`: ```sh qpdf --linearize --deterministic-id --object-streams=disable --compress-streams=n \ - tests/Corpus/page-tree-inherited.pdf tests/Corpus/linearized.pdf # qpdf 12.4.2 + tests/Corpus/page-tree-inherited.pdf tests/Corpus/linearized.pdf # qpdf 12.4.2 +qpdf --linearize --deterministic-id --object-streams=generate --compress-streams=n \ + tests/Corpus/page-tree-inherited.pdf tests/Corpus/linearized-xref-stream.pdf # qpdf 12.4.2 ``` -`--object-streams=disable` keeps classic cross-reference tables (no cross-reference streams) and `--compress-streams=n` leaves the hint stream unfiltered, so the file reads without either. `generate.py` does not write or delete it. +`--object-streams=disable` keeps classic cross-reference tables (no cross-reference streams); `--object-streams=generate` writes cross-reference streams and one object stream instead. `--compress-streams=n` leaves every stream, the hint stream and the cross-reference streams included, unfiltered. `generate.py` does not write or delete either file. `generate.py` self-tests its codecs against known answers before writing anything (the LZW example in clause 7.4.4.2, FIPS-197 AES vectors, an RC4 vector). @@ -39,6 +41,7 @@ Verification was run with qpdf 12.4.2 (`qpdf --check`), poppler (`pdfinfo`, `pdf | `incremental-update.pdf` | `empty-page.pdf` followed by one update section that replaces object 3 with an A4 `/MediaBox`; update trailer carries `/Prev`. | 7.5.6 | `pdfinfo` shows `595 x 842 pts (A4)` | clean | | `hybrid-xref.pdf` | Classic table for objects 1-3 (4-6 listed free), then an object stream (5) holding the `/Info` dictionary (4), a cross-reference stream (6, `/Index [4 3]`) describing it, and an empty update section whose trailer has `/Prev` and `/XRefStm`. Each section ends with `startxref` and `%%EOF` (7.5.6), so the file has two revisions. Mirrors the example in 7.5.8.4. A reader that follows `/XRefStm` sees the title; one that does not sees no `/Info`. | 7.5.8.4 Table 19 | `pdfinfo` shows `Title: hybrid` | clean | | `linearized.pdf` | `page-tree-inherited.pdf` linearized by qpdf 12.4.2 (command above): linearization parameter dictionary (object 5, `/L 1627 /H [590 130] /O 8 /E 1079 /N 2 /T 1409`), first-page cross-reference section for objects 5-12 whose trailer `/Prev` points forward to the main section (objects 0-4), unfiltered primary hint stream (object 7, `/S 44`), inherited attributes pushed down to the pages. Two Letter pages. | F.3, F.3.3, F.3.4, F.4.1-F.4.3 | `qpdf --check` (`File is linearized`), `qpdf --check-linearization` (`no linearization errors`), `qpdf --show-linearization`; `pdfinfo` shows `Optimized: yes`, 2 Letter pages; `pdftotext` prints `Page 1` and `Page 2` | clean; hint tables per `qpdf --show-linearization`: page 0 = 5 objects from 8, 359 bytes at 720, no shared references; page 1 = 2 objects from 1, 184 bytes at 1079, shared groups 2, 3, 4; shared groups 0-4 = objects 8-12, one each, lengths 98, 86, 98, 32, 45 from 720 | +| `linearized-xref-stream.pdf` | `page-tree-inherited.pdf` linearized by qpdf 12.4.2 with object streams (command above): linearization parameter dictionary (object 4, `/L 1661 /H [575 133] /O 8 /E 1260 /N 2 /T 1444`), first-page cross-reference stream (object 5, `/Index [4 12]`, `/W [1 2 1]`) whose `/Prev` points forward to the main cross-reference stream (object 3, objects 0-3), objects 13-15 stored in object stream 10 (type 2 entries), unfiltered hint stream (object 7, `/S 46`). Two Letter pages. | F.3, F.3.4, 7.5.7, 7.5.8 | `qpdf --check` (`File is linearized`), `qpdf --check-linearization` (`no linearization errors`), `qpdf --show-xref` (13-15 `compressed; stream = 10`); `pdfinfo` shows `Optimized: yes`, 2 Letter pages; `pdftotext` prints `Page 1` and `Page 2` | clean | | `flate-stream.pdf` | Content stream with `/Filter /FlateDecode`. | 7.4.4 | `pdftotext` prints `FlateDecode` | clean | | `lzw-stream.pdf` | Content stream with `/Filter /LZWDecode`, `EarlyChange` 1 (default), clear code first, EOD last. | 7.4.4.2, Table 8 | `pdftotext` prints `LZWDecode` | clean | | `ascii85-stream.pdf` | Content stream with `/Filter /ASCII85Decode`, `~>` terminator. | 7.4.3 | `pdftotext` prints `ASCII85Decode` | clean | diff --git a/tests/Corpus/linearized-xref-stream.pdf b/tests/Corpus/linearized-xref-stream.pdf new file mode 100644 index 0000000000000000000000000000000000000000..b91dac9f920ad1d023a5965d76adfa04863927c3 GIT binary patch literal 1661 zcmc&!&2G~`5MHP0p_UM@FdQP_0QNdgoJds){fVf6CQ2-U6!ox)H>s=EMz&iOBqUyd zX8aUh5CVZ%Wj5aR?s&d$X1-c~yL*e@_RQM(mp5Ncmu!m1 zhvxb^Sr5WUiX?m{1L9Z_Z#MCNk4Dt+8pP{$+9#_=EwXlqJ58IcJ#xtMiMy^#osKD^ zK>4EoFw8~?i2wA7B$8HqJGiA<6tW4Ugy^*_7!t!mPm1I z8tf`F*e7OGuD~{6ADOXo9rm0V)mN}{R$-osTuCNs>svq9HVD=uvTpFu*R>l~y zwQDb5-(d%A8Dy&z#8w<-GRjhF>%bq%AQYSN8F8*R`Xa%5WKk~%GL27?iGu3r9Sv2% zFX2?)3TEaA>t%$SK3QE9lS}@TJcm5nCO@DXxf_0y{6pIDm$Jj{l3V@V-uQ5s9beGs z;0W5P4)0--BJ5U));u`?f_mimaXW9@t@s4^(1`cLAXO!hbRnD=G)* z2sPtILDoVQ=*pNo*c7Skf^!IiJUW$GI1$i;Xc7luG((St(cLHwFE@rK<1BAS6%6D= z$CP`}im_O~dDay1BZOpA6G`&gXwX7i@}w1s$-O94$OH&c7&@I&5*4iC>_wf-v;LRr zM0qPd@!NIc{H#tC{e@Re*n*fTX<87oT(De-+CR`F)r>~ Date: Fri, 9 Oct 2026 14:11:00 -0500 Subject: [PATCH 009/152] fix(cos): XRefStm entries replace free entries of their own table (#39) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ISO 32000-2 §7.5.8.4: "A PDF reader shall look in the cross-reference stream first, find the object there, and shall ignore the free entry"; the NOTE places the free entry only typically in a previous section. A free entry in a hybrid table now gives way to its XRefStm stream's entry for the same number; an in-use table entry still wins. Co-Authored-By: Claude Opus 5.5 --- docs/conformance/iso-32000-2.md | 2 +- src/Broadside/Parsing/CrossReference.cs | 20 ++++++++-- src/Broadside/Parsing/CrossReferenceReader.cs | 3 +- .../Document/HybridFileTests.cs | 39 ++++++++++++------- 4 files changed, 46 insertions(+), 18 deletions(-) diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index fb3f59f9..4db34fed 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -36,7 +36,7 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.5.5 | File trailer | partial | `CrossReferenceReader`, `CrossReference`, `PdfDocument` | `Broadside.Tests.Document.FileStructureTests.A_startxref_offset_on_the_white_space_before_xref_is_repaired_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_file_with_no_startxref_cannot_be_read_even_leniently`, `Broadside.Tests.Document.FileStructureTests.A_trailer_without_root_cannot_be_read`, `Broadside.Tests.Document.FileStructureTests.A_prev_chain_that_loops_ends_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic` | Last startxref, Prev chain with loop guard, Root; trailer merged newest-first; ignoring entries beyond Size, startxref recovery and trailer reconstruction are #41; Encrypt is #42 | | 7.5.6 | Incremental updates | done | `CrossReference`, `RevisionReader`, `PdfRevision`, `PdfDocument` | `Broadside.Tests.Document.IncrementalUpdateTests.An_updated_file_has_one_revision_per_update_and_the_first_is_the_original_file`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_is_the_file_as_it_was_after_that_save`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_has_its_own_trailer`, `Broadside.Tests.Document.IncrementalUpdateTests.A_hybrid_file_has_its_main_section_and_its_update_section_as_two_revisions`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_earlier_revision_without_its_end_of_file_marker_ends_after_its_startxref_offset_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev` | Revisions oldest first, each the byte prefix up to its %%EOF and end-of-line; newest section decides per object number, free hides older copies, a reference must match the live generation; Root, Info, Encrypt and ID missing from the newest trailer are taken from an older one with TrailerEntryFromOlderRevision; a linearized pair is one revision; a hybrid XRefStm stream joins its table's revision; writing updates is #44 | | 7.5.7 | Object streams | done | `ObjectStream`, `ObjectLoader` | `Broadside.Tests.Document.ObjectStreamTests.The_catalog_page_tree_and_page_resolve_from_an_object_stream`, `Broadside.Tests.Document.ObjectStreamTests.A_reference_to_a_member_with_a_generation_other_than_0_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.Members_need_no_white_space_between_them`, `Broadside.Tests.Document.ObjectStreamTests.A_member_at_another_index_than_its_entry_says_is_found_by_its_object_number`, `Broadside.Tests.Document.ObjectStreamTests.Offsets_out_of_order_bound_each_member_by_the_next_offset_in_sorted_order`, `Broadside.Tests.Document.ObjectStreamTests.A_member_the_object_stream_does_not_hold_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_whose_N_is_one_of_its_own_members_resolves_its_members_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_listed_as_compressed_itself_is_not_read`, `Broadside.Tests.Document.ObjectStreamTests.A_type_2_entry_naming_an_object_that_is_not_a_stream_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.A_flate_encoded_object_stream_is_decoded_through_the_filters`, `Broadside.Tests.Document.ObjectStreamTests.Members_of_one_object_stream_resolve_to_the_same_instances_from_concurrent_threads`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file` | Members located by type 2 entries (index checked against the header, searched by number when wrong, with ObjectStreamIndexMismatch); each member parsed over exactly the bytes up to the next offset (NOTE 7); out-of-order offsets sorted; container decoded once per document and shared, decrypted as a whole (members skip hooks 1 and 2); nested containers and self-referencing N/First/Filter end with ObjectStreamNested/ObjectStreamCycle; /Extends ignored (grouping only); object-stream.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `object-stream`; writing is #44 | -| 7.5.8 | Cross-reference streams | done | `XrefStreamReader`, `CrossReferenceReader`, `CrossReference` | `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file`, `Broadside.Tests.Document.CrossReferenceStreamTests.Strict_mode_opens_a_file_with_compressed_structures`, `Broadside.Tests.Document.CrossReferenceStreamTests.The_trailer_of_a_cross_reference_stream_is_its_dictionary_without_the_entries_that_describe_the_stream`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_type_field_makes_every_entry_type_1`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_generation_field_defaults_to_generation_0`, `Broadside.Tests.Document.CrossReferenceStreamTests.Index_with_two_subsections_numbers_the_entries_of_each_from_its_first_object_number`, `Broadside.Tests.Document.CrossReferenceStreamTests.Wide_fields_are_read_big_endian`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_entry_of_an_unknown_type_is_a_reference_to_the_null_object`, `Broadside.Tests.Document.CrossReferenceStreamTests.Data_shorter_than_the_entries_ends_the_section_where_the_data_ends`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_without_type_XRef_is_read_with_a_diagnostic`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_whose_W_cannot_be_read_is_not_a_cross_reference_section`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_update_written_as_a_cross_reference_stream_overrides_the_original_section`, `Broadside.Tests.Document.HybridFileTests.An_object_only_the_XRefStm_stream_lists_is_found`, `Broadside.Tests.Document.HybridFileTests.The_table_of_a_section_takes_precedence_over_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.The_XRefStm_streams_dictionary_is_not_the_trailer_and_its_Prev_is_not_followed`, `Broadside.Tests.Document.HybridFileTests.An_XRefStm_offset_that_names_no_stream_is_reported_and_the_table_is_still_read`, `Broadside.Tests.Document.LinearizationTests.A_linearized_file_with_cross_reference_streams_has_its_first_page_and_main_streams_as_one_revision` | 7.5.8.1 to 7.5.8.4. W (0 to 8 bytes per field, W[0] = 0 means type 1), Index (default [0 Size]), Size, Prev; entries big-endian into long; type 0/1/2, other types are the null object; dictionary minus Type, Length, W, Index, Filter, DecodeParms, DL, F, FFilter, FDecodeParms is the trailer; data decoded through the filter pipeline under the engine's decoded-length limit, never decrypted; hybrid XRefStm read after its table and before Prev, its own Prev not followed and its dictionary not a trailer; xref-stream.pdf, object-stream.pdf, png-predictor.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `xref-stream`; writing is #44 | +| 7.5.8 | Cross-reference streams | done | `XrefStreamReader`, `CrossReferenceReader`, `CrossReference` | `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file`, `Broadside.Tests.Document.CrossReferenceStreamTests.Strict_mode_opens_a_file_with_compressed_structures`, `Broadside.Tests.Document.CrossReferenceStreamTests.The_trailer_of_a_cross_reference_stream_is_its_dictionary_without_the_entries_that_describe_the_stream`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_type_field_makes_every_entry_type_1`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_generation_field_defaults_to_generation_0`, `Broadside.Tests.Document.CrossReferenceStreamTests.Index_with_two_subsections_numbers_the_entries_of_each_from_its_first_object_number`, `Broadside.Tests.Document.CrossReferenceStreamTests.Wide_fields_are_read_big_endian`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_entry_of_an_unknown_type_is_a_reference_to_the_null_object`, `Broadside.Tests.Document.CrossReferenceStreamTests.Data_shorter_than_the_entries_ends_the_section_where_the_data_ends`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_without_type_XRef_is_read_with_a_diagnostic`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_whose_W_cannot_be_read_is_not_a_cross_reference_section`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_update_written_as_a_cross_reference_stream_overrides_the_original_section`, `Broadside.Tests.Document.HybridFileTests.An_object_only_the_XRefStm_stream_lists_is_found`, `Broadside.Tests.Document.HybridFileTests.An_in_use_entry_in_the_table_of_a_section_takes_precedence_over_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.A_free_entry_in_the_table_of_a_section_gives_way_to_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.The_XRefStm_streams_dictionary_is_not_the_trailer_and_its_Prev_is_not_followed`, `Broadside.Tests.Document.HybridFileTests.An_XRefStm_offset_that_names_no_stream_is_reported_and_the_table_is_still_read`, `Broadside.Tests.Document.LinearizationTests.A_linearized_file_with_cross_reference_streams_has_its_first_page_and_main_streams_as_one_revision` | 7.5.8.1 to 7.5.8.4. W (0 to 8 bytes per field, W[0] = 0 means type 1), Index (default [0 Size]), Size, Prev; entries big-endian into long; type 0/1/2, other types are the null object; dictionary minus Type, Length, W, Index, Filter, DecodeParms, DL, F, FFilter, FDecodeParms is the trailer; data decoded through the filter pipeline under the engine's decoded-length limit, never decrypted; hybrid XRefStm read after its table and before Prev, its entries replacing the table's free entries (an in-use table entry wins), its own Prev not followed and its dictionary not a trailer; xref-stream.pdf, object-stream.pdf, png-predictor.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `xref-stream`; writing is #44 | | 7.6 | Encryption | not started | | | | | 7.7.1 | General | n/a | | | Introductory text | | 7.7.2 | Document catalog dictionary | partial | `PdfDocument`, `PdfVersion` | `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_catalog_version_written_as_a_number_is_read_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.A_malformed_catalog_version_is_ignored_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_catalog_without_its_type_is_read_with_a_diagnostic` | Type, Version (effective version = later of header and catalog) and Pages; the other Table 29 entries arrive with their features (outlines, names, AcroForm, ...) | diff --git a/src/Broadside/Parsing/CrossReference.cs b/src/Broadside/Parsing/CrossReference.cs index c1cbca9f..a12a526f 100644 --- a/src/Broadside/Parsing/CrossReference.cs +++ b/src/Broadside/Parsing/CrossReference.cs @@ -73,7 +73,8 @@ internal sealed record XrefSection(long Offset, long End, XrefSectionKind Kind, /// /// /// ISO 32000-2 §7.5.4, §7.5.5 and §7.5.6. Lookup is newest first, first write wins: an object number takes its entry from the most -/// recent section that lists it. The trailer is the newest section's, with keys only an older trailer has filled in (a lenient +/// recent section that lists it; a hybrid table's free entry gives way to its own XRefStm stream's entry (§7.5.8.4), which +/// otherwise comes after the table and before older sections. The trailer is the newest section's, with keys only an older trailer has filled in (a lenient /// fallback; §7.5.6 says each update's trailer repeats them). /// internal sealed class CrossReference @@ -91,11 +92,24 @@ public CrossReference(IReadOnlyList sections) var inherited = new List(); for (int revision = Revisions.Count - 1; revision >= 0; revision--) { - foreach (XrefSection section in Revisions[revision].Sections) + IReadOnlyList revisionSections = Revisions[revision].Sections; + for (int index = 0; index < revisionSections.Count; index++) { + XrefSection section = revisionSections[index]; + XrefSection? hybridStream = section.XRefStreamOffset is { } streamOffset + && index + 1 < revisionSections.Count + && revisionSections[index + 1].Offset == streamOffset + ? revisionSections[index + 1] + : null; foreach ((int number, XrefEntry entry) in section.Entries) { - _merged.TryAdd(number, entry); + // §7.5.8.4: a free table entry is the pre-1.5 marker of an object the section's XRefStm stream defines, and + // "a PDF reader shall look in the cross-reference stream first"; an in-use table entry still wins. + XrefEntry effective = entry.Kind == XrefEntryKind.Free && hybridStream is not null + && hybridStream.Entries.TryGetValue(number, out XrefEntry fromStream) + ? fromStream + : entry; + _merged.TryAdd(number, effective); } foreach (KeyValuePair entry in section.Trailer) diff --git a/src/Broadside/Parsing/CrossReferenceReader.cs b/src/Broadside/Parsing/CrossReferenceReader.cs index 5550d247..aa5e6631 100644 --- a/src/Broadside/Parsing/CrossReferenceReader.cs +++ b/src/Broadside/Parsing/CrossReferenceReader.cs @@ -17,7 +17,8 @@ namespace Broadside.Parsing; /// /// /// Hybrid files (§7.5.8.4): a table whose trailer has XRefStm is followed, in , by the -/// cross-reference stream it names, so lookup consults the table, then that stream, then the older sections. The stream's own +/// cross-reference stream it names, so lookup consults the table, then that stream, then the older sections; a free entry in the +/// table gives way to the stream's entry for the same number ("A PDF reader shall look in the cross-reference stream first"). The stream's own /// Prev is not followed ("not meaningful in hybrid-reference files", Table 17) and its dictionary is not a trailer. /// /// diff --git a/tests/Broadside.Tests/Document/HybridFileTests.cs b/tests/Broadside.Tests/Document/HybridFileTests.cs index c1985bc1..87342b5c 100644 --- a/tests/Broadside.Tests/Document/HybridFileTests.cs +++ b/tests/Broadside.Tests/Document/HybridFileTests.cs @@ -24,10 +24,10 @@ public void An_object_only_the_XRefStm_stream_lists_is_found() } [Fact] - public void The_table_of_a_section_takes_precedence_over_its_XRefStm_stream() + public void An_in_use_entry_in_the_table_of_a_section_takes_precedence_over_its_XRefStm_stream() { - // §7.5.8.4: the stream is searched only for entries the table does not have. - byte[] file = Hybrid(tableHasObject4: true, streamEntries: string.Empty); + // §7.5.8.4: the stream is searched for an object the table does not define; an in-use table entry defines it. + byte[] file = Hybrid(object4InTable: "in use", streamEntries: string.Empty); using PdfDocument document = PdfDocument.Open(file); @@ -36,11 +36,25 @@ public void The_table_of_a_section_takes_precedence_over_its_XRefStm_stream() Assert.Empty(document.Diagnostics); } + [Fact] + public void A_free_entry_in_the_table_of_a_section_gives_way_to_its_XRefStm_stream() + { + // §7.5.8.4: "A PDF reader shall look in the cross-reference stream first, find the object there, and shall ignore the free + // entry"; the NOTE puts the free entry only typically in a previous section, so a free entry in the same table yields too. + byte[] file = Hybrid(object4InTable: "free", streamEntries: string.Empty); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal("stream", Assert.IsType(document.Resolve(new CosReference(4, 0))).DecodeText()); + Assert.Single(document.Pages); + Assert.Empty(document.Diagnostics); + } + [Fact] public void The_XRefStm_streams_dictionary_is_not_the_trailer_and_its_Prev_is_not_followed() { // Table 17: Prev in an XRefStm stream is "not meaningful in hybrid-reference files"; Root comes from the table's trailer. - byte[] file = Hybrid(tableHasObject4: false, streamEntries: "/Prev 999999 /Root 3 0 R /Info 4 0 R"); + byte[] file = Hybrid(object4InTable: null, streamEntries: "/Prev 999999 /Root 3 0 R /Info 4 0 R"); using PdfDocument document = PdfDocument.Open(file); @@ -53,7 +67,7 @@ public void The_XRefStm_streams_dictionary_is_not_the_trailer_and_its_Prev_is_no [Fact] public void An_XRefStm_offset_that_names_no_stream_is_reported_and_the_table_is_still_read() { - byte[] file = Hybrid(tableHasObject4: false, streamEntries: string.Empty, xrefStm: "13"); + byte[] file = Hybrid(object4InTable: null, streamEntries: string.Empty, xrefStm: "13"); using PdfDocument document = PdfDocument.Open(file); @@ -63,11 +77,11 @@ public void An_XRefStm_offset_that_names_no_stream_is_reported_and_the_table_is_ } /// - /// One section: objects 1-3 (and 4, "(table)", when ) in the classic table, which lists nothing - /// else, object stream 5 - /// holding 4 as "(stream)", and cross-reference stream 6 for 4-6 named by the trailer's XRefStm (or by ). + /// One section: objects 1-3 in the classic table, and object 4 listed there as says ("in use", + /// written as "(table)"; "free"; or not listed when ); object stream 5 holding 4 as "(stream)"; and + /// cross-reference stream 6 for 4-6 named by the trailer's XRefStm (or by ). /// - private static byte[] Hybrid(bool tableHasObject4, string streamEntries, string? xrefStm = null) + private static byte[] Hybrid(string? object4InTable, string streamEntries, string? xrefStm = null) { var text = new StringBuilder("%PDF-1.5\n"); var offsets = new Dictionary(); @@ -82,7 +96,7 @@ void Add(int number, string body) Add(index + 1, XrefStreamPdf.OnePage[index]); } - if (tableHasObject4) + if (object4InTable == "in use") { Add(4, "(table)"); } @@ -93,12 +107,11 @@ void Add(int number, string body) text.Append(CultureInfo.InvariantCulture, $"6 0 obj\n<< /Type /XRef /Size 7 /Index [4 3] /W [1 2 1] {streamEntries} /Length {rows.Length} >>\nstream\n"); text.Append(Encoding.Latin1.GetString(rows)).Append("\nendstream\nendobj\n"); int table = text.Length; - // The table lists only the objects it holds: a free entry for 4 would be found in the table and hide the stream's (§7.5.8.4). - int listed = tableHasObject4 ? 4 : 3; + int listed = object4InTable is null ? 3 : 4; text.Append(CultureInfo.InvariantCulture, $"xref\n0 {listed + 1}\n0000000000 65535 f \n"); for (int number = 1; number <= listed; number++) { - text.Append(CultureInfo.InvariantCulture, $"{offsets[number]:D10} 00000 n \n"); + text.Append(offsets.TryGetValue(number, out int offset) ? $"{offset:D10} 00000 n \n" : "0000000000 00001 f \n"); } text.Append(CultureInfo.InvariantCulture, $"trailer\n<< /Size 7 /Root 1 0 R /XRefStm {xrefStm ?? stream.ToString(CultureInfo.InvariantCulture)} >>\nstartxref\n{table}\n%%EOF\n"); From 7066aaed0a831bcc41126a7bbadb9965ab51b7d6 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:33:39 -0500 Subject: [PATCH 010/152] feat(cos): lenient repair with diagnostics; strict mode throws (#41) Damaged files open and say what was repaired (ADR 0005, ISO 32000-2 7.5): - One windowed scan of the file (FileScan) finds object headers, xref and trailer keywords and /XRef, /ObjStm, /Catalog names, linearly and without materializing the file. - A startxref or Prev offset at neither xref nor N G obj reads the nearest section (table wins ties, never one already read). - An entry whose offset does not hold its object is searched near the offset, then in the whole-file scan (XrefEntryOffsetInvalid, Warning when found, Error when not). - Missing or unusable startxref, or a Root that does not lead to the catalog, rebuilds the cross-reference from the scan: newest copy of each object, object stream members indexed, newest trailer whose Root leads to a catalog (Encrypt/ID/Info from any trailer), else the newest /Catalog (TrailerMissing / RootMissing); no catalog -> CatalogNotFound. - Stream lengths that refer to each other no longer loop; a stream without endstream ends at endobj. - Classic tables: entries not 20 bytes long reported once per section; a subsection numbered from 1 starting with the free-list head is renumbered from 0. Diagnostic model: DiagnosticSeverity gains Information (never thrown, logged at Information); strict mode throws Warning and Error. The sink records each repair once (same code, offset and object) and offers ReportOnce (one per code per object) for hot paths. The five broken corpus files record exactly the diagnostics now listed in tests/Corpus/README.md; wrong-stream-length.pdf recovers 46 bytes (the EOL before endstream is not data, 7.3.8.1). New fuzz target `repair`, benchmarks RepairBenchmarks and ReconstructionBenchmarks. Co-Authored-By: Claude Opus 5.5 --- .../ReconstructionBenchmarks.cs | 50 +++ .../Broadside.Benchmarks/RepairBenchmarks.cs | 30 ++ docs/conformance/iso-32000-2.md | 14 +- src/Broadside/Diagnostics/Diagnostic.cs | 17 +- src/Broadside/Diagnostics/DiagnosticLog.cs | 7 +- .../Diagnostics/DiagnosticSeverity.cs | 15 +- src/Broadside/Objects/CosParser.cs | 8 + src/Broadside/Objects/CosRepair.cs | 4 +- src/Broadside/Parsing/CrossReference.cs | 6 + src/Broadside/Parsing/CrossReferenceReader.cs | 98 ++++- .../Parsing/CrossReferenceReconstructor.cs | 298 ++++++++++++++++ src/Broadside/Parsing/DiagnosticCodes.cs | 10 +- src/Broadside/Parsing/DiagnosticSink.cs | 85 ++++- src/Broadside/Parsing/FileHeader.cs | 3 +- src/Broadside/Parsing/FileScan.cs | 336 ++++++++++++++++++ src/Broadside/Parsing/ObjectLoader.cs | 45 ++- src/Broadside/Parsing/ObjectLoaderHooks.cs | 38 +- src/Broadside/Parsing/RevisionReader.cs | 7 + src/Broadside/Parsing/XrefTableReader.cs | 53 ++- src/Broadside/PdfDocument.cs | 68 +++- src/Broadside/PublicAPI.Unshipped.txt | 5 +- tests/Broadside.Fuzz/FuzzTargets.cs | 53 +++ tests/Broadside.Fuzz/README.md | 2 +- .../Document/BrokenCorpusTests.cs | 81 +++++ .../Document/CrossReferenceStreamTests.cs | 9 +- .../Document/DiagnosticModelTests.cs | 89 +++++ .../Document/FileStructureTests.cs | 50 ++- tests/Broadside.Tests/Document/RepairTests.cs | 188 ++++++++++ tests/Corpus/README.md | 12 +- 29 files changed, 1589 insertions(+), 92 deletions(-) create mode 100644 bench/Broadside.Benchmarks/ReconstructionBenchmarks.cs create mode 100644 bench/Broadside.Benchmarks/RepairBenchmarks.cs create mode 100644 src/Broadside/Parsing/CrossReferenceReconstructor.cs create mode 100644 src/Broadside/Parsing/FileScan.cs create mode 100644 tests/Broadside.Tests/Document/BrokenCorpusTests.cs create mode 100644 tests/Broadside.Tests/Document/DiagnosticModelTests.cs create mode 100644 tests/Broadside.Tests/Document/RepairTests.cs diff --git a/bench/Broadside.Benchmarks/ReconstructionBenchmarks.cs b/bench/Broadside.Benchmarks/ReconstructionBenchmarks.cs new file mode 100644 index 00000000..f469028c --- /dev/null +++ b/bench/Broadside.Benchmarks/ReconstructionBenchmarks.cs @@ -0,0 +1,50 @@ +using System.Globalization; +using System.Text; +using BenchmarkDotNet.Attributes; +using Broadside.IO; +using Broadside.Parsing; + +namespace Broadside.Benchmarks; + +/// +/// Cross-reference reconstruction at scale (issue #41): the one-pass scan over a synthesized file of +/// objects with no cross-reference table, and a lenient open of that file, which rebuilds the table from the scan. The scan reads +/// the file in windows and allocates only for the positions it finds, so its Allocated grows with the number of objects, +/// not with the file length, and its time is linear in the file length. +/// +[MemoryDiagnoser] +public class ReconstructionBenchmarks +{ + /// How many objects the synthesized file holds. + public const int ObjectCount = 10_000; + + private byte[] _bytes = []; + + [GlobalSetup] + public void Setup() + { + var text = new StringBuilder("%PDF-1.7\n1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n"); + for (int number = 3; number < ObjectCount; number++) + { + text.Append(CultureInfo.InvariantCulture, $"{number} 0 obj\n<< /Index {number} /Data (some bytes of data in a string) >>\nendobj\n"); + } + + _bytes = Encoding.Latin1.GetBytes(text.Append("%%EOF\n").ToString()); + } + + /// Scans the file once for object headers and file-structure keywords. + [Benchmark] + public int Scan() + { + using PdfSource source = PdfSource.FromMemory(_bytes); + return FileScan.Run(source).Objects.Count; + } + + /// Opens the file, which has no cross-reference table, so the table is rebuilt from the scan. + [Benchmark] + public int OpenAndRebuild() + { + using PdfDocument document = PdfDocument.Open(_bytes); + return document.Diagnostics.Count; + } +} diff --git a/bench/Broadside.Benchmarks/RepairBenchmarks.cs b/bench/Broadside.Benchmarks/RepairBenchmarks.cs new file mode 100644 index 00000000..a7665cdb --- /dev/null +++ b/bench/Broadside.Benchmarks/RepairBenchmarks.cs @@ -0,0 +1,30 @@ +using BenchmarkDotNet.Attributes; +using Broadside.TestSupport; + +namespace Broadside.Benchmarks; + +/// +/// Lenient repair (ADR 0005, issue #41): opening each deliberately broken corpus file and walking its pages, which runs the repair +/// (object search, nearest section, reconstruction, stream length recovery). measures the +/// scan the reconstruction is built on at scale. +/// +[MemoryDiagnoser] +public class RepairBenchmarks +{ + private byte[] _bytes = []; + + /// The broken corpus file to open. + [Params("broken-xref-offsets.pdf", "missing-endobj.pdf", "wrong-stream-length.pdf", "no-xref.pdf", "startxref-wrong.pdf")] + public string File { get; set; } = ""; + + [GlobalSetup] + public void Setup() => _bytes = System.IO.File.ReadAllBytes(Path.Combine(CorpusLocator.CorpusDirectory, File)); + + /// Opens the broken file leniently and walks its pages. + [Benchmark] + public int OpenBrokenFile() + { + using PdfDocument document = PdfDocument.Open(_bytes); + return document.Pages.Count + document.Diagnostics.Count; + } +} diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index 4db34fed..d2cc0b1d 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -16,9 +16,9 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.3.5 | Name objects | done | `CosName` | `Broadside.Tests.Objects.StringAndNameParsingTests.Names_from_table_4_expand_number_sign_escapes`, `Broadside.Tests.Objects.StringAndNameParsingTests.Names_are_equal_when_their_expanded_bytes_are_equal`, `Broadside.Tests.Objects.SerializationTests.Names_escape_delimiters_white_space_number_signs_and_non_ascii_bytes` | | | 7.3.6 | Array objects | done | `CosArray` | `Broadside.Tests.Objects.ContainerParsingTests.Parses_the_array_example`, `Broadside.Tests.Objects.ContainerParsingTests.Arrays_nest_hold_references_and_keep_null_elements` | | | 7.3.7 | Dictionary objects | done | `CosDictionary` | `Broadside.Tests.Objects.ContainerParsingTests.Parses_the_dictionary_example`, `Broadside.Tests.Objects.ContainerParsingTests.A_null_valued_entry_is_the_same_as_an_absent_one` | Null-valued entries are never stored | -| 7.3.8 | Stream objects | partial | `CosStream` | `Broadside.Tests.Objects.ContainerParsingTests.A_stream_takes_its_data_from_its_length_or_from_endstream`, `Broadside.Tests.Objects.ContainerParsingTests.Streams_with_a_wrong_length_or_no_endstream_are_rejected`, `Broadside.Tests.Objects.CorpusObjectTests.The_metadata_stream_of_metadata_xmp_pdf_holds_its_declared_length` | Extent from a direct or indirect Length (`Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length`), else from endstream; filters decode through `PdfDocument.DecodeStream` (7.4) with DL as a capacity hint; external stream files (F, FFilter, FDecodeParms) are not read: `StreamExternalFileUnsupported` and the embedded bytes decode instead (`Broadside.Tests.Filters.FilterPipelineTests.Data_in_an_external_file_is_not_read_and_the_stream_bytes_decode_instead_with_a_diagnostic`) | +| 7.3.8 | Stream objects | partial | `CosStream`, `DefaultStreamExtentResolver` | `Broadside.Tests.Objects.ContainerParsingTests.A_stream_takes_its_data_from_its_length_or_from_endstream`, `Broadside.Tests.Objects.ContainerParsingTests.Streams_with_a_wrong_length_or_no_endstream_are_rejected`, `Broadside.Tests.Objects.CorpusObjectTests.The_metadata_stream_of_metadata_xmp_pdf_holds_its_declared_length`, `Broadside.Tests.Document.BrokenCorpusTests.A_wrong_stream_length_is_recovered_from_endstream_without_changing_the_length_entry`, `Broadside.Tests.Document.RepairTests.Stream_lengths_that_refer_to_each_other_are_recovered_from_endstream`, `Broadside.Tests.Document.RepairTests.A_stream_without_endstream_ends_at_endobj` | Extent from a direct or indirect Length (`Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length`), else from endstream; filters decode through `PdfDocument.DecodeStream` (7.4) with DL as a capacity hint; external stream files (F, FFilter, FDecodeParms) are not read: `StreamExternalFileUnsupported` and the embedded bytes decode instead (`Broadside.Tests.Filters.FilterPipelineTests.Data_in_an_external_file_is_not_read_and_the_stream_bytes_decode_instead_with_a_diagnostic`); a wrong, missing or unresolvable Length is recovered from endstream without the end-of-line before it (StreamLengthInvalid; the Length entry is not changed), lengths that refer to each other are unknown rather than looping, and a stream without endstream ends at endobj (EndstreamMissing) | | 7.3.9 | Null object | done | `CosNull` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_null_as_the_single_null_object`, `Broadside.Tests.Objects.ContainerParsingTests.A_null_valued_entry_is_the_same_as_an_absent_one` | | -| 7.3.10 | Indirect objects | done | `CosReference`, `PdfDocument` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_indirect_references`, `Broadside.Tests.Document.FileStructureTests.References_to_missing_free_or_other_generation_objects_resolve_to_null_without_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.An_object_without_endobj_is_read_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_reads_as_null_with_a_diagnostic` | `PdfDocument.Resolve`; references to missing, free or other-generation objects are null with no diagnostic; loading goes through the internal `ObjectLoader` (hooks for #41, #42, #45); a misplaced object reads as null until #41 searches for it | +| 7.3.10 | Indirect objects | done | `CosReference`, `PdfDocument`, `ObjectLoader`, `FileScan` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_indirect_references`, `Broadside.Tests.Document.FileStructureTests.References_to_missing_free_or_other_generation_objects_resolve_to_null_without_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.An_object_without_endobj_is_read_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_is_read_from_where_its_header_is_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.An_entry_for_an_object_the_file_does_not_hold_reads_as_null_with_an_error`, `Broadside.Tests.Document.BrokenCorpusTests.A_broken_file_opens_leniently_with_exactly_the_documented_diagnostics_and_the_intact_pages` | `PdfDocument.Resolve`; references to missing, free or other-generation objects are null with no diagnostic; loading goes through the internal `ObjectLoader` (hooks for #42, #45); an entry whose offset does not hold the object's header is searched near the offset, then in a scan of the whole file (newest copy), with XrefEntryOffsetInvalid (Warning when found, Error and null when not); a missing endobj ends the object at the next keyword (MissingEndobj); broken-xref-offsets.pdf, missing-endobj.pdf | | 7.4.1 | General | done | `IStreamFilter`, `FilterContext`, `StreamDecoder`, `FilterRegistry`, `PdfDocument`, `PdfOptions` | `Broadside.Tests.Filters.CorpusFilterTests.A_filtered_content_stream_decodes_to_the_bytes_that_were_encoded`, `Broadside.Tests.Filters.CorpusFilterTests.Every_page_content_stream_of_a_well_formed_file_decodes_with_no_diagnostics`, `Broadside.Tests.Filters.FilterPipelineTests.Filters_apply_in_array_order_and_the_same_filter_may_appear_twice`, `Broadside.Tests.Filters.FilterPipelineTests.Decode_parameters_align_with_the_filter_array_and_null_means_defaults`, `Broadside.Tests.Filters.FilterPipelineTests.Deviations_from_table_5_are_repaired_with_one_diagnostic`, `Broadside.Tests.Filters.FilterPipelineTests.An_unknown_filter_leaves_the_stream_readable_as_raw_bytes_with_a_diagnostic`, `Broadside.Tests.Filters.FilterPipelineTests.Output_beyond_the_decoded_length_limit_is_truncated_with_a_diagnostic`, `Broadside.Tests.Filters.FilterExtensionPointTests.A_decorator_registered_through_the_options_replaces_the_default_flate_filter`, `Broadside.Tests.Filters.FilterExtensionPointTests.Two_engines_in_one_process_keep_their_own_filters` | `PdfDocument.DecodeStream`; filter extension point `PdfOptions.UseFilter` (per engine, no static registry); unknown or not-yet-implemented filters stop the chain with `FilterUnsupported`; decoded-length limit `PdfOptions.WithMaxDecodedStreamLength`; fuzz targets `filter-*`, `document` decodes page contents; Table 92 abbreviations outside inline images read with a diagnostic | | 7.4.2 | ASCIIHexDecode filter | done | `AsciiHexDecodeFilter` | `Broadside.Tests.Filters.AsciiFilterTests.Ascii_hex_decodes_digit_pairs_ignores_white_space_and_pads_an_odd_final_digit`, `Broadside.Tests.Filters.AsciiFilterTests.Ascii_hex_skips_invalid_characters_with_one_diagnostic`, `Broadside.Tests.Filters.AsciiFilterTests.Ascii_hex_without_the_end_marker_decodes_to_its_end_with_a_diagnostic`, `Broadside.Tests.Filters.AsciiFilterTests.Both_filters_round_trip_the_encoders_of_the_corpus_generator` | Decode; `asciihex-stream.pdf`; `AsciiHexBenchmarks`; fuzz `filter-asciihex`; encoding is Phase 4 | | 7.4.3 | ASCII85Decode filter | done | `Ascii85DecodeFilter` | `Broadside.Tests.Filters.AsciiFilterTests.Ascii85_decodes_groups_z_partial_groups_and_ignores_white_space`, `Broadside.Tests.Filters.AsciiFilterTests.Ascii85_repairs_impossible_sequences_with_a_diagnostic`, `Broadside.Tests.Filters.AsciiFilterTests.Ascii85_without_the_end_marker_decodes_the_partial_group_with_a_diagnostic`, `Broadside.Tests.Filters.AsciiFilterTests.Strict_mode_throws_for_an_invalid_character` | Decode; `ascii85-stream.pdf`, `filter-chain.pdf`; `Ascii85Benchmarks`; fuzz `filter-ascii85`; encoding is Phase 4 | @@ -30,13 +30,13 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.4.9 | JPXDecode filter | not started | | | Phase 2B (#67, #68) | | 7.4.10 | Crypt filter | partial | `StreamDecoder`, `ICryptFilterHandler` | `Broadside.Tests.Filters.FilterPipelineTests.The_identity_crypt_filter_passes_the_data_through`, `Broadside.Tests.Filters.FilterPipelineTests.A_crypt_filter_the_security_handler_does_not_know_leaves_the_data_encrypted_with_a_diagnostic`, `Broadside.Tests.Filters.FilterPipelineTests.A_crypt_filter_that_is_not_first_is_applied_where_it_is_with_a_diagnostic` | Slot only: Identity passes through, other crypt filter names are `CryptFilterUnsupported` until the security handler (#42) sets `StreamDecoder.CryptFilter` | | 7.5.1 | General | done | `PdfDocument`, `CrossReferenceReader` | `Broadside.Tests.Document.OpenDocumentTests.A_file_opens_identically_from_a_path_a_stream_and_bytes_with_no_diagnostics`, `Broadside.Tests.Document.WellFormedCorpusTests.A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics` | Read from the end through startxref, the cross-reference table and the trailer, never serially; linearized files read through the same path (Annex F) | -| 7.5.2 | File header | done | `FileHeader`, `PdfVersion`, `PdfDocument` | `Broadside.Tests.Document.FileStructureTests.Offsets_count_from_the_header_so_bytes_before_it_do_not_matter`, `Broadside.Tests.Document.FileStructureTests.A_file_without_a_header_opens_from_byte_0_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_header_without_a_valid_version_takes_the_catalog_version_with_a_diagnostic` | Header searched in the first 1024 bytes; every stated offset is relative to it; missing header: offsets from byte 0, version 1.4 unless the catalog says otherwise; the unshifted-offset retry is #41 | +| 7.5.2 | File header | done | `FileHeader`, `PdfVersion`, `PdfDocument` | `Broadside.Tests.Document.FileStructureTests.Offsets_count_from_the_header_so_bytes_before_it_do_not_matter`, `Broadside.Tests.Document.FileStructureTests.A_file_without_a_header_opens_from_byte_0_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_header_without_a_valid_version_takes_the_catalog_version_with_a_diagnostic`, `Broadside.Tests.Document.RepairTests.Offsets_counted_from_byte_0_instead_of_the_header_are_repaired` | Header searched in the first 1024 bytes; every stated offset is relative to it; missing header: offsets from byte 0, version 1.4 unless the catalog says otherwise; offsets a writer counted from byte 0 despite junk before the header are repaired by the nearest-section and object searches | | 7.5.3 | File body | done | `ObjectLoader` | `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length` | Objects load lazily by cross-reference entry, from the file body or an object stream (7.5.7) | -| 7.5.4 | Cross-reference table | partial | `XrefTableReader`, `CrossReference` | `Broadside.Tests.Document.FileStructureTests.Entries_are_read_as_tokens_not_fixed_width_records`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_reads_as_null_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation` | Subsections and n/f entries read as tokens; offset-0 in-use entries read as free; reconstruction by scanning when the table is wrong, and diagnostics for non-20-byte entries and comments, are #41 | -| 7.5.5 | File trailer | partial | `CrossReferenceReader`, `CrossReference`, `PdfDocument` | `Broadside.Tests.Document.FileStructureTests.A_startxref_offset_on_the_white_space_before_xref_is_repaired_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_file_with_no_startxref_cannot_be_read_even_leniently`, `Broadside.Tests.Document.FileStructureTests.A_trailer_without_root_cannot_be_read`, `Broadside.Tests.Document.FileStructureTests.A_prev_chain_that_loops_ends_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic` | Last startxref, Prev chain with loop guard, Root; trailer merged newest-first; ignoring entries beyond Size, startxref recovery and trailer reconstruction are #41; Encrypt is #42 | +| 7.5.4 | Cross-reference table | done | `XrefTableReader`, `CrossReference`, `FileScan`, `CrossReferenceReconstructor` | `Broadside.Tests.Document.FileStructureTests.Entries_are_read_as_tokens_not_fixed_width_records`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_is_read_from_where_its_header_is_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation`, `Broadside.Tests.Document.RepairTests.Entries_that_are_not_20_bytes_long_are_read_with_one_diagnostic_per_section`, `Broadside.Tests.Document.RepairTests.A_subsection_numbered_from_1_whose_first_entry_is_the_free_list_head_is_renumbered_from_0`, `Broadside.Tests.Document.RepairTests.A_file_whose_line_endings_were_converted_to_crlf_opens_with_the_intact_pages`, `Broadside.Tests.Document.RepairTests.Rebuilding_an_updated_file_keeps_the_newest_copy_of_each_object_and_the_newest_trailer`, `Broadside.Tests.Document.RepairTests.A_repair_met_twice_is_recorded_once`, `Broadside.Tests.Document.BrokenCorpusTests.A_broken_file_opens_leniently_with_exactly_the_documented_diagnostics_and_the_intact_pages`, `Broadside.Tests.Document.BrokenCorpusTests.Strict_mode_throws_on_a_broken_file_with_the_code_of_its_first_diagnostic` | Subsections and n/f entries read as tokens; entries not 20 bytes long reported once per section (XrefEntryFormatInvalid); a subsection numbered from 1 whose first entry is the free-list head renumbered from 0 (XrefSubsectionNumberingInvalid); offset-0 in-use entries read as free; misplaced objects searched (7.3.10); an unreadable table is rebuilt by one windowed scan for N G obj headers (newest copy wins), object stream members and trailers (repair is informative, ADR 0005); comments inside a table are read silently; broken-xref-offsets.pdf, no-xref.pdf; fuzz `repair` | +| 7.5.5 | File trailer | partial | `CrossReferenceReader`, `CrossReference`, `PdfDocument`, `CrossReferenceReconstructor` | `Broadside.Tests.Document.FileStructureTests.A_startxref_offset_on_the_white_space_before_xref_is_repaired_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_file_with_no_startxref_is_rebuilt_by_scanning_and_keeps_its_trailer`, `Broadside.Tests.Document.FileStructureTests.A_trailer_without_root_is_repaired_by_finding_the_catalog_by_scanning`, `Broadside.Tests.Document.FileStructureTests.A_prev_chain_that_loops_ends_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic`, `Broadside.Tests.Document.RepairTests.A_wrong_prev_offset_reads_the_nearest_older_section`, `Broadside.Tests.Document.RepairTests.Rebuilding_an_encrypted_file_keeps_its_encryption_dictionary_and_identifier`, `Broadside.Tests.Document.RepairTests.A_compressed_catalog_is_found_when_no_trailer_survives`, `Broadside.Tests.Document.RepairTests.A_file_with_nothing_but_junk_cannot_be_read`, `Broadside.Tests.Document.BrokenCorpusTests.A_broken_file_opens_leniently_with_exactly_the_documented_diagnostics_and_the_intact_pages` | Last startxref, Prev chain with loop guard, Root; trailer merged newest-first; a startxref or Prev offset at neither xref nor N G obj reads the nearest section (table wins ties, never one already read); missing or unusable startxref, or a Root that does not lead to the catalog, rebuilds the cross-reference from a scan: newest trailer or xref-stream dictionary whose Root leads to a catalog, Encrypt/ID/Info from any trailer, else the newest /Catalog (TrailerMissing or RootMissing); no catalog at all throws CatalogNotFound; startxref-wrong.pdf, no-xref.pdf; ignoring entries beyond Size is not done; Encrypt is #42 | | 7.5.6 | Incremental updates | done | `CrossReference`, `RevisionReader`, `PdfRevision`, `PdfDocument` | `Broadside.Tests.Document.IncrementalUpdateTests.An_updated_file_has_one_revision_per_update_and_the_first_is_the_original_file`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_is_the_file_as_it_was_after_that_save`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_has_its_own_trailer`, `Broadside.Tests.Document.IncrementalUpdateTests.A_hybrid_file_has_its_main_section_and_its_update_section_as_two_revisions`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_earlier_revision_without_its_end_of_file_marker_ends_after_its_startxref_offset_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev` | Revisions oldest first, each the byte prefix up to its %%EOF and end-of-line; newest section decides per object number, free hides older copies, a reference must match the live generation; Root, Info, Encrypt and ID missing from the newest trailer are taken from an older one with TrailerEntryFromOlderRevision; a linearized pair is one revision; a hybrid XRefStm stream joins its table's revision; writing updates is #44 | -| 7.5.7 | Object streams | done | `ObjectStream`, `ObjectLoader` | `Broadside.Tests.Document.ObjectStreamTests.The_catalog_page_tree_and_page_resolve_from_an_object_stream`, `Broadside.Tests.Document.ObjectStreamTests.A_reference_to_a_member_with_a_generation_other_than_0_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.Members_need_no_white_space_between_them`, `Broadside.Tests.Document.ObjectStreamTests.A_member_at_another_index_than_its_entry_says_is_found_by_its_object_number`, `Broadside.Tests.Document.ObjectStreamTests.Offsets_out_of_order_bound_each_member_by_the_next_offset_in_sorted_order`, `Broadside.Tests.Document.ObjectStreamTests.A_member_the_object_stream_does_not_hold_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_whose_N_is_one_of_its_own_members_resolves_its_members_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_listed_as_compressed_itself_is_not_read`, `Broadside.Tests.Document.ObjectStreamTests.A_type_2_entry_naming_an_object_that_is_not_a_stream_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.A_flate_encoded_object_stream_is_decoded_through_the_filters`, `Broadside.Tests.Document.ObjectStreamTests.Members_of_one_object_stream_resolve_to_the_same_instances_from_concurrent_threads`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file` | Members located by type 2 entries (index checked against the header, searched by number when wrong, with ObjectStreamIndexMismatch); each member parsed over exactly the bytes up to the next offset (NOTE 7); out-of-order offsets sorted; container decoded once per document and shared, decrypted as a whole (members skip hooks 1 and 2); nested containers and self-referencing N/First/Filter end with ObjectStreamNested/ObjectStreamCycle; /Extends ignored (grouping only); object-stream.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `object-stream`; writing is #44 | -| 7.5.8 | Cross-reference streams | done | `XrefStreamReader`, `CrossReferenceReader`, `CrossReference` | `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file`, `Broadside.Tests.Document.CrossReferenceStreamTests.Strict_mode_opens_a_file_with_compressed_structures`, `Broadside.Tests.Document.CrossReferenceStreamTests.The_trailer_of_a_cross_reference_stream_is_its_dictionary_without_the_entries_that_describe_the_stream`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_type_field_makes_every_entry_type_1`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_generation_field_defaults_to_generation_0`, `Broadside.Tests.Document.CrossReferenceStreamTests.Index_with_two_subsections_numbers_the_entries_of_each_from_its_first_object_number`, `Broadside.Tests.Document.CrossReferenceStreamTests.Wide_fields_are_read_big_endian`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_entry_of_an_unknown_type_is_a_reference_to_the_null_object`, `Broadside.Tests.Document.CrossReferenceStreamTests.Data_shorter_than_the_entries_ends_the_section_where_the_data_ends`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_without_type_XRef_is_read_with_a_diagnostic`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_whose_W_cannot_be_read_is_not_a_cross_reference_section`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_update_written_as_a_cross_reference_stream_overrides_the_original_section`, `Broadside.Tests.Document.HybridFileTests.An_object_only_the_XRefStm_stream_lists_is_found`, `Broadside.Tests.Document.HybridFileTests.An_in_use_entry_in_the_table_of_a_section_takes_precedence_over_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.A_free_entry_in_the_table_of_a_section_gives_way_to_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.The_XRefStm_streams_dictionary_is_not_the_trailer_and_its_Prev_is_not_followed`, `Broadside.Tests.Document.HybridFileTests.An_XRefStm_offset_that_names_no_stream_is_reported_and_the_table_is_still_read`, `Broadside.Tests.Document.LinearizationTests.A_linearized_file_with_cross_reference_streams_has_its_first_page_and_main_streams_as_one_revision` | 7.5.8.1 to 7.5.8.4. W (0 to 8 bytes per field, W[0] = 0 means type 1), Index (default [0 Size]), Size, Prev; entries big-endian into long; type 0/1/2, other types are the null object; dictionary minus Type, Length, W, Index, Filter, DecodeParms, DL, F, FFilter, FDecodeParms is the trailer; data decoded through the filter pipeline under the engine's decoded-length limit, never decrypted; hybrid XRefStm read after its table and before Prev, its entries replacing the table's free entries (an in-use table entry wins), its own Prev not followed and its dictionary not a trailer; xref-stream.pdf, object-stream.pdf, png-predictor.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `xref-stream`; writing is #44 | +| 7.5.7 | Object streams | done | `ObjectStream`, `ObjectLoader` | `Broadside.Tests.Document.ObjectStreamTests.The_catalog_page_tree_and_page_resolve_from_an_object_stream`, `Broadside.Tests.Document.ObjectStreamTests.A_reference_to_a_member_with_a_generation_other_than_0_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.Members_need_no_white_space_between_them`, `Broadside.Tests.Document.ObjectStreamTests.A_member_at_another_index_than_its_entry_says_is_found_by_its_object_number`, `Broadside.Tests.Document.ObjectStreamTests.Offsets_out_of_order_bound_each_member_by_the_next_offset_in_sorted_order`, `Broadside.Tests.Document.ObjectStreamTests.A_member_the_object_stream_does_not_hold_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_whose_N_is_one_of_its_own_members_resolves_its_members_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_listed_as_compressed_itself_is_not_read`, `Broadside.Tests.Document.ObjectStreamTests.A_type_2_entry_naming_an_object_that_is_not_a_stream_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.A_flate_encoded_object_stream_is_decoded_through_the_filters`, `Broadside.Tests.Document.ObjectStreamTests.Members_of_one_object_stream_resolve_to_the_same_instances_from_concurrent_threads`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file`, `Broadside.Tests.Document.RepairTests.Objects_in_object_streams_survive_a_damaged_cross_reference_stream` | Members located by type 2 entries (index checked against the header, searched by number when wrong, with ObjectStreamIndexMismatch); each member parsed over exactly the bytes up to the next offset (NOTE 7); out-of-order offsets sorted; container decoded once per document and shared, decrypted as a whole (members skip hooks 1 and 2); nested containers and self-referencing N/First/Filter end with ObjectStreamNested/ObjectStreamCycle; /Extends ignored (grouping only); object-stream.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `object-stream`; writing is #44; a rebuilt cross-reference indexes the members of every object stream found by scanning (#41) | +| 7.5.8 | Cross-reference streams | done | `XrefStreamReader`, `CrossReferenceReader`, `CrossReference` | `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file`, `Broadside.Tests.Document.CrossReferenceStreamTests.Strict_mode_opens_a_file_with_compressed_structures`, `Broadside.Tests.Document.CrossReferenceStreamTests.The_trailer_of_a_cross_reference_stream_is_its_dictionary_without_the_entries_that_describe_the_stream`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_type_field_makes_every_entry_type_1`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_generation_field_defaults_to_generation_0`, `Broadside.Tests.Document.CrossReferenceStreamTests.Index_with_two_subsections_numbers_the_entries_of_each_from_its_first_object_number`, `Broadside.Tests.Document.CrossReferenceStreamTests.Wide_fields_are_read_big_endian`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_entry_of_an_unknown_type_is_a_reference_to_the_null_object`, `Broadside.Tests.Document.CrossReferenceStreamTests.Data_shorter_than_the_entries_ends_the_section_where_the_data_ends`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_without_type_XRef_is_read_with_a_diagnostic`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_whose_W_cannot_be_read_is_not_a_cross_reference_section_so_the_file_is_rebuilt_by_scanning`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_update_written_as_a_cross_reference_stream_overrides_the_original_section`, `Broadside.Tests.Document.HybridFileTests.An_object_only_the_XRefStm_stream_lists_is_found`, `Broadside.Tests.Document.HybridFileTests.An_in_use_entry_in_the_table_of_a_section_takes_precedence_over_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.A_free_entry_in_the_table_of_a_section_gives_way_to_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.The_XRefStm_streams_dictionary_is_not_the_trailer_and_its_Prev_is_not_followed`, `Broadside.Tests.Document.HybridFileTests.An_XRefStm_offset_that_names_no_stream_is_reported_and_the_table_is_still_read`, `Broadside.Tests.Document.LinearizationTests.A_linearized_file_with_cross_reference_streams_has_its_first_page_and_main_streams_as_one_revision` | 7.5.8.1 to 7.5.8.4. W (0 to 8 bytes per field, W[0] = 0 means type 1), Index (default [0 Size]), Size, Prev; entries big-endian into long; type 0/1/2, other types are the null object; dictionary minus Type, Length, W, Index, Filter, DecodeParms, DL, F, FFilter, FDecodeParms is the trailer; data decoded through the filter pipeline under the engine's decoded-length limit, never decrypted; hybrid XRefStm read after its table and before Prev, its entries replacing the table's free entries (an in-use table entry wins), its own Prev not followed and its dictionary not a trailer; xref-stream.pdf, object-stream.pdf, png-predictor.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `xref-stream`; writing is #44 | | 7.6 | Encryption | not started | | | | | 7.7.1 | General | n/a | | | Introductory text | | 7.7.2 | Document catalog dictionary | partial | `PdfDocument`, `PdfVersion` | `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_catalog_version_written_as_a_number_is_read_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.A_malformed_catalog_version_is_ignored_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_catalog_without_its_type_is_read_with_a_diagnostic` | Type, Version (effective version = later of header and catalog) and Pages; the other Table 29 entries arrive with their features (outlines, names, AcroForm, ...) | diff --git a/src/Broadside/Diagnostics/Diagnostic.cs b/src/Broadside/Diagnostics/Diagnostic.cs index dfd390ba..2b63792f 100644 --- a/src/Broadside/Diagnostics/Diagnostic.cs +++ b/src/Broadside/Diagnostics/Diagnostic.cs @@ -8,10 +8,21 @@ namespace Broadside.Diagnostics; /// /// /// ADR 0005: in lenient mode a reader repairs what it can and records a diagnostic on the document; in strict mode the first -/// diagnostic is thrown as a . A well-formed file produces no diagnostics: a diagnostic means a -/// "shall" of ISO 32000-2 was violated or the reader changed what it read, never that a "should" was not followed. +/// or is thrown as a . +/// A well-formed file produces no warnings and no errors: one means a "shall" of ISO 32000-2 was violated or the reader changed what +/// it read, never that a "should" was not followed. notes a valid feature the library +/// preserves without supporting it, and is never thrown. +/// +/// +/// Codes are stable PascalCase identifiers, such as StreamLengthInvalid or PageTreeCountMismatch; match on +/// , and , never on . A document records each +/// repair once: the same code at the same offset in the same object is not recorded twice, however often it is met. +/// +/// +/// ISO 32000-2 §7.5 describes the file structure a reader repairs (cross-reference table, trailer, startxref) but does not +/// specify repair; the codes for it are StartxrefMissing, StartxrefInvalid, TrailerMissing, +/// RootMissing, XrefEntryOffsetInvalid, MissingEndobj and StreamLengthInvalid, among others. /// -/// Codes are stable PascalCase identifiers, such as StreamLengthInvalid or PageTreeCountMismatch. /// public sealed class Diagnostic { diff --git a/src/Broadside/Diagnostics/DiagnosticLog.cs b/src/Broadside/Diagnostics/DiagnosticLog.cs index 88da980f..0ba7b4a3 100644 --- a/src/Broadside/Diagnostics/DiagnosticLog.cs +++ b/src/Broadside/Diagnostics/DiagnosticLog.cs @@ -32,7 +32,12 @@ internal static partial class DiagnosticLog /// The diagnostic. public static void Log(ILogger logger, Diagnostic diagnostic) => DiagnosticRecorded( logger, - diagnostic.Severity == DiagnosticSeverity.Error ? LogLevel.Error : LogLevel.Warning, + diagnostic.Severity switch + { + DiagnosticSeverity.Error => LogLevel.Error, + DiagnosticSeverity.Warning => LogLevel.Warning, + _ => LogLevel.Information, + }, diagnostic.Severity, diagnostic.Code, diagnostic.ObjectReference, diff --git a/src/Broadside/Diagnostics/DiagnosticSeverity.cs b/src/Broadside/Diagnostics/DiagnosticSeverity.cs index 03aa8a9b..39306f6f 100644 --- a/src/Broadside/Diagnostics/DiagnosticSeverity.cs +++ b/src/Broadside/Diagnostics/DiagnosticSeverity.cs @@ -1,12 +1,21 @@ namespace Broadside.Diagnostics; /// How much the repair recorded by a may have changed the document. -/// ADR 0005. There is no informational level: a well-formed file produces no diagnostics at all. +/// +/// ADR 0005. Ordered: a higher value is more severe. A well-formed file produces no and no +/// ; strict mode throws on those two and never on . +/// public enum DiagnosticSeverity { + /// + /// The file is valid, but uses a feature the library reads and preserves without supporting it (parse-and-preserve: XFA, + /// JavaScript, multimedia). Nothing was repaired; strict mode does not throw. + /// + Information = 0, + /// The file deviates from the specification, and the repair is believed to have kept all of its content. - Warning = 0, + Warning = 1, /// The file deviates from the specification, and the repair probably lost or invented content. - Error = 1, + Error = 2, } diff --git a/src/Broadside/Objects/CosParser.cs b/src/Broadside/Objects/CosParser.cs index abbef6b5..d9197ab3 100644 --- a/src/Broadside/Objects/CosParser.cs +++ b/src/Broadside/Objects/CosParser.cs @@ -512,7 +512,15 @@ private CosStream ParseStreamData(CosDictionary dictionary, CosToken keyword) return new CosStream(dictionary, source[dataStart..dataEnd].ToArray()); } + // No endstream: the data ends at the stated Length, or at endobj when that comes first (as PDFBox does), or at the end. int end = declared >= 0 && declared <= source.Length - dataStart ? dataStart + (int)declared : source.Length; + int endobj = source[dataStart..].IndexOf("endobj"u8); + if (endobj >= 0 && dataStart + endobj < end) + { + end = dataStart + endobj; + end -= EndOfLineLengthBefore(source, dataStart, end); + } + Report(CosRepairCodes.EndstreamMissing, keyword.Start, "The stream has no endstream keyword."); _lexer.Position = end; return new CosStream(dictionary, source[dataStart..end].ToArray()); diff --git a/src/Broadside/Objects/CosRepair.cs b/src/Broadside/Objects/CosRepair.cs index 4ff12294..7b1d1e24 100644 --- a/src/Broadside/Objects/CosRepair.cs +++ b/src/Broadside/Objects/CosRepair.cs @@ -6,8 +6,8 @@ namespace Broadside.Objects; /// One deviation from ISO 32000-2 §7.2 or §7.3 the parser found, and repaired, while reading objects. /// /// -/// Internal until the public diagnostic model lands (issue #41), which is expected to adopt as its diagnostic -/// code. Codes are stable PascalCase identifiers, listed in . +/// The object loader turns each repair into a public with the same , the +/// absolute offset and the object (issue #41). Codes are stable PascalCase identifiers, listed in . /// /// The stable identifier of the kind of deviation. /// The byte offset in the parsed source where the deviation was found. diff --git a/src/Broadside/Parsing/CrossReference.cs b/src/Broadside/Parsing/CrossReference.cs index a12a526f..939fabef 100644 --- a/src/Broadside/Parsing/CrossReference.cs +++ b/src/Broadside/Parsing/CrossReference.cs @@ -66,6 +66,12 @@ internal sealed record XrefSection(long Offset, long End, XrefSectionKind Kind, /// Gets the cross-reference stream object of a section, as parsed. public CosStream? Stream { get; init; } + + /// + /// Gets a value indicating whether the section was rebuilt by scanning the file rather than read from it (issue #41, + /// ). Such a section is the only one, and its revision spans the whole file. + /// + public bool IsReconstructed { get; init; } } /// diff --git a/src/Broadside/Parsing/CrossReferenceReader.cs b/src/Broadside/Parsing/CrossReferenceReader.cs index aa5e6631..feed3995 100644 --- a/src/Broadside/Parsing/CrossReferenceReader.cs +++ b/src/Broadside/Parsing/CrossReferenceReader.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Broadside.Diagnostics; using Broadside.Filters; using Broadside.IO; @@ -22,8 +23,9 @@ namespace Broadside.Parsing; /// Prev is not followed ("not meaningful in hybrid-reference files", Table 17) and its dictionary is not a trailer. /// /// -/// Extension: issue #41 locates startxref when it is wrong and reconstructs the table when nothing here can be read -/// ( returns ). +/// Repair (issue #41): a startxref or Prev offset that points at neither xref nor N G obj reads the +/// nearest section found by a ; when nothing can be read, returns +/// and the caller rebuilds the table with . /// /// internal static class CrossReferenceReader @@ -38,9 +40,14 @@ internal static class CrossReferenceReader /// The header, whose offset every stated offset is relative to. /// The filter pipeline cross-reference streams are decoded with. /// Where to report deviations. + /// + /// The scan of the file a wrong startxref or Prev offset is repaired from, run only when one is wrong; a new one + /// when . + /// /// The cross-reference information, or when no section could be read. - public static CrossReference? Read(PdfSource source, FileHeader header, StreamDecoder streams, DiagnosticSink diagnostics) + public static CrossReference? Read(PdfSource source, FileHeader header, StreamDecoder streams, DiagnosticSink diagnostics, Lazy? scan = null) { + scan ??= new Lazy(() => FileScan.Run(source)); if (!TryReadStartxref(source, header, diagnostics, out long first)) { return null; @@ -61,7 +68,7 @@ internal static class CrossReferenceReader break; } - XrefSection? section = ReadSection(source, offset, isFirst: sections.Count == 0, streams, diagnostics); + XrefSection? section = ReadSection(source, offset, isFirst: sections.Count == 0, streams, diagnostics, scan, visited); if (section is null) { break; @@ -119,7 +126,10 @@ private static bool TryReadStartxref(PdfSource source, FileHeader header, Diagno long keyword = FindLast(source, "startxref"u8); if (keyword < 0) { - diagnostics.Report(DiagnosticCodes.StartxrefMissing, DiagnosticSeverity.Error, "The file has no startxref keyword."); + diagnostics.Report( + DiagnosticCodes.StartxrefMissing, + DiagnosticSeverity.Warning, + "The file has no startxref keyword; the cross-reference information is rebuilt by scanning the file."); return false; } @@ -130,8 +140,8 @@ private static bool TryReadStartxref(PdfSource source, FileHeader header, Diagno { diagnostics.Report( DiagnosticCodes.StartxrefInvalid, - DiagnosticSeverity.Error, - "The startxref keyword is not followed by a byte offset.", + DiagnosticSeverity.Warning, + "The startxref keyword is not followed by a byte offset; the cross-reference information is rebuilt by scanning the file.", keyword); return false; } @@ -149,14 +159,29 @@ private static bool TryReadStartxref(PdfSource source, FileHeader header, Diagno return true; } - /// Reads the section at : a table when it starts with xref, else a stream. - private static XrefSection? ReadSection(PdfSource source, long offset, bool isFirst, StreamDecoder streams, DiagnosticSink diagnostics) + /// + /// Reads the section at : a table when it starts with xref, a stream when it starts with + /// N G obj. When neither is there, reads the section whose start is nearest to instead (issue + /// #41, as PDFBox does): a table wins a tie, and a section already read is never chosen again. + /// + private static XrefSection? ReadSection( + PdfSource source, + long offset, + bool isFirst, + StreamDecoder streams, + DiagnosticSink diagnostics, + Lazy? scan, + HashSet visited) { ReadOnlySpan window = source.GetWindow(offset).Span; var lexer = new CosLexer(window); CosToken first = lexer.Next(); bool isTable = StructureTokens.IsKeyword(window, first, "xref"u8); - if (isTable || first.Kind == CosTokenKind.Integer) + bool isStream = !isTable + && first.Kind == CosTokenKind.Integer + && StructureTokens.TryReadUnsigned(ref lexer, out _) + && StructureTokens.TryReadKeyword(ref lexer, "obj"u8); + if (isTable || isStream) { if (first.Start != 0) { @@ -173,16 +198,63 @@ private static bool TryReadStartxref(PdfSource source, FileHeader header, Diagno return isTable ? XrefTableReader.Read(window, offset, diagnostics) : XrefStreamReader.Read(source, offset, streams, diagnostics); } + string stated = isFirst ? "startxref" : "Prev"; + if (scan is not null && FindNearestSection(scan.Value, offset, visited) is { } nearest) + { + diagnostics.Report( + isFirst ? DiagnosticCodes.StartxrefInvalid : DiagnosticCodes.TrailerPrevInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The {stated} offset does not point at a cross-reference section; the section nearest to it, at offset {nearest}, is read instead."), + offset); + visited.Add(nearest); + return ReadSection(source, nearest, isFirst, streams, diagnostics, scan: null, visited); + } + diagnostics.Report( isFirst ? DiagnosticCodes.StartxrefInvalid : DiagnosticCodes.TrailerPrevInvalid, - DiagnosticSeverity.Error, + isFirst ? DiagnosticSeverity.Warning : DiagnosticSeverity.Error, isFirst - ? "The startxref offset does not point at a cross-reference section." - : "The Prev offset does not point at a cross-reference section.", + ? "The startxref offset does not point at a cross-reference section, and the file has none; the cross-reference information is rebuilt by scanning the file." + : "The Prev offset does not point at a cross-reference section; older sections are not read.", offset); return null; } + /// + /// Returns the start of the cross-reference section nearest to that has not been read: an xref + /// keyword, or the header of an object whose dictionary names the type /XRef. + /// + private static long? FindNearestSection(FileScan scan, long offset, HashSet visited) + { + long? nearest = null; + long distance = long.MaxValue; + foreach (long table in scan.XrefKeywords) + { + Consider(table); + } + + foreach (long name in scan.XrefStreamNames) + { + if (scan.TryFindObjectBefore(name, out ScannedObject header)) + { + Consider(header.Offset); + } + } + + return nearest; + + // Tables are considered first, so on a tie (equal distance) the table wins. + void Consider(long candidate) + { + long candidateDistance = Math.Abs(candidate - offset); + if (candidateDistance < distance && !visited.Contains(candidate)) + { + nearest = candidate; + distance = candidateDistance; + } + } + } + /// /// Reads the cross-reference stream a hybrid file's table names through its trailer's XRefStm entry (§7.5.8.4, Table 19). /// diff --git a/src/Broadside/Parsing/CrossReferenceReconstructor.cs b/src/Broadside/Parsing/CrossReferenceReconstructor.cs new file mode 100644 index 00000000..0630f33b --- /dev/null +++ b/src/Broadside/Parsing/CrossReferenceReconstructor.cs @@ -0,0 +1,298 @@ +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Filters; +using Broadside.IO; +using Broadside.Objects; + +namespace Broadside.Parsing; + +/// +/// Rebuilds the cross-reference information of a file whose own cannot be read, from a of its bytes. +/// +/// +/// +/// ISO 32000-2 §7.5.4 and §7.5.5 define the cross-reference table and trailer; §7.5 does not define repair, so this follows pdf.js +/// and PDFBox, keeping what each gets right: +/// +/// +/// Every N G obj header becomes an in-use entry; when a number occurs more than once, the copy furthest into the file +/// wins, since an incremental update appends newer copies (§7.5.6). +/// Every object stream (/Type /ObjStm) is decoded and its members become compressed entries (§7.5.7), unless a copy of +/// the member stored later in the file body supersedes it; without this, a file whose cross-reference stream is damaged loses every +/// compressed object (a pdf.js limitation). +/// The trailer is the newest trailer dictionary or cross-reference stream dictionary whose Root resolves to a +/// catalog with a Pages dictionary (both engines take the oldest, which loses updates). Encrypt and ID come +/// from any trailer that has them when the chosen one does not (PDFBox's fallback loses them, so encrypted files fail). +/// With no usable trailer, the catalog is the newest object of type /Catalog whose Pages resolves, and a +/// or diagnostic says so. +/// +/// The result has one synthetic section, marked , that spans the whole file. +/// +internal static class CrossReferenceReconstructor +{ + private static readonly CosName XRef = new("XRef"); + private static readonly CosName ObjStm = new("ObjStm"); + private static readonly CosName N = new("N"); + private static readonly CosName First = new("First"); + private static readonly CosName XRefStm = new("XRefStm"); + + /// The cross-reference stream entries that describe the stream, not the file (§7.5.8.2, Table 17). + private static readonly CosName[] StreamOnlyKeys = + [ + KnownNames.Type, KnownNames.Length, new("W"), new("Index"), new("Filter"), new("DecodeParms"), new("DL"), new("F"), + new("FFilter"), new("FDecodeParms"), + ]; + + /// Rebuilds the cross-reference information of . + /// The file. + /// The header; offsets in the result are relative to it, like any entry's. + /// The scan of the file. + /// The filter pipeline object streams are decoded with. + /// Where to report deviations. + /// + /// when the caller already reported why the trailer is unusable, so only a file with no trailer at all + /// adds a diagnostic. + /// + /// The cross-reference information, or when the file holds no catalog. + public static CrossReference? Reconstruct( + PdfSource source, + FileHeader header, + FileScan scan, + StreamDecoder streams, + DiagnosticSink diagnostics, + bool reportMissingTrailer = true) + { + // 1. File-body objects: the last copy of each number wins. + var entries = new Dictionary(); + var bodyOffsets = new Dictionary(); + foreach (ScannedObject found in scan.Objects) + { + if (found.Offset < header.Offset) + { + continue; + } + + entries[found.Number] = new XrefEntry(XrefEntryKind.InUse, found.Offset - header.Offset, found.Generation); + bodyOffsets[found.Number] = found.Offset; + } + + ObjectLoader loader = LoaderOver(source, header, entries, new CosDictionary(), streams, diagnostics); + + // 2. Members of object streams, unless a later file-body copy supersedes them. + if (AddObjectStreamMembers(scan, loader, entries, bodyOffsets, streams, diagnostics)) + { + loader = LoaderOver(source, header, entries, new CosDictionary(), streams, diagnostics); + } + + // 3. The trailer: the newest candidate whose Root leads to a catalog with a page tree. + List<(long Offset, CosDictionary Trailer)> trailers = TrailerCandidates(source, scan, loader); + OrderedDictionary? chosen = null; + foreach ((long _, CosDictionary candidate) in trailers) + { + if (candidate.TryGetValue(KnownNames.Root, out CosObject? root) && IsCatalog(loader, loader.Resolve(root))) + { + chosen = Without(candidate, KnownNames.Prev, XRefStm, KnownNames.Size); + break; + } + } + + if (chosen is null) + { + if (FindCatalog(scan, loader, entries) is not { } catalog) + { + return null; + } + + if (trailers.Count == 0 || reportMissingTrailer) + { + diagnostics.Report( + trailers.Count == 0 ? DiagnosticCodes.TrailerMissing : DiagnosticCodes.RootMissing, + DiagnosticSeverity.Warning, + trailers.Count == 0 + ? string.Create(CultureInfo.InvariantCulture, $"The file has no trailer dictionary; the catalog is object {catalog.ObjectNumber} {catalog.Generation}, found by scanning the file.") + : string.Create(CultureInfo.InvariantCulture, $"No trailer's Root entry leads to the catalog; the catalog is object {catalog.ObjectNumber} {catalog.Generation}, found by scanning the file.")); + } + + chosen = new OrderedDictionary { [KnownNames.Root] = catalog }; + } + + foreach (CosName key in (ReadOnlySpan)[KnownNames.Encrypt, KnownNames.ID, KnownNames.Info]) + { + if (!chosen.ContainsKey(key) && trailers.FirstOrDefault(candidate => candidate.Trailer.ContainsKey(key)).Trailer is { } other) + { + chosen.Add(key, other[key]); + } + } + + chosen.Insert(0, KnownNames.Size, new CosInteger(entries.Count == 0 ? 1 : entries.Keys.Max() + 1L)); + CosDictionary trailer = CosDictionary.FromOwnedEntries(chosen); + var section = new XrefSection(source.Length, source.Length, XrefSectionKind.Table, entries, trailer) { IsReconstructed = true }; + return new CrossReference([section]); + } + + /// A loader over a provisional cross-reference, to read objects while the final one is being built. + private static ObjectLoader LoaderOver( + PdfSource source, + FileHeader header, + Dictionary entries, + CosDictionary trailer, + StreamDecoder streams, + DiagnosticSink diagnostics) + { + var section = new XrefSection(source.Length, source.Length, XrefSectionKind.Table, entries, trailer) + { + IsReconstructed = true, + }; + return new ObjectLoader(source, header, new CrossReference([section]), diagnostics, new ObjectLoaderHooks(), streams); + } + + /// Decodes every object stream the scan found and registers its members as compressed entries (§7.5.7). + /// when an entry was added or changed. + private static bool AddObjectStreamMembers( + FileScan scan, + ObjectLoader loader, + Dictionary entries, + Dictionary bodyOffsets, + StreamDecoder streams, + DiagnosticSink diagnostics) + { + var containers = new SortedSet<(long Offset, int Number)>(); + foreach (long name in scan.ObjectStreamNames) + { + // Only the copy of each container the entries settled on (the last in the file) is read. + if (scan.TryFindObjectBefore(name, out ScannedObject container) + && bodyOffsets.TryGetValue(container.Number, out long offset) + && offset == container.Offset) + { + containers.Add((container.Offset, container.Number)); + } + } + + var memberOffsets = new Dictionary(); + bool changed = false; + foreach ((long containerOffset, int number) in containers) + { + XrefEntry entry = entries[number]; + var reference = new CosReference(number, entry.Generation); + if (loader.Load(reference) is not CosStream stream + || !stream.Dictionary.TryGetValue(KnownNames.Type, out CosObject? type) + || !ObjStm.Equals(type)) + { + continue; + } + + CosObject count = loader.Resolve(stream.Dictionary.TryGetValue(N, out CosObject? n) ? n : null); + CosObject first = loader.Resolve(stream.Dictionary.TryGetValue(First, out CosObject? f) ? f : null); + ObjectStream objectStream = ObjectStream.Read(new CosReference(number, 0), streams.Decode(stream), count, first, diagnostics); + IReadOnlyList members = objectStream.ObjectNumbers; + for (int index = 0; index < members.Count; index++) + { + int member = members[index]; + bool supersededByBody = bodyOffsets.TryGetValue(member, out long bodyOffset) && bodyOffset > containerOffset; + bool supersededByStream = memberOffsets.TryGetValue(member, out long otherContainer) && otherContainer > containerOffset; + if (member != number && !supersededByBody && !supersededByStream) + { + entries[member] = new XrefEntry(XrefEntryKind.Compressed, number, index); + memberOffsets[member] = containerOffset; + changed = true; + } + } + } + + return changed; + } + + /// + /// Collects the dictionaries after trailer keywords and of cross-reference streams, newest (furthest into the file) first. + /// + private static List<(long Offset, CosDictionary Trailer)> TrailerCandidates(PdfSource source, FileScan scan, ObjectLoader loader) + { + var candidates = new List<(long Offset, CosDictionary Trailer)>(); + foreach (long keyword in scan.TrailerKeywords) + { + ReadOnlySpan window = source.GetWindow(keyword + "trailer"u8.Length).Span; + if (new CosParser(window, new CosRepairLog()).ParseObject() is CosDictionary trailer) + { + candidates.Add((keyword, trailer)); + } + } + + var seen = new HashSet(); + foreach (long name in scan.XrefStreamNames) + { + if (scan.TryFindObjectBefore(name, out ScannedObject header) + && seen.Add(header.Offset) + && loader.CrossReference.TryGetEntry(header.Number, out XrefEntry entry) + && entry.Kind == XrefEntryKind.InUse + && entry.Offset + loader.Header.Offset == header.Offset + && loader.Load(new CosReference(header.Number, header.Generation)) is CosStream stream + && stream.Dictionary.TryGetValue(KnownNames.Type, out CosObject? type) + && XRef.Equals(type)) + { + candidates.Add((header.Offset, CosDictionary.FromOwnedEntries(Without(stream.Dictionary, StreamOnlyKeys)))); + } + } + + candidates.Sort(static (left, right) => right.Offset.CompareTo(left.Offset)); + return candidates; + } + + /// Finds the newest catalog: an object of type /Catalog whose Pages resolves to a dictionary (§7.7.2). + private static CosReference? FindCatalog(FileScan scan, ObjectLoader loader, Dictionary entries) + { + CosReference? best = null; + long bestOffset = -1; + foreach (long name in scan.CatalogNames) + { + if (scan.TryFindObjectBefore(name, out ScannedObject header) && header.Offset > bestOffset) + { + var reference = new CosReference(header.Number, header.Generation); + if (IsCatalog(loader, loader.Load(reference))) + { + best = reference; + bestOffset = header.Offset; + } + } + } + + if (best is not null) + { + return best; + } + + // The catalog may be compressed, where the scan cannot see its type: look at the members of object streams, newest number first. + foreach (int number in entries.Where(static entry => entry.Value.Kind == XrefEntryKind.Compressed).Select(static entry => entry.Key).OrderDescending()) + { + var reference = new CosReference(number, 0); + if (loader.Load(reference) is CosDictionary dictionary + && dictionary.TryGetValue(KnownNames.Type, out CosObject? type) + && KnownNames.Catalog.Equals(type) + && IsCatalog(loader, dictionary)) + { + return reference; + } + } + + return null; + } + + private static bool IsCatalog(ObjectLoader loader, CosObject value) => + value is CosDictionary catalog + && catalog.TryGetValue(KnownNames.Pages, out CosObject? pages) + && loader.Resolve(pages) is CosDictionary; + + /// Copies the entries of but , for a dictionary that reads as parsed (ADR 0004). + private static OrderedDictionary Without(CosDictionary dictionary, params ReadOnlySpan keys) + { + var copy = new OrderedDictionary(); + foreach (KeyValuePair entry in dictionary) + { + if (!keys.Contains(entry.Key)) + { + copy.Add(entry.Key, entry.Value); + } + } + + return copy; + } +} diff --git a/src/Broadside/Parsing/DiagnosticCodes.cs b/src/Broadside/Parsing/DiagnosticCodes.cs index bd32f737..975a9bbf 100644 --- a/src/Broadside/Parsing/DiagnosticCodes.cs +++ b/src/Broadside/Parsing/DiagnosticCodes.cs @@ -4,7 +4,10 @@ namespace Broadside.Parsing; /// The codes of the diagnostics the file reader and the document model record, grouped by area. Object syntax codes are in /// . Codes are stable: tests, logs and users match on them. /// -/// Issue #41 owns the public catalogue of codes; every ticket adds its own group here. +/// +/// Every ticket adds its own group here. The catalogue is internal while parallel tickets add codes; the codes reach users as +/// strings. +/// internal static class DiagnosticCodes { // File header (ISO 32000-2 §7.5.2). @@ -20,9 +23,14 @@ internal static class DiagnosticCodes public const string RootMissing = nameof(RootMissing); public const string RootNotIndirect = nameof(RootNotIndirect); + // Repair by scanning (§7.5; issue #41). + public const string CatalogNotFound = nameof(CatalogNotFound); + // Cross-reference table (§7.5.4). public const string XrefSectionInvalid = nameof(XrefSectionInvalid); public const string XrefEntryInvalid = nameof(XrefEntryInvalid); + public const string XrefEntryFormatInvalid = nameof(XrefEntryFormatInvalid); + public const string XrefSubsectionNumberingInvalid = nameof(XrefSubsectionNumberingInvalid); public const string XrefPrevLoop = nameof(XrefPrevLoop); // Cross-reference streams and hybrid files (§7.5.8). diff --git a/src/Broadside/Parsing/DiagnosticSink.cs b/src/Broadside/Parsing/DiagnosticSink.cs index 8a14ea65..48f5f5c1 100644 --- a/src/Broadside/Parsing/DiagnosticSink.cs +++ b/src/Broadside/Parsing/DiagnosticSink.cs @@ -6,35 +6,79 @@ namespace Broadside.Parsing; /// /// The one place a document's reader records deviations. Lenient: append and continue. Strict: append, then throw a -/// for the first deviation (ADR 0005). +/// for the first deviation of severity or +/// (ADR 0005); never throws. /// /// +/// /// Thread-safe: objects load lazily after open, possibly on several threads (issue #45), and every load reports here. The -/// optional observer sees each diagnostic before strict mode throws (issue #46 logs through it). +/// optional observer sees each recorded diagnostic before strict mode throws (issue #46 logs through it). +/// +/// +/// Each repair is recorded once. drops a diagnostic equal in code, offset and object to one already recorded +/// (the same object loaded on two threads, a lazy value computed twice, a structure validated before and after reconstruction). +/// keeps only the first diagnostic of a code per object, whatever its offset: for deviations that can +/// repeat many times inside one object, such as an operator error in every line of a page's content. A dropped duplicate is not +/// observed and not added, but strict mode still throws it: the operation that met it failed again. +/// /// internal sealed class DiagnosticSink(bool strict, Action? observer = null) { private readonly Lock _gate = new(); private readonly List _diagnostics = []; + private readonly HashSet<(string Code, long? Offset, CosReference? Reference)> _recorded = []; + private HashSet<(string Code, CosReference? Reference)>? _recordedPerObject; /// Gets a value indicating whether the first deviation throws. public bool IsStrict => strict; - /// Records a deviation; in strict mode, throws it. + /// Records a deviation, unless an equal one is already recorded; in strict mode, throws it. /// The diagnostic code, from or . /// How much the repair may have changed the document. /// What was wrong and what the reader did. /// The absolute byte offset in the file, when known. /// The object the deviation is in, when known. - /// The sink is strict. + /// The sink is strict and the severity is not . public void Report(string code, DiagnosticSeverity severity, string message, long? offset = null, CosReference? objectReference = null) { var diagnostic = new Diagnostic(code, severity, message, offset, objectReference); - Add(diagnostic); - if (strict) + bool added; + lock (_gate) { - throw new DiagnosticException(diagnostic); + added = _recorded.Add((code, offset, objectReference)); + if (added) + { + _diagnostics.Add(diagnostic); + } + } + + Publish(diagnostic, added); + } + + /// + /// Records a deviation unless one with the same code is already recorded for ; in strict mode, + /// throws it. For deviations that repeat inside one object (one per code per object, or per page when the object is the page). + /// + /// The diagnostic code. + /// How much the repair may have changed the document. + /// What was wrong and what the reader did. + /// The absolute byte offset in the file, when known; not part of the key. + /// The object the deviation is in, when known. + /// The sink is strict and the severity is not . + public void ReportOnce(string code, DiagnosticSeverity severity, string message, long? offset = null, CosReference? objectReference = null) + { + var diagnostic = new Diagnostic(code, severity, message, offset, objectReference); + bool added; + lock (_gate) + { + added = (_recordedPerObject ??= []).Add((code, objectReference)) && _recorded.Add((code, offset, objectReference)); + if (added) + { + _diagnostics.Add(diagnostic); + } } + + Publish(diagnostic, added); } /// Records a deviation the reader cannot repair, and throws it in either mode. @@ -46,7 +90,21 @@ public void Report(string code, DiagnosticSeverity severity, string message, lon public void Fail(string code, string message, long? offset = null) { var diagnostic = new Diagnostic(code, DiagnosticSeverity.Error, message, offset); - Add(diagnostic); + bool added; + lock (_gate) + { + added = _recorded.Add((code, offset, null)); + if (added) + { + _diagnostics.Add(diagnostic); + } + } + + if (added) + { + observer?.Invoke(diagnostic); + } + throw new DiagnosticException(diagnostic); } @@ -60,13 +118,16 @@ public Diagnostic[] Snapshot() } } - private void Add(Diagnostic diagnostic) + private void Publish(Diagnostic diagnostic, bool added) { - lock (_gate) + if (added) { - _diagnostics.Add(diagnostic); + observer?.Invoke(diagnostic); } - observer?.Invoke(diagnostic); + if (strict && diagnostic.Severity != DiagnosticSeverity.Information) + { + throw new DiagnosticException(diagnostic); + } } } diff --git a/src/Broadside/Parsing/FileHeader.cs b/src/Broadside/Parsing/FileHeader.cs index 7c417cf8..85d7b5aa 100644 --- a/src/Broadside/Parsing/FileHeader.cs +++ b/src/Broadside/Parsing/FileHeader.cs @@ -8,7 +8,8 @@ namespace Broadside.Parsing; /// /// ISO 32000-2 §7.5.2. Byte offsets in the file (startxref, cross-reference entries, Prev) are counted from the /// percent sign of the header, and arbitrary bytes may precede it (NOTE 1), so every offset the file states is relative to -/// . Issue #41 adds the retry with unshifted offsets for files whose writer counted from byte 0 anyway. +/// . A file whose writer counted from byte 0 anyway is repaired by the loader's object search and the +/// nearest-section search for startxref (issue #41). /// /// The absolute position of the % of %PDF-; 0 when no header was found. /// The version the header states, or when it is missing or malformed. diff --git a/src/Broadside/Parsing/FileScan.cs b/src/Broadside/Parsing/FileScan.cs new file mode 100644 index 00000000..e1014c9b --- /dev/null +++ b/src/Broadside/Parsing/FileScan.cs @@ -0,0 +1,336 @@ +using System.Buffers; +using Broadside.IO; +using Broadside.Objects; + +namespace Broadside.Parsing; + +/// An N G obj header found by scanning. +/// The object number. +/// The generation number. +/// The absolute byte offset of the first digit of the object number. +internal readonly record struct ScannedObject(int Number, int Generation, long Offset); + +/// +/// The positions of the file-structure keywords in a file, found in one pass over its bytes: what the reader repairs a damaged +/// file from when its cross-reference information cannot be trusted. +/// +/// +/// +/// ISO 32000-2 §7.5 (repair is not specified; this follows pdf.js and PDFBox). The scan reads the file in windows through +/// , so it never holds the whole file, and looks for each keyword with a vectorized span search: it is +/// linear in the file length and allocates only for what it finds. It looks for indirect object headers (N G obj, preceded +/// by white-space, a delimiter or the start of the file), the xref and trailer keywords, and the names +/// /XRef, /ObjStm and /Catalog, which mark the cross-reference streams, object streams and catalogs whose +/// object headers precede them. +/// +/// +/// Matches inside stream data are found too, as in both reference engines; callers parse what they find and discard what does not +/// parse. The result is immutable and safe to share between threads. +/// +/// +internal sealed class FileScan +{ + /// How many bytes each window of the scan covers. + private const int WindowLength = 64 * 1024; + + /// How many bytes before a window are kept so a header that straddles it is recognized. + private const int LookBehind = 32; + + /// How many bytes after a window are kept so the delimiter after a keyword is seen. + private const int LookAhead = 16; + + private readonly List _objects = []; + private readonly List _xrefKeywords = []; + private readonly List _trailerKeywords = []; + private readonly List _xrefStreamNames = []; + private readonly List _objectStreamNames = []; + private readonly List _catalogNames = []; + + private readonly Lazy> _newest; + + private FileScan() => _newest = new(IndexNewest, LazyThreadSafetyMode.ExecutionAndPublication); + + /// Gets the object headers, in file order. + public IReadOnlyList Objects => _objects; + + /// Gets the offsets of the xref keywords that start classic cross-reference sections, in file order. + public IReadOnlyList XrefKeywords => _xrefKeywords; + + /// Gets the offsets of the trailer keywords, in file order. + public IReadOnlyList TrailerKeywords => _trailerKeywords; + + /// Gets the offsets of the name /XRef (a cross-reference stream's type), in file order. + public IReadOnlyList XrefStreamNames => _xrefStreamNames; + + /// Gets the offsets of the name /ObjStm (an object stream's type), in file order. + public IReadOnlyList ObjectStreamNames => _objectStreamNames; + + /// Gets the offsets of the name /Catalog, in file order. + public IReadOnlyList CatalogNames => _catalogNames; + + /// Scans the whole of . + /// The file. + /// The scan. + public static FileScan Run(PdfSource source) => Run(source, 0, source.Length); + + /// Scans the bytes of in [, ). + /// The file. + /// The first offset a match may start at. + /// The offset no match may start at or after. + /// The scan. + public static FileScan Run(PdfSource source, long start, long end) + { + var scan = new FileScan(); + start = Math.Max(0, start); + end = Math.Min(end, source.Length); + byte[] buffer = ArrayPool.Shared.Rent(LookBehind + WindowLength + LookAhead); + try + { + for (long windowStart = start; windowStart < end; windowStart += WindowLength) + { + long bufferStart = Math.Max(0, windowStart - LookBehind); + int read = source.Read(bufferStart, buffer.AsSpan(0, (int)(windowStart - bufferStart) + WindowLength + LookAhead)); + int first = (int)(windowStart - bufferStart); + int last = (int)Math.Min(end - bufferStart, first + WindowLength); + scan.ScanWindow(buffer.AsSpan(0, read), bufferStart, first, last); + } + } + finally + { + ArrayPool.Shared.Return(buffer); + } + + return scan; + } + + /// Returns the object header that most closely precedes , the object a name at it is in. + /// An absolute offset. + /// The header. + /// when a header precedes the offset. + public bool TryFindObjectBefore(long offset, out ScannedObject found) + { + int low = 0; + int high = _objects.Count - 1; + int best = -1; + while (low <= high) + { + int middle = (low + high) >>> 1; + if (_objects[middle].Offset < offset) + { + best = middle; + low = middle + 1; + } + else + { + high = middle - 1; + } + } + + found = best >= 0 ? _objects[best] : default; + return best >= 0; + } + + /// + /// Finds the header of object closest to , or the + /// last one in the file when is (an incremental update appends newer copies). + /// + /// The object number. + /// The generation number. + /// The offset to stay close to, or . + /// The header's absolute offset. + /// when found. + public bool TryFindObject(int number, int generation, long? near, out long offset) + { + if (near is null) + { + return _newest.Value.TryGetValue((number, generation), out offset); + } + + offset = -1; + long distance = long.MaxValue; + foreach (ScannedObject header in _objects) + { + if (header.Number != number || header.Generation != generation) + { + continue; + } + + long candidate = Math.Abs(header.Offset - near.Value); + if (offset < 0 || candidate < distance) + { + offset = header.Offset; + distance = candidate; + } + } + + return offset >= 0; + } + + /// Indexes the last header of each object number and generation, so lookups after a full scan are not linear. + private Dictionary<(int Number, int Generation), long> IndexNewest() + { + var newest = new Dictionary<(int Number, int Generation), long>(); + foreach (ScannedObject header in _objects) + { + newest[(header.Number, header.Generation)] = header.Offset; + } + + return newest; + } + + private static bool IsWhiteSpace(byte value) => value is 0 or (byte)'\t' or (byte)'\n' or (byte)'\f' or (byte)'\r' or (byte)' '; + + private static bool IsDelimiter(byte value) => + value is (byte)'(' or (byte)')' or (byte)'<' or (byte)'>' or (byte)'[' or (byte)']' or (byte)'{' or (byte)'}' or (byte)'/' or (byte)'%'; + + private static bool IsBoundary(ReadOnlySpan buffer, int position) => + position < 0 || position >= buffer.Length || IsWhiteSpace(buffer[position]) || IsDelimiter(buffer[position]); + + private static bool IsDigit(byte value) => value is >= (byte)'0' and <= (byte)'9'; + + /// Scans matches that start in [, ) of . + private void ScanWindow(ReadOnlySpan buffer, long bufferStart, int first, int last) + { + foreach (int position in Matches(buffer, first, last, "obj"u8)) + { + if (IsBoundary(buffer, position + 3) && TryReadHeaderBefore(buffer, position, out int number, out int generation, out int start)) + { + _objects.Add(new ScannedObject(number, generation, bufferStart + start)); + } + } + + AddKeywords(buffer, bufferStart, first, last, "xref"u8, _xrefKeywords, requireWhiteSpaceBefore: true); + AddKeywords(buffer, bufferStart, first, last, "trailer"u8, _trailerKeywords, requireWhiteSpaceBefore: false); + AddKeywords(buffer, bufferStart, first, last, "/XRef"u8, _xrefStreamNames, requireWhiteSpaceBefore: false); + AddKeywords(buffer, bufferStart, first, last, "/ObjStm"u8, _objectStreamNames, requireWhiteSpaceBefore: false); + AddKeywords(buffer, bufferStart, first, last, "/Catalog"u8, _catalogNames, requireWhiteSpaceBefore: false); + } + + private static void AddKeywords( + ReadOnlySpan buffer, + long bufferStart, + int first, + int last, + ReadOnlySpan keyword, + List found, + bool requireWhiteSpaceBefore) + { + bool isName = keyword[0] == (byte)'/'; + foreach (int position in Matches(buffer, first, last, keyword)) + { + bool before = requireWhiteSpaceBefore + ? position == 0 && bufferStart == 0 || position > 0 && IsWhiteSpace(buffer[position - 1]) + : isName || IsBoundary(buffer, position - 1) || position == 0; + if (before && IsBoundary(buffer, position + keyword.Length)) + { + found.Add(bufferStart + position); + } + } + } + + /// + /// Reads N G backwards from the obj at : white-space, the generation (1-5 digits), + /// white-space, the object number (1-10 digits), then white-space, a delimiter or the start of the buffer. + /// + private static bool TryReadHeaderBefore(ReadOnlySpan buffer, int keyword, out int number, out int generation, out int start) + { + number = 0; + generation = 0; + start = 0; + int position = keyword - 1; + if (position < 0 || !IsWhiteSpace(buffer[position])) + { + return false; + } + + while (position >= 0 && IsWhiteSpace(buffer[position])) + { + position--; + } + + int generationEnd = position + 1; + while (position >= 0 && IsDigit(buffer[position])) + { + position--; + } + + int generationStart = position + 1; + if (generationEnd - generationStart is < 1 or > 5 || position < 0 || !IsWhiteSpace(buffer[position])) + { + return false; + } + + while (position >= 0 && IsWhiteSpace(buffer[position])) + { + position--; + } + + int numberEnd = position + 1; + while (position >= 0 && IsDigit(buffer[position])) + { + position--; + } + + int numberStart = position + 1; + if (numberEnd - numberStart is < 1 or > 10 || (position >= 0 && !IsWhiteSpace(buffer[position]) && !IsDelimiter(buffer[position]))) + { + return false; + } + + long parsedNumber = Parse(buffer[numberStart..numberEnd]); + long parsedGeneration = Parse(buffer[generationStart..generationEnd]); + if (parsedNumber is 0 or > int.MaxValue || parsedGeneration > CosReference.MaxGeneration) + { + return false; + } + + number = (int)parsedNumber; + generation = (int)parsedGeneration; + start = numberStart; + return true; + } + + private static long Parse(ReadOnlySpan digits) + { + long value = 0; + foreach (byte digit in digits) + { + value = (value * 10) + (digit - '0'); + } + + return value; + } + + /// Enumerates the positions in [, ) where starts. + private static MatchEnumerator Matches(ReadOnlySpan buffer, int first, int last, ReadOnlySpan value) => new(buffer, first, last, value); + + private ref struct MatchEnumerator(ReadOnlySpan buffer, int first, int last, ReadOnlySpan value) + { + private readonly ReadOnlySpan _buffer = buffer; + private readonly ReadOnlySpan _value = value; + private int _next = first; + + public int Current { get; private set; } + + public readonly MatchEnumerator GetEnumerator() => this; + + public bool MoveNext() + { + if (_next >= last || _next >= _buffer.Length) + { + return false; + } + + int found = _buffer[_next..].IndexOf(_value); + if (found < 0 || _next + found >= last) + { + _next = last; + return false; + } + + Current = _next + found; + _next = Current + 1; + return true; + } + } +} diff --git a/src/Broadside/Parsing/ObjectLoader.cs b/src/Broadside/Parsing/ObjectLoader.cs index 1fd3f24b..b1ad2fac 100644 --- a/src/Broadside/Parsing/ObjectLoader.cs +++ b/src/Broadside/Parsing/ObjectLoader.cs @@ -18,8 +18,8 @@ namespace Broadside.Parsing; /// /// /// Order for every object (see ): cache lookup; locate; parse, with hook 1 resolving stream extents; -/// hook 2 decryption; hook 3 cache publication. Issue #41 adds recovery when the header at an offset does not match in -/// . +/// hook 2 decryption; hook 3 cache publication. When the header at an entry's offset does not match, +/// looks for the object near the offset and then in a scan of the whole file (issue #41). /// /// /// An object stored in an object stream (§7.5.7, a entry) is parsed from its container's @@ -34,6 +34,9 @@ internal sealed class ObjectLoader /// How many loads may nest (an indirect Length loads while its stream loads) before the inner one reads null. public const int MaxDepth = 32; + /// How far before and after a wrong offset the object's header is looked for before the whole file is scanned. + private const int NearSearchDistance = 1024; + private static readonly CosName ObjStm = new("ObjStm"); private static readonly CosName N = new("N"); private static readonly CosName First = new("First"); @@ -68,6 +71,7 @@ public ObjectLoader( CrossReference = crossReference; _diagnostics = diagnostics; Hooks = hooks; + Scan = new Lazy(() => FileScan.Run(source), LazyThreadSafetyMode.ExecutionAndPublication); } /// Gets the file header. @@ -79,6 +83,12 @@ public ObjectLoader( /// Gets the hooks. public ObjectLoaderHooks Hooks { get; } + /// + /// Gets the scan of the whole file that objects whose entries are wrong are searched in, run on first use (issue #41). The open + /// path shares one scan between cross-reference repair and the loader. + /// + public Lazy Scan { get; init; } + /// Returns , or the object it refers to when it is an indirect reference. /// A direct object, a reference, or for an absent entry. /// The direct object; for an absent entry or a reference to nothing. @@ -221,16 +231,35 @@ private ConcurrentDictionary ObjectStreams private CosObject Resolve(CosObject? value, int depth) => value is CosReference reference ? Load(reference, depth) : value ?? CosNull.Instance; - /// Handles an entry whose offset does not hold the expected N G obj header. Issue #41 searches for the object. - private CosNull LoadMisplaced(in ObjectLoadContext context) + /// + /// Handles an entry whose offset does not hold the expected N G obj header: looks for the header near the stated offset, + /// then anywhere in the file (the newest copy), and parses the object where it is found (issue #41). + /// + private CosObject LoadMisplaced(in ObjectLoadContext context) { + CosReference reference = context.Reference; + long nearStart = context.Offset - NearSearchDistance; + bool found = FileScan.Run(_source, nearStart, context.Offset + NearSearchDistance) + .TryFindObject(reference.ObjectNumber, reference.Generation, context.Offset, out long offset) + || Scan.Value.TryFindObject(reference.ObjectNumber, reference.Generation, near: null, out offset); + if (!found || offset == context.Offset) + { + _diagnostics.Report( + DiagnosticCodes.XrefEntryOffsetInvalid, + DiagnosticSeverity.Error, + "The cross-reference entry's offset does not point at the object's header, and the file holds no such header; read as null.", + context.Offset, + reference); + return CosNull.Instance; + } + _diagnostics.Report( DiagnosticCodes.XrefEntryOffsetInvalid, - DiagnosticSeverity.Error, - "The cross-reference entry's offset does not point at the object's header; read as null.", + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The cross-reference entry's offset does not point at the object's header; the object is read from offset {offset}, where its header is."), context.Offset, - context.Reference); - return CosNull.Instance; + reference); + return ParseIndirectObject(context with { Offset = offset }); } /// Parses N G obj object endobj at the context's offset (§7.3.10). diff --git a/src/Broadside/Parsing/ObjectLoaderHooks.cs b/src/Broadside/Parsing/ObjectLoaderHooks.cs index 32658b9a..71771d75 100644 --- a/src/Broadside/Parsing/ObjectLoaderHooks.cs +++ b/src/Broadside/Parsing/ObjectLoaderHooks.cs @@ -26,7 +26,7 @@ internal enum ObjectOrigin : byte /// /// Hook 1 of the object loader: resolves a stream's Length so the parser can find the end of the data (§7.3.8.2). Runs during -/// parsing. Issue #41 extends recovery of wrong lengths behind it. +/// parsing. A null result makes the parser recover the extent from endstream with a diagnostic (issue #41). /// internal interface IStreamExtentResolver { @@ -77,19 +77,43 @@ internal interface IObjectCache CosObject Publish(CosReference reference, CosObject value); } -/// The default : a direct integer, or an indirect reference loaded through the loader. +/// +/// The default : a direct integer, or an indirect reference loaded through the loader. A +/// Length that refers, directly or through other streams' lengths, to a stream whose length is being resolved on this thread +/// is unknown, so the parser recovers the extent from endstream with a diagnostic instead of looping (issue #41). +/// internal sealed class DefaultStreamExtentResolver : IStreamExtentResolver { + /// The streams whose Length this thread is resolving, across loaders. + [ThreadStatic] + private static List<(ObjectLoader Loader, CosReference Stream)>? _resolving; + /// Gets the shared instance; it holds no state. public static DefaultStreamExtentResolver Instance { get; } = new(); /// public long? ResolveLength(CosObject lengthEntry, ObjectLoader loader, in ObjectLoadContext context) { - CosObject value = lengthEntry is CosReference reference && !reference.Equals(context.Reference) - ? loader.Load(reference, context.Depth + 1) - : lengthEntry; - return value is CosInteger { Value: >= 0 } length ? length.Value : null; + if (lengthEntry is not CosReference reference) + { + return lengthEntry is CosInteger { Value: >= 0 } direct ? direct.Value : null; + } + + List<(ObjectLoader Loader, CosReference Stream)> resolving = _resolving ??= []; + if (reference.Equals(context.Reference) || resolving.Contains((loader, reference))) + { + return null; + } + + resolving.Add((loader, context.Reference)); + try + { + return loader.Load(reference, context.Depth + 1) is CosInteger { Value: >= 0 } length ? length.Value : null; + } + finally + { + resolving.RemoveAt(resolving.Count - 1); + } } } @@ -123,7 +147,7 @@ internal sealed class ObjectLoaderHooks { private volatile IObjectDecryptor _decryptor = NullObjectDecryptor.Instance; - /// Gets hook 1, stream extent resolution (issue #41 extends it). + /// Gets hook 1, stream extent resolution. public IStreamExtentResolver StreamExtent { get; init; } = DefaultStreamExtentResolver.Instance; /// diff --git a/src/Broadside/Parsing/RevisionReader.cs b/src/Broadside/Parsing/RevisionReader.cs index 4c0c59bc..8e983202 100644 --- a/src/Broadside/Parsing/RevisionReader.cs +++ b/src/Broadside/Parsing/RevisionReader.cs @@ -30,6 +30,13 @@ public static long[] ReadEnds(PdfSource source, CrossReference crossReference, D for (int index = 0; index < revisions.Count; index++) { bool newest = index == revisions.Count - 1; + if (revisions[index].LastInFile.IsReconstructed) + { + // A rebuilt cross-reference has no trailer of its own to end at: the one revision is the whole file. + ends[index] = source.Length; + continue; + } + ends[index] = FindEnd(source, revisions[index].LastInFile.End, reportMissing: !newest, diagnostics); } diff --git a/src/Broadside/Parsing/XrefTableReader.cs b/src/Broadside/Parsing/XrefTableReader.cs index 4d3a02f5..9e48b989 100644 --- a/src/Broadside/Parsing/XrefTableReader.cs +++ b/src/Broadside/Parsing/XrefTableReader.cs @@ -7,7 +7,8 @@ namespace Broadside.Parsing; /// /// /// ISO 32000-2 §7.5.4 and §7.5.5. Entries are read as tokens, not as fixed 20-byte records, so a table with wrong line endings or -/// padding still reads (as pdf.js and PDFBox do); whether such a table is reported is issue #41's decision. +/// padding still reads (as pdf.js and PDFBox do), with one per section. A +/// subsection numbered from 1 whose first entry is the head of the free list is renumbered from 0, as pdf.js does. /// /// /// An in-use entry with offset 0 is read as free (as pdf.js does) with a diagnostic, and object number 0 is always free (§7.5.4) @@ -67,6 +68,7 @@ internal static class XrefTableReader /// when the table is malformed; the lexer is then somewhere inside it. private static bool ReadSubsections(ref CosLexer lexer, Dictionary entries, long sectionOffset, DiagnosticSink diagnostics) { + bool formatReported = false; while (true) { CosToken next = lexer.Peek(); @@ -89,9 +91,9 @@ private static bool ReadSubsections(ref CosLexer lexer, Dictionary int.MaxValue) + int entryPosition = lexer.Peek().Start; + long entryStart = sectionOffset + entryPosition; + if (!TryReadEntry(ref lexer, out XrefEntry entry) || first + index > int.MaxValue) { diagnostics.Report( DiagnosticCodes.XrefEntryInvalid, @@ -101,6 +103,30 @@ private static bool ReadSubsections(ref CosLexer lexer, DictionaryWhether starts with the exact 20-byte form of §7.5.4: nnnnnnnnnn ggggg n plus a two-byte end of line. + private static bool IsTwentyByteEntry(ReadOnlySpan entry) + { + if (entry.Length < 20 || entry[10] != (byte)' ' || entry[16] != (byte)' ' || entry[17] is not ((byte)'n' or (byte)'f')) + { + return false; + } + + for (int index = 0; index < 16; index++) + { + if (index != 10 && entry[index] is < (byte)'0' or > (byte)'9') + { + return false; + } + } + + return (entry[18], entry[19]) is ((byte)' ', (byte)'\r') or ((byte)' ', (byte)'\n') or ((byte)'\r', (byte)'\n'); + } + private static bool TryReadEntry(ref CosLexer lexer, out XrefEntry entry) { entry = XrefEntry.Free; diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 339aebd8..c0b8d20d 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -18,7 +18,15 @@ namespace Broadside; /// /// Reading is lenient by default: deviations are repaired and recorded in . In strict mode the first /// deviation throws a ; deviations in objects loaded after open (the page tree, for instance) throw -/// from the member that loads them. +/// from the member that loads them, so strict validation at open is not exhaustive. +/// +/// +/// Repairs (ISO 32000-2 §7.5 describes the structure but not its repair; ADR 0005): a wrong startxref or Prev offset +/// reads the nearest cross-reference section; an entry whose offset does not hold its object is looked up near that offset, then +/// anywhere in the file; a missing or unusable cross-reference table or trailer is rebuilt by scanning the file for object headers, +/// object streams and trailers, and the catalog is found by its type when no trailer leads to it; a wrong stream Length is +/// recovered from endstream (or endobj), without changing the Length entry; a missing endobj ends the +/// object at the next keyword. /// /// Safe for concurrent reads from several threads while nobody changes it; changes are single-threaded. /// @@ -229,10 +237,26 @@ internal static PdfDocument Read(PdfSource source, EngineConfiguration configura configuration.MaxDecodedStreamLength, diagnostics, value => loader is not null ? loader.Resolve(value) : value is null or CosReference ? CosNull.Instance : value); - CrossReference crossReference = CrossReferenceReader.Read(source, header, streams, diagnostics) ?? Reconstruct(diagnostics); - loader = new ObjectLoader(source, header, crossReference, diagnostics, new ObjectLoaderHooks(), streams); + var scan = new Lazy(() => FileScan.Run(source), LazyThreadSafetyMode.ExecutionAndPublication); + CrossReference? crossReference = CrossReferenceReader.Read(source, header, streams, diagnostics, scan); + bool reconstructed = crossReference is null; + crossReference ??= Reconstruct(source, header, scan.Value, streams, diagnostics, reportMissingTrailer: true); + loader = new ObjectLoader(source, header, crossReference, diagnostics, new ObjectLoaderHooks(), streams) { Scan = scan }; + CosDictionary? catalog = ReadCatalog(loader, diagnostics, reportUnusableRoot: reconstructed); + if (catalog is null) + { + // §7.5.5: the trailer's Root shall lead to the catalog. When it does not, the cross-reference information is not + // trusted either: rebuild it by scanning, which also finds a catalog no trailer names. + diagnostics.Report( + DiagnosticCodes.RootMissing, + DiagnosticSeverity.Warning, + "The trailer has no Root entry that resolves to the catalog dictionary; the cross-reference information is rebuilt by scanning the file."); + crossReference = Reconstruct(source, header, scan.Value, streams, diagnostics, reportMissingTrailer: false); + loader = new ObjectLoader(source, header, crossReference, diagnostics, new ObjectLoaderHooks(), streams) { Scan = scan }; + catalog = ReadCatalog(loader, diagnostics, reportUnusableRoot: true)!; + } + IReadOnlyList revisions = ReadRevisions(source, crossReference, diagnostics); - CosDictionary catalog = ReadCatalog(loader, diagnostics); PdfLinearization? linearization = LinearizationReader.Read(source, loader, diagnostics); return new PdfDocument(source, diagnostics, loader, streams, catalog, revisions, linearization); } @@ -256,14 +280,32 @@ private static PdfRevision[] ReadRevisions(PdfSource source, CrossReference cros return revisions; } - /// Rebuilds the cross-reference information by scanning the file when it cannot be read (§7.5.4). Issue #41. - private static CrossReference Reconstruct(DiagnosticSink diagnostics) => - throw new DiagnosticException(diagnostics.Snapshot() is [.., var last] - ? last - : new Diagnostic(DiagnosticCodes.StartxrefMissing, DiagnosticSeverity.Error, "The cross-reference information cannot be read.")); + /// + /// Rebuilds the cross-reference information by scanning the file when it cannot be read or does not lead to the catalog (§7.5.4, + /// §7.5.5; issue #41). Throws when the file holds no catalog at all. + /// + private static CrossReference Reconstruct( + PdfSource source, + FileHeader header, + FileScan scan, + StreamDecoder streams, + DiagnosticSink diagnostics, + bool reportMissingTrailer) + { + CrossReference? crossReference = CrossReferenceReconstructor.Reconstruct(source, header, scan, streams, diagnostics, reportMissingTrailer); + if (crossReference is null) + { + diagnostics.Fail( + DiagnosticCodes.CatalogNotFound, + "The cross-reference information cannot be read, and scanning the file finds no catalog dictionary: the file cannot be read."); + } + + return crossReference; + } /// Loads the catalog through the trailer's Root and checks its Type and Version (§7.7.2). - private static CosDictionary ReadCatalog(ObjectLoader loader, DiagnosticSink diagnostics) + /// The catalog, or when Root does not resolve to a dictionary. + private static CosDictionary? ReadCatalog(ObjectLoader loader, DiagnosticSink diagnostics, bool reportUnusableRoot) { CosDictionary trailer = loader.CrossReference.Trailer; trailer.TryGetValue(KnownNames.Root, out CosObject? root); @@ -277,7 +319,11 @@ private static CosDictionary ReadCatalog(ObjectLoader loader, DiagnosticSink dia if (loader.Resolve(root) is not CosDictionary catalog) { - diagnostics.Fail(DiagnosticCodes.RootMissing, "The trailer has no Root entry that resolves to the catalog dictionary."); + if (reportUnusableRoot) + { + diagnostics.Fail(DiagnosticCodes.RootMissing, "The trailer has no Root entry that resolves to the catalog dictionary."); + } + return null; } diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index 49b61793..db463766 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -105,8 +105,9 @@ Broadside.Diagnostics.DiagnosticException.DiagnosticException(Broadside.Diagnost Broadside.Diagnostics.DiagnosticException.DiagnosticException(string? message) -> void Broadside.Diagnostics.DiagnosticException.DiagnosticException(string? message, System.Exception? innerException) -> void Broadside.Diagnostics.DiagnosticSeverity -Broadside.Diagnostics.DiagnosticSeverity.Error = 1 -> Broadside.Diagnostics.DiagnosticSeverity -Broadside.Diagnostics.DiagnosticSeverity.Warning = 0 -> Broadside.Diagnostics.DiagnosticSeverity +Broadside.Diagnostics.DiagnosticSeverity.Error = 2 -> Broadside.Diagnostics.DiagnosticSeverity +Broadside.Diagnostics.DiagnosticSeverity.Information = 0 -> Broadside.Diagnostics.DiagnosticSeverity +Broadside.Diagnostics.DiagnosticSeverity.Warning = 1 -> Broadside.Diagnostics.DiagnosticSeverity Broadside.Filters.Ascii85DecodeFilter Broadside.Filters.Ascii85DecodeFilter.Ascii85DecodeFilter() -> void Broadside.Filters.Ascii85DecodeFilter.Decode(System.ReadOnlyMemory encoded, System.Buffers.IBufferWriter! output, Broadside.Filters.FilterContext! context) -> void diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 332f7742..78a977de 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -23,6 +23,7 @@ internal static class FuzzTargets ["hint-tables"] = HintTables, ["xref-stream"] = XrefStream, ["object-stream"] = ObjectStreamTarget, + ["repair"] = Repair, ["filter-asciihex"] = data => Filter(new AsciiHexDecodeFilter(), data, parameters: null, maxRatio: 1), ["filter-ascii85"] = data => Filter(new Ascii85DecodeFilter(), data, parameters: null, maxRatio: 4), ["filter-lzw"] = Lzw, @@ -193,6 +194,58 @@ private static void HintTables(ReadOnlySpan data) } } + /// + /// Scans the input as a damaged file and rebuilds its cross-reference information from the scan, as a lenient open does when the + /// file's own cannot be read. Every position the scan reports must lie inside the input, in file order, and every rebuilt in-use + /// entry must point at an object header the scan found. + /// + /// ISO 32000-2 §7.5.4, §7.5.5 and §7.5.7 (repair itself is not specified; issue #41). + private static void Repair(ReadOnlySpan data) + { + var diagnostics = new DiagnosticSink(strict: false); + var streams = new StreamDecoder(FilterRegistry.Create([]), PdfOptions.DefaultMaxDecodedStreamLength, diagnostics, static value => value ?? CosNull.Instance); + using PdfSource source = PdfSource.FromMemory(data.ToArray()); + FileHeader header = FileHeader.Locate(source, diagnostics); + + FileScan scan = FileScan.Run(source); + CrossReference? crossReference = CrossReferenceReconstructor.Reconstruct(source, header, scan, streams, diagnostics); + + IReadOnlyList[] found = + [ + scan.XrefKeywords, scan.TrailerKeywords, scan.XrefStreamNames, scan.ObjectStreamNames, scan.CatalogNames, + [.. scan.Objects.Select(static item => item.Offset)], + ]; + foreach (IReadOnlyList positions in found) + { + for (int index = 0; index < positions.Count; index++) + { + if (positions[index] < 0 || positions[index] >= data.Length || (index > 0 && positions[index] <= positions[index - 1])) + { + throw new InvalidOperationException($"Scan position {positions[index]} is outside the input or out of order."); + } + } + } + + if (crossReference is null) + { + return; + } + + HashSet headers = [.. scan.Objects.Select(static item => item.Offset)]; + foreach (XrefEntry entry in crossReference.Sections.SelectMany(static section => section.Entries.Values)) + { + if (entry.Kind == XrefEntryKind.InUse && !headers.Contains(header.Offset + entry.Offset)) + { + throw new InvalidOperationException($"Rebuilt entry offset {entry.Offset} is not an object header the scan found."); + } + } + + if (!crossReference.Trailer.ContainsKey(KnownNames.Root)) + { + throw new InvalidOperationException("A rebuilt cross-reference has a trailer without Root."); + } + } + /// /// Reads the input as cross-reference stream data: bytes 0 to 2 are the field widths of W (0 to 9, so invalid widths are /// tried too), byte 3 selects whether Index is [0 Size] by default or two subsections, the rest is the data. The diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index e62cdaf7..aa0b41a8 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` for a file whose cross-reference information cannot be read is the one allowed outcome until #41 reconstructs it; it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. diff --git a/tests/Broadside.Tests/Document/BrokenCorpusTests.cs b/tests/Broadside.Tests/Document/BrokenCorpusTests.cs new file mode 100644 index 00000000..577c349f --- /dev/null +++ b/tests/Broadside.Tests/Document/BrokenCorpusTests.cs @@ -0,0 +1,81 @@ +using System.Text; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// +/// The deliberately broken corpus files (tests/Corpus/README.md, "Deliberately broken files"; ADR 0005): each opens leniently with +/// exactly the documented diagnostics and the same pages as its intact counterpart, and strict mode throws the first of them. +/// ISO 32000-2 §7.3.8.2, §7.3.10, §7.5.4, §7.5.5. +/// +public class BrokenCorpusTests +{ + /// File, intact counterpart, then the expected diagnostics as "Code object offset" ("-" when unknown), in order. + public static TheoryData BrokenFiles => new() + { + { "broken-xref-offsets.pdf", "empty-page.pdf", ["XrefEntryOffsetInvalid 1 19", "XrefEntryOffsetInvalid 2 68", "XrefEntryOffsetInvalid 3 125"] }, + { "missing-endobj.pdf", "empty-page.pdf", ["MissingEndobj 3 196"] }, + { "wrong-stream-length.pdf", "text-standard14.pdf", ["StreamLengthInvalid 4 267"] }, + { "no-xref.pdf", "empty-page.pdf", ["StartxrefMissing - -", "TrailerMissing - -"] }, + { "startxref-wrong.pdf", "empty-page.pdf", ["StartxrefInvalid - 303"] }, + }; + + [Theory] + [MemberData(nameof(BrokenFiles))] + public void A_broken_file_opens_leniently_with_exactly_the_documented_diagnostics_and_the_intact_pages( + string fileName, + string intactFileName, + string[] expected) + { + using PdfDocument intact = PdfDocument.Open(Corpus.Path(intactFileName)); + using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName)); + + Assert.Equal(Pages(intact), Pages(document)); + foreach (PdfPage page in document.Pages) + { + _ = document.Resolve(page.Dictionary.TryGetValue(new CosName("Contents"), out CosObject? contents) ? contents : null); + } + + Assert.Equal(expected, document.Diagnostics.Select(Describe)); + Assert.All(document.Diagnostics, static diagnostic => Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity)); + } + + [Theory] + [MemberData(nameof(BrokenFiles))] + public void Strict_mode_throws_on_a_broken_file_with_the_code_of_its_first_diagnostic(string fileName, string intactFileName, string[] expected) + { + _ = intactFileName; + + DiagnosticException error = Assert.Throws(() => + { + using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName), new PdfOptions().UseStrict()); + foreach (PdfPage page in document.Pages) + { + _ = document.Resolve(page.Dictionary.TryGetValue(new CosName("Contents"), out CosObject? contents) ? contents : null); + } + }); + + Assert.Equal(expected[0], Describe(error.Diagnostic)); + } + + [Fact] + public void A_wrong_stream_length_is_recovered_from_endstream_without_changing_the_length_entry() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("wrong-stream-length.pdf")); + + CosStream contents = Assert.IsType(document.Resolve(new CosReference(4, 0))); + + Assert.Equal("BT /F1 24 Tf 72 700 Td (Length is wrong) Tj ET", Encoding.Latin1.GetString(contents.EncodedData.Span)); + Assert.Equal(46, contents.EncodedData.Length); // §7.3.8.1: the end-of-line marker before endstream is not data. + Assert.Equal(new CosInteger(10), contents.Dictionary[new CosName("Length")]); + Assert.False(contents.IsDirty); + } + + private static string Pages(PdfDocument document) => DocumentProjection.Of(document).Pages; + + private static string Describe(Diagnostic diagnostic) => + $"{diagnostic.Code} {diagnostic.ObjectReference?.ObjectNumber.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "-"} " + + $"{diagnostic.Offset?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "-"}"; +} diff --git a/tests/Broadside.Tests/Document/CrossReferenceStreamTests.cs b/tests/Broadside.Tests/Document/CrossReferenceStreamTests.cs index 31f0fdfa..8f9027d6 100644 --- a/tests/Broadside.Tests/Document/CrossReferenceStreamTests.cs +++ b/tests/Broadside.Tests/Document/CrossReferenceStreamTests.cs @@ -169,14 +169,17 @@ public void A_stream_without_type_XRef_is_read_with_a_diagnostic() } [Fact] - public void A_stream_whose_W_cannot_be_read_is_not_a_cross_reference_section() + public void A_stream_whose_W_cannot_be_read_is_not_a_cross_reference_section_so_the_file_is_rebuilt_by_scanning() { var pdf = new XrefStreamPdf().AddOnePage(); byte[] file = pdf.Finish(4, "/Size 4 /Root 1 0 R /W [1 2]", W121, (0, 0, 255), (1, pdf.Offset(1), 0), (1, pdf.Offset(2), 0), (1, pdf.Offset(3), 0)); - DiagnosticException error = Assert.Throws(() => PdfDocument.Open(file)); + using PdfDocument document = PdfDocument.Open(file); - Assert.Equal("XrefStreamWidthsInvalid", error.Diagnostic.Code); + Assert.Single(document.Pages); + Assert.Equal(["XrefStreamWidthsInvalid"], document.Diagnostics.Select(static diagnostic => diagnostic.Code)); + Assert.Equal(new CosReference(1, 0), document.Trailer[new CosName("Root")]); + Assert.Throws(() => PdfDocument.Open(file, new PdfOptions().UseStrict())); } [Fact] diff --git a/tests/Broadside.Tests/Document/DiagnosticModelTests.cs b/tests/Broadside.Tests/Document/DiagnosticModelTests.cs new file mode 100644 index 00000000..7e8a443b --- /dev/null +++ b/tests/Broadside.Tests/Document/DiagnosticModelTests.cs @@ -0,0 +1,89 @@ +using System.Buffers; +using Broadside.Diagnostics; +using Broadside.Filters; +using Broadside.Objects; +using Broadside.Tests.Filters; +using Broadside.Tests.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Broadside.Tests.Document; + +/// +/// The public diagnostic model (ADR 0005): severities, what strict mode throws, and that each repair is recorded once. +/// +public class DiagnosticModelTests +{ + [Fact] + public void Severities_are_ordered_from_information_to_error() + { + Assert.True(DiagnosticSeverity.Information < DiagnosticSeverity.Warning); + Assert.True(DiagnosticSeverity.Warning < DiagnosticSeverity.Error); + } + + [Fact] + public void Information_is_recorded_and_never_thrown_even_in_strict_mode() + { + byte[] file = FilterTesting.FileWithStream("/Filter /NotedDecode", "data"u8); + using PdfDocument document = PdfDocument.Open(file, new PdfOptions().UseStrict().UseFilter(new NotingFilter())); + + ReadOnlyMemory decoded = document.DecodeStream((CosStream)document.Resolve(FilterTesting.StreamReference)); + + Assert.Equal("data"u8.ToArray(), decoded.ToArray()); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("FeatureNoted", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Information, diagnostic.Severity); + } + + [Fact] + public void Information_is_logged_at_the_information_level() + { + using var logs = new CapturingLoggerProvider(); + using ServiceProvider services = new ServiceCollection() + .AddLogging(logging => logging.AddProvider(logs)) + .AddBroadside(static options => options.UseFilter(new NotingFilter())) + .BuildServiceProvider(); + using PdfDocument document = services.GetRequiredService().Open(FilterTesting.FileWithStream("/Filter /NotedDecode", "data"u8)); + + _ = document.DecodeStream((CosStream)document.Resolve(FilterTesting.StreamReference)); + + Assert.Equal(LogLevel.Information, Assert.Single(logs.Entries).Level); + } + + [Fact] + public void Decoding_a_damaged_stream_twice_records_its_diagnostic_once() + { + using PdfDocument document = PdfDocument.Open(FilterTesting.FileWithStream("/Filter /ASCIIHexDecode", "4G1x42>"u8)); + var stream = (CosStream)document.Resolve(FilterTesting.StreamReference); + + _ = document.DecodeStream(stream); + _ = document.DecodeStream(stream); + + Assert.Equal("FilterDataInvalid", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void Strict_mode_throws_a_warning_every_time_it_is_met() + { + using PdfDocument document = PdfDocument.Open( + FilterTesting.FileWithStream("/Filter /ASCIIHexDecode", "4G1x42>"u8), + new PdfOptions().UseStrict()); + var stream = (CosStream)document.Resolve(FilterTesting.StreamReference); + + Assert.Equal("FilterDataInvalid", Assert.Throws(() => document.DecodeStream(stream)).Diagnostic.Code); + Assert.Equal("FilterDataInvalid", Assert.Throws(() => document.DecodeStream(stream)).Diagnostic.Code); + Assert.Single(document.Diagnostics); + } + + /// A pass-through filter that notes a legal feature it does not support, the use the Information severity is for. + private sealed class NotingFilter : IStreamFilter + { + public CosName Name { get; } = new("NotedDecode"); + + public void Decode(ReadOnlyMemory encoded, IBufferWriter output, FilterContext context) + { + context.Report("FeatureNoted", DiagnosticSeverity.Information, "The stream uses a feature that is read and preserved but not supported."); + output.Write(encoded.Span); + } + } +} diff --git a/tests/Broadside.Tests/Document/FileStructureTests.cs b/tests/Broadside.Tests/Document/FileStructureTests.cs index d464a478..4299666c 100644 --- a/tests/Broadside.Tests/Document/FileStructureTests.cs +++ b/tests/Broadside.Tests/Document/FileStructureTests.cs @@ -80,22 +80,40 @@ public void A_startxref_offset_on_the_white_space_before_xref_is_repaired_with_a } [Fact] - public void A_file_with_no_startxref_cannot_be_read_even_leniently() + public void A_file_with_no_startxref_is_rebuilt_by_scanning_and_keeps_its_trailer() { string text = Encoding.Latin1.GetString(Corpus.Bytes("empty-page.pdf")).Replace("startxref", "startxrex", StringComparison.Ordinal); - DiagnosticException error = Assert.Throws(() => PdfDocument.Open(Encoding.Latin1.GetBytes(text))); + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + + Assert.Equal(new PdfRectangle(0, 0, 612, 792), Assert.Single(document.Pages).MediaBox); + Assert.Equal("StartxrefMissing", Assert.Single(document.Diagnostics).Code); + Assert.Equal(new CosReference(1, 0), document.Trailer[new CosName("Root")]); + Assert.Equal(new CosInteger(4), document.Trailer[new CosName("Size")]); + Assert.Equal(text.Length, Assert.Single(document.Revisions).Length); + } + + [Fact] + public void A_file_that_holds_no_catalog_cannot_be_read_even_leniently() + { + DiagnosticException error = Assert.Throws(() => PdfDocument.Open(Encoding.Latin1.GetBytes("%PDF-1.7\n1 0 obj\n(text)\nendobj\n"))); - Assert.Equal("StartxrefMissing", error.Diagnostic.Code); + Assert.Equal("CatalogNotFound", error.Diagnostic.Code); } [Fact] - public void A_trailer_without_root_cannot_be_read() + public void A_trailer_without_root_is_repaired_by_finding_the_catalog_by_scanning() { string text = Encoding.Latin1.GetString(Corpus.Bytes("empty-page.pdf")).Replace("/Root 1 0 R", "/Rood 1 0 R", StringComparison.Ordinal); - DiagnosticException error = Assert.Throws(() => PdfDocument.Open(Encoding.Latin1.GetBytes(text))); + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + Assert.Single(document.Pages); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("RootMissing", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); + Assert.Equal(new CosReference(1, 0), document.Trailer[new CosName("Root")]); + DiagnosticException error = Assert.Throws(() => PdfDocument.Open(Encoding.Latin1.GetBytes(text), new PdfOptions().UseStrict())); Assert.Equal("RootMissing", error.Diagnostic.Code); } @@ -172,7 +190,7 @@ public void An_indirect_length_that_is_wrong_falls_back_to_endstream_with_a_diag } [Fact] - public void An_entry_whose_offset_does_not_hold_the_object_reads_as_null_with_a_diagnostic() + public void An_entry_whose_offset_does_not_hold_the_object_is_read_from_where_its_header_is_with_a_diagnostic() { byte[] file = new TestPdf().Build("<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>", "(three)"); string text = Encoding.Latin1.GetString(file); @@ -181,12 +199,30 @@ public void An_entry_whose_offset_does_not_hold_the_object_reads_as_null_with_a_ using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + CosObject three = document.Resolve(new CosReference(3, 0)); + Assert.Equal(new CosString("three"u8), three); + Assert.Same(three, document.Resolve(new CosReference(3, 0))); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("XrefEntryOffsetInvalid", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); + Assert.Equal(new CosReference(3, 0), diagnostic.ObjectReference); + Assert.Equal(third + 1, diagnostic.Offset); + } + + [Fact] + public void An_entry_for_an_object_the_file_does_not_hold_reads_as_null_with_an_error() + { + byte[] file = new TestPdf().Build("<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [] /Count 0 >>", "(three)"); + string text = Encoding.Latin1.GetString(file).Replace("3 0 obj", "4 0 obj", StringComparison.Ordinal); + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + Assert.Same(CosNull.Instance, document.Resolve(new CosReference(3, 0))); Assert.Same(CosNull.Instance, document.Resolve(new CosReference(3, 0))); Diagnostic diagnostic = Assert.Single(document.Diagnostics); Assert.Equal("XrefEntryOffsetInvalid", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity); Assert.Equal(new CosReference(3, 0), diagnostic.ObjectReference); - Assert.Equal(third + 1, diagnostic.Offset); } [Fact] diff --git a/tests/Broadside.Tests/Document/RepairTests.cs b/tests/Broadside.Tests/Document/RepairTests.cs new file mode 100644 index 00000000..008e510a --- /dev/null +++ b/tests/Broadside.Tests/Document/RepairTests.cs @@ -0,0 +1,188 @@ +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// +/// Damage the minimal corpus does not cover, built in the test from a well-formed corpus file: lenient reading repairs it with +/// diagnostics (ADR 0005). ISO 32000-2 §7.3.8.2, §7.5.2, §7.5.4, §7.5.5, §7.5.6, §7.5.7, §7.5.8. +/// +public partial class RepairTests +{ + [Fact] + public void A_file_whose_line_endings_were_converted_to_crlf_opens_with_the_intact_pages() + { + string text = Latin1("empty-page.pdf").Replace("\n", "\r\n", StringComparison.Ordinal); + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + + Assert.Equal(new PdfRectangle(0, 0, 612, 792), Assert.Single(document.Pages).MediaBox); + Assert.Equal("StartxrefInvalid", document.Diagnostics[0].Code); + Assert.Contains(document.Diagnostics, static diagnostic => diagnostic.Code == "XrefEntryOffsetInvalid"); + Assert.All(document.Diagnostics, static diagnostic => Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity)); + } + + [Fact] + public void Offsets_counted_from_byte_0_instead_of_the_header_are_repaired() + { + // §7.5.2: offsets count from the %PDF- header; this writer counted from the start of the file, before 300 bytes of junk. + const int junk = 300; + string text = new string('J', junk) + OffsetPattern().Replace(Latin1("empty-page.pdf"), static match => + (long.Parse(match.Value, CultureInfo.InvariantCulture) + junk).ToString(match.Length == 10 ? "D10" : "D", CultureInfo.InvariantCulture)); + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + + Assert.Equal(new PdfRectangle(0, 0, 612, 792), Assert.Single(document.Pages).MediaBox); + Assert.Equal( + ["StartxrefInvalid", "XrefEntryOffsetInvalid", "XrefEntryOffsetInvalid", "XrefEntryOffsetInvalid"], + document.Diagnostics.Select(static diagnostic => diagnostic.Code)); + } + + [Fact] + public void A_wrong_prev_offset_reads_the_nearest_older_section() + { + string text = Latin1("incremental-update.pdf").Replace("/Prev 203", "/Prev 230", StringComparison.Ordinal); + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + + Assert.Equal(new PdfRectangle(0, 0, 595, 842), Assert.Single(document.Pages).MediaBox); + Assert.Equal(2, document.Revisions.Count); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("TrailerPrevInvalid", diagnostic.Code); + Assert.Equal(230, diagnostic.Offset); + } + + [Fact] + public void Rebuilding_an_updated_file_keeps_the_newest_copy_of_each_object_and_the_newest_trailer() + { + string text = Latin1("incremental-update.pdf").Replace("startxref", "startxrex", StringComparison.Ordinal); + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + + Assert.Equal(new PdfRectangle(0, 0, 595, 842), Assert.Single(document.Pages).MediaBox); + Assert.Equal("StartxrefMissing", Assert.Single(document.Diagnostics).Code); + Assert.False(document.Trailer.ContainsKey(new CosName("Prev"))); + } + + [Fact] + public void Rebuilding_an_encrypted_file_keeps_its_encryption_dictionary_and_identifier() + { + string text = Latin1("encrypted-rc4-40.pdf").Replace("startxref", "startxrex", StringComparison.Ordinal); + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + + Assert.Single(document.Pages); + Assert.IsType(document.Resolve(document.Trailer[new CosName("Encrypt")])); + Assert.IsType(document.Trailer[new CosName("ID")]); + } + + [Fact] + public void Objects_in_object_streams_survive_a_damaged_cross_reference_stream() + { + string text = Latin1("object-stream.pdf").Replace("/W [1 2 1]", "/W [1 2 ]", StringComparison.Ordinal); + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + + Assert.Equal(new PdfRectangle(0, 0, 612, 792), Assert.Single(document.Pages).MediaBox); + Assert.Equal(["XrefStreamWidthsInvalid"], document.Diagnostics.Select(static diagnostic => diagnostic.Code)); + } + + [Fact] + public void A_compressed_catalog_is_found_when_no_trailer_survives() + { + string text = Latin1("object-stream.pdf") + .Replace("/Type /XRef", "/Type /XReg", StringComparison.Ordinal) + .Replace("startxref", "startxrex", StringComparison.Ordinal); + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + + Assert.Equal(new PdfRectangle(0, 0, 612, 792), Assert.Single(document.Pages).MediaBox); + Assert.Equal(["StartxrefMissing", "TrailerMissing"], document.Diagnostics.Select(static diagnostic => diagnostic.Code)); + Assert.Equal(new CosReference(1, 0), document.Trailer[new CosName("Root")]); + } + + [Fact] + public void A_subsection_numbered_from_1_whose_first_entry_is_the_free_list_head_is_renumbered_from_0() + { + string text = Latin1("empty-page.pdf").Replace("xref\n0 4\n", "xref\n1 4\n", StringComparison.Ordinal); + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + + Assert.Equal(new PdfRectangle(0, 0, 612, 792), Assert.Single(document.Pages).MediaBox); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("XrefSubsectionNumberingInvalid", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); + } + + [Fact] + public void Entries_that_are_not_20_bytes_long_are_read_with_one_diagnostic_per_section() + { + string text = Latin1("empty-page.pdf").Replace(" n \n", " n\n", StringComparison.Ordinal); + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + + Assert.Single(document.Pages); + Assert.Equal(["XrefEntryFormatInvalid"], document.Diagnostics.Select(static diagnostic => diagnostic.Code)); + } + + [Fact] + public void Stream_lengths_that_refer_to_each_other_are_recovered_from_endstream() + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [] /Count 0 >>", + "<< /Length 4 0 R >>\nstream\nthree\nendstream", + "<< /Length 3 0 R >>\nstream\nfour\nendstream")); + + CosStream three = Assert.IsType(document.Resolve(new CosReference(3, 0))); + + Assert.Equal("three", Encoding.Latin1.GetString(three.EncodedData.Span)); + Assert.Equal( + ["StreamLengthInvalid 4", "StreamLengthInvalid 3"], + document.Diagnostics.Select(static diagnostic => $"{diagnostic.Code} {diagnostic.ObjectReference?.ObjectNumber}")); + } + + [Fact] + public void A_stream_without_endstream_ends_at_endobj() + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [] /Count 0 >>", + "<< /Length 99 >>\nstream\nthree")); + + CosStream three = Assert.IsType(document.Resolve(new CosReference(3, 0))); + + Assert.Equal("three", Encoding.Latin1.GetString(three.EncodedData.Span)); + Assert.Equal(["EndstreamMissing"], document.Diagnostics.Select(static diagnostic => diagnostic.Code)); + } + + [Fact] + public void A_repair_met_twice_is_recorded_once() + { + byte[] file = Encoding.Latin1.GetBytes(Latin1("empty-page.pdf").Replace("0000000115 00000 n", "0000000117 00000 n", StringComparison.Ordinal)); + using PdfDocument document = PdfDocument.Open(file); + + Parallel.For(0, 8, _ => document.Resolve(new CosReference(3, 0))); + _ = document.Pages.Count; + + Assert.Equal("XrefEntryOffsetInvalid", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_file_with_nothing_but_junk_cannot_be_read() + { + DiagnosticException error = Assert.Throws(() => PdfDocument.Open(Encoding.Latin1.GetBytes(new string('x', 5000)))); + + Assert.Equal("CatalogNotFound", error.Diagnostic.Code); + } + + private static string Latin1(string fileName) => Encoding.Latin1.GetString(Corpus.Bytes(fileName)); + + /// The 10-digit entry offsets of the table and the startxref value. + [GeneratedRegex(@"\d{10}(?= 00000 n)|(?<=startxref\n)\d+")] + private static partial Regex OffsetPattern(); +} diff --git a/tests/Corpus/README.md b/tests/Corpus/README.md index 792a46b6..9c22c2cf 100644 --- a/tests/Corpus/README.md +++ b/tests/Corpus/README.md @@ -64,15 +64,15 @@ The crypt filter `/Length` entries in the R4 and R6 files are `16` and `32` (byt ## Deliberately broken files -Each file is `empty-page.pdf` (or `text-standard14.pdf`) with exactly one defect. The "lenient mode" column says what a Phase 1 reader is expected to do under ADR 0005: repair, record one `Diagnostic`, and expose the same document as the intact file. In strict mode the same condition is an error. The diagnostic names are the ones Phase 1 is expected to define; adjust this table if the final names differ. +Each file is `empty-page.pdf` (or `text-standard14.pdf`) with exactly one defect. The "lenient mode" column says what a Phase 1 reader is expected to do under ADR 0005: repair, record one `Diagnostic`, and expose the same document as the intact file. In strict mode the same condition is an error: the `DiagnosticException` carries the first diagnostic listed. The codes, objects and offsets (absolute, from byte 0) below are what Broadside records, all at `Warning` severity; `BrokenCorpusTests` asserts them exactly. | File | Defect | Clauses | What qpdf 12.4.2 and poppler report | Lenient mode | |---|---|---|---|---| -| `broken-xref-offsets.pdf` | Every in-use entry in the cross-reference table is 10 bytes past the object it points to. | 7.5.4 | qpdf (exit 3): `file is damaged`, `(object 1 0, offset 19): expected n n obj`, `Attempting to reconstruct cross-reference table`. pdfinfo opens the file and prints `Internal Error: xref num 1 not found but needed, try to reconstruct`. | Reconstruct the table by scanning for `N G obj` headers; record `XrefEntryOffsetInvalid` (or one `XrefReconstructed`) and open the document with one Letter page. | -| `missing-endobj.pdf` | Object 3 (the page) has no `endobj`; the `xref` keyword follows its dictionary directly. | 7.3.10 | qpdf (exit 3): `(object 3 0, offset 196): expected endobj`. pdfinfo: clean. | Parse the object, treat the next keyword as the end of the object, record `MissingEndobj` for object 3; the page is intact. | -| `wrong-stream-length.pdf` | The content stream says `/Length 10` but holds 47 bytes; `endstream` is at the correct place. | 7.3.8.2 | qpdf (exit 3): `(object 4 0, offset 284): expected endstream`, `attempting to recover stream length`, `recovered stream length: 47`. pdftotext prints `Length is wrong` and then `Syntax Error (331): Missing 'endstream' or incorrect stream length`. | Recover the length by searching for `endstream` (47 bytes), record `StreamLengthInvalid` for object 4; `pdftotext`-equivalent output is `Length is wrong`. | -| `no-xref.pdf` | No `xref`, `trailer` or `startxref` at all; the objects are followed by `%%EOF`. | 7.5.4, 7.5.5 | qpdf (exit 3): `can't find startxref`, `Attempting to reconstruct cross-reference table`, `unable to find trailer dictionary while recovering damaged file`, then opens the document (it finds the catalog by scanning). pdfinfo and pdftotext fail (exit 1): `Couldn't find trailer dictionary`, `Couldn't read xref table`. | Reconstruct the table by scanning, locate the catalog by scanning for `/Type /Catalog`, record `StartxrefMissing` and `TrailerMissing`; the document opens with one Letter page. | -| `startxref-wrong.pdf` | `startxref` points 100 bytes past the real `xref` keyword (into the table body). | 7.5.5 | qpdf (exit 3): `(offset 303): xref not found`, `Attempting to reconstruct cross-reference table`. pdfinfo: clean. | Search near the stated offset for the `xref` keyword (or reconstruct by scanning), record `StartxrefInvalid`; the document opens with one Letter page. | +| `broken-xref-offsets.pdf` | Every in-use entry in the cross-reference table is 10 bytes past the object it points to. | 7.5.4 | qpdf (exit 3): `file is damaged`, `(object 1 0, offset 19): expected n n obj`, `Attempting to reconstruct cross-reference table`. pdfinfo opens the file and prints `Internal Error: xref num 1 not found but needed, try to reconstruct`. | Look for each object's `N G obj` header near the stated offset (then in a scan of the whole file) and read it there; record one `XrefEntryOffsetInvalid` per object as it loads: object 1 at offset 19 (on open), objects 2 and 3 at offsets 68 and 125 (when the pages are read). The document has one Letter page. | +| `missing-endobj.pdf` | Object 3 (the page) has no `endobj`; the `xref` keyword follows its dictionary directly. | 7.3.10 | qpdf (exit 3): `(object 3 0, offset 196): expected endobj`. pdfinfo: clean. | Parse the object, treat the next keyword as the end of the object, record `MissingEndobj` for object 3 at offset 196 (the `xref` keyword); the page is intact. | +| `wrong-stream-length.pdf` | The content stream says `/Length 10` but holds 46 bytes of data followed by the end-of-line marker before `endstream` (7.3.8.1: the marker is not part of the data, so qpdf's 47 counts one byte too many); `endstream` is at the correct place. | 7.3.8.2 | qpdf (exit 3): `(object 4 0, offset 284): expected endstream`, `attempting to recover stream length`, `recovered stream length: 47`. pdftotext prints `Length is wrong` and then `Syntax Error (331): Missing 'endstream' or incorrect stream length`. | Recover the length by searching for `endstream` (46 bytes, without the end-of-line marker), record `StreamLengthInvalid` for object 4 at offset 267 (the `stream` keyword); the `/Length` entry is left as stored. `pdftotext`-equivalent output is `Length is wrong`. | +| `no-xref.pdf` | No `xref`, `trailer` or `startxref` at all; the objects are followed by `%%EOF`. | 7.5.4, 7.5.5 | qpdf (exit 3): `can't find startxref`, `Attempting to reconstruct cross-reference table`, `unable to find trailer dictionary while recovering damaged file`, then opens the document (it finds the catalog by scanning). pdfinfo and pdftotext fail (exit 1): `Couldn't find trailer dictionary`, `Couldn't read xref table`. | Reconstruct the table by scanning, locate the catalog by scanning for `/Type /Catalog`, record `StartxrefMissing` and `TrailerMissing` (neither has an offset or object); the document opens with one Letter page. | +| `startxref-wrong.pdf` | `startxref` points 100 bytes past the real `xref` keyword (into the table body). | 7.5.5 | qpdf (exit 3): `(offset 303): xref not found`, `Attempting to reconstruct cross-reference table`. pdfinfo: clean. | Read the cross-reference section nearest to the stated offset (the `xref` keyword at 203), record `StartxrefInvalid` at offset 303; the document opens with one Letter page. | ## Adding a file From dc2eb09b4cda7981e3c778f2bbc63147badad66e Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:36:24 -0500 Subject: [PATCH 011/152] feat(writing): save unchanged documents and create an empty one (#44) PdfDocument.Save(Stream|path[, PdfSaveOptions]) and SaveAsync write a complete file: header with binary comment, every in-use object under its own number and generation, a classic cross-reference table or a cross-reference stream, with or without object streams (PdfCrossReferenceLayout), and a trailer with file identifiers. Objects that are unchanged and were read without repair are copied from their source bytes, which the loader now records per object (file body ranges and object-stream member slices); changed and repaired objects are serialized. Old xref streams, object streams and linearization data are dropped unless something refers to them. Save and SaveAsync share one chunked writer, so they write the same bytes. Encrypted documents are refused until Phase 4E. PdfDocument.Create / PdfEngine.Create build a PDF 2.0 document with one empty Letter page. Adds the `save` fuzz target, DocumentSaveBenchmarks, qpdf/pdfinfo checks in tests (skipped when absent; CI installs them on Linux). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 5 + .../DocumentSaveBenchmarks.cs | 33 ++ docs/conformance/iso-32000-2.md | 20 +- src/Broadside/Parsing/CrossReference.cs | 3 + src/Broadside/Parsing/ObjectLoader.cs | 46 +- src/Broadside/Parsing/ObjectSourceBytes.cs | 43 ++ src/Broadside/Parsing/ObjectStream.cs | 40 +- src/Broadside/PdfCrossReferenceLayout.cs | 38 ++ src/Broadside/PdfDocument.cs | 143 +++++- src/Broadside/PdfEngine.cs | 11 +- src/Broadside/PdfSaveOptions.cs | 42 ++ src/Broadside/PublicAPI.Unshipped.txt | 14 + src/Broadside/Writing/FileWriter.cs | 432 ++++++++++++++++++ src/Broadside/Writing/SavePlan.cs | 223 +++++++++ tests/Broadside.Fuzz/FuzzTargets.cs | 35 ++ tests/Broadside.Fuzz/README.md | 4 +- tests/Broadside.Tests/Document/EngineTests.cs | 7 - tests/Broadside.Tests/Writing/CreateTests.cs | 73 +++ tests/Broadside.Tests/Writing/ExternalTool.cs | 54 +++ tests/Broadside.Tests/Writing/ObjectBodies.cs | 87 ++++ tests/Broadside.Tests/Writing/SaveTests.cs | 425 +++++++++++++++++ 21 files changed, 1746 insertions(+), 32 deletions(-) create mode 100644 bench/Broadside.Benchmarks/DocumentSaveBenchmarks.cs create mode 100644 src/Broadside/Parsing/ObjectSourceBytes.cs create mode 100644 src/Broadside/PdfCrossReferenceLayout.cs create mode 100644 src/Broadside/PdfSaveOptions.cs create mode 100644 src/Broadside/Writing/FileWriter.cs create mode 100644 src/Broadside/Writing/SavePlan.cs create mode 100644 tests/Broadside.Tests/Writing/CreateTests.cs create mode 100644 tests/Broadside.Tests/Writing/ExternalTool.cs create mode 100644 tests/Broadside.Tests/Writing/ObjectBodies.cs create mode 100644 tests/Broadside.Tests/Writing/SaveTests.cs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0b2a23e1..ff6c50d4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -60,6 +60,11 @@ jobs: timeout-minutes: 20 run: dotnet workload install macos ios maccatalyst android + - name: Install qpdf and poppler-utils (Linux) + # Written files are checked with qpdf --check and pdfinfo (issue #44); the tests skip where the tools are missing. + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y qpdf poppler-utils + - name: Restore run: dotnet restore Broadside.slnx diff --git a/bench/Broadside.Benchmarks/DocumentSaveBenchmarks.cs b/bench/Broadside.Benchmarks/DocumentSaveBenchmarks.cs new file mode 100644 index 00000000..8689e329 --- /dev/null +++ b/bench/Broadside.Benchmarks/DocumentSaveBenchmarks.cs @@ -0,0 +1,33 @@ +using BenchmarkDotNet.Attributes; +using Broadside.TestSupport; + +namespace Broadside.Benchmarks; + +/// +/// Opens a corpus file from memory and saves it, unchanged, to a null stream in each cross-reference layout (ISO 32000-2 §7.5): every +/// object loaded, unchanged objects copied from their source bytes, and a new cross-reference table or stream (with object streams, +/// Flate-encoded). Saving builds output by design, so Allocated is a baseline to watch, not a zero to assert. +/// +[MemoryDiagnoser] +public class DocumentSaveBenchmarks +{ + private byte[] _bytes = []; + + /// The corpus file to save: one page, an embedded font, and a file with an object stream. + [Params("empty-page.pdf", "text-truetype-embedded.pdf", "object-stream.pdf")] + public string File { get; set; } = ""; + + /// The layout to write. + [Params(PdfCrossReferenceLayout.Table, PdfCrossReferenceLayout.StreamWithObjectStreams)] + public PdfCrossReferenceLayout Layout { get; set; } + + [GlobalSetup] + public void Setup() => _bytes = System.IO.File.ReadAllBytes(Path.Combine(CorpusLocator.CorpusDirectory, File)); + + [Benchmark] + public void OpenAndSave() + { + using PdfDocument document = PdfDocument.Open(_bytes); + document.Save(Stream.Null, new PdfSaveOptions().WithCrossReferenceLayout(Layout)); + } +} diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index 4db34fed..e5fe9baf 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -16,9 +16,9 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.3.5 | Name objects | done | `CosName` | `Broadside.Tests.Objects.StringAndNameParsingTests.Names_from_table_4_expand_number_sign_escapes`, `Broadside.Tests.Objects.StringAndNameParsingTests.Names_are_equal_when_their_expanded_bytes_are_equal`, `Broadside.Tests.Objects.SerializationTests.Names_escape_delimiters_white_space_number_signs_and_non_ascii_bytes` | | | 7.3.6 | Array objects | done | `CosArray` | `Broadside.Tests.Objects.ContainerParsingTests.Parses_the_array_example`, `Broadside.Tests.Objects.ContainerParsingTests.Arrays_nest_hold_references_and_keep_null_elements` | | | 7.3.7 | Dictionary objects | done | `CosDictionary` | `Broadside.Tests.Objects.ContainerParsingTests.Parses_the_dictionary_example`, `Broadside.Tests.Objects.ContainerParsingTests.A_null_valued_entry_is_the_same_as_an_absent_one` | Null-valued entries are never stored | -| 7.3.8 | Stream objects | partial | `CosStream` | `Broadside.Tests.Objects.ContainerParsingTests.A_stream_takes_its_data_from_its_length_or_from_endstream`, `Broadside.Tests.Objects.ContainerParsingTests.Streams_with_a_wrong_length_or_no_endstream_are_rejected`, `Broadside.Tests.Objects.CorpusObjectTests.The_metadata_stream_of_metadata_xmp_pdf_holds_its_declared_length` | Extent from a direct or indirect Length (`Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length`), else from endstream; filters decode through `PdfDocument.DecodeStream` (7.4) with DL as a capacity hint; external stream files (F, FFilter, FDecodeParms) are not read: `StreamExternalFileUnsupported` and the embedded bytes decode instead (`Broadside.Tests.Filters.FilterPipelineTests.Data_in_an_external_file_is_not_read_and_the_stream_bytes_decode_instead_with_a_diagnostic`) | +| 7.3.8 | Stream objects | partial | `CosStream`, `FileWriter` | `Broadside.Tests.Objects.ContainerParsingTests.A_stream_takes_its_data_from_its_length_or_from_endstream`, `Broadside.Tests.Objects.ContainerParsingTests.Streams_with_a_wrong_length_or_no_endstream_are_rejected`, `Broadside.Tests.Objects.CorpusObjectTests.The_metadata_stream_of_metadata_xmp_pdf_holds_its_declared_length`, `Broadside.Tests.Writing.SaveTests.A_repaired_object_is_written_as_repaired_so_the_saved_file_needs_no_repair` | Extent from a direct or indirect Length (`Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length`), else from endstream; filters decode through `PdfDocument.DecodeStream` (7.4) with DL as a capacity hint; external stream files (F, FFilter, FDecodeParms) are not read: `StreamExternalFileUnsupported` and the embedded bytes decode instead (`Broadside.Tests.Filters.FilterPipelineTests.Data_in_an_external_file_is_not_read_and_the_stream_bytes_decode_instead_with_a_diagnostic`); written as `stream` LF, the data, LF `endstream` with a direct Length equal to the data; a stream read with a wrong Length is re-serialized with the right one, never copied (#44) | | 7.3.9 | Null object | done | `CosNull` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_null_as_the_single_null_object`, `Broadside.Tests.Objects.ContainerParsingTests.A_null_valued_entry_is_the_same_as_an_absent_one` | | -| 7.3.10 | Indirect objects | done | `CosReference`, `PdfDocument` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_indirect_references`, `Broadside.Tests.Document.FileStructureTests.References_to_missing_free_or_other_generation_objects_resolve_to_null_without_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.An_object_without_endobj_is_read_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_reads_as_null_with_a_diagnostic` | `PdfDocument.Resolve`; references to missing, free or other-generation objects are null with no diagnostic; loading goes through the internal `ObjectLoader` (hooks for #41, #42, #45); a misplaced object reads as null until #41 searches for it | +| 7.3.10 | Indirect objects | done | `CosReference`, `PdfDocument`, `FileWriter`, `SavePlan` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_indirect_references`, `Broadside.Tests.Document.FileStructureTests.References_to_missing_free_or_other_generation_objects_resolve_to_null_without_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.An_object_without_endobj_is_read_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_reads_as_null_with_a_diagnostic`, `Broadside.Tests.Writing.SaveTests.Objects_that_were_not_changed_keep_their_source_bytes_in_any_layout`, `Broadside.Tests.Writing.SaveTests.Bytes_a_canonical_writer_would_change_are_kept_in_every_layout`, `Broadside.Tests.Writing.SaveTests.A_changed_object_is_written_with_its_new_value_and_the_others_keep_their_bytes` | `PdfDocument.Resolve`; references to missing, free or other-generation objects are null with no diagnostic; loading goes through the internal `ObjectLoader` (hooks for #41, #42, #45); a misplaced object reads as null until #41 searches for it; a save writes `N G obj` LF value LF `endobj` under the source number and generation; an unchanged object read without repair keeps its exact bytes (from the first token after obj to the end of its last token), others are serialized (#44) | | 7.4.1 | General | done | `IStreamFilter`, `FilterContext`, `StreamDecoder`, `FilterRegistry`, `PdfDocument`, `PdfOptions` | `Broadside.Tests.Filters.CorpusFilterTests.A_filtered_content_stream_decodes_to_the_bytes_that_were_encoded`, `Broadside.Tests.Filters.CorpusFilterTests.Every_page_content_stream_of_a_well_formed_file_decodes_with_no_diagnostics`, `Broadside.Tests.Filters.FilterPipelineTests.Filters_apply_in_array_order_and_the_same_filter_may_appear_twice`, `Broadside.Tests.Filters.FilterPipelineTests.Decode_parameters_align_with_the_filter_array_and_null_means_defaults`, `Broadside.Tests.Filters.FilterPipelineTests.Deviations_from_table_5_are_repaired_with_one_diagnostic`, `Broadside.Tests.Filters.FilterPipelineTests.An_unknown_filter_leaves_the_stream_readable_as_raw_bytes_with_a_diagnostic`, `Broadside.Tests.Filters.FilterPipelineTests.Output_beyond_the_decoded_length_limit_is_truncated_with_a_diagnostic`, `Broadside.Tests.Filters.FilterExtensionPointTests.A_decorator_registered_through_the_options_replaces_the_default_flate_filter`, `Broadside.Tests.Filters.FilterExtensionPointTests.Two_engines_in_one_process_keep_their_own_filters` | `PdfDocument.DecodeStream`; filter extension point `PdfOptions.UseFilter` (per engine, no static registry); unknown or not-yet-implemented filters stop the chain with `FilterUnsupported`; decoded-length limit `PdfOptions.WithMaxDecodedStreamLength`; fuzz targets `filter-*`, `document` decodes page contents; Table 92 abbreviations outside inline images read with a diagnostic | | 7.4.2 | ASCIIHexDecode filter | done | `AsciiHexDecodeFilter` | `Broadside.Tests.Filters.AsciiFilterTests.Ascii_hex_decodes_digit_pairs_ignores_white_space_and_pads_an_odd_final_digit`, `Broadside.Tests.Filters.AsciiFilterTests.Ascii_hex_skips_invalid_characters_with_one_diagnostic`, `Broadside.Tests.Filters.AsciiFilterTests.Ascii_hex_without_the_end_marker_decodes_to_its_end_with_a_diagnostic`, `Broadside.Tests.Filters.AsciiFilterTests.Both_filters_round_trip_the_encoders_of_the_corpus_generator` | Decode; `asciihex-stream.pdf`; `AsciiHexBenchmarks`; fuzz `filter-asciihex`; encoding is Phase 4 | | 7.4.3 | ASCII85Decode filter | done | `Ascii85DecodeFilter` | `Broadside.Tests.Filters.AsciiFilterTests.Ascii85_decodes_groups_z_partial_groups_and_ignores_white_space`, `Broadside.Tests.Filters.AsciiFilterTests.Ascii85_repairs_impossible_sequences_with_a_diagnostic`, `Broadside.Tests.Filters.AsciiFilterTests.Ascii85_without_the_end_marker_decodes_the_partial_group_with_a_diagnostic`, `Broadside.Tests.Filters.AsciiFilterTests.Strict_mode_throws_for_an_invalid_character` | Decode; `ascii85-stream.pdf`, `filter-chain.pdf`; `Ascii85Benchmarks`; fuzz `filter-ascii85`; encoding is Phase 4 | @@ -30,13 +30,13 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.4.9 | JPXDecode filter | not started | | | Phase 2B (#67, #68) | | 7.4.10 | Crypt filter | partial | `StreamDecoder`, `ICryptFilterHandler` | `Broadside.Tests.Filters.FilterPipelineTests.The_identity_crypt_filter_passes_the_data_through`, `Broadside.Tests.Filters.FilterPipelineTests.A_crypt_filter_the_security_handler_does_not_know_leaves_the_data_encrypted_with_a_diagnostic`, `Broadside.Tests.Filters.FilterPipelineTests.A_crypt_filter_that_is_not_first_is_applied_where_it_is_with_a_diagnostic` | Slot only: Identity passes through, other crypt filter names are `CryptFilterUnsupported` until the security handler (#42) sets `StreamDecoder.CryptFilter` | | 7.5.1 | General | done | `PdfDocument`, `CrossReferenceReader` | `Broadside.Tests.Document.OpenDocumentTests.A_file_opens_identically_from_a_path_a_stream_and_bytes_with_no_diagnostics`, `Broadside.Tests.Document.WellFormedCorpusTests.A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics` | Read from the end through startxref, the cross-reference table and the trailer, never serially; linearized files read through the same path (Annex F) | -| 7.5.2 | File header | done | `FileHeader`, `PdfVersion`, `PdfDocument` | `Broadside.Tests.Document.FileStructureTests.Offsets_count_from_the_header_so_bytes_before_it_do_not_matter`, `Broadside.Tests.Document.FileStructureTests.A_file_without_a_header_opens_from_byte_0_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_header_without_a_valid_version_takes_the_catalog_version_with_a_diagnostic` | Header searched in the first 1024 bytes; every stated offset is relative to it; missing header: offsets from byte 0, version 1.4 unless the catalog says otherwise; the unshifted-offset retry is #41 | -| 7.5.3 | File body | done | `ObjectLoader` | `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length` | Objects load lazily by cross-reference entry, from the file body or an object stream (7.5.7) | -| 7.5.4 | Cross-reference table | partial | `XrefTableReader`, `CrossReference` | `Broadside.Tests.Document.FileStructureTests.Entries_are_read_as_tokens_not_fixed_width_records`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_reads_as_null_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation` | Subsections and n/f entries read as tokens; offset-0 in-use entries read as free; reconstruction by scanning when the table is wrong, and diagnostics for non-20-byte entries and comments, are #41 | -| 7.5.5 | File trailer | partial | `CrossReferenceReader`, `CrossReference`, `PdfDocument` | `Broadside.Tests.Document.FileStructureTests.A_startxref_offset_on_the_white_space_before_xref_is_repaired_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_file_with_no_startxref_cannot_be_read_even_leniently`, `Broadside.Tests.Document.FileStructureTests.A_trailer_without_root_cannot_be_read`, `Broadside.Tests.Document.FileStructureTests.A_prev_chain_that_loops_ends_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic` | Last startxref, Prev chain with loop guard, Root; trailer merged newest-first; ignoring entries beyond Size, startxref recovery and trailer reconstruction are #41; Encrypt is #42 | -| 7.5.6 | Incremental updates | done | `CrossReference`, `RevisionReader`, `PdfRevision`, `PdfDocument` | `Broadside.Tests.Document.IncrementalUpdateTests.An_updated_file_has_one_revision_per_update_and_the_first_is_the_original_file`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_is_the_file_as_it_was_after_that_save`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_has_its_own_trailer`, `Broadside.Tests.Document.IncrementalUpdateTests.A_hybrid_file_has_its_main_section_and_its_update_section_as_two_revisions`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_earlier_revision_without_its_end_of_file_marker_ends_after_its_startxref_offset_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev` | Revisions oldest first, each the byte prefix up to its %%EOF and end-of-line; newest section decides per object number, free hides older copies, a reference must match the live generation; Root, Info, Encrypt and ID missing from the newest trailer are taken from an older one with TrailerEntryFromOlderRevision; a linearized pair is one revision; a hybrid XRefStm stream joins its table's revision; writing updates is #44 | -| 7.5.7 | Object streams | done | `ObjectStream`, `ObjectLoader` | `Broadside.Tests.Document.ObjectStreamTests.The_catalog_page_tree_and_page_resolve_from_an_object_stream`, `Broadside.Tests.Document.ObjectStreamTests.A_reference_to_a_member_with_a_generation_other_than_0_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.Members_need_no_white_space_between_them`, `Broadside.Tests.Document.ObjectStreamTests.A_member_at_another_index_than_its_entry_says_is_found_by_its_object_number`, `Broadside.Tests.Document.ObjectStreamTests.Offsets_out_of_order_bound_each_member_by_the_next_offset_in_sorted_order`, `Broadside.Tests.Document.ObjectStreamTests.A_member_the_object_stream_does_not_hold_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_whose_N_is_one_of_its_own_members_resolves_its_members_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_listed_as_compressed_itself_is_not_read`, `Broadside.Tests.Document.ObjectStreamTests.A_type_2_entry_naming_an_object_that_is_not_a_stream_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.A_flate_encoded_object_stream_is_decoded_through_the_filters`, `Broadside.Tests.Document.ObjectStreamTests.Members_of_one_object_stream_resolve_to_the_same_instances_from_concurrent_threads`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file` | Members located by type 2 entries (index checked against the header, searched by number when wrong, with ObjectStreamIndexMismatch); each member parsed over exactly the bytes up to the next offset (NOTE 7); out-of-order offsets sorted; container decoded once per document and shared, decrypted as a whole (members skip hooks 1 and 2); nested containers and self-referencing N/First/Filter end with ObjectStreamNested/ObjectStreamCycle; /Extends ignored (grouping only); object-stream.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `object-stream`; writing is #44 | -| 7.5.8 | Cross-reference streams | done | `XrefStreamReader`, `CrossReferenceReader`, `CrossReference` | `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file`, `Broadside.Tests.Document.CrossReferenceStreamTests.Strict_mode_opens_a_file_with_compressed_structures`, `Broadside.Tests.Document.CrossReferenceStreamTests.The_trailer_of_a_cross_reference_stream_is_its_dictionary_without_the_entries_that_describe_the_stream`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_type_field_makes_every_entry_type_1`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_generation_field_defaults_to_generation_0`, `Broadside.Tests.Document.CrossReferenceStreamTests.Index_with_two_subsections_numbers_the_entries_of_each_from_its_first_object_number`, `Broadside.Tests.Document.CrossReferenceStreamTests.Wide_fields_are_read_big_endian`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_entry_of_an_unknown_type_is_a_reference_to_the_null_object`, `Broadside.Tests.Document.CrossReferenceStreamTests.Data_shorter_than_the_entries_ends_the_section_where_the_data_ends`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_without_type_XRef_is_read_with_a_diagnostic`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_whose_W_cannot_be_read_is_not_a_cross_reference_section`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_update_written_as_a_cross_reference_stream_overrides_the_original_section`, `Broadside.Tests.Document.HybridFileTests.An_object_only_the_XRefStm_stream_lists_is_found`, `Broadside.Tests.Document.HybridFileTests.An_in_use_entry_in_the_table_of_a_section_takes_precedence_over_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.A_free_entry_in_the_table_of_a_section_gives_way_to_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.The_XRefStm_streams_dictionary_is_not_the_trailer_and_its_Prev_is_not_followed`, `Broadside.Tests.Document.HybridFileTests.An_XRefStm_offset_that_names_no_stream_is_reported_and_the_table_is_still_read`, `Broadside.Tests.Document.LinearizationTests.A_linearized_file_with_cross_reference_streams_has_its_first_page_and_main_streams_as_one_revision` | 7.5.8.1 to 7.5.8.4. W (0 to 8 bytes per field, W[0] = 0 means type 1), Index (default [0 Size]), Size, Prev; entries big-endian into long; type 0/1/2, other types are the null object; dictionary minus Type, Length, W, Index, Filter, DecodeParms, DL, F, FFilter, FDecodeParms is the trailer; data decoded through the filter pipeline under the engine's decoded-length limit, never decrypted; hybrid XRefStm read after its table and before Prev, its entries replacing the table's free entries (an in-use table entry wins), its own Prev not followed and its dictionary not a trailer; xref-stream.pdf, object-stream.pdf, png-predictor.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `xref-stream`; writing is #44 | +| 7.5.2 | File header | done | `FileHeader`, `PdfVersion`, `PdfDocument`, `FileWriter` | `Broadside.Tests.Document.FileStructureTests.Offsets_count_from_the_header_so_bytes_before_it_do_not_matter`, `Broadside.Tests.Document.FileStructureTests.A_file_without_a_header_opens_from_byte_0_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_header_without_a_valid_version_takes_the_catalog_version_with_a_diagnostic`, `Broadside.Tests.Writing.SaveTests.The_header_keeps_the_version_unless_the_layout_needs_a_later_one`, `Broadside.Tests.Writing.CreateTests.A_created_document_has_one_empty_letter_page_and_is_PDF_2_0` | Header searched in the first 1024 bytes; every stated offset is relative to it; missing header: offsets from byte 0, version 1.4 unless the catalog says otherwise; the unshifted-offset retry is #41; written: `%PDF-n.m` LF, then a comment of four bytes above 127; the document version is kept and raised to 1.5 for cross-reference streams (ADR 0003); `Create` writes 2.0 (#44) | +| 7.5.3 | File body | done | `ObjectLoader`, `FileWriter` | `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_reopens_with_the_same_objects_and_no_diagnostics`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_passes_qpdf_check` | Objects load lazily by cross-reference entry, from the file body or an object stream (7.5.7); a full save writes every in-use object of the newest revision, dropping only old cross-reference streams, object streams and linearization data that nothing refers to (#44) | +| 7.5.4 | Cross-reference table | partial | `XrefTableReader`, `CrossReference`, `FileWriter` | `Broadside.Tests.Document.FileStructureTests.Entries_are_read_as_tokens_not_fixed_width_records`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_reads_as_null_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation`, `Broadside.Tests.Writing.SaveTests.Startxref_gives_the_offset_of_the_cross_reference_information`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_passes_qpdf_check` | Subsections and n/f entries read as tokens; offset-0 in-use entries read as free; reconstruction by scanning when the table is wrong, and diagnostics for non-20-byte entries and comments, are #41; written as one subsection from 0 with 20-byte entries (CR LF), free entries linked from object 0 (generation 65535); offsets above ten digits refuse the table layout (#44) | +| 7.5.5 | File trailer | partial | `CrossReferenceReader`, `CrossReference`, `PdfDocument`, `FileWriter` | `Broadside.Tests.Document.FileStructureTests.A_startxref_offset_on_the_white_space_before_xref_is_repaired_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_file_with_no_startxref_cannot_be_read_even_leniently`, `Broadside.Tests.Document.FileStructureTests.A_trailer_without_root_cannot_be_read`, `Broadside.Tests.Document.FileStructureTests.A_prev_chain_that_loops_ends_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic`, `Broadside.Tests.Writing.SaveTests.Saving_an_updated_file_collapses_its_revisions_into_one_with_the_newest_objects`, `Broadside.Tests.Writing.SaveTests.Startxref_gives_the_offset_of_the_cross_reference_information` | Last startxref, Prev chain with loop guard, Root; trailer merged newest-first; ignoring entries beyond Size, startxref recovery and trailer reconstruction are #41; Encrypt is #42; written trailer: Size, the source trailer without Size, Prev, XRefStm and ID, then ID; startxref and %%EOF (#44) | +| 7.5.6 | Incremental updates | done | `CrossReference`, `RevisionReader`, `PdfRevision`, `PdfDocument` | `Broadside.Tests.Document.IncrementalUpdateTests.An_updated_file_has_one_revision_per_update_and_the_first_is_the_original_file`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_is_the_file_as_it_was_after_that_save`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_has_its_own_trailer`, `Broadside.Tests.Document.IncrementalUpdateTests.A_hybrid_file_has_its_main_section_and_its_update_section_as_two_revisions`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_earlier_revision_without_its_end_of_file_marker_ends_after_its_startxref_offset_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`, `Broadside.Tests.Writing.SaveTests.Saving_an_updated_file_collapses_its_revisions_into_one_with_the_newest_objects` | Revisions oldest first, each the byte prefix up to its %%EOF and end-of-line; newest section decides per object number, free hides older copies, a reference must match the live generation; Root, Info, Encrypt and ID missing from the newest trailer are taken from an older one with TrailerEntryFromOlderRevision; a linearized pair is one revision; a hybrid XRefStm stream joins its table's revision; a full save collapses the revisions into one (#44); writing an incremental update is Phase 4 | +| 7.5.7 | Object streams | done | `ObjectStream`, `ObjectLoader`, `FileWriter` | `Broadside.Tests.Document.ObjectStreamTests.The_catalog_page_tree_and_page_resolve_from_an_object_stream`, `Broadside.Tests.Document.ObjectStreamTests.A_reference_to_a_member_with_a_generation_other_than_0_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.Members_need_no_white_space_between_them`, `Broadside.Tests.Document.ObjectStreamTests.A_member_at_another_index_than_its_entry_says_is_found_by_its_object_number`, `Broadside.Tests.Document.ObjectStreamTests.Offsets_out_of_order_bound_each_member_by_the_next_offset_in_sorted_order`, `Broadside.Tests.Document.ObjectStreamTests.A_member_the_object_stream_does_not_hold_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_whose_N_is_one_of_its_own_members_resolves_its_members_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_listed_as_compressed_itself_is_not_read`, `Broadside.Tests.Document.ObjectStreamTests.A_type_2_entry_naming_an_object_that_is_not_a_stream_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.A_flate_encoded_object_stream_is_decoded_through_the_filters`, `Broadside.Tests.Document.ObjectStreamTests.Members_of_one_object_stream_resolve_to_the_same_instances_from_concurrent_threads`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file`, `Broadside.Tests.Writing.SaveTests.Objects_that_were_not_changed_keep_their_source_bytes_in_any_layout`, `Broadside.Tests.Writing.SaveTests.The_information_dictionary_of_a_hybrid_file_survives_from_its_object_stream` | Members located by type 2 entries (index checked against the header, searched by number when wrong, with ObjectStreamIndexMismatch); each member parsed over exactly the bytes up to the next offset (NOTE 7); out-of-order offsets sorted; container decoded once per document and shared, decrypted as a whole (members skip hooks 1 and 2); nested containers and self-referencing N/First/Filter end with ObjectStreamNested/ObjectStreamCycle; /Extends ignored (grouping only); object-stream.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `object-stream`; written by `PdfCrossReferenceLayout.StreamWithObjectStreams`: every object with generation 0 that is not a stream or a bare reference, at most 100 per Flate-encoded object stream; unchanged members keep their bytes (#44) | +| 7.5.8 | Cross-reference streams | done | `XrefStreamReader`, `CrossReferenceReader`, `CrossReference`, `FileWriter`, `PdfCrossReferenceLayout` | `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file`, `Broadside.Tests.Document.CrossReferenceStreamTests.Strict_mode_opens_a_file_with_compressed_structures`, `Broadside.Tests.Document.CrossReferenceStreamTests.The_trailer_of_a_cross_reference_stream_is_its_dictionary_without_the_entries_that_describe_the_stream`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_type_field_makes_every_entry_type_1`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_generation_field_defaults_to_generation_0`, `Broadside.Tests.Document.CrossReferenceStreamTests.Index_with_two_subsections_numbers_the_entries_of_each_from_its_first_object_number`, `Broadside.Tests.Document.CrossReferenceStreamTests.Wide_fields_are_read_big_endian`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_entry_of_an_unknown_type_is_a_reference_to_the_null_object`, `Broadside.Tests.Document.CrossReferenceStreamTests.Data_shorter_than_the_entries_ends_the_section_where_the_data_ends`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_without_type_XRef_is_read_with_a_diagnostic`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_whose_W_cannot_be_read_is_not_a_cross_reference_section`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_update_written_as_a_cross_reference_stream_overrides_the_original_section`, `Broadside.Tests.Document.HybridFileTests.An_object_only_the_XRefStm_stream_lists_is_found`, `Broadside.Tests.Document.HybridFileTests.An_in_use_entry_in_the_table_of_a_section_takes_precedence_over_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.A_free_entry_in_the_table_of_a_section_gives_way_to_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.The_XRefStm_streams_dictionary_is_not_the_trailer_and_its_Prev_is_not_followed`, `Broadside.Tests.Document.HybridFileTests.An_XRefStm_offset_that_names_no_stream_is_reported_and_the_table_is_still_read`, `Broadside.Tests.Document.LinearizationTests.A_linearized_file_with_cross_reference_streams_has_its_first_page_and_main_streams_as_one_revision`, `Broadside.Tests.Writing.SaveTests.Startxref_gives_the_offset_of_the_cross_reference_information`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_passes_qpdf_check` | 7.5.8.1 to 7.5.8.4. W (0 to 8 bytes per field, W[0] = 0 means type 1), Index (default [0 Size]), Size, Prev; entries big-endian into long; type 0/1/2, other types are the null object; dictionary minus Type, Length, W, Index, Filter, DecodeParms, DL, F, FFilter, FDecodeParms is the trailer; data decoded through the filter pipeline under the engine's decoded-length limit, never decrypted; hybrid XRefStm read after its table and before Prev, its entries replacing the table's free entries (an in-use table entry wins), its own Prev not followed and its dictionary not a trailer; xref-stream.pdf, object-stream.pdf, png-predictor.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `xref-stream`; written by `PdfCrossReferenceLayout.Stream` and `StreamWithObjectStreams`: W [1 n 2] with n the fewest bytes for the largest offset, an entry for the stream itself, Flate with Predictor 12, trailer keys in its dictionary; hybrid files are not written (#44) | | 7.6 | Encryption | not started | | | | | 7.7.1 | General | n/a | | | Introductory text | | 7.7.2 | Document catalog dictionary | partial | `PdfDocument`, `PdfVersion` | `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_catalog_version_written_as_a_number_is_read_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.A_malformed_catalog_version_is_ignored_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_catalog_without_its_type_is_read_with_a_diagnostic` | Type, Version (effective version = later of header and catalog) and Pages; the other Table 29 entries arrive with their features (outlines, names, AcroForm, ...) | @@ -110,7 +110,7 @@ Clause numbers at the second level; split rows to the third level as clauses are | 14.1 | Document interchange: General | not started | | | | | 14.2 | Procedure sets | not started | | | | | 14.3 | Metadata | not started | | | | -| 14.4 | File identifiers | not started | | | | +| 14.4 | File identifiers | partial | `FileWriter` | `Broadside.Tests.Writing.SaveTests.Saving_twice_writes_the_same_bytes_and_keeps_the_first_file_identifier`, `Broadside.Tests.Writing.SaveTests.A_file_without_identifiers_gets_two_equal_ones_when_saved`, `Broadside.Tests.Writing.CreateTests.A_saved_created_document_reopens_with_two_equal_file_identifiers` | written on save: the first identifier is kept, the second is the first 16 bytes of SHA-256 of the bytes before the cross-reference information (deterministic; MD5 is unavailable on browser-wasm); a file without identifiers gets two equal ones; incremental updates are Phase 4 | | 14.5 | Page-piece dictionaries | not started | | | | | 14.6 | Marked content | not started | | | | | 14.7 | Logical structure | not started | | | | diff --git a/src/Broadside/Parsing/CrossReference.cs b/src/Broadside/Parsing/CrossReference.cs index a12a526f..35bcfa3b 100644 --- a/src/Broadside/Parsing/CrossReference.cs +++ b/src/Broadside/Parsing/CrossReference.cs @@ -146,6 +146,9 @@ public CrossReference(IReadOnlyList sections) /// public IReadOnlyList InheritedTrailerKeys { get; } + /// Gets the merged lookup: for every object number a section lists, the entry returns. + public IReadOnlyDictionary Entries => _merged; + /// Gets the merged trailer dictionary. public CosDictionary Trailer { get; } diff --git a/src/Broadside/Parsing/ObjectLoader.cs b/src/Broadside/Parsing/ObjectLoader.cs index 1fd3f24b..0e2f3cc8 100644 --- a/src/Broadside/Parsing/ObjectLoader.cs +++ b/src/Broadside/Parsing/ObjectLoader.cs @@ -46,6 +46,7 @@ internal sealed class ObjectLoader private readonly DiagnosticSink _diagnostics; private readonly StreamDecoder _streams; private ConcurrentDictionary? _objectStreams; + private ConcurrentDictionary? _sourceBytes; /// Initializes a new instance of the class. /// The file. @@ -79,6 +80,24 @@ public ObjectLoader( /// Gets the hooks. public ObjectLoaderHooks Hooks { get; } + /// + /// Finds the source bytes of an object this loader has loaded and read without repairs, so a writer can copy them instead of + /// re-serializing the object (issue #44). + /// + /// The object's number and generation. + /// Where the object's bytes are. + /// when the object was loaded, read without any repair, and its bytes are known. + public bool TryGetSourceBytes(CosReference reference, out ObjectSourceBytes bytes) + { + if (Volatile.Read(ref _sourceBytes) is { } sourceBytes) + { + return sourceBytes.TryGetValue(reference, out bytes); + } + + bytes = default; + return false; + } + /// Returns , or the object it refers to when it is an indirect reference. /// A direct object, a reference, or for an absent entry. /// The direct object; for an absent entry or a reference to nothing. @@ -156,7 +175,12 @@ private CosObject LoadCompressed(CosReference reference, XrefEntry entry, int de ObjectStream container = objectStreams.TryGetValue(containerNumber, out ObjectStream? cached) ? cached : objectStreams.GetOrAdd(containerNumber, ReadObjectStream(containerNumber, reference, depth)); - CosObject loaded = container.Parse(reference, entry.Generation, _diagnostics); + CosObject loaded = container.Parse(reference, entry.Generation, _diagnostics, out ReadOnlyMemory? memberBytes); + if (memberBytes is { } bytes) + { + SourceBytes[reference] = ObjectSourceBytes.InObjectStream(bytes); + } + return Hooks.Cache.Publish(reference, loaded); } @@ -217,6 +241,16 @@ private ConcurrentDictionary ObjectStreams } } + /// Gets the recorded source bytes by object, created on first use. + private ConcurrentDictionary SourceBytes + { + get + { + ConcurrentDictionary? sourceBytes = Volatile.Read(ref _sourceBytes); + return sourceBytes ?? Interlocked.CompareExchange(ref _sourceBytes, new(), null) ?? _sourceBytes; + } + } + private bool IsDecoding(int containerNumber) => _decoding is { Count: > 0 } decoding && decoding.Contains((this, containerNumber)); private CosObject Resolve(CosObject? value, int depth) => value is CosReference reference ? Load(reference, depth) : value ?? CosNull.Instance; @@ -247,9 +281,12 @@ private CosObject ParseIndirectObject(in ObjectLoadContext context) return LoadMisplaced(context); } + lexer.SkipWhitespaceAndComments(); + int bodyStart = lexer.Position; var repairs = new CosRepairLog(keepAll: true); - var parser = new CosParser(window, repairs, lexer.Position, new LengthResolver(this, context)); + var parser = new CosParser(window, repairs, bodyStart, new LengthResolver(this, context)); CosObject value = parser.ParseObject(); + int bodyEnd = parser.Position; foreach (CosRepair repair in repairs.All) { _diagnostics.Report(repair.Code, DiagnosticSeverity.Warning, repair.Message, context.Offset + repair.Offset, context.Reference); @@ -266,6 +303,11 @@ private CosObject ParseIndirectObject(in ObjectLoadContext context) context.Offset + end.Start, context.Reference); } + else if (repairs.Count == 0) + { + // Only bytes read without any repair may be copied by a writer; a repaired object is re-serialized (issue #44). + SourceBytes[context.Reference] = ObjectSourceBytes.InFile(context.Offset + bodyStart, bodyEnd - bodyStart); + } return value; } diff --git a/src/Broadside/Parsing/ObjectSourceBytes.cs b/src/Broadside/Parsing/ObjectSourceBytes.cs new file mode 100644 index 00000000..a6f78ff3 --- /dev/null +++ b/src/Broadside/Parsing/ObjectSourceBytes.cs @@ -0,0 +1,43 @@ +namespace Broadside.Parsing; + +/// +/// Where the bytes of an indirect object's value are in the source, as the loader read them: from the first token after +/// N G obj to the end of the value's last token (the endstream keyword for a stream), or, for an object-stream +/// member, the member's slice of the decoded object stream without surrounding white-space. +/// +/// +/// ISO 32000-2 §7.3.10 and §7.5.7. Recorded only for objects read without any repair, so a writer may copy them unchanged instead of +/// re-serializing (issue #44): a literal string such as (a\053b) keeps its form, which signatures and byte-level diffs need. +/// +internal readonly struct ObjectSourceBytes +{ + private ObjectSourceBytes(long fileOffset, int length, ReadOnlyMemory member) + { + FileOffset = fileOffset; + Length = length; + Member = member; + } + + /// Gets the absolute offset of the first byte in the file, or -1 for an object-stream member. + public long FileOffset { get; } + + /// Gets the number of bytes. + public int Length { get; } + + /// Gets the bytes of an object-stream member, from its container's decoded data; empty for an object in the file body. + public ReadOnlyMemory Member { get; } + + /// Gets a value indicating whether the bytes are in the file body rather than in a decoded object stream. + public bool IsInFile => FileOffset >= 0; + + /// Describes bytes in the file body. + /// The absolute offset of the first byte. + /// The number of bytes. + /// The description. + public static ObjectSourceBytes InFile(long offset, int length) => new(offset, length, ReadOnlyMemory.Empty); + + /// Describes the bytes of an object-stream member. + /// The member's bytes in its container's decoded data. + /// The description. + public static ObjectSourceBytes InObjectStream(ReadOnlyMemory bytes) => new(-1, bytes.Length, bytes); +} diff --git a/src/Broadside/Parsing/ObjectStream.cs b/src/Broadside/Parsing/ObjectStream.cs index 036f9eb1..0d027d3f 100644 --- a/src/Broadside/Parsing/ObjectStream.cs +++ b/src/Broadside/Parsing/ObjectStream.cs @@ -127,8 +127,23 @@ public static ObjectStream Read(CosReference reference, ReadOnlyMemory dat /// The index from the type 2 cross-reference entry (Table 18). /// Where to report deviations. /// The object, or when the object stream does not hold it. - public CosObject Parse(CosReference member, int index, DiagnosticSink diagnostics) + public CosObject Parse(CosReference member, int index, DiagnosticSink diagnostics) => Parse(member, index, diagnostics, out _); + + /// + /// Parses the member the cross-reference stream places at and returns the bytes it + /// was read from, so a writer can copy them (issue #44). + /// + /// The member's reference (generation 0). + /// The index from the type 2 cross-reference entry (Table 18). + /// Where to report deviations. + /// + /// The member's bytes without surrounding white-space, when it was read without any repair and is not a stream (which an object + /// stream shall not hold); otherwise . + /// + /// The object, or when the object stream does not hold it. + public CosObject Parse(CosReference member, int index, DiagnosticSink diagnostics, out ReadOnlyMemory? memberBytes) { + memberBytes = null; if (!IsReadable) { return CosNull.Instance; @@ -171,10 +186,33 @@ public CosObject Parse(CosReference member, int index, DiagnosticSink diagnostic "A stream shall not be stored in an object stream (§7.5.7); it is read anyway.", objectReference: member); } + else if (repairs.Count == 0) + { + memberBytes = Trim(_data[_starts[position].._ends[position]]); + } return value; } + /// Removes the white-space around a member's bytes (§7.2.3, Table 1). + private static ReadOnlyMemory Trim(ReadOnlyMemory bytes) + { + ReadOnlySpan span = bytes.Span; + int start = 0; + while (start < span.Length && CosLexer.IsWhitespace(span[start])) + { + start++; + } + + int end = span.Length; + while (end > start && CosLexer.IsWhitespace(span[end - 1])) + { + end--; + } + + return bytes[start..end]; + } + /// Returns, for each start, the nearest greater start of another member, or the end of the data. private static int[] Ends(List starts, int dataLength, out bool ordered) { diff --git a/src/Broadside/PdfCrossReferenceLayout.cs b/src/Broadside/PdfCrossReferenceLayout.cs new file mode 100644 index 00000000..ad3448f5 --- /dev/null +++ b/src/Broadside/PdfCrossReferenceLayout.cs @@ -0,0 +1,38 @@ +namespace Broadside; + +/// How a saved file stores its cross-reference information and its objects. +/// +/// ISO 32000-2 §7.5.4 (cross-reference table), §7.5.7 (object streams) and §7.5.8 (cross-reference streams). +/// +/// The supported combinations, and the minimum PDF version each needs (the header is raised to it when the document's own version is +/// lower; ADR 0003): +/// +/// +/// LayoutCross-reference / object streams / minimum version +/// Classic table / none / 1.0 +/// Cross-reference stream / none / 1.5 +/// Cross-reference stream / yes / 1.5 +/// +/// +/// A classic table with object streams is possible only as a hybrid file (§7.5.8.4), which is meant for readers older than +/// PDF 1.5 and is not written. +/// +/// +public enum PdfCrossReferenceLayout +{ + /// + /// A classic cross-reference table and every object at the top level of the file body (§7.5.4). Readable by every PDF reader. + /// Offsets are limited to ten digits, so the file must be smaller than 10 GB. + /// + Table, + + /// A cross-reference stream (§7.5.8) and every object at the top level of the file body. PDF 1.5. + Stream, + + /// + /// A cross-reference stream (§7.5.8), with every object that may be stored in an object stream stored in one (§7.5.7): neither + /// streams nor objects with a generation other than 0 nor objects that are only an indirect reference. The most compact layout. + /// PDF 1.5. + /// + StreamWithObjectStreams, +} diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 339aebd8..163918bd 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -4,6 +4,7 @@ using Broadside.IO; using Broadside.Objects; using Broadside.Parsing; +using Broadside.Writing; namespace Broadside; @@ -160,17 +161,101 @@ public PdfVersion Version /// ISO 32000-2 §7.5. public static PdfDocument Open(ReadOnlyMemory bytes, PdfOptions options) => new PdfEngine(options).Open(bytes); - /// Creates a new, empty document with default options. - /// The document. - /// Always, for now: writing arrives in a later version. + /// Creates a new document with one empty US Letter page (612 by 792 points), with default options. + /// The document. Dispose it when done. + /// + /// ISO 32000-2 §7.7.2 (catalog), §7.7.3 (page tree) and §7.5.2: the document is PDF 2.0. The same as + /// on an engine with default options. + /// public static PdfDocument Create() => PdfEngine.Default.Create(); - /// Creates a new, empty document. + /// Creates a new document with one empty US Letter page (612 by 792 points). /// The options. - /// The document. - /// Always, for now: writing arrives in a later version. + /// The document. Dispose it when done. + /// + /// ISO 32000-2 §7.7.2, §7.7.3 and §7.5.2. The same as on an engine built from + /// . + /// public static PdfDocument Create(PdfOptions options) => new PdfEngine(options).Create(); + /// Writes the document to as a complete file with a classic cross-reference table. + /// Where to write, from its current position. It is not disposed. + /// The document is encrypted, or uses object numbers above 8,388,607; saving either arrives in a later version. + /// In strict mode, for the first deviation found while loading the objects to write. + /// ISO 32000-2 §7.5. As with default . + public void Save(Stream stream) => Save(stream, new PdfSaveOptions()); + + /// Writes the document to as a complete file. + /// Where to write, from its current position. It is not disposed. + /// How to lay the file out. + /// The document is encrypted, or uses object numbers above 8,388,607; saving either arrives in a later version. + /// In strict mode, for the first deviation found while loading the objects to write. + /// + /// + /// ISO 32000-2 §7.5: a header, every object, the cross-reference information and the trailer. Objects keep their numbers and + /// generations. An object that has not changed since it was read, and was read without any repair, is written with exactly the + /// bytes it was read from; changed, repaired and new objects are serialized. The revisions of an incrementally updated file + /// collapse into one, and a linearized file is written unlinearized (Annex F). + /// + /// + /// The header keeps the document's version, raised to 1.5 when the layout needs cross-reference streams. The trailer's first + /// file identifier is kept; the second is derived from the written bytes, so saving the same document the same way always writes + /// the same bytes (§14.4). + /// + /// + public void Save(Stream stream, PdfSaveOptions options) + { + ArgumentNullException.ThrowIfNull(stream); + foreach (ReadOnlyMemory chunk in PlanSave(options).Write()) + { + stream.Write(chunk.Span); + } + } + + /// Writes the document to the file at , replacing it, with a classic cross-reference table. + /// The file path. Do not name the file the document was opened from. + /// The document is encrypted, or uses object numbers above 8,388,607; saving either arrives in a later version. + /// In strict mode, for the first deviation found while loading the objects to write. + /// ISO 32000-2 §7.5. As with default . + public void Save(string path) => Save(path, new PdfSaveOptions()); + + /// Writes the document to the file at , replacing it. + /// The file path. Do not name the file the document was opened from. + /// How to lay the file out. + /// The document is encrypted, or uses object numbers above 8,388,607; saving either arrives in a later version. + /// In strict mode, for the first deviation found while loading the objects to write. + /// ISO 32000-2 §7.5. As . + public void Save(string path, PdfSaveOptions options) + { + ArgumentException.ThrowIfNullOrEmpty(path); + FileWriter writer = PlanSave(options); + using FileStream stream = File.Create(path); + foreach (ReadOnlyMemory chunk in writer.Write()) + { + stream.Write(chunk.Span); + } + } + + /// Writes the document to as a complete file, writing asynchronously. + /// Where to write, from its current position. It is not disposed. + /// How to lay the file out; for the defaults (a classic cross-reference table). + /// Cancels the writes. + /// A task that completes when the file is written. + /// The document is encrypted, or uses object numbers above 8,388,607; saving either arrives in a later version. + /// In strict mode, for the first deviation found while loading the objects to write. + /// + /// ISO 32000-2 §7.5. Writes exactly the bytes writes, from the same writer; only the + /// writes to are asynchronous. + /// + public async Task SaveAsync(Stream stream, PdfSaveOptions? options = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(stream); + foreach (ReadOnlyMemory chunk in PlanSave(options ?? new PdfSaveOptions()).Write()) + { + await stream.WriteAsync(chunk, cancellationToken).ConfigureAwait(false); + } + } + /// Returns , or the indirect object it refers to when it is a . /// A COS object from this document, or . /// @@ -210,6 +295,52 @@ public void DecodeStream(CosStream stream, IBufferWriter output) /// public void Dispose() => _source.Dispose(); + /// Builds the bytes of a new one-page document and opens them (issue #44). + /// The engine's configuration. + /// The document. + /// + /// ISO 32000-2 §7.7.2, §7.7.3, Table 31: a catalog, a page tree root and one US Letter page whose Resources is the empty + /// dictionary (no resources) and which has no Contents (an empty page). Written as PDF 2.0 with file identifiers. + /// + internal static PdfDocument CreateNew(EngineConfiguration configuration) => Read(PdfSource.FromMemory(NewDocumentFile()), configuration); + + /// Writes the file opens. + private static byte[] NewDocumentFile() + { + var catalog = new CosReference(1, 0); + var pages = new CosReference(2, 0); + var page = new CosReference(3, 0); + var mediaBox = new CosArray([new CosInteger(0), new CosInteger(0), new CosInteger(612), new CosInteger(792)]); + WriterObject[] objects = + [ + new(catalog, new CosDictionary { [KnownNames.Type] = KnownNames.Catalog, [KnownNames.Pages] = pages }, null), + new(pages, new CosDictionary { [KnownNames.Type] = KnownNames.Pages, [KnownNames.Kids] = new CosArray([page]), [KnownNames.Count] = new CosInteger(1) }, null), + new(page, new CosDictionary { [KnownNames.Type] = KnownNames.Page, [KnownNames.Parent] = pages, [KnownNames.MediaBox] = mediaBox, [KnownNames.Resources] = new CosDictionary() }, null), + ]; + var writer = new FileWriter( + source: null, + new PdfVersion(2, 0), + objects, + new Dictionary(), + new CosDictionary { [KnownNames.Root] = catalog }, + firstIdentifier: null, + PdfCrossReferenceLayout.Table); + using var bytes = new MemoryStream(); + foreach (ReadOnlyMemory chunk in writer.Write()) + { + bytes.Write(chunk.Span); + } + + return bytes.ToArray(); + } + + /// Plans a full save; throws for what cannot be saved before anything is written. + private FileWriter PlanSave(PdfSaveOptions options) + { + ArgumentNullException.ThrowIfNull(options); + return SavePlan.Create(_source, _loader, Linearization, options.CrossReferenceLayout); + } + /// The open path shared by every entry point: header, cross-reference information, trailer, catalog. /// The file; owned by the document, disposed if opening fails. /// The engine's configuration. diff --git a/src/Broadside/PdfEngine.cs b/src/Broadside/PdfEngine.cs index cc6fecb7..39c4571d 100644 --- a/src/Broadside/PdfEngine.cs +++ b/src/Broadside/PdfEngine.cs @@ -89,8 +89,11 @@ public PdfDocument Open(Stream stream) /// ISO 32000-2 §7.5. public PdfDocument Open(ReadOnlyMemory bytes) => PdfDocument.Read(PdfSource.FromMemory(bytes), _configuration); - /// Creates a new, empty document. - /// The document. - /// Always, for now: writing arrives in a later version. - public PdfDocument Create() => throw new NotSupportedException("Creating a document is not implemented yet."); + /// Creates a new document with one empty US Letter page (612 by 792 points). + /// The document. Dispose it when done. + /// + /// ISO 32000-2 §7.7.2 (catalog), §7.7.3 (page tree) and §7.5.2: the document is PDF 2.0, has a catalog, a page tree root and one + /// page with empty resources and no content, and reads like a file of those three objects. + /// + public PdfDocument Create() => PdfDocument.CreateNew(_configuration); } diff --git a/src/Broadside/PdfSaveOptions.cs b/src/Broadside/PdfSaveOptions.cs new file mode 100644 index 00000000..d4f908ba --- /dev/null +++ b/src/Broadside/PdfSaveOptions.cs @@ -0,0 +1,42 @@ +namespace Broadside; + +/// Options for one save: how the written file is laid out. +/// +/// ISO 32000-2 §7.5. Separate from , which configures reading, because a document can be saved several times +/// in different layouts. The defaults write a classic cross-reference table, which every reader supports. +/// +public sealed class PdfSaveOptions +{ + private PdfCrossReferenceLayout _crossReferenceLayout = PdfCrossReferenceLayout.Table; + + /// + /// Gets or sets how the file stores its cross-reference information and objects. The default is + /// . + /// + /// ISO 32000-2 §7.5.4, §7.5.7, §7.5.8. See for the combinations and their versions. + /// The value is not a defined layout. + public PdfCrossReferenceLayout CrossReferenceLayout + { + get => _crossReferenceLayout; + set + { + if (!Enum.IsDefined(value)) + { + throw new ArgumentOutOfRangeException(nameof(value), value, "Not a cross-reference layout."); + } + + _crossReferenceLayout = value; + } + } + + /// Sets . + /// The layout. + /// These options. + /// is not a defined layout. + /// ISO 32000-2 §7.5.4, §7.5.7, §7.5.8. + public PdfSaveOptions WithCrossReferenceLayout(PdfCrossReferenceLayout layout) + { + CrossReferenceLayout = layout; + return this; + } +} diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index 49b61793..1bbbe66b 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -265,3 +265,17 @@ Broadside.PdfOptions.WithLoggerFactory(Microsoft.Extensions.Logging.ILoggerFacto Microsoft.Extensions.DependencyInjection.BroadsideServiceCollectionExtensions static Microsoft.Extensions.DependencyInjection.BroadsideServiceCollectionExtensions.AddBroadside(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! static Microsoft.Extensions.DependencyInjection.BroadsideServiceCollectionExtensions.AddBroadside(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, System.Action! configure) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! +Broadside.PdfCrossReferenceLayout +Broadside.PdfCrossReferenceLayout.Stream = 1 -> Broadside.PdfCrossReferenceLayout +Broadside.PdfCrossReferenceLayout.StreamWithObjectStreams = 2 -> Broadside.PdfCrossReferenceLayout +Broadside.PdfCrossReferenceLayout.Table = 0 -> Broadside.PdfCrossReferenceLayout +Broadside.PdfDocument.Save(string! path) -> void +Broadside.PdfDocument.Save(string! path, Broadside.PdfSaveOptions! options) -> void +Broadside.PdfDocument.Save(System.IO.Stream! stream) -> void +Broadside.PdfDocument.Save(System.IO.Stream! stream, Broadside.PdfSaveOptions! options) -> void +Broadside.PdfDocument.SaveAsync(System.IO.Stream! stream, Broadside.PdfSaveOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Broadside.PdfSaveOptions +Broadside.PdfSaveOptions.CrossReferenceLayout.get -> Broadside.PdfCrossReferenceLayout +Broadside.PdfSaveOptions.CrossReferenceLayout.set -> void +Broadside.PdfSaveOptions.PdfSaveOptions() -> void +Broadside.PdfSaveOptions.WithCrossReferenceLayout(Broadside.PdfCrossReferenceLayout layout) -> Broadside.PdfSaveOptions! diff --git a/src/Broadside/Writing/FileWriter.cs b/src/Broadside/Writing/FileWriter.cs new file mode 100644 index 00000000..ac06e63d --- /dev/null +++ b/src/Broadside/Writing/FileWriter.cs @@ -0,0 +1,432 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.Globalization; +using System.IO.Compression; +using System.Security.Cryptography; +using Broadside.Filters; +using Broadside.IO; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Writing; + +/// One indirect object to write: its number and generation, its value, and its source bytes when they may be copied. +/// The object's number and generation, kept from the source. +/// The object. +/// The bytes the object was read from, copied instead of serializing ; to serialize. +internal readonly record struct WriterObject(CosReference Reference, CosObject Value, ObjectSourceBytes? Source); + +/// +/// Writes a complete PDF file: header, objects, cross-reference information and trailer, as a sequence of chunks that a synchronous +/// and an asynchronous caller write out the same way, so both produce the same bytes. +/// +/// +/// +/// ISO 32000-2 §7.5.2 (header with a binary comment line), §7.3.10 (N G obj … endobj), §7.3.8 (streams with a direct +/// Length), §7.5.4 (classic table, one subsection, 20-byte entries, free entries linked from object 0), §7.5.5 (trailer, +/// startxref, %%EOF), §7.5.7 (object streams), §7.5.8 (cross-reference stream with an entry for itself) and §14.4 +/// (file identifiers). +/// +/// +/// Output is deterministic: the second file identifier is the first 16 bytes of the SHA-256 hash of everything written before the +/// cross-reference information, and the first is the source's or, for a file without one, the same value (§14.4: both are equal +/// when a file is first written). Nothing depends on the clock or a random source. +/// +/// +internal sealed class FileWriter +{ + /// How many bytes are gathered before a chunk is handed out. + private const int ChunkSize = 64 * 1024; + + /// The most objects one object stream holds, to keep random access cheap (§7.5.7, NOTE 4). + private const int ObjectStreamCapacity = 100; + + /// The largest offset a classic cross-reference entry's ten digits can state (§7.5.4). + private const long MaxTableOffset = 9_999_999_999; + + private static readonly PdfVersion StreamVersion = new(1, 5); + private static readonly CosName XRef = new("XRef"); + private static readonly CosName ObjStm = new("ObjStm"); + private static readonly CosName FlateDecode = new("FlateDecode"); + private static readonly CosName W = new("W"); + private static readonly CosName N = new("N"); + private static readonly CosName First = new("First"); + private static readonly CosName Filter = new("Filter"); + private static readonly CosName DecodeParms = new("DecodeParms"); + private static readonly CosName Predictor = new("Predictor"); + private static readonly CosName Columns = new("Columns"); + + private readonly PdfSource? _source; + private readonly PdfVersion _version; + private readonly IReadOnlyList _objects; + private readonly IReadOnlyDictionary _freeGenerations; + private readonly CosDictionary _trailer; + private readonly CosString? _firstIdentifier; + private readonly PdfCrossReferenceLayout _layout; + + /// Initializes a new instance of the class. + /// The file source bytes are copied from; when no object has source bytes. + /// The version for the header; raised to 1.5 for a cross-reference stream. + /// The objects to write, in ascending object number. + /// For object numbers that are free, the generation their free entry carries; others default to 0. + /// The trailer entries to write besides Size and ID. + /// The first file identifier to keep, or for a file written for the first time. + /// The cross-reference layout. + public FileWriter( + PdfSource? source, + PdfVersion version, + IReadOnlyList objects, + IReadOnlyDictionary freeGenerations, + CosDictionary trailer, + CosString? firstIdentifier, + PdfCrossReferenceLayout layout) + { + _source = source; + _version = layout != PdfCrossReferenceLayout.Table && version < StreamVersion ? StreamVersion : version; + _objects = objects; + _freeGenerations = freeGenerations; + _trailer = trailer; + _firstIdentifier = firstIdentifier; + _layout = layout; + } + + /// Writes the file. Each chunk is valid until the next one is requested. + /// The file's bytes, in order. + public IEnumerable> Write() + { + using var buffer = new PooledBufferWriter(ChunkSize * 2, Array.MaxLength); + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var entries = new Dictionary(); + long flushed = 0; + + WriteHeader(buffer); + + bool compress = _layout == PdfCrossReferenceLayout.StreamWithObjectStreams; + var compressible = new List(); + int maxNumber = _freeGenerations.Count == 0 ? 0 : _freeGenerations.Keys.Max(); + foreach (WriterObject item in _objects) + { + maxNumber = Math.Max(maxNumber, item.Reference.ObjectNumber); + if (compress && CanBeCompressed(item)) + { + compressible.Add(item); + continue; + } + + entries[item.Reference.ObjectNumber] = new XrefEntry(XrefEntryKind.InUse, flushed + buffer.WrittenSpan.Length, item.Reference.Generation); + WriteIndirectObject(buffer, item.Reference, item, _source); + if (buffer.WrittenSpan.Length >= ChunkSize) + { + hash.AppendData(buffer.WrittenSpan); + yield return buffer.WrittenMemory; + flushed += buffer.WrittenSpan.Length; + buffer.Clear(); + } + } + + int nextNumber = maxNumber + 1; + for (int start = 0; start < compressible.Count; start += ObjectStreamCapacity) + { + int container = nextNumber++; + int count = Math.Min(ObjectStreamCapacity, compressible.Count - start); + for (int index = 0; index < count; index++) + { + entries[compressible[start + index].Reference.ObjectNumber] = new XrefEntry(XrefEntryKind.Compressed, container, index); + } + + CosStream objectStream = BuildObjectStream(compressible, start, count); + var reference = new CosReference(container, 0); + entries[container] = new XrefEntry(XrefEntryKind.InUse, flushed + buffer.WrittenSpan.Length, 0); + WriteIndirectObject(buffer, reference, new WriterObject(reference, objectStream, null), source: null); + if (buffer.WrittenSpan.Length >= ChunkSize) + { + hash.AppendData(buffer.WrittenSpan); + yield return buffer.WrittenMemory; + flushed += buffer.WrittenSpan.Length; + buffer.Clear(); + } + } + + hash.AppendData(buffer.WrittenSpan); + if (buffer.WrittenSpan.Length > 0) + { + yield return buffer.WrittenMemory; + flushed += buffer.WrittenSpan.Length; + buffer.Clear(); + } + + byte[] digest = hash.GetHashAndReset(); + var secondIdentifier = new CosString(digest.AsSpan(0, 16), hexadecimal: true); + var identifier = new CosArray([_firstIdentifier ?? secondIdentifier, secondIdentifier]); + + if (_layout == PdfCrossReferenceLayout.Table) + { + WriteTable(buffer, entries, nextNumber, flushed, identifier); + } + else + { + WriteStream(buffer, entries, nextNumber, flushed, identifier); + } + + yield return buffer.WrittenMemory; + } + + /// Whether an object may be stored in an object stream (§7.5.7). + private static bool CanBeCompressed(WriterObject item) => + item.Reference.Generation == 0 && item.Value is not (CosStream or CosReference); + + /// Writes %PDF-n.m and a comment line of four bytes above 127, marking the file as binary (§7.5.2). + private void WriteHeader(IBufferWriter buffer) + { + buffer.Write("%PDF-"u8); + WriteAscii(buffer, _version.ToString()); + buffer.Write("\n%"u8); + buffer.Write([0xE2, 0xE3, 0xCF, 0xD3, (byte)'\n']); + } + + /// Writes N G obj, the object's bytes, and endobj (§7.3.10). + private static void WriteIndirectObject(PooledBufferWriter buffer, CosReference reference, WriterObject item, PdfSource? source) + { + WriteInteger(buffer, reference.ObjectNumber); + buffer.Write(" "u8); + WriteInteger(buffer, reference.Generation); + buffer.Write(" obj\n"u8); + WriteBody(buffer, item, source); + buffer.Write("\nendobj\n"u8); + } + + /// Writes an object's bytes: copied from the source when it has them, serialized otherwise. + private static void WriteBody(PooledBufferWriter buffer, WriterObject item, PdfSource? source) + { + if (item.Source is not { } bytes) + { + item.Value.WriteTo(buffer); + return; + } + + if (!bytes.IsInFile) + { + buffer.Write(bytes.Member.Span); + return; + } + + if (source is null) + { + throw new InvalidOperationException("Object bytes in a file were given without the file."); + } + + Span target = buffer.GetSpan(bytes.Length)[..bytes.Length]; + int read = source.Read(bytes.FileOffset, target); + if (read != bytes.Length) + { + throw new InvalidOperationException("The source file ended before the bytes of an object it holds."); + } + + buffer.Advance(read); + } + + /// Builds an object stream holding objects from (§7.5.7, Table 16). + private CosStream BuildObjectStream(List objects, int start, int count) + { + using var bodies = new PooledBufferWriter(ChunkSize, Array.MaxLength); + var header = new ArrayBufferWriter(); + for (int index = 0; index < count; index++) + { + WriterObject item = objects[start + index]; + if (index > 0) + { + header.Write(" "u8); + bodies.Write("\n"u8); + } + + WriteInteger(header, item.Reference.ObjectNumber); + header.Write(" "u8); + WriteInteger(header, bodies.WrittenSpan.Length); + WriteBody(bodies, item, _source); + } + + header.Write("\n"u8); + var data = new MemoryStream(); + using (var zlib = new ZLibStream(data, CompressionLevel.Optimal, leaveOpen: true)) + { + zlib.Write(header.WrittenSpan); + zlib.Write(bodies.WrittenSpan); + } + + var dictionary = new CosDictionary + { + [KnownNames.Type] = ObjStm, + [N] = new CosInteger(count), + [First] = new CosInteger(header.WrittenCount), + [Filter] = FlateDecode, + }; + return new CosStream(dictionary, data.ToArray()); + } + + /// Writes a classic cross-reference table and trailer (§7.5.4, §7.5.5). + private void WriteTable(PooledBufferWriter buffer, Dictionary entries, int size, long xrefOffset, CosArray identifier) + { + XrefEntry[] table = Complete(entries, size); + buffer.Write("xref\n0 "u8); + WriteInteger(buffer, size); + buffer.Write("\n"u8); + foreach (XrefEntry entry in table) + { + if (entry.Offset > MaxTableOffset) + { + throw new InvalidOperationException( + "The file is too large for a classic cross-reference table, whose offsets have ten digits; save with PdfCrossReferenceLayout.Stream."); + } + + Span line = buffer.GetSpan(20); + entry.Offset.TryFormat(line, out _, "D10", CultureInfo.InvariantCulture); + line[10] = (byte)' '; + entry.Generation.TryFormat(line[11..], out _, "D5", CultureInfo.InvariantCulture); + line[16] = (byte)' '; + line[17] = entry.Kind == XrefEntryKind.Free ? (byte)'f' : (byte)'n'; + line[18] = (byte)'\r'; + line[19] = (byte)'\n'; + buffer.Advance(20); + } + + CosDictionary trailer = TrailerDictionary(size, identifier); + buffer.Write("trailer\n"u8); + trailer.WriteTo(buffer); + WriteEnd(buffer, xrefOffset); + } + + /// Writes a cross-reference stream that lists itself, then the end of the file (§7.5.8). + private void WriteStream(PooledBufferWriter buffer, Dictionary entries, int number, long offset, CosArray identifier) + { + int size = number + 1; + entries[number] = new XrefEntry(XrefEntryKind.InUse, offset, 0); + XrefEntry[] table = Complete(entries, size); + + long largest = 0; + foreach (XrefEntry entry in table) + { + largest = Math.Max(largest, entry.Offset); + } + + int middle = 1; + while (middle < 8 && largest >> (8 * middle) != 0) + { + middle++; + } + + int columns = 1 + middle + 2; + byte[] rows = new byte[size * (columns + 1)]; + byte[] previous = new byte[columns]; + byte[] row = new byte[columns]; + Span field = stackalloc byte[8]; + for (int index = 0; index < size; index++) + { + XrefEntry entry = table[index]; + row[0] = entry.Kind switch + { + XrefEntryKind.Free => 0, + XrefEntryKind.InUse => 1, + _ => 2, + }; + BinaryPrimitives.WriteInt64BigEndian(field, entry.Offset); + field[(8 - middle)..].CopyTo(row.AsSpan(1, middle)); + BinaryPrimitives.WriteUInt16BigEndian(row.AsSpan(1 + middle, 2), (ushort)entry.Generation); + + // PNG Up predictor (§7.4.4.4, Predictor 12): each byte minus the byte above it. + int at = index * (columns + 1); + rows[at] = 2; + for (int column = 0; column < columns; column++) + { + rows[at + 1 + column] = (byte)(row[column] - previous[column]); + } + + (previous, row) = (row, previous); + } + + var data = new MemoryStream(); + using (var zlib = new ZLibStream(data, CompressionLevel.Optimal, leaveOpen: true)) + { + zlib.Write(rows); + } + + var dictionary = new CosDictionary + { + [KnownNames.Type] = XRef, + }; + foreach (KeyValuePair entry in TrailerDictionary(size, identifier)) + { + dictionary[entry.Key] = entry.Value; + } + + dictionary[W] = new CosArray([new CosInteger(1), new CosInteger(middle), new CosInteger(2)]); + dictionary[Filter] = FlateDecode; + dictionary[DecodeParms] = new CosDictionary { [Predictor] = new CosInteger(12), [Columns] = new CosInteger(columns) }; + + var reference = new CosReference(number, 0); + WriteIndirectObject(buffer, reference, new WriterObject(reference, new CosStream(dictionary, data.ToArray()), null), source: null); + WriteEnd(buffer, offset); + } + + /// The trailer: Size, the given entries, then ID (§7.5.5, Table 15). + private CosDictionary TrailerDictionary(int size, CosArray identifier) + { + var trailer = new CosDictionary { [KnownNames.Size] = new CosInteger(size) }; + foreach (KeyValuePair entry in _trailer) + { + trailer[entry.Key] = entry.Value; + } + + trailer[KnownNames.ID] = identifier; + return trailer; + } + + /// + /// Fills in a free entry for every number below that holds no object, and links the free entries into a + /// list from object 0, which has generation 65535 (§7.5.4). + /// + private XrefEntry[] Complete(Dictionary entries, int size) + { + var table = new XrefEntry[size]; + int lastFree = 0; + for (int number = size - 1; number >= 0; number--) + { + if (number > 0 && entries.TryGetValue(number, out XrefEntry entry)) + { + table[number] = entry; + continue; + } + + int generation = number == 0 ? CosReference.MaxGeneration : _freeGenerations.GetValueOrDefault(number); + table[number] = new XrefEntry(XrefEntryKind.Free, lastFree, generation); + lastFree = number; + } + + return table; + } + + /// Writes startxref, the offset of the cross-reference information, and %%EOF (§7.5.5). + private static void WriteEnd(IBufferWriter buffer, long xrefOffset) + { + buffer.Write("\nstartxref\n"u8); + WriteInteger(buffer, xrefOffset); + buffer.Write("\n%%EOF\n"u8); + } + + private static void WriteInteger(IBufferWriter buffer, long value) + { + Span span = buffer.GetSpan(20); + value.TryFormat(span, out int written, default, CultureInfo.InvariantCulture); + buffer.Advance(written); + } + + private static void WriteAscii(IBufferWriter buffer, string text) + { + Span span = buffer.GetSpan(text.Length); + for (int index = 0; index < text.Length; index++) + { + span[index] = (byte)text[index]; + } + + buffer.Advance(text.Length); + } +} diff --git a/src/Broadside/Writing/SavePlan.cs b/src/Broadside/Writing/SavePlan.cs new file mode 100644 index 00000000..df3b8576 --- /dev/null +++ b/src/Broadside/Writing/SavePlan.cs @@ -0,0 +1,223 @@ +using Broadside.IO; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Writing; + +/// Decides what a full save of an opened document writes, and builds the that writes it. +/// +/// +/// ISO 32000-2 §7.5. Every object the cross-reference information lists as in use is written under its own number and generation, +/// whether it sat in the file body or in an object stream; the newest revision's copy wins, so the revisions of an incrementally +/// updated file collapse into one (§7.5.6). Objects that describe the old file's structure are dropped and their numbers freed: +/// cross-reference streams (§7.5.8) and object streams (§7.5.7), which the new file replaces with its own, and the linearization +/// parameter dictionary and hint streams (Annex F, F.3.6: a regenerated file is no longer linearized). Such an object is kept, +/// as an ordinary object, when a kept object or the trailer refers to it, which only a damaged file does. +/// +/// +/// An object that has not changed () and was read without any repair is copied byte for byte from +/// the source; any other object is serialized. Every object is loaded first, so in strict mode a deviation throws before anything +/// is written. +/// +/// +internal static class SavePlan +{ + /// + /// The largest object number a saved file may use: the limit ISO 32000-1 Annex C, Table C.1 gives for the number of indirect + /// objects. A classic table lists every number up to the largest (§7.5.4), so a larger number in a damaged or hostile file would + /// make the table gigabytes long; such a file needs renumbering, which the full rewrite of a later phase does. + /// + public const int MaxObjectNumber = 8_388_607; + + private static readonly CosName XRef = new("XRef"); + private static readonly CosName ObjStm = new("ObjStm"); + private static readonly CosName XRefStm = new("XRefStm"); + + /// Plans the save of an opened document. + /// The document's file. + /// The document's loader. + /// The document's linearization information, whose objects are dropped. + /// The cross-reference layout. + /// The writer. + /// The document is encrypted, or uses object numbers above . + public static FileWriter Create(PdfSource source, ObjectLoader loader, PdfLinearization? linearization, PdfCrossReferenceLayout layout) + { + CrossReference crossReference = loader.CrossReference; + CosDictionary sourceTrailer = crossReference.Trailer; + if (sourceTrailer.ContainsKey(KnownNames.Encrypt)) + { + throw new NotSupportedException( + "Saving an encrypted document is not supported yet: its objects would be written with keys that no longer match, or as plain text."); + } + + if (crossReference.Entries.Keys.DefaultIfEmpty().Max() > MaxObjectNumber) + { + throw new NotSupportedException( + $"The document uses object numbers above {MaxObjectNumber}; saving it needs renumbering, which is not supported yet."); + } + + var candidates = new HashSet(); + if (linearization is not null) + { + candidates.Add(linearization.Reference.ObjectNumber); + AddHintStreams(linearization, crossReference, candidates); + } + + var loaded = new List<(CosReference Reference, CosObject Value)>(); + var freeGenerations = new Dictionary(); + foreach ((int number, XrefEntry entry) in crossReference.Entries.OrderBy(pair => pair.Key)) + { + CosReference reference; + switch (entry.Kind) + { + case XrefEntryKind.InUse: + reference = new CosReference(number, entry.Generation); + break; + case XrefEntryKind.Compressed: + reference = new CosReference(number, 0); + break; + default: + freeGenerations[number] = entry.Generation; + continue; + } + + CosObject value = loader.Load(reference); + if (IsFileStructure(value)) + { + candidates.Add(number); + } + + loaded.Add((reference, value)); + } + + HashSet referenced = FindReferenced(sourceTrailer, loaded, candidates); + var objects = new List(loaded.Count); + foreach ((CosReference reference, CosObject value) in loaded) + { + if (candidates.Contains(reference.ObjectNumber) && !referenced.Contains(reference)) + { + freeGenerations[reference.ObjectNumber] = Math.Min(reference.Generation + 1, CosReference.MaxGeneration); + continue; + } + + ObjectSourceBytes? bytes = !value.IsDirty && loader.TryGetSourceBytes(reference, out ObjectSourceBytes found) ? found : null; + objects.Add(new WriterObject(reference, value, bytes)); + } + + var trailer = new CosDictionary(); + foreach (KeyValuePair entry in sourceTrailer) + { + if (!entry.Key.Equals(KnownNames.Size) && !entry.Key.Equals(KnownNames.Prev) && !entry.Key.Equals(XRefStm) && !entry.Key.Equals(KnownNames.ID)) + { + trailer[entry.Key] = entry.Value; + } + } + + CosString? firstIdentifier = sourceTrailer.TryGetValue(KnownNames.ID, out CosObject? id) + && loader.Resolve(id) is CosArray { Count: 2 } identifiers + && loader.Resolve(identifiers[0]) is CosString first + && loader.Resolve(identifiers[1]) is CosString + ? first + : null; + + return new FileWriter( + source, + loader.Header.Version ?? FileHeader.DefaultVersion, + objects, + freeGenerations, + trailer, + firstIdentifier, + layout); + } + + /// + /// Finds the references the trailer and the objects that are kept contain. A file-structure object is dropped only when nothing + /// kept refers to it: in a well-formed file nothing does, and in a damaged one dropping it would change what the document shows. + /// A candidate something refers to is kept, and what it refers to is followed in turn. + /// + private static HashSet FindReferenced(CosDictionary trailer, List<(CosReference Reference, CosObject Value)> loaded, HashSet candidates) + { + var referenced = new HashSet(); + var candidateValues = new Dictionary(); + var pending = new Stack(); + pending.Push(trailer); + foreach ((CosReference reference, CosObject value) in loaded) + { + if (candidates.Contains(reference.ObjectNumber)) + { + candidateValues[reference] = value; + } + else + { + pending.Push(value); + } + } + + while (pending.TryPop(out CosObject? value)) + { + switch (value) + { + case CosReference reference: + if (referenced.Add(reference) && candidateValues.TryGetValue(reference, out CosObject? kept)) + { + pending.Push(kept); + } + + break; + case CosArray array: + foreach (CosObject item in array) + { + pending.Push(item); + } + + break; + case CosDictionary dictionary: + foreach (CosObject item in dictionary.Values) + { + pending.Push(item); + } + + break; + case CosStream stream: + pending.Push(stream.Dictionary); + break; + default: + break; + } + } + + return referenced; + } + + /// Whether an object is a cross-reference stream or an object stream, which the new file replaces. + private static bool IsFileStructure(CosObject value) => + value is CosStream stream + && stream.Dictionary.TryGetValue(KnownNames.Type, out CosObject? type) + && (XRef.Equals(type) || ObjStm.Equals(type)); + + /// Adds the objects at the hint stream offsets the linearization dictionary's H entry gives (F.3.3, Table F.1). + private static void AddHintStreams(PdfLinearization linearization, CrossReference crossReference, HashSet candidates) + { + if (!linearization.Dictionary.TryGetValue(PdfLinearization.Names.H, out CosObject? h) || h is not CosArray hints) + { + return; + } + + var offsets = new HashSet(); + for (int index = 0; index < hints.Count; index += 2) + { + if (hints[index] is CosInteger offset) + { + offsets.Add(offset.Value); + } + } + + foreach ((int number, XrefEntry entry) in crossReference.Entries) + { + if (entry.Kind == XrefEntryKind.InUse && offsets.Contains(entry.Offset)) + { + candidates.Add(number); + } + } + } +} diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 332f7742..71163593 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -20,6 +20,7 @@ internal static class FuzzTargets ["lexer"] = Lexer, ["object-parser"] = ObjectParser, ["document"] = Document, + ["save"] = Save, ["hint-tables"] = HintTables, ["xref-stream"] = XrefStream, ["object-stream"] = ObjectStreamTarget, @@ -90,6 +91,40 @@ private static void Document(ReadOnlySpan data) } } + /// + /// Opens the input as a whole file in lenient mode, saves it in the layout the input's length selects, and reopens the output. + /// Whatever opened must save, and what was saved must open again with the same number of pages: a full save writes every object + /// (repaired ones re-serialized), so nothing the first open could read may become unreadable. + /// is the documented outcome for an encrypted file or one with object numbers above the save limit. + /// + /// ISO 32000-2 §7.5 (issue #44). + private static void Save(ReadOnlySpan data) + { + using PdfDocument? document = OpenOrNull(data); + if (document is null) + { + return; + } + + int pages = document.Pages.Count; + var layout = (PdfCrossReferenceLayout)(data.Length % 3); + using var output = new MemoryStream(); + try + { + document.Save(output, new PdfSaveOptions().WithCrossReferenceLayout(layout)); + } + catch (NotSupportedException) + { + return; + } + + using PdfDocument saved = PdfDocument.Open(output.ToArray()); + if (saved.Pages.Count != pages) + { + throw new InvalidOperationException($"The saved file has {saved.Pages.Count} pages; the input had {pages}."); + } + } + /// /// Decodes the input as a raw stream body with one filter in lenient mode. The output must stay within /// bytes per input byte (plus one group), the most any encoding of that filter can expand. diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index e62cdaf7..cf10dab5 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` for a file whose cross-reference information cannot be read is the one allowed outcome until #41 reconstructs it; it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` for a file whose cross-reference information cannot be read is the one allowed outcome until #41 reconstructs it; it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. @@ -25,7 +25,7 @@ dotnet run -c Release --project tests/Broadside.Fuzz -- --run object-parser arti `--run ` executes the target once on one input, which is also how to replay a crash found by libFuzzer or AFL. -Whole corpus files are the right seeds for `lexer` and `object-parser`, which read any bytes as a file body, and for `document`, which reads whole files. `hint-tables` reads raw hint stream data, for which whole files are a weak seed; for libFuzzer and AFL seed it with the hint stream of `linearized.pdf` behind its three control bytes (two pages, shared table at 44): +Whole corpus files are the right seeds for `lexer` and `object-parser`, which read any bytes as a file body, and for `document` and `save`, which read whole files. `hint-tables` reads raw hint stream data, for which whole files are a weak seed; for libFuzzer and AFL seed it with the hint stream of `linearized.pdf` behind its three control bytes (two pages, shared table at 44): ```sh mkdir -p artifacts/fuzz/seeds-hints diff --git a/tests/Broadside.Tests/Document/EngineTests.cs b/tests/Broadside.Tests/Document/EngineTests.cs index bc4d1be2..512fc7bf 100644 --- a/tests/Broadside.Tests/Document/EngineTests.cs +++ b/tests/Broadside.Tests/Document/EngineTests.cs @@ -94,13 +94,6 @@ public void Options_are_lenient_by_default_and_fluent() Assert.Equal(PdfReadingMode.Lenient, options.ReadingMode); } - [Fact] - public void Create_is_a_stub_until_writing_lands() - { - Assert.Throws(() => PdfDocument.Create()); - Assert.Throws(() => new PdfEngine().Create()); - } - [Fact] public void A_disposed_document_cannot_load_more_objects() { diff --git a/tests/Broadside.Tests/Writing/CreateTests.cs b/tests/Broadside.Tests/Writing/CreateTests.cs new file mode 100644 index 00000000..6edce7ef --- /dev/null +++ b/tests/Broadside.Tests/Writing/CreateTests.cs @@ -0,0 +1,73 @@ +using Broadside.Objects; + +namespace Broadside.Tests.Writing; + +/// Creating a document from scratch. ISO 32000-2 §7.5.2, §7.7.2, §7.7.3, §14.4. +public class CreateTests +{ + [Fact] + public void A_created_document_has_one_empty_letter_page_and_is_PDF_2_0() + { + using PdfDocument document = PdfDocument.Create(); + + PdfPage page = Assert.Single(document.Pages); + Assert.Equal(new PdfRectangle(0, 0, 612, 792), page.MediaBox); + Assert.Empty(Assert.IsType(page.Resources)); + Assert.False(page.Dictionary.ContainsKey(new CosName("Contents"))); + Assert.Equal(new PdfVersion(2, 0), document.Version); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_created_document_is_the_same_through_an_engine_and_in_strict_mode() + { + using PdfDocument document = new PdfEngine(new PdfOptions().UseStrict()).Create(); + + Assert.Equal(new PdfRectangle(0, 0, 612, 792), Assert.Single(document.Pages).MediaBox); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_saved_created_document_passes_qpdf_check() + { + using PdfDocument document = PdfDocument.Create(); + + (int exitCode, string output) = ExternalTool.Run("qpdf", Saved(document), "--check"); + + Assert.True(exitCode == 0, output); + } + + [Fact] + public void A_saved_created_document_opens_in_pdfinfo_as_one_letter_page() + { + using PdfDocument document = PdfDocument.Create(); + + (int exitCode, string output) = ExternalTool.Run("pdfinfo", Saved(document)); + + Assert.True(exitCode == 0, output); + Assert.Matches(@"Pages:\s+1\n", output); + Assert.Matches(@"Page size:\s+612 x 792 pts \(letter\)", output); + Assert.Matches(@"PDF version:\s+2\.0", output); + } + + [Fact] + public void A_saved_created_document_reopens_with_two_equal_file_identifiers() + { + using PdfDocument document = PdfDocument.Create(); + + using PdfDocument reopened = PdfDocument.Open(Saved(document)); + + // §14.4: "When a PDF file is first written, both identifiers shall be set to the same value"; Table 15 requires ID in 2.0. + var id = Assert.IsType(reopened.Trailer[new CosName("ID")]); + Assert.Equal(id[0], id[1]); + Assert.Equal(new PdfRectangle(0, 0, 612, 792), Assert.Single(reopened.Pages).MediaBox); + Assert.Empty(reopened.Diagnostics); + } + + private static byte[] Saved(PdfDocument document) + { + using var output = new MemoryStream(); + document.Save(output); + return output.ToArray(); + } +} diff --git a/tests/Broadside.Tests/Writing/ExternalTool.cs b/tests/Broadside.Tests/Writing/ExternalTool.cs new file mode 100644 index 00000000..abca40e3 --- /dev/null +++ b/tests/Broadside.Tests/Writing/ExternalTool.cs @@ -0,0 +1,54 @@ +using System.Diagnostics; + +namespace Broadside.Tests.Writing; + +/// +/// Runs a command-line PDF tool (qpdf, pdfinfo) on a file as an independent check of written output. A test that needs a tool which +/// is not on the PATH is skipped, not failed; CI installs both (qpdf and poppler-utils). +/// +internal static class ExternalTool +{ + /// Writes to a temporary path and runs with the arguments and that path last. + /// The exit code and the standard output and error, joined. + public static (int ExitCode, string Output) Run(string tool, byte[] file, params string[] arguments) + { + string? executable = Find(tool); + if (executable is null) + { + Assert.Skip($"{tool} is not on the PATH."); + } + + string path = Path.Combine(Path.GetTempPath(), $"broadside-{Guid.NewGuid():N}.pdf"); + File.WriteAllBytes(path, file); + try + { + var start = new ProcessStartInfo(executable) + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + }; + foreach (string argument in arguments) + { + start.ArgumentList.Add(argument); + } + + start.ArgumentList.Add(path); + using Process process = Process.Start(start)!; + string output = process.StandardOutput.ReadToEnd() + process.StandardError.ReadToEnd(); + process.WaitForExit(); + return (process.ExitCode, output); + } + finally + { + File.Delete(path); + } + } + + private static string? Find(string tool) + { + string[] directories = (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries); + string[] names = OperatingSystem.IsWindows() ? [tool + ".exe", tool] : [tool]; + return directories.SelectMany(directory => names.Select(name => Path.Combine(directory, name))).FirstOrDefault(File.Exists); + } +} diff --git a/tests/Broadside.Tests/Writing/ObjectBodies.cs b/tests/Broadside.Tests/Writing/ObjectBodies.cs new file mode 100644 index 00000000..29e9f2cd --- /dev/null +++ b/tests/Broadside.Tests/Writing/ObjectBodies.cs @@ -0,0 +1,87 @@ +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; +using Broadside.Objects; + +namespace Broadside.Tests.Writing; + +/// +/// Finds the bytes of every indirect object in a file, independently of the library's reader, so a test can compare a saved file +/// with its source. An object's bytes are those from the first token after N G obj to the last byte before endobj, +/// white-space trimmed; for a member of an object stream (ISO 32000-2 §7.5.7), its slice of the decoded stream up to the next +/// member's offset, white-space trimmed. A top-level object defined twice (an incremental update) keeps its last definition. +/// +internal static partial class ObjectBodies +{ + private static readonly CosName ObjStm = new("ObjStm"); + private static readonly CosName Type = new("Type"); + private static readonly CosName N = new("N"); + private static readonly CosName First = new("First"); + + /// Reads the bytes of every object in , keyed by object number and generation. + public static Dictionary<(int Number, int Generation), byte[]> Read(byte[] file) + { + string text = Encoding.Latin1.GetString(file); + var bodies = new Dictionary<(int, int), byte[]>(); + var objectStreams = new List<(int, int)>(); + int position = 0; + while (Header().Match(text, position) is { Success: true } header) + { + int start = header.Index + header.Length; + int streamAt = text.IndexOf("stream", start, StringComparison.Ordinal); + int endobj = text.IndexOf("endobj", start, StringComparison.Ordinal); + if (streamAt >= 0 && streamAt < endobj) + { + int endstream = text.IndexOf("endstream", streamAt, StringComparison.Ordinal); + endobj = text.IndexOf("endobj", endstream, StringComparison.Ordinal); + } + + var key = (int.Parse(header.Groups[1].Value, CultureInfo.InvariantCulture), int.Parse(header.Groups[2].Value, CultureInfo.InvariantCulture)); + bodies[key] = Trim(file.AsSpan(start, endobj - start)).ToArray(); + if (ObjStmType().IsMatch(text.AsSpan(start, Math.Min(200, endobj - start)))) + { + objectStreams.Add(key); + } + + position = endobj + "endobj".Length; + } + + if (objectStreams.Count > 0) + { + using PdfDocument document = PdfDocument.Open(file); + foreach ((int number, int generation) in objectStreams) + { + if (document.Resolve(new CosReference(number, generation)) is not CosStream stream || !ObjStm.Equals(stream.Dictionary[Type])) + { + continue; + } + + byte[] data = document.DecodeStream(stream).ToArray(); + long count = ((CosInteger)stream.Dictionary[N]).Value; + int first = (int)((CosInteger)stream.Dictionary[First]).Value; + string[] pairs = Encoding.Latin1.GetString(data, 0, first).Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); + var members = new List<(int Number, int Offset)>(); + for (int index = 0; index < count; index++) + { + members.Add((int.Parse(pairs[2 * index], CultureInfo.InvariantCulture), first + int.Parse(pairs[(2 * index) + 1], CultureInfo.InvariantCulture))); + } + + for (int index = 0; index < members.Count; index++) + { + int end = index + 1 < members.Count ? members[index + 1].Offset : data.Length; + bodies.TryAdd((members[index].Number, 0), Trim(data.AsSpan(members[index].Offset, end - members[index].Offset)).ToArray()); + } + } + } + + return bodies; + } + + private static ReadOnlySpan Trim(ReadOnlySpan bytes) => bytes.Trim("\0\t\n\f\r "u8); + + [GeneratedRegex(@"(?Saving an opened document as a complete new file. ISO 32000-2 §7.5, §7.3.8, §7.3.10. +public class SaveTests +{ + private static readonly PdfCrossReferenceLayout[] Layouts = Enum.GetValues(); + + /// Every unencrypted well-formed corpus file with every layout (encrypted files cannot be saved yet). + public static TheoryData FilesAndLayouts + { + get + { + var data = new TheoryData(); + foreach (string file in Corpus.WellFormedFileNames.Where(name => !name.StartsWith("encrypted-", StringComparison.Ordinal))) + { + foreach (PdfCrossReferenceLayout layout in Layouts) + { + data.Add(file, layout); + } + } + + return data; + } + } + + [Fact] + public void A_saved_file_reopens_with_the_same_pages_and_no_diagnostics() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + using var output = new MemoryStream(); + + document.Save(output); + + using PdfDocument reopened = PdfDocument.Open(output.ToArray()); + Assert.Equal(new PdfRectangle(0, 0, 612, 792), Assert.Single(reopened.Pages).MediaBox); + Assert.Empty(reopened.Diagnostics); + } + + [Theory] + [MemberData(nameof(FilesAndLayouts))] + public void A_well_formed_file_saved_in_any_layout_reopens_with_the_same_objects_and_no_diagnostics(string fileName, PdfCrossReferenceLayout layout) + { + using PdfDocument source = PdfDocument.Open(Corpus.Path(fileName)); + + using PdfDocument saved = PdfDocument.Open(Save(source, layout)); + + Assert.Equal(source.Pages.Count, saved.Pages.Count); + for (int index = 0; index < source.Pages.Count; index++) + { + Assert.Equal(source.Pages[index].MediaBox, saved.Pages[index].MediaBox); + Assert.Equal(source.Pages[index].CropBox, saved.Pages[index].CropBox); + Assert.Equal(source.Pages[index].Rotation, saved.Pages[index].Rotation); + } + + AssertSameObjectGraph(source, saved); + Assert.Empty(saved.Diagnostics); + } + + [Theory] + [MemberData(nameof(FilesAndLayouts))] + public void A_well_formed_file_saved_in_any_layout_passes_qpdf_check(string fileName, PdfCrossReferenceLayout layout) + { + using PdfDocument source = PdfDocument.Open(Corpus.Path(fileName)); + + (int exitCode, string output) = ExternalTool.Run("qpdf", Save(source, layout), "--check"); + + Assert.True(exitCode == 0, output); + } + + [Theory] + [MemberData(nameof(FilesAndLayouts))] + public void Objects_that_were_not_changed_keep_their_source_bytes_in_any_layout(string fileName, PdfCrossReferenceLayout layout) + { + byte[] file = Corpus.Bytes(fileName); + using PdfDocument source = PdfDocument.Open(file); + + byte[] saved = Save(source, layout); + + Dictionary<(int Number, int Generation), byte[]> before = ObjectBodies.Read(file); + Dictionary<(int Number, int Generation), byte[]> after = ObjectBodies.Read(saved); + foreach (((int number, int generation), byte[] bytes) in before) + { + if (after.TryGetValue((number, generation), out byte[]? written)) + { + Assert.True(bytes.AsSpan().SequenceEqual(written), $"Object {number} {generation} changed bytes."); + } + else + { + Assert.True(IsDroppedOnSave(source, new CosReference(number, generation)), $"Object {number} {generation} was not written."); + } + } + } + + [Fact] + public void Bytes_a_canonical_writer_would_change_are_kept_in_every_layout() + { + // (en\055US) is "en-US" with an octal escape, and the dictionary has no spaces: re-serializing would change both (§7.3.4.2). + const string catalog = "<>"; + byte[] file = new Document.TestPdf().Build( + catalog, + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612.0 792.00] >>"); + using PdfDocument source = PdfDocument.Open(file); + + foreach (PdfCrossReferenceLayout layout in Layouts) + { + Dictionary<(int Number, int Generation), byte[]> written = ObjectBodies.Read(Save(source, layout)); + Assert.Equal(catalog, System.Text.Encoding.Latin1.GetString(written[(1, 0)])); + Assert.Equal("<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612.0 792.00] >>", System.Text.Encoding.Latin1.GetString(written[(3, 0)])); + } + } + + [Fact] + public void A_changed_object_is_written_with_its_new_value_and_the_others_keep_their_bytes() + { + byte[] file = Corpus.Bytes("page-tree-inherited.pdf"); + using PdfDocument source = PdfDocument.Open(file); + PdfPage page = source.Pages[0]; + page.Dictionary[new CosName("MediaBox")] = new CosArray([new CosInteger(0), new CosInteger(0), new CosInteger(100), new CosInteger(200)]); + + byte[] saved = Save(source, PdfCrossReferenceLayout.Table); + + using PdfDocument reopened = PdfDocument.Open(saved); + Assert.Equal(new PdfRectangle(0, 0, 100, 200), reopened.Pages[0].MediaBox); + Assert.Equal(source.Pages[1].MediaBox, reopened.Pages[1].MediaBox); + Assert.Empty(reopened.Diagnostics); + Dictionary<(int Number, int Generation), byte[]> before = ObjectBodies.Read(file); + Dictionary<(int Number, int Generation), byte[]> after = ObjectBodies.Read(saved); + (int, int) changed = (page.Reference!.ObjectNumber, page.Reference.Generation); + Assert.False(before[changed].AsSpan().SequenceEqual(after[changed])); + Assert.All(before.Keys.Where(key => key != changed), key => Assert.True(before[key].AsSpan().SequenceEqual(after[key]))); + } + + [Theory] + [InlineData("missing-endobj.pdf", "MissingEndobj")] + [InlineData("wrong-stream-length.pdf", "StreamLengthInvalid")] + public void A_repaired_object_is_written_as_repaired_so_the_saved_file_needs_no_repair(string fileName, string repair) + { + using PdfDocument source = PdfDocument.Open(Corpus.Path(fileName)); + Assert.Equal(source.Pages.Count, source.Pages.Count); + + byte[] saved = Save(source, PdfCrossReferenceLayout.Table); + + Assert.Contains(source.Diagnostics, diagnostic => diagnostic.Code == repair); + using PdfDocument reopened = PdfDocument.Open(saved); + AssertSameObjectGraph(source, reopened); + Assert.Empty(reopened.Diagnostics); + (int exitCode, string output) = ExternalTool.Run("qpdf", saved, "--check"); + Assert.True(exitCode == 0, output); + } + + [Fact] + public void Saving_an_updated_file_collapses_its_revisions_into_one_with_the_newest_objects() + { + using PdfDocument source = PdfDocument.Open(Corpus.Path("incremental-update.pdf")); + + byte[] saved = Save(source, PdfCrossReferenceLayout.Table); + + using PdfDocument reopened = PdfDocument.Open(saved); + Assert.Single(reopened.Revisions); + Assert.Equal(new PdfRectangle(0, 0, 595, 842), Assert.Single(reopened.Pages).MediaBox); + Assert.Equal(1, CountOf(saved, "\nxref\n"u8)); + Assert.Equal(1, CountOf(saved, "%%EOF"u8)); + Assert.False(reopened.Trailer.ContainsKey(new CosName("Prev"))); + } + + [Theory] + [InlineData(PdfCrossReferenceLayout.Table)] + [InlineData(PdfCrossReferenceLayout.Stream)] + [InlineData(PdfCrossReferenceLayout.StreamWithObjectStreams)] + public void The_information_dictionary_of_a_hybrid_file_survives_from_its_object_stream(PdfCrossReferenceLayout layout) + { + using PdfDocument source = PdfDocument.Open(Corpus.Path("hybrid-xref.pdf")); + + using PdfDocument reopened = PdfDocument.Open(Save(source, layout)); + + var info = Assert.IsType(reopened.Resolve(reopened.Trailer[new CosName("Info")])); + Assert.Equal("hybrid", Assert.IsType(info[new CosName("Title")]).DecodeText()); + Assert.False(reopened.Trailer.ContainsKey(new CosName("XRefStm"))); + } + + [Fact] + public void A_linearized_file_is_saved_without_its_linearization_dictionary_and_hint_stream() + { + using PdfDocument source = PdfDocument.Open(Corpus.Path("linearized.pdf")); + Assert.True(source.IsLinearized); + + using PdfDocument reopened = PdfDocument.Open(Save(source, PdfCrossReferenceLayout.Table)); + + Assert.Null(reopened.Linearization); + Assert.False(reopened.IsLinearized); + Assert.Equal(CosNull.Instance, reopened.Resolve(source.Linearization!.Reference)); + Assert.Equal(CosNull.Instance, reopened.Resolve(new CosReference(7, 0))); + Assert.Equal(2, reopened.Pages.Count); + } + + [Fact] + public void A_linearization_dictionary_the_page_tree_refers_to_is_kept() + { + // A damaged file (found by the save fuzz target): the page tree root's kid is the linearization dictionary, object 5. + byte[] file = Corpus.Bytes("linearized.pdf"); + int kids = file.AsSpan().IndexOf("/Kids [ 4 0 R ]"u8); + file[kids + "/Kids [ ".Length] = (byte)'5'; + using PdfDocument source = PdfDocument.Open(file); + + using PdfDocument reopened = PdfDocument.Open(Save(source, PdfCrossReferenceLayout.Table)); + + Assert.Equal(source.Pages.Count, reopened.Pages.Count); + Assert.True(CosObject.DeepEquals(source.Resolve(new CosReference(5, 0)), reopened.Resolve(new CosReference(5, 0)))); + } + + [Fact] + public void A_document_with_object_numbers_beyond_the_limit_is_not_saved() + { + // A classic table lists every number up to the largest; renumbering is not supported yet. + byte[] file = Document.TestPdf.AppendUpdate( + Document.TestPdf.OnePage(string.Empty), + "/Size 9000001 /Root 1 0 R", + (9_000_000, 0, "<< /Unused true >>")); + using PdfDocument source = PdfDocument.Open(file); + using var output = new MemoryStream(); + + Assert.Throws(() => source.Save(output)); + Assert.Equal(0, output.Length); + } + + [Fact] + public void An_encrypted_document_is_not_saved() + { + using PdfDocument source = PdfDocument.Open(Corpus.Path("encrypted-rc4-128.pdf")); + using var output = new MemoryStream(); + + Assert.Throws(() => source.Save(output)); + Assert.Equal(0, output.Length); + } + + [Theory] + [InlineData(PdfCrossReferenceLayout.Table)] + [InlineData(PdfCrossReferenceLayout.Stream)] + [InlineData(PdfCrossReferenceLayout.StreamWithObjectStreams)] + public async Task SaveAsync_writes_the_same_bytes_as_Save(PdfCrossReferenceLayout layout) + { + using PdfDocument source = PdfDocument.Open(Corpus.Path("object-stream.pdf")); + var options = new PdfSaveOptions().WithCrossReferenceLayout(layout); + using var synchronous = new MemoryStream(); + using var asynchronous = new MemoryStream(); + +#pragma warning disable CA1849 // The synchronous path is what the asynchronous one is compared with. + source.Save(synchronous, options); +#pragma warning restore CA1849 + await source.SaveAsync(asynchronous, options, TestContext.Current.CancellationToken); + + Assert.True(synchronous.ToArray().AsSpan().SequenceEqual(asynchronous.ToArray())); + } + + [Fact] + public void Saving_to_a_path_writes_the_same_bytes_as_saving_to_a_stream() + { + using PdfDocument source = PdfDocument.Open(Corpus.Path("flate-stream.pdf")); + string path = Path.Combine(Path.GetTempPath(), $"broadside-{Guid.NewGuid():N}.pdf"); + try + { + source.Save(path); + + Assert.Equal(Save(source, PdfCrossReferenceLayout.Table), File.ReadAllBytes(path)); + } + finally + { + File.Delete(path); + } + } + + [Fact] + public void Saving_twice_writes_the_same_bytes_and_keeps_the_first_file_identifier() + { + using PdfDocument source = PdfDocument.Open(Corpus.Path("linearized.pdf")); + var sourceId = (CosArray)source.Trailer[new CosName("ID")]; + + byte[] first = Save(source, PdfCrossReferenceLayout.Table); + byte[] second = Save(source, PdfCrossReferenceLayout.Table); + + Assert.Equal(first, second); + using PdfDocument reopened = PdfDocument.Open(first); + var id = Assert.IsType(reopened.Trailer[new CosName("ID")]); + Assert.Equal(sourceId[0], id[0]); + Assert.Equal(16, Assert.IsType(id[1]).Bytes.Length); + } + + [Fact] + public void A_file_without_identifiers_gets_two_equal_ones_when_saved() + { + using PdfDocument source = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + Assert.False(source.Trailer.ContainsKey(new CosName("ID"))); + + using PdfDocument reopened = PdfDocument.Open(Save(source, PdfCrossReferenceLayout.Stream)); + + var id = Assert.IsType(reopened.Trailer[new CosName("ID")]); + Assert.Equal(2, id.Count); + Assert.Equal(id[0], id[1]); + Assert.Equal(16, Assert.IsType(id[0]).Bytes.Length); + } + + [Theory] + [InlineData("%PDF-1.4", PdfCrossReferenceLayout.Table, "1.4")] + [InlineData("%PDF-1.4", PdfCrossReferenceLayout.Stream, "1.5")] + [InlineData("%PDF-1.4", PdfCrossReferenceLayout.StreamWithObjectStreams, "1.5")] + [InlineData("%PDF-2.0", PdfCrossReferenceLayout.Stream, "2.0")] + public void The_header_keeps_the_version_unless_the_layout_needs_a_later_one(string header, PdfCrossReferenceLayout layout, string expected) + { + using PdfDocument source = PdfDocument.Open(Document.TestPdf.OnePage(string.Empty, header: header)); + + byte[] saved = Save(source, layout); + + Assert.StartsWith($"%PDF-{expected}\n%", System.Text.Encoding.Latin1.GetString(saved, 0, 10), StringComparison.Ordinal); + Assert.True(saved[10] >= 128 && saved[11] >= 128 && saved[12] >= 128 && saved[13] >= 128, "The second line marks the file as binary (§7.5.2)."); + } + + [Theory] + [InlineData(PdfCrossReferenceLayout.Table, "xref\n0 ")] + [InlineData(PdfCrossReferenceLayout.Stream, "")] + public void Startxref_gives_the_offset_of_the_cross_reference_information(PdfCrossReferenceLayout layout, string expectedStart) + { + using PdfDocument source = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + + byte[] saved = Save(source, layout); + + string text = System.Text.Encoding.Latin1.GetString(saved); + int startxref = text.LastIndexOf("startxref\n", StringComparison.Ordinal); + int offset = int.Parse(text.AsSpan(startxref + 10, text.IndexOf('\n', startxref + 10) - startxref - 10), System.Globalization.CultureInfo.InvariantCulture); + Assert.StartsWith(expectedStart, text[offset..], StringComparison.Ordinal); + if (layout == PdfCrossReferenceLayout.Stream) + { + Assert.Matches(@"^[0-9]+ 0 obj\n<< /Type /XRef ", text[offset..]); + } + else + { + // One subsection from 0; every entry is exactly 20 bytes (§7.5.4). + string[] lines = text[(offset + 5)..text.IndexOf("trailer", offset, StringComparison.Ordinal)].Split('\n', StringSplitOptions.RemoveEmptyEntries); + Assert.All(lines.Skip(1), line => Assert.Equal(19, line.Length)); + Assert.StartsWith("0000000000 65535 f", lines[1], StringComparison.Ordinal); + } + + Assert.EndsWith("%%EOF\n", text, StringComparison.Ordinal); + } + + private static int CountOf(byte[] file, ReadOnlySpan value) + { + int count = 0; + ReadOnlySpan rest = file; + for (int at = rest.IndexOf(value); at >= 0; at = rest.IndexOf(value)) + { + count++; + rest = rest[(at + value.Length)..]; + } + + return count; + } + + /// Saves through the public API into memory. + private static byte[] Save(PdfDocument document, PdfCrossReferenceLayout layout) + { + using var output = new MemoryStream(); + document.Save(output, new PdfSaveOptions().WithCrossReferenceLayout(layout)); + return output.ToArray(); + } + + /// + /// The objects a full save does not write: old cross-reference and object streams, the linearization dictionary and hint streams + /// (Annex F), and objects an update deleted. + /// + private static bool IsDroppedOnSave(PdfDocument source, CosReference reference) + { + CosObject value = source.Resolve(reference); + if (value is CosNull || reference.Equals(source.Linearization?.Reference)) + { + return true; + } + + return value is CosStream stream + && ((stream.Dictionary.TryGetValue(new CosName("Type"), out CosObject? type) && (type.Equals(new CosName("XRef")) || type.Equals(new CosName("ObjStm")))) + || (source.Linearization is not null && stream.Dictionary.ContainsKey(new CosName("S")))); + } + + /// Walks every object reachable from the trailer of both documents and compares them structurally. + private static void AssertSameObjectGraph(PdfDocument expected, PdfDocument actual) + { + var pending = new Queue(); + var seen = new HashSet(); + foreach (string key in (string[])["Root", "Info"]) + { + if (expected.Trailer.TryGetValue(new CosName(key), out CosObject? value)) + { + Assert.True(actual.Trailer.TryGetValue(new CosName(key), out CosObject? other), $"The trailer lost {key}."); + Assert.True(CosObject.DeepEquals(value, other), $"The trailer's {key} changed."); + pending.Enqueue(value); + } + } + + while (pending.TryDequeue(out CosObject? value)) + { + switch (value) + { + case CosReference reference when seen.Add(reference): + CosObject left = expected.Resolve(reference); + Assert.True(CosObject.DeepEquals(left, actual.Resolve(reference)), $"Object {reference} differs."); + pending.Enqueue(left); + break; + case CosArray array: + array.ToList().ForEach(pending.Enqueue); + break; + case CosDictionary dictionary: + dictionary.Values.ToList().ForEach(pending.Enqueue); + break; + case CosStream stream: + pending.Enqueue(stream.Dictionary); + break; + default: + break; + } + } + } +} From e3a430c6f1330c6c5d8d8b90665bce61440475fc Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:37:31 -0500 Subject: [PATCH 012/152] feat(cos): lazy loading, parse-once object cache and the concurrency contract (#45) Sources: bytes (zero-copy, stream data slices the caller's memory), paths and FileStreams (memory-mapped, windows are views of the mapping), any other seekable stream (read in place under a lock, in growing windows), and non-seekable streams (copied at open into memory up to PdfOptions.StreamBufferLimit, then into a delete-on-close temp file). PdfDocument/PdfEngine.OpenAsync copy a non-seekable stream asynchronously. Objects are parsed once per (number, generation) through a shared OnceCache helper that waits for in-flight loads and refuses waits that would close a cycle (same thread or across threads), so malformed self-referring files neither throw nor deadlock. Object streams are decoded once. Stream data stays in the source and is read on access, so a 2.1 GiB file opens and reads its last page with ~10 MiB managed growth. Parses and object-stream decodes are traced at Trace level (events 2, 3). Co-Authored-By: Claude Opus 5.5 --- .../LazyLoadingBenchmarks.cs | 71 +++++ src/Broadside/Broadside.csproj | 5 + src/Broadside/Caching/OnceCache.cs | 283 ++++++++++++++++++ src/Broadside/Diagnostics/ObjectLog.cs | 35 +++ src/Broadside/EngineConfiguration.cs | 11 + src/Broadside/Filters/StreamDecoder.cs | 2 +- src/Broadside/IO/MappedFileSource.cs | 163 ++++++++++ src/Broadside/IO/PdfSource.cs | 201 +++++++++++-- src/Broadside/IO/StreamSource.cs | 96 ++++++ src/Broadside/Objects/CosParser.cs | 22 +- src/Broadside/Objects/CosStream.cs | 21 +- src/Broadside/Objects/CosWriter.cs | 5 +- src/Broadside/Objects/IStreamDataFactory.cs | 32 ++ src/Broadside/Parsing/DiagnosticCodes.cs | 3 + src/Broadside/Parsing/ObjectLoader.cs | 211 ++++++++----- src/Broadside/Parsing/ObjectLoaderHooks.cs | 51 +++- src/Broadside/PdfDocument.cs | 58 +++- src/Broadside/PdfEngine.cs | 24 +- src/Broadside/PdfOptions.cs | 35 +++ src/Broadside/PublicAPI.Unshipped.txt | 8 + tests/Broadside.Fuzz/FuzzTargets.cs | 54 ++++ tests/Broadside.Fuzz/README.md | 2 +- .../Document/ConcurrencyTests.cs | 161 ++++++++++ .../Document/LargeFileTests.cs | 119 ++++++++ .../Document/LazyLoadingTests.cs | 200 +++++++++++++ .../Document/OpenDocumentTests.cs | 7 +- tests/Broadside.Tests/Document/ProbeStream.cs | 87 ++++++ tests/Broadside.Tests/Document/SourceTests.cs | 180 +++++++++++ 28 files changed, 2032 insertions(+), 115 deletions(-) create mode 100644 bench/Broadside.Benchmarks/LazyLoadingBenchmarks.cs create mode 100644 src/Broadside/Caching/OnceCache.cs create mode 100644 src/Broadside/Diagnostics/ObjectLog.cs create mode 100644 src/Broadside/IO/MappedFileSource.cs create mode 100644 src/Broadside/IO/StreamSource.cs create mode 100644 src/Broadside/Objects/IStreamDataFactory.cs create mode 100644 tests/Broadside.Tests/Document/ConcurrencyTests.cs create mode 100644 tests/Broadside.Tests/Document/LargeFileTests.cs create mode 100644 tests/Broadside.Tests/Document/LazyLoadingTests.cs create mode 100644 tests/Broadside.Tests/Document/ProbeStream.cs create mode 100644 tests/Broadside.Tests/Document/SourceTests.cs diff --git a/bench/Broadside.Benchmarks/LazyLoadingBenchmarks.cs b/bench/Broadside.Benchmarks/LazyLoadingBenchmarks.cs new file mode 100644 index 00000000..c0d596d7 --- /dev/null +++ b/bench/Broadside.Benchmarks/LazyLoadingBenchmarks.cs @@ -0,0 +1,71 @@ +using BenchmarkDotNet.Attributes; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Benchmarks; + +/// +/// Lazy loading through the cross-reference table and the parse-once object cache (ISO 32000-2 §7.5.4, issue #45). +/// is the hot path every reference takes once its object is loaded: a lock-free cache lookup that must +/// allocate nothing (Allocated = -). The open-and-resolve benchmarks are baselines: loading allocates the objects. +/// +[MemoryDiagnoser] +public class LazyLoadingBenchmarks +{ + private string _path = ""; + private byte[] _bytes = []; + private PdfDocument? _document; + private CosReference[] _references = []; + + /// A file of plain objects with an inherited page tree, and one whose objects sit in an object stream. + [Params("page-tree-inherited.pdf", "object-stream.pdf")] + public string File { get; set; } = ""; + + [GlobalSetup] + public void Setup() + { + _path = Path.Combine(CorpusLocator.CorpusDirectory, File); + _bytes = System.IO.File.ReadAllBytes(_path); + _document = PdfDocument.Open(_bytes); + long size = ((CosInteger)_document.Trailer[new CosName("Size")]).Value; + _references = [.. Enumerable.Range(1, (int)size - 1).Select(number => new CosReference(number, 0))]; + _ = ResolveAll(_document); + } + + [GlobalCleanup] + public void Cleanup() => _document?.Dispose(); + + /// Resolves every object of a document that has loaded them all: cache hits only. + [Benchmark] + public int ResolveCached() => ResolveAll(_document!); + + /// Opens the file from memory and resolves every object once: one parse each. + [Benchmark] + public int OpenFromBytesAndResolveAll() + { + using PdfDocument document = PdfDocument.Open(_bytes); + return ResolveAll(document); + } + + /// Opens the file by path (memory-mapped) and resolves every object once. + [Benchmark] + public int OpenFromPathAndResolveAll() + { + using PdfDocument document = PdfDocument.Open(_path); + return ResolveAll(document); + } + + private int ResolveAll(PdfDocument document) + { + int found = 0; + foreach (CosReference reference in _references) + { + if (document.Resolve(reference) is not CosNull) + { + found++; + } + } + + return found; + } +} diff --git a/src/Broadside/Broadside.csproj b/src/Broadside/Broadside.csproj index 1c017167..a10d20e5 100644 --- a/src/Broadside/Broadside.csproj +++ b/src/Broadside/Broadside.csproj @@ -4,6 +4,11 @@ The core of Broadside, a fully managed .NET implementation of ISO 32000-2: the COS object layer, the document model, stream filters, font program parsers, image codecs, the content interpreter, the display list and backend contract, text extraction, the layout tree, logical structure, forms, annotations, security handlers, signatures, canvas writing, diagnostics and dependency-injection registration. No native dependencies. + + + true + + diff --git a/src/Broadside/Caching/OnceCache.cs b/src/Broadside/Caching/OnceCache.cs new file mode 100644 index 00000000..0af59e03 --- /dev/null +++ b/src/Broadside/Caching/OnceCache.cs @@ -0,0 +1,283 @@ +using System.Collections.Concurrent; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.ExceptionServices; + +namespace Broadside.Caching; + +/// What a factory produced, and whether the cache keeps it. +/// The value type. +/// The value, returned to the caller (and to the threads that waited for it). +/// +/// when the value depends on how it was reached (it was cut short by a cycle) rather than on the key alone: +/// it is returned but not cached, and the next request computes the value again. +/// +internal readonly record struct Created(TValue Value, bool Keep = true); + +/// +/// The thread-safety rule for every lazily computed cache of a document (CLAUDE.md, spec #33 "Thread safety"): each value is +/// computed at most once per key however many threads ask for it at the same time; threads that ask while it is being computed wait +/// for it; a value whose computation needs itself, on the same thread or through threads waiting on each other, does not deadlock. +/// +/// +/// +/// Why not with : a factory that reaches its own +/// value on the same thread makes throw, and two threads each computing a value the other needs deadlock. A +/// malformed file can do both (a stream whose Length is a stream whose Length is the first stream, an object stream +/// whose N is one of its own members). Here the thread that would close such a cycle gets the cycle fallback instead of +/// waiting, and that fallback is not cached. +/// +/// +/// A cached value is read without a lock. A factory exception is cached and rethrown to every later caller: the same input gives the +/// same outcome (strict mode throws the same diagnostic again rather than recording it twice). +/// +/// +/// The key type. +/// The value type. +internal sealed class OnceCache + where TKey : notnull +{ + private readonly ConcurrentDictionary _entries = new(); + + /// Returns the cached value for , when one has been computed. + /// The key. + /// The value. + /// when cached; a cached exception is rethrown. + public bool TryGet(TKey key, [MaybeNullWhen(false)] out TValue value) + { + if (_entries.TryGetValue(key, out Entry? entry) && entry.IsCompleted) + { + value = entry.Result; + return true; + } + + value = default; + return false; + } + + /// Caches for unless a value is cached or being computed already. + /// The key. + /// The value. + /// The cached value when there is one, else . + public TValue Add(TKey key, TValue value) + { + Entry entry = _entries.GetOrAdd(key, static (_, value) => Entry.Completed(value), value); + return entry.IsCompleted ? entry.Result : value; + } + + /// Returns the value for , computing it with when nobody has. + /// What the factories need, passed through so they can be static. + /// The key. + /// The factories' state. + /// Computes the value; runs at most once per key while its results are kept. + /// + /// The value for a request that would wait on itself: the key is being computed further up this thread's stack, or by a thread + /// that is (directly or through others) waiting for this one. Not cached. + /// + /// The value. + public TValue GetOrCreate(TKey key, TState state, Func> create, Func cycle) + { + while (true) + { + if (_entries.TryGetValue(key, out Entry? entry)) + { + if (entry.IsCompleted) + { + return entry.Result; + } + + if (entry.IsAbandoned) + { + _entries.TryRemove(new KeyValuePair(key, entry)); + continue; + } + + if (entry.Owner == Environment.CurrentManagedThreadId || !WaitGraph.Wait(entry)) + { + return cycle(key, state); + } + + continue; + } + + var mine = new Entry(); + if (!_entries.TryAdd(key, mine)) + { + continue; + } + + Created created; + try + { + created = create(key, state); + } + catch (Exception exception) + { + mine.Fail(ExceptionDispatchInfo.Capture(exception)); + throw; + } + + if (created.Keep) + { + mine.Complete(created.Value); + } + else + { + _entries.TryRemove(new KeyValuePair(key, mine)); + mine.Abandon(); + } + + return created.Value; + } + } + + /// One key's computation: running on its owner thread, then completed, failed or abandoned. + private sealed class Entry : OnceEntry + { + private TValue? _value; + private ExceptionDispatchInfo? _error; + + /// Gets the value of a completed entry, or rethrows the exception of a failed one. + public TValue Result + { + get + { + _error?.Throw(); + return _value!; + } + } + + public static Entry Completed(TValue value) + { + var entry = new Entry { _value = value }; + entry.Finish(OnceEntryState.Completed); + return entry; + } + + public void Complete(TValue value) + { + _value = value; + Finish(OnceEntryState.Completed); + } + + public void Fail(ExceptionDispatchInfo error) + { + _error = error; + Finish(OnceEntryState.Completed); + } + + public void Abandon() => Finish(OnceEntryState.Abandoned); + } +} + +/// The state of a . +internal enum OnceEntryState +{ + /// The owner thread is computing the value. + Running, + + /// The value (or the exception) is available. + Completed, + + /// The owner computed a value it does not keep; ask again. + Abandoned, +} + +/// The part of a cache entry the process-wide wait graph sees: its owner and whether it is still running. +internal abstract class OnceEntry +{ + private int _state; + private object? _gate; + + /// Gets the managed thread id of the thread computing the value. + public int Owner { get; } = Environment.CurrentManagedThreadId; + + /// Gets a value indicating whether the owner is still computing the value. + public bool IsRunning => State == OnceEntryState.Running; + + /// Gets a value indicating whether the value or exception is available. + public bool IsCompleted => State == OnceEntryState.Completed; + + /// Gets a value indicating whether the owner dropped its value. + public bool IsAbandoned => State == OnceEntryState.Abandoned; + + private OnceEntryState State => (OnceEntryState)Volatile.Read(ref _state); + + /// Publishes the final state and wakes the waiting threads, if any. + /// The final state. + protected void Finish(OnceEntryState state) + { + // A full fence between the state write and the gate read pairs with the one in WaitUntilFinished between the gate write and + // the state read: either the waiter sees the final state, or the owner sees the waiter's gate and pulses it. + Interlocked.Exchange(ref _state, (int)state); + if (Volatile.Read(ref _gate) is { } gate) + { + lock (gate) + { + Monitor.PulseAll(gate); + } + } + } + + /// Blocks until the owner finishes. The wait gate is created by the first waiter: an uncontended entry has none. + internal void WaitUntilFinished() + { + object gate = Volatile.Read(ref _gate) ?? Interlocked.CompareExchange(ref _gate, new object(), null) ?? _gate!; + lock (gate) + { + while (IsRunning) + { + Monitor.Wait(gate); + } + } + } +} + +/// +/// Which thread waits for which running entry, across every of the process, so a wait that +/// would close a cycle (thread A waits for B's entry while B waits for A's) is refused instead of deadlocking. Touched only when a +/// thread finds a value still being computed by another thread. +/// +internal static class WaitGraph +{ + private static readonly Lock Gate = new(); + private static readonly Dictionary WaitingOn = []; + + /// Waits until finishes, unless waiting would deadlock. + /// An entry another thread owns. + /// when waiting would close a cycle; the caller takes its cycle fallback. + public static bool Wait(OnceEntry entry) + { + int self = Environment.CurrentManagedThreadId; + lock (Gate) + { + // Follow owner -> the entry that owner waits for -> its owner ...; reaching this thread means a cycle. No other cycle can + // exist in the graph: the thread that would have closed it was refused. + OnceEntry? next = entry; + while (next is { IsRunning: true }) + { + if (next.Owner == self) + { + return false; + } + + WaitingOn.TryGetValue(next.Owner, out next); + } + + WaitingOn[self] = entry; + } + + try + { + entry.WaitUntilFinished(); + } + finally + { + lock (Gate) + { + WaitingOn.Remove(self); + } + } + + return true; + } +} diff --git a/src/Broadside/Diagnostics/ObjectLog.cs b/src/Broadside/Diagnostics/ObjectLog.cs new file mode 100644 index 00000000..3c41ca5d --- /dev/null +++ b/src/Broadside/Diagnostics/ObjectLog.cs @@ -0,0 +1,35 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Broadside.Diagnostics; + +/// +/// Traces lazy loading through the logging abstractions: each object parsed (event 2, ObjectParsed) and each object stream +/// decoded (event 3, ObjectStreamDecoded), at , under the same category as diagnostics. With +/// lazy loading (ISO 32000-2 §7.5.4) and the parse-once cache these show what a read actually touched. Source-generated: nothing is +/// formatted unless trace logging is enabled, and nothing at all runs when the engine has no logger factory. +/// +internal static partial class ObjectLog +{ + /// Returns the logger an engine hands its documents' loaders, or when nothing logs. + /// The logger factory, or . + /// The logger, created once per engine. + public static ILogger? CreateLogger(ILoggerFactory? loggerFactory) => + loggerFactory is null or NullLoggerFactory ? null : loggerFactory.CreateLogger(DiagnosticLog.Category); + + /// Logs that an indirect object was parsed: from the file body at , or from an object stream. + /// The logger. + /// The object number. + /// The generation number. + /// The absolute offset of N G obj, for an object in the file body. + /// The object number of the object stream holding it, for a compressed object. + [LoggerMessage(EventId = 2, EventName = "ObjectParsed", Level = LogLevel.Trace, Message = "Parsed object {ObjectNumber} {Generation} at offset {Offset} in object stream {ObjectStream}")] + public static partial void ObjectParsed(ILogger logger, int objectNumber, int generation, long? offset, int? objectStream); + + /// Logs that an object stream was decoded and its header read. + /// The logger. + /// The object stream's object number. + /// How many members its header lists. + [LoggerMessage(EventId = 3, EventName = "ObjectStreamDecoded", Level = LogLevel.Trace, Message = "Decoded object stream {ObjectNumber} with {Members} objects")] + public static partial void ObjectStreamDecoded(ILogger logger, int objectNumber, int members); +} diff --git a/src/Broadside/EngineConfiguration.cs b/src/Broadside/EngineConfiguration.cs index a7c87a6c..9ef361d1 100644 --- a/src/Broadside/EngineConfiguration.cs +++ b/src/Broadside/EngineConfiguration.cs @@ -24,12 +24,21 @@ internal sealed class EngineConfiguration /// public Action? DiagnosticObserver { get; private init; } + /// + /// Gets the logger lazy loading is traced through (issue #45: ObjectParsed, ObjectStreamDecoded), or + /// when nothing logs. + /// + public ILogger? Logger { get; private init; } + /// Gets the filters by name: the managed defaults with the options' registrations applied (issue #38). public FilterRegistry Filters { get; private init; } = FilterRegistry.Create([]); /// Gets the most bytes one stream may decode to (issue #38). public long MaxDecodedStreamLength { get; private init; } = PdfOptions.DefaultMaxDecodedStreamLength; + /// Gets how many bytes of a non-seekable stream are copied into memory before a temporary file is used (issue #45). + public long StreamBufferLimit { get; private init; } = PdfOptions.DefaultStreamBufferLimit; + /// Copies the current values of . /// The options. /// The container's logger factory, used when the options set none. @@ -37,7 +46,9 @@ internal sealed class EngineConfiguration public static EngineConfiguration From(PdfOptions options, ILoggerFactory? hostLoggerFactory = null) => new(options.ReadingMode) { DiagnosticObserver = DiagnosticLog.CreateObserver(options.LoggerFactory ?? hostLoggerFactory), + Logger = ObjectLog.CreateLogger(options.LoggerFactory ?? hostLoggerFactory), Filters = FilterRegistry.Create(options.Filters), MaxDecodedStreamLength = options.MaxDecodedStreamLength, + StreamBufferLimit = options.StreamBufferLimit, }; } diff --git a/src/Broadside/Filters/StreamDecoder.cs b/src/Broadside/Filters/StreamDecoder.cs index 41f5d281..abd17611 100644 --- a/src/Broadside/Filters/StreamDecoder.cs +++ b/src/Broadside/Filters/StreamDecoder.cs @@ -157,7 +157,7 @@ public void Decode(CosStream stream, IBufferWriter output, int depth = 0) private static long InitialCapacity(CosStream stream) => stream.Dictionary.TryGetValue(FilterNames.DL, out CosObject? hint) && hint is CosInteger { Value: > 0 } length ? length.Value - : (long)stream.EncodedData.Length * 4; + : (long)stream.EncodedLength * 4; /// Runs one filter; returns when the chain cannot continue past it. private bool RunStage(FilterStage stage, int index, ReadOnlyMemory data, PooledBufferWriter output, FilterContext context) diff --git a/src/Broadside/IO/MappedFileSource.cs b/src/Broadside/IO/MappedFileSource.cs new file mode 100644 index 00000000..4a5e22a7 --- /dev/null +++ b/src/Broadside/IO/MappedFileSource.cs @@ -0,0 +1,163 @@ +using System.Buffers; +using System.IO.MemoryMappedFiles; + +namespace Broadside.IO; + +/// +/// A file mapped into memory: windows are views of the mapping, so parsing an object reads only the pages it touches and copies +/// nothing, whatever the size of the file. +/// +/// +/// +/// ISO 32000-2 §7.5.4: random access through the cross-reference table. The whole file is mapped once, read-only. A span cannot +/// exceed bytes, so the mapping is handed out through overlapping segments that start every 1 GiB and +/// reach up to 2 GiB: a window from any offset has at least 1 GiB (or the rest of the file) in it. +/// +/// +/// Reads copy out of the mapping while holding a reference on it, so disposing the source while another thread reads makes that +/// read throw or complete, never fault. Windows are not protected that way: disposing a +/// document while other threads still parse it is the caller's error. The file must not be truncated or rewritten while it is open. +/// +/// +internal sealed unsafe class MappedFileSource : PdfSource +{ + private const long SegmentStride = 1L << 30; + + private readonly MemoryMappedFile _file; + private readonly MemoryMappedViewAccessor _view; + private readonly FileStream? _ownedFile; + private readonly byte* _start; + private readonly long _length; + private readonly Segment?[] _segments; + + private MappedFileSource(MemoryMappedFile file, MemoryMappedViewAccessor view, FileStream? ownedFile, long start, long length) + { + _file = file; + _view = view; + _ownedFile = ownedFile; + _length = length; + byte* pointer = null; + view.SafeMemoryMappedViewHandle.AcquirePointer(ref pointer); + _start = pointer + view.PointerOffset + start; + _segments = new Segment?[(int)((length + SegmentStride - 1) / SegmentStride)]; + } + + /// + public override long Length => _length; + + /// Maps from its current position to its end. + /// The file; it must be readable. + /// Whether the source disposes the file. + /// The source, or when the platform or the file cannot be mapped. + public static PdfSource? TryCreate(FileStream file, bool ownsFile) + { + if (OperatingSystem.IsBrowser() || OperatingSystem.IsWasi()) + { + return null; + } + + long start = file.Position; + long length = file.Length - start; + if (length <= 0) + { + if (ownsFile) + { + file.Dispose(); + } + + return FromMemory(ReadOnlyMemory.Empty); + } + + MemoryMappedFile? mapping = null; + try + { + mapping = MemoryMappedFile.CreateFromFile(file, mapName: null, capacity: 0, MemoryMappedFileAccess.Read, HandleInheritability.None, leaveOpen: true); + MemoryMappedViewAccessor view = mapping.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read); + return new MappedFileSource(mapping, view, ownsFile ? file : null, start, length); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or NotSupportedException or PlatformNotSupportedException) + { + mapping?.Dispose(); + return null; + } + } + + /// + public override int Read(long offset, Span destination) + { + ThrowIfDisposed(); + if (offset < 0 || offset >= _length) + { + return 0; + } + + int count = (int)Math.Min(destination.Length, _length - offset); + bool added = false; + try + { + // Holds the mapping open across the copy: Dispose unmaps only after the last reader releases it. + _view.SafeMemoryMappedViewHandle.DangerousAddRef(ref added); + new ReadOnlySpan(_start + offset, count).CopyTo(destination); + } + finally + { + if (added) + { + _view.SafeMemoryMappedViewHandle.DangerousRelease(); + } + } + + return count; + } + + /// + public override ReadOnlyMemory GetWindow(long offset, int minimumLength) + { + ThrowIfDisposed(); + if (offset < 0 || offset >= _length) + { + return ReadOnlyMemory.Empty; + } + + int index = (int)(offset / SegmentStride); + Segment segment = Volatile.Read(ref _segments[index]) ?? CreateSegment(index); + return segment.Memory[(int)(offset - (index * SegmentStride))..]; + } + + /// + protected override void Dispose(bool disposing) + { + if (disposing) + { + _view.SafeMemoryMappedViewHandle.ReleasePointer(); + _view.Dispose(); + _file.Dispose(); + _ownedFile?.Dispose(); + } + + base.Dispose(disposing); + } + + private Segment CreateSegment(int index) + { + long start = index * SegmentStride; + var segment = new Segment(_start + start, (int)Math.Min(int.MaxValue, _length - start)); + return Interlocked.CompareExchange(ref _segments[index], segment, null) ?? segment; + } + + /// Up to 2 GiB of the mapping as . + private sealed class Segment(byte* pointer, int length) : MemoryManager + { + public override Span GetSpan() => new(pointer, length); + + public override MemoryHandle Pin(int elementIndex = 0) => new(pointer + elementIndex); + + public override void Unpin() + { + } + + protected override void Dispose(bool disposing) + { + } + } +} diff --git a/src/Broadside/IO/PdfSource.cs b/src/Broadside/IO/PdfSource.cs index 8291a900..c6fbb60c 100644 --- a/src/Broadside/IO/PdfSource.cs +++ b/src/Broadside/IO/PdfSource.cs @@ -1,19 +1,33 @@ +using System.IO.MemoryMappedFiles; +using Broadside.Objects; + namespace Broadside.IO; /// The bytes of one PDF file, read by position. /// /// -/// ISO 32000-2 §7.5.1: a file is read at random, through its cross-reference table, never serially. A source therefore has no -/// cursor: every read names its offset, so concurrent readers never interfere. Offsets are everywhere. +/// ISO 32000-2 §7.5.1: a file is read at random, through its cross-reference table, never serially; §7.5.4: the table "permits +/// random access to indirect objects ... so that the entire PDF file need not be read". A source therefore has no cursor: every read +/// names its offset, so concurrent readers never interfere. Offsets are everywhere. /// /// -/// Issue #37 ships the in-memory source only; paths and streams are copied into memory. Issue #45 adds file, memory-mapped and -/// windowed stream sources behind this same contract. +/// Implementations: memory (the caller's bytes, never copied), a memory-mapped file (a path, or a ), a +/// seekable stream read in place under a lock, and a non-seekable stream copied when the document is opened (into memory, or into a +/// temporary file past the engine's buffer limit). Every implementation is safe for concurrent reads; none survives +/// , after which reads throw . /// /// internal abstract class PdfSource : IDisposable { - private bool _disposed; + /// + /// The window asks a windowed source for: enough for any cross-reference section, trailer or + /// object stream header a structure reader parses in one piece. + /// + public const int StructureWindow = 4 << 20; + + private const int CopyBufferLength = 81920; + + private volatile bool _disposed; /// Gets the length of the file in bytes. public abstract long Length { get; } @@ -23,19 +37,118 @@ internal abstract class PdfSource : IDisposable /// The source. public static PdfSource FromMemory(ReadOnlyMemory bytes) => new MemorySource(bytes); - /// Creates a source over the file at . + /// Creates a source over the file at , memory-mapped: nothing is read until it is used. /// The file path. /// The source. - public static PdfSource FromFile(string path) => new MemorySource(File.ReadAllBytes(path)); + public static PdfSource FromFile(string path) + { + FileStream? file = new(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1, FileOptions.RandomAccess); + try + { + PdfSource source = FromOwnedFile(file); + file = null; + return source; + } + finally + { + file?.Dispose(); + } + } - /// Creates a source over the bytes of from its current position to its end. - /// The stream; read once, not disposed. + /// + /// Creates a source over the bytes of from its current position to its end. A seekable stream is read + /// in place, a memory-mapped; a non-seekable one is copied now. + /// + /// The stream; not disposed, and it must stay open and unchanged while the source is in use. + /// How many bytes of a non-seekable stream to copy into memory before using a temporary file. /// The source. - public static PdfSource FromStream(Stream stream) + public static PdfSource FromStream(Stream stream, long bufferLimit) { - using var copy = new MemoryStream(); - stream.CopyTo(copy); - return new MemorySource(copy.ToArray()); + if (stream.CanSeek) + { + return FromSeekableStream(stream); + } + + bufferLimit = Math.Min(bufferLimit, Array.MaxLength); + byte[] buffer = new byte[CopyBufferLength]; + var memory = new MemoryStream(); + int read; + while ((read = stream.Read(buffer)) > 0) + { + if (memory.Length + read > bufferLimit) + { + FileStream? file = CreateTemporaryFile(asynchronous: false); + try + { + memory.WriteTo(file); + file.Write(buffer, 0, read); + stream.CopyTo(file); + file.Flush(); + file.Position = 0; + PdfSource source = FromOwnedFile(file); + file = null; + return source; + } + finally + { + file?.Dispose(); + } + } + + memory.Write(buffer, 0, read); + } + + return new MemorySource(memory.GetBuffer().AsMemory(0, (int)memory.Length)); + } + + /// As , copying a non-seekable stream asynchronously; a seekable one is read in place later. + /// The stream; not disposed. + /// How many bytes of a non-seekable stream to copy into memory before using a temporary file. + /// Cancels the copy. + /// The source. + public static async Task FromStreamAsync(Stream stream, long bufferLimit, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + if (stream.CanSeek) + { + return FromSeekableStream(stream); + } + + bufferLimit = Math.Min(bufferLimit, Array.MaxLength); + byte[] buffer = new byte[CopyBufferLength]; + var memory = new MemoryStream(); + int read; + while ((read = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0) + { + if (memory.Length + read > bufferLimit) + { +#pragma warning disable CA2000 // Disposed in the finally below unless the source took ownership; the analyzer cannot follow await. + FileStream? file = CreateTemporaryFile(asynchronous: true); +#pragma warning restore CA2000 + try + { + await file.WriteAsync(memory.GetBuffer().AsMemory(0, (int)memory.Length), cancellationToken).ConfigureAwait(false); + await file.WriteAsync(buffer.AsMemory(0, read), cancellationToken).ConfigureAwait(false); + await stream.CopyToAsync(file, cancellationToken).ConfigureAwait(false); + await file.FlushAsync(cancellationToken).ConfigureAwait(false); + file.Position = 0; + PdfSource source = FromOwnedFile(file); + file = null; + return source; + } + finally + { + if (file is not null) + { + await file.DisposeAsync().ConfigureAwait(false); + } + } + } + + await memory.WriteAsync(buffer.AsMemory(0, read), cancellationToken).ConfigureAwait(false); + } + + return new MemorySource(memory.GetBuffer().AsMemory(0, (int)memory.Length)); } /// Copies the bytes at into . @@ -46,12 +159,29 @@ public static PdfSource FromStream(Stream stream) /// /// Returns a contiguous view of the bytes from on, for the span-based parsers. The view ends at the end - /// of the file or, for a source that cannot map the whole file, at the end of the source's window; parsers treat its end as the - /// end of input. + /// of the file or, for a source that reads in windows, after at least bytes; parsers treat its end as + /// the end of input. /// /// The offset of the first byte of the view. /// The view, empty when is at or past the end of the file. - public abstract ReadOnlyMemory GetWindow(long offset); + public ReadOnlyMemory GetWindow(long offset) => GetWindow(offset, StructureWindow); + + /// + /// Returns a contiguous view of the bytes from on, at least long unless + /// the file ends sooner. A source that holds or maps the whole file returns the rest of it (up to 1 GiB or more) whatever the + /// minimum; a source that reads in windows reads about bytes. + /// + /// The offset of the first byte of the view. + /// The least number of bytes the caller needs, when the file has them. + /// The view, empty when is at or past the end of the file. + public abstract ReadOnlyMemory GetWindow(long offset, int minimumLength); + + /// Creates the stream object for data at , without copying the data out of the source. + /// The stream dictionary. + /// The absolute offset of the first data byte. + /// The number of data bytes. + /// The stream, whose data is read from this source on each access. + public virtual CosStream CreateStream(CosDictionary dictionary, long offset, int length) => new(dictionary, new SourceData(this, offset, length)); /// public void Dispose() @@ -67,6 +197,40 @@ public void Dispose() /// Throws once the source is disposed. protected void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this); + /// A file the source owns: mapped where the platform allows it, else read in place. + private static PdfSource FromOwnedFile(FileStream file) => MappedFileSource.TryCreate(file, ownsFile: true) ?? new StreamSource(file, ownsStream: true); + + private static PdfSource FromSeekableStream(Stream stream) => + (stream is FileStream { CanRead: true } file ? MappedFileSource.TryCreate(file, ownsFile: false) : null) ?? new StreamSource(stream, ownsStream: false); + + /// A temporary file deleted when the source closes it. + private static FileStream CreateTemporaryFile(bool asynchronous) => new( + Path.Combine(Path.GetTempPath(), "broadside-" + Path.GetRandomFileName()), + FileMode.CreateNew, + FileAccess.ReadWrite, + FileShare.None, + CopyBufferLength, + FileOptions.DeleteOnClose | (asynchronous ? FileOptions.Asynchronous : FileOptions.None)); + + /// Stream data read from the source on each access, so a cached stream object holds no data. + private sealed class SourceData(PdfSource source, long offset, int length) : DeferredStreamData + { + public override int Length => length; + + public override ReadOnlyMemory Read() + { + if (length == 0) + { + return ReadOnlyMemory.Empty; + } + + byte[] data = GC.AllocateUninitializedArray(length); + int read = source.Read(offset, data); + return data.AsMemory(0, read); + } + } + + /// The caller's bytes: windows and stream data are slices of them. private sealed class MemorySource(ReadOnlyMemory bytes) : PdfSource { public override long Length => bytes.Length; @@ -85,10 +249,13 @@ public override int Read(long offset, Span destination) return count; } - public override ReadOnlyMemory GetWindow(long offset) + public override ReadOnlyMemory GetWindow(long offset, int minimumLength) { ThrowIfDisposed(); return offset < 0 || offset >= bytes.Length ? ReadOnlyMemory.Empty : bytes[(int)offset..]; } + + // The caller keeps the bytes alive and unchanged, so a slice is as good as a copy and costs nothing. + public override CosStream CreateStream(CosDictionary dictionary, long offset, int length) => new(dictionary, bytes.Slice((int)offset, length)); } } diff --git a/src/Broadside/IO/StreamSource.cs b/src/Broadside/IO/StreamSource.cs new file mode 100644 index 00000000..11d21586 --- /dev/null +++ b/src/Broadside/IO/StreamSource.cs @@ -0,0 +1,96 @@ +namespace Broadside.IO; + +/// +/// A seekable stream read in place: each read seeks and reads under a lock, since a has one shared position and +/// is not safe for concurrent use. Windows are copies of the bytes read. +/// +/// +/// ISO 32000-2 §7.5.4: random access through the cross-reference table, so opening a large file through a stream reads its +/// structure and the objects used, not the whole stream. The stream's length is read once, when the source is created; the stream +/// must stay open and unchanged while the source is in use. +/// +internal sealed class StreamSource : PdfSource +{ + private readonly Lock _gate = new(); + private readonly Stream _stream; + private readonly bool _ownsStream; + private readonly long _start; + private readonly long _length; + + /// Initializes a new instance of the class over from its current position. + /// The stream; seekable and readable. + /// Whether the source disposes the stream. + public StreamSource(Stream stream, bool ownsStream) + { + _stream = stream; + _ownsStream = ownsStream; + _start = stream.Position; + _length = Math.Max(0, stream.Length - _start); + } + + /// + public override long Length => _length; + + /// + public override int Read(long offset, Span destination) + { + ThrowIfDisposed(); + if (offset < 0 || offset >= _length) + { + return 0; + } + + destination = destination[..(int)Math.Min(destination.Length, _length - offset)]; + lock (_gate) + { + ThrowIfDisposed(); + _stream.Position = _start + offset; + int total = 0; + while (total < destination.Length) + { + int read = _stream.Read(destination[total..]); + if (read == 0) + { + break; + } + + total += read; + } + + return total; + } + } + + /// + public override ReadOnlyMemory GetWindow(long offset, int minimumLength) + { + ThrowIfDisposed(); + if (offset < 0 || offset >= _length) + { + return ReadOnlyMemory.Empty; + } + + byte[] window = GC.AllocateUninitializedArray((int)Math.Min(Math.Max(minimumLength, 1), _length - offset)); + return window.AsMemory(0, Read(offset, window)); + } + + /// + protected override void Dispose(bool disposing) + { + if (disposing) + { + lock (_gate) + { + base.Dispose(disposing); + if (_ownsStream) + { + _stream.Dispose(); + } + } + + return; + } + + base.Dispose(disposing); + } +} diff --git a/src/Broadside/Objects/CosParser.cs b/src/Broadside/Objects/CosParser.cs index abbef6b5..f62569ea 100644 --- a/src/Broadside/Objects/CosParser.cs +++ b/src/Broadside/Objects/CosParser.cs @@ -25,6 +25,7 @@ internal ref struct CosParser private CosLexer _lexer; private readonly CosRepairLog? _repairs; private readonly IStreamLengthResolver? _lengthResolver; + private readonly IStreamDataFactory? _dataFactory; /// Initializes a new instance of the struct. /// The bytes to parse. @@ -34,11 +35,20 @@ internal ref struct CosParser /// Resolves a stream's Length entry when it is an indirect reference (§7.3.8.2), or when there is no /// file to resolve it in; the data then ends at endstream without a repair. /// - public CosParser(ReadOnlySpan source, CosRepairLog? repairs, int position = 0, IStreamLengthResolver? lengthResolver = null) + /// + /// Creates stream objects over data located in (issue #45), or to copy the data. + /// + public CosParser( + ReadOnlySpan source, + CosRepairLog? repairs, + int position = 0, + IStreamLengthResolver? lengthResolver = null, + IStreamDataFactory? dataFactory = null) { _lexer = new CosLexer(source, position); _repairs = repairs; _lengthResolver = lengthResolver; + _dataFactory = dataFactory; } /// Gets or sets the offset of the next byte to read. @@ -491,7 +501,7 @@ private CosStream ParseStreamData(CosDictionary dictionary, CosToken keyword) if (declared >= 0 && declared <= source.Length - dataStart && TryMatchEndstream(source, dataStart + (int)declared, out int afterEndstream)) { _lexer.Position = afterEndstream; - return new CosStream(dictionary, source.Slice(dataStart, (int)declared).ToArray()); + return CreateStream(dictionary, source, dataStart, (int)declared); } int found = source[dataStart..].IndexOf("endstream"u8); @@ -509,15 +519,19 @@ private CosStream ParseStreamData(CosDictionary dictionary, CosToken keyword) } _lexer.Position = dataStart + found + "endstream"u8.Length; - return new CosStream(dictionary, source[dataStart..dataEnd].ToArray()); + return CreateStream(dictionary, source, dataStart, dataEnd - dataStart); } int end = declared >= 0 && declared <= source.Length - dataStart ? dataStart + (int)declared : source.Length; Report(CosRepairCodes.EndstreamMissing, keyword.Start, "The stream has no endstream keyword."); _lexer.Position = end; - return new CosStream(dictionary, source[dataStart..end].ToArray()); + return CreateStream(dictionary, source, dataStart, end - dataStart); } + /// Creates the stream over its located data: through the factory when there is one, else as a copy. + private readonly CosStream CreateStream(CosDictionary dictionary, ReadOnlySpan source, int start, int length) => + _dataFactory?.CreateStream(dictionary, start, length) ?? new CosStream(dictionary, source.Slice(start, length).ToArray()); + /// /// Skips the end-of-line marker after the stream keyword, which shall be CRLF or LF (§7.3.8.1), and returns where the data /// starts. A CR alone, or spaces before the marker, are repaired. diff --git a/src/Broadside/Objects/CosStream.cs b/src/Broadside/Objects/CosStream.cs index da1a9717..918dc392 100644 --- a/src/Broadside/Objects/CosStream.cs +++ b/src/Broadside/Objects/CosStream.cs @@ -12,6 +12,7 @@ namespace Broadside.Objects; public sealed class CosStream : CosObject { private ReadOnlyMemory _encodedData; + private DeferredStreamData? _deferred; private bool _changed; /// Initializes a new instance of the class from its dictionary and data. @@ -24,21 +25,37 @@ public CosStream(CosDictionary dictionary, ReadOnlyMemory encodedData) _encodedData = encodedData; } + /// Initializes a new instance of the class whose data stays in the file until read. + /// The stream dictionary. + /// Where the data is; read on each access to . + internal CosStream(CosDictionary dictionary, DeferredStreamData encodedData) + { + Dictionary = dictionary; + _deferred = encodedData; + } + /// Gets the stream dictionary. public CosDictionary Dictionary { get; } /// Gets or sets the stream's data as stored in the file, before any filter is decoded. Setting marks the stream dirty. - /// ISO 32000-2 §7.3.8.1. Setting the data does not change the dictionary's Filter entry; keep the two consistent. + /// + /// ISO 32000-2 §7.3.8.1. Setting the data does not change the dictionary's Filter entry; keep the two consistent. A stream + /// of a document opened from a file or a stream keeps its data in the file and reads it on each get, so read it once per use. + /// public ReadOnlyMemory EncodedData { - get => _encodedData; + get => _deferred is { } deferred ? deferred.Read() : _encodedData; set { _encodedData = value; + _deferred = null; _changed = true; } } + /// Gets the length of without reading it. + internal int EncodedLength => _deferred is { } deferred ? deferred.Length : _encodedData.Length; + /// public override bool IsDirty => _changed || Dictionary.IsDirty; } diff --git a/src/Broadside/Objects/CosWriter.cs b/src/Broadside/Objects/CosWriter.cs index 4483e731..4b309a47 100644 --- a/src/Broadside/Objects/CosWriter.cs +++ b/src/Broadside/Objects/CosWriter.cs @@ -48,9 +48,10 @@ public static void Write(CosObject value, IBufferWriter writer) WriteDictionary(dictionary, writer, streamLength: -1); break; case CosStream stream: - WriteDictionary(stream.Dictionary, writer, stream.EncodedData.Length); + ReadOnlyMemory data = stream.EncodedData; + WriteDictionary(stream.Dictionary, writer, data.Length); writer.Write("\nstream\n"u8); - writer.Write(stream.EncodedData.Span); + writer.Write(data.Span); writer.Write("\nendstream"u8); break; case CosReference reference: diff --git a/src/Broadside/Objects/IStreamDataFactory.cs b/src/Broadside/Objects/IStreamDataFactory.cs new file mode 100644 index 00000000..78c06b0a --- /dev/null +++ b/src/Broadside/Objects/IStreamDataFactory.cs @@ -0,0 +1,32 @@ +namespace Broadside.Objects; + +/// Creates the stream object for data the parser has located, so a file reader can keep the data in its source. +/// +/// ISO 32000-2 §7.3.8.1 and §7.5.4: a stream's data is located in the file, not part of the object's syntax tree. Without a factory +/// the parser copies the data into the stream; a file reader instead refers to the bytes where they are (a slice of the caller's +/// memory, or a range read from the file on demand), so a cached stream object never holds its data (issue #45). +/// +internal interface IStreamDataFactory +{ + /// Creates a stream over the data at in the parser's input. + /// The stream dictionary. + /// The offset of the first data byte in the parser's input. + /// The number of data bytes. + /// The stream. + CosStream CreateStream(CosDictionary dictionary, int start, int length); +} + +/// Stream data that stays in its source and is read on each access. +/// +/// Lets a cached hold only its dictionary and the extent of its data, so a large file's streams cost no memory +/// until they are read, and none after. Reading is safe from several threads at once. +/// +internal abstract class DeferredStreamData +{ + /// Gets the number of bytes. + public abstract int Length { get; } + + /// Reads the bytes. + /// The data; each call may return a new copy. + public abstract ReadOnlyMemory Read(); +} diff --git a/src/Broadside/Parsing/DiagnosticCodes.cs b/src/Broadside/Parsing/DiagnosticCodes.cs index bd32f737..a8b696d9 100644 --- a/src/Broadside/Parsing/DiagnosticCodes.cs +++ b/src/Broadside/Parsing/DiagnosticCodes.cs @@ -55,6 +55,9 @@ internal static class DiagnosticCodes public const string MissingEndobj = nameof(MissingEndobj); public const string ReferenceChainTooDeep = nameof(ReferenceChainTooDeep); + // Lazy loading (§7.5.4): an object whose loading needs the object itself. + public const string ObjectReferenceCycle = nameof(ObjectReferenceCycle); + // Stream filters (§7.3.8.2 Table 5, §7.4). public const string FilterInvalid = nameof(FilterInvalid); public const string FilterUnsupported = nameof(FilterUnsupported); diff --git a/src/Broadside/Parsing/ObjectLoader.cs b/src/Broadside/Parsing/ObjectLoader.cs index 1fd3f24b..0f29202e 100644 --- a/src/Broadside/Parsing/ObjectLoader.cs +++ b/src/Broadside/Parsing/ObjectLoader.cs @@ -1,9 +1,10 @@ -using System.Collections.Concurrent; using System.Globalization; +using Broadside.Caching; using Broadside.Diagnostics; using Broadside.Filters; using Broadside.IO; using Broadside.Objects; +using Microsoft.Extensions.Logging; namespace Broadside.Parsing; @@ -34,18 +35,20 @@ internal sealed class ObjectLoader /// How many loads may nest (an indirect Length loads while its stream loads) before the inner one reads null. public const int MaxDepth = 32; + /// The first window a windowed source is asked for per object: most objects are smaller. + private const int InitialObjectWindow = 4096; + + /// The largest window an object is parsed in; an object that does not end within 1 GiB is read as repaired. + private const int MaxObjectWindow = 1 << 30; + private static readonly CosName ObjStm = new("ObjStm"); private static readonly CosName N = new("N"); private static readonly CosName First = new("First"); - /// The object streams this thread is decoding, across loaders, so a container that needs its own member ends. - [ThreadStatic] - private static List<(ObjectLoader Loader, int Number)>? _decoding; - private readonly PdfSource _source; private readonly DiagnosticSink _diagnostics; private readonly StreamDecoder _streams; - private ConcurrentDictionary? _objectStreams; + private OnceCache? _objectStreams; /// Initializes a new instance of the class. /// The file. @@ -79,6 +82,9 @@ public ObjectLoader( /// Gets the hooks. public ObjectLoaderHooks Hooks { get; } + /// Gets the logger loads are traced through (), or . + public ILogger? Logger { get; init; } + /// Returns , or the object it refers to when it is an indirect reference. /// A direct object, a reference, or for an absent entry. /// The direct object; for an absent entry or a reference to nothing. @@ -105,7 +111,13 @@ public CosObject Load(CosReference reference, int depth) return cached; } - if (!CrossReference.TryGetEntry(reference.ObjectNumber, out XrefEntry entry)) + if (!CrossReference.TryGetEntry(reference.ObjectNumber, out XrefEntry entry) + || entry.Kind switch + { + XrefEntryKind.InUse => entry.Generation != reference.Generation, + XrefEntryKind.Compressed => reference.Generation != 0, + _ => true, + }) { return CosNull.Instance; } @@ -120,44 +132,79 @@ public CosObject Load(CosReference reference, int depth) return CosNull.Instance; } - CosObject loaded; - ObjectLoadContext context; - switch (entry.Kind) + // Hook 3 runs the load at most once per object, however many threads ask (issue #45). + return Hooks.Cache.GetOrLoad( + reference, + (Loader: this, Entry: entry, Depth: depth), + static (reference, state) => state.Loader.LoadUncached(reference, state.Entry, state.Depth), + static (reference, state) => state.Loader.ReportCycle(reference, state.Entry)); + } + + /// Locates and parses an object nobody has loaded yet, then runs hook 2. + private Created LoadUncached(CosReference reference, XrefEntry entry, int depth) + { + if (entry.Kind == XrefEntryKind.Compressed) { - case XrefEntryKind.InUse when entry.Generation == reference.Generation: - context = new ObjectLoadContext(reference, Header.Offset + entry.Offset, ObjectOrigin.FileBody, depth); - loaded = ParseIndirectObject(context); - break; - case XrefEntryKind.Compressed when reference.Generation == 0: - return LoadCompressed(reference, entry, depth); - default: - return CosNull.Instance; + return LoadCompressed(reference, entry, depth); } - loaded = Hooks.Decryptor.Decrypt(loaded, context); - return Hooks.Cache.Publish(reference, loaded); + var context = new ObjectLoadContext(reference, Header.Offset + entry.Offset, ObjectOrigin.FileBody, depth); + CosObject loaded = ParseIndirectObject(context); + if (Logger is { } logger) + { + ObjectLog.ObjectParsed(logger, reference.ObjectNumber, reference.Generation, context.Offset, objectStream: null); + } + + return new(Hooks.Decryptor.Decrypt(loaded, context)); } - /// Loads an object stored in an object stream (§7.5.7): container, then the member at the entry's index. - private CosObject LoadCompressed(CosReference reference, XrefEntry entry, int depth) + /// Reads as null an object whose loading needs the object itself, which the cache detected; the null is not cached. + private CosNull ReportCycle(CosReference reference, XrefEntry entry) { - int containerNumber = (int)entry.Offset; - if (IsDecoding(containerNumber)) + if (entry.Kind == XrefEntryKind.Compressed) { _diagnostics.Report( DiagnosticCodes.ObjectStreamCycle, DiagnosticSeverity.Error, - string.Create(CultureInfo.InvariantCulture, $"Object stream {containerNumber} needs this object, which it holds, to be decoded; read as null."), + string.Create(CultureInfo.InvariantCulture, $"Object stream {entry.Offset} needs this object, which it holds, to be decoded; read as null."), objectReference: reference); - return CosNull.Instance; + } + else + { + _diagnostics.Report( + DiagnosticCodes.ObjectReferenceCycle, + DiagnosticSeverity.Error, + "Loading the object needs the object itself (a stream's Length refers back to it); read as null where it is needed.", + objectReference: reference); + } + + return CosNull.Instance; + } + + /// Loads an object stored in an object stream (§7.5.7): container, then the member at the entry's index. + private Created LoadCompressed(CosReference reference, XrefEntry entry, int depth) + { + int containerNumber = (int)entry.Offset; + ObjectStream? container = ObjectStreams.GetOrCreate( + containerNumber, + (Loader: this, Member: reference, Depth: depth), + static (number, state) => new Created(state.Loader.ReadObjectStream(number, state.Member, state.Depth)), + static (_, _) => null); + if (container is null) + { + // The container is being decoded further up this thread's stack (its N, First, Filter or Length is one of its own + // members) or by a thread waiting for this one. The null depends on how the member was reached: not cached. + ReportCycle(reference, entry); + return new(CosNull.Instance, Keep: false); } - ConcurrentDictionary objectStreams = ObjectStreams; - ObjectStream container = objectStreams.TryGetValue(containerNumber, out ObjectStream? cached) - ? cached - : objectStreams.GetOrAdd(containerNumber, ReadObjectStream(containerNumber, reference, depth)); CosObject loaded = container.Parse(reference, entry.Generation, _diagnostics); - return Hooks.Cache.Publish(reference, loaded); + if (Logger is { } logger) + { + ObjectLog.ObjectParsed(logger, reference.ObjectNumber, reference.Generation, offset: null, containerNumber); + } + + return new(loaded); } /// Loads and decodes object stream and reads its header (§7.5.7, Table 16). @@ -174,51 +221,46 @@ private ObjectStream ReadObjectStream(int number, CosReference member, int depth return ObjectStream.Unreadable(reference); } - List<(ObjectLoader Loader, int Number)> decoding = _decoding ??= []; - decoding.Add((this, number)); - try + if (Load(reference, depth + 1) is not CosStream stream) { - if (Load(reference, depth + 1) is not CosStream stream) - { - _diagnostics.Report( - DiagnosticCodes.ObjectStreamInvalid, - DiagnosticSeverity.Error, - string.Create(CultureInfo.InvariantCulture, $"The cross-reference entry places the object in object {number}, which is not a stream; read as null."), - objectReference: member); - return ObjectStream.Unreadable(reference); - } - - if (!stream.Dictionary.TryGetValue(KnownNames.Type, out CosObject? type) || !ObjStm.Equals(type)) - { - _diagnostics.Report( - DiagnosticCodes.ObjectStreamTypeInvalid, - DiagnosticSeverity.Warning, - "The object stream's Type entry shall be /ObjStm; the stream is read as one.", - objectReference: reference); - } + _diagnostics.Report( + DiagnosticCodes.ObjectStreamInvalid, + DiagnosticSeverity.Error, + string.Create(CultureInfo.InvariantCulture, $"The cross-reference entry places the object in object {number}, which is not a stream; read as null."), + objectReference: member); + return ObjectStream.Unreadable(reference); + } - CosObject count = Resolve(stream.Dictionary.TryGetValue(N, out CosObject? n) ? n : null, depth + 1); - CosObject first = Resolve(stream.Dictionary.TryGetValue(First, out CosObject? f) ? f : null, depth + 1); - return ObjectStream.Read(reference, _streams.Decode(stream), count, first, _diagnostics); + if (!stream.Dictionary.TryGetValue(KnownNames.Type, out CosObject? type) || !ObjStm.Equals(type)) + { + _diagnostics.Report( + DiagnosticCodes.ObjectStreamTypeInvalid, + DiagnosticSeverity.Warning, + "The object stream's Type entry shall be /ObjStm; the stream is read as one.", + objectReference: reference); } - finally + + CosObject count = Resolve(stream.Dictionary.TryGetValue(N, out CosObject? n) ? n : null, depth + 1); + CosObject first = Resolve(stream.Dictionary.TryGetValue(First, out CosObject? f) ? f : null, depth + 1); + ObjectStream container = ObjectStream.Read(reference, _streams.Decode(stream), count, first, _diagnostics); + if (Logger is { } logger) { - decoding.Remove((this, number)); + ObjectLog.ObjectStreamDecoded(logger, number, container.ObjectNumbers.Count); } + + return container; } /// Gets the decoded object streams by object number, created on first use so a file without them pays nothing. - private ConcurrentDictionary ObjectStreams + private OnceCache ObjectStreams { get { - ConcurrentDictionary? objectStreams = Volatile.Read(ref _objectStreams); + OnceCache? objectStreams = Volatile.Read(ref _objectStreams); return objectStreams ?? Interlocked.CompareExchange(ref _objectStreams, new(), null) ?? _objectStreams; } } - private bool IsDecoding(int containerNumber) => _decoding is { Count: > 0 } decoding && decoding.Contains((this, containerNumber)); - private CosObject Resolve(CosObject? value, int depth) => value is CosReference reference ? Load(reference, depth) : value ?? CosNull.Instance; /// Handles an entry whose offset does not hold the expected N G obj header. Issue #41 searches for the object. @@ -233,10 +275,33 @@ private CosNull LoadMisplaced(in ObjectLoadContext context) return CosNull.Instance; } - /// Parses N G obj object endobj at the context's offset (§7.3.10). + /// + /// Parses N G obj object endobj at the context's offset (§7.3.10). A source that reads in windows (a stream) is + /// asked for a small window first and a larger one while the object does not end inside it. + /// private CosObject ParseIndirectObject(in ObjectLoadContext context) { - ReadOnlySpan window = _source.GetWindow(context.Offset).Span; + long available = _source.Length - context.Offset; + int minimum = InitialObjectWindow; + while (true) + { + ReadOnlyMemory window = _source.GetWindow(context.Offset, minimum); + bool truncated = window.Length < available; + if (ParseIndirectObject(context, window.Span, final: !truncated || window.Length >= MaxObjectWindow) is { } value) + { + return value; + } + + minimum = (int)Math.Min(MaxObjectWindow, (long)window.Length * 2); + } + } + + /// + /// Parses the object in ; returns , reporting nothing, when it does not end inside a + /// window that is not . + /// + private CosObject? ParseIndirectObject(in ObjectLoadContext context, ReadOnlySpan window, bool final) + { var lexer = new CosLexer(window); if (!StructureTokens.TryReadUnsigned(ref lexer, out long number) || !StructureTokens.TryReadUnsigned(ref lexer, out long generation) @@ -248,16 +313,22 @@ private CosObject ParseIndirectObject(in ObjectLoadContext context) } var repairs = new CosRepairLog(keepAll: true); - var parser = new CosParser(window, repairs, lexer.Position, new LengthResolver(this, context)); + var parser = new CosParser(window, repairs, lexer.Position, new LengthResolver(this, context), new StreamDataFactory(_source, context.Offset)); CosObject value = parser.ParseObject(); + lexer.Position = parser.Position; + CosToken end = lexer.Next(); + bool ended = StructureTokens.IsKeyword(window, end, "endobj"u8); + if (!final && (!ended || repairs.Count > 0)) + { + return null; + } + foreach (CosRepair repair in repairs.All) { _diagnostics.Report(repair.Code, DiagnosticSeverity.Warning, repair.Message, context.Offset + repair.Offset, context.Reference); } - lexer.Position = parser.Position; - CosToken end = lexer.Next(); - if (!StructureTokens.IsKeyword(window, end, "endobj"u8)) + if (!ended) { _diagnostics.Report( DiagnosticCodes.MissingEndobj, @@ -270,6 +341,12 @@ private CosObject ParseIndirectObject(in ObjectLoadContext context) return value; } + /// Keeps a parsed stream's data in the source: the parser's window starts at . + private sealed class StreamDataFactory(PdfSource source, long windowOffset) : IStreamDataFactory + { + public CosStream CreateStream(CosDictionary dictionary, int start, int length) => source.CreateStream(dictionary, windowOffset + start, length); + } + /// Adapts hook 1 to the parser's resolver contract for one object load. private sealed class LengthResolver(ObjectLoader loader, ObjectLoadContext context) : IStreamLengthResolver { diff --git a/src/Broadside/Parsing/ObjectLoaderHooks.cs b/src/Broadside/Parsing/ObjectLoaderHooks.cs index 32658b9a..00811cb7 100644 --- a/src/Broadside/Parsing/ObjectLoaderHooks.cs +++ b/src/Broadside/Parsing/ObjectLoaderHooks.cs @@ -1,5 +1,5 @@ -using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; +using Broadside.Caching; using Broadside.Objects; namespace Broadside.Parsing; @@ -59,9 +59,14 @@ internal interface IObjectDecryptor /// /// Hook 3 of the object loader: the cache loaded objects are published to, so each indirect object is parsed once and every -/// reference to it yields the same instance (a live view needs one instance to view). Issue #45 replaces the default with a -/// lazy-once, memory-bounded cache under the concurrency contract. +/// reference to it yields the same instance (a live view needs one instance to view). The loader runs the whole load (locate, parse, +/// hooks 1 and 2) inside , so the cache decides how many times an object is parsed. /// +/// +/// ISO 32000-2 §7.5.4: objects are reached at random through the cross-reference table, on first use. The concurrency contract of a +/// document (CLAUDE.md): concurrent reads are safe while nobody mutates it, so an implementation must be safe for concurrent calls +/// and must parse each object once however many threads ask for it (). +/// internal interface IObjectCache { /// Looks up a loaded object. @@ -70,7 +75,20 @@ internal interface IObjectCache /// when cached. bool TryGet(CosReference reference, [NotNullWhen(true)] out CosObject? value); - /// Publishes a loaded object, or returns the one another thread published first. + /// Returns the cached object, or loads it with once, however many threads ask at the same time. + /// The loader's state for the factories. + /// The object's number and generation. + /// The factories' state. + /// Locates, parses and decrypts the object; its result is cached unless it says otherwise. + /// The value for a load that needs itself (on this thread, or through threads waiting on each other); not cached. + /// The cached instance, which every caller must use. + CosObject GetOrLoad( + CosReference reference, + TState state, + Func> load, + Func cycle); + + /// Publishes an object loaded outside , or returns the one cached first. /// The object's number and generation. /// The loaded object. /// The cached instance, which every caller must use. @@ -103,16 +121,27 @@ internal sealed class NullObjectDecryptor : IObjectDecryptor public CosObject Decrypt(CosObject value, in ObjectLoadContext context) => value; } -/// The default : an unbounded concurrent dictionary, first publisher wins. -internal sealed class ConcurrentObjectCache : IObjectCache +/// +/// The default : every object loaded once and kept for the document's lifetime, so references keep +/// resolving to one instance. Memory stays bounded by the objects' dictionaries and arrays: stream data is not held (a stream read +/// from a file or stream source reads its data from the source on each access). +/// +internal sealed class ObjectCache : IObjectCache { - private readonly ConcurrentDictionary _objects = new(); + private readonly OnceCache _objects = new(); + + /// + public bool TryGet(CosReference reference, [NotNullWhen(true)] out CosObject? value) => _objects.TryGet(reference, out value); /// - public bool TryGet(CosReference reference, [NotNullWhen(true)] out CosObject? value) => _objects.TryGetValue(reference, out value); + public CosObject GetOrLoad( + CosReference reference, + TState state, + Func> load, + Func cycle) => _objects.GetOrCreate(reference, state, load, cycle); /// - public CosObject Publish(CosReference reference, CosObject value) => _objects.GetOrAdd(reference, value); + public CosObject Publish(CosReference reference, CosObject value) => _objects.Add(reference, value); } /// @@ -136,6 +165,6 @@ public IObjectDecryptor Decryptor set => _decryptor = value; } - /// Gets hook 3, cache publication (issue #45 replaces it). - public IObjectCache Cache { get; init; } = new ConcurrentObjectCache(); + /// Gets hook 3, cache publication (issue #45): load once, publish, share across threads. + public IObjectCache Cache { get; init; } = new ObjectCache(); } diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 339aebd8..3df12c55 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -20,7 +20,21 @@ namespace Broadside; /// deviation throws a ; deviations in objects loaded after open (the page tree, for instance) throw /// from the member that loads them. /// -/// Safe for concurrent reads from several threads while nobody changes it; changes are single-threaded. +/// +/// Objects load lazily through the cross-reference table (§7.5.4: it "permits random access to indirect objects ... so that the +/// entire PDF file need not be read"), are parsed once, and are kept: every reference to an object resolves to the same instance. +/// A file opened from a path is memory-mapped and a seekable stream is read in place, so memory grows with the objects used, not +/// with the file: stream data stays in the file and is read each time it is asked for (). A +/// 2 GiB file opens and reads its last page in a few megabytes of managed memory. A non-seekable stream is copied when opened. +/// +/// +/// Concurrency contract. While nobody mutates the document, any number of threads may read it at the same time: resolve +/// objects, walk pages, decode streams, read diagnostics, render. Each object is still parsed once, and every thread sees the same +/// instance. Mutation (changing a COS object reachable from the document) is single-threaded and the caller's responsibility to +/// synchronize: no read may run while a mutation runs, and reading concurrently with a mutation is undefined. Disposing the +/// document while another thread reads it is a caller error too; reads after throw +/// . +/// /// public sealed class PdfDocument : IDisposable { @@ -116,7 +130,7 @@ public PdfVersion Version public IReadOnlyList Diagnostics => _diagnostics.Snapshot(); /// Opens the PDF file at with default options. - /// The file path. + /// The file path. The file is memory-mapped and shared for reading: do not change it until the document is disposed. /// The document. Dispose it when done. /// The file cannot be read at all. /// ISO 32000-2 §7.5. The same as on an engine with default options. @@ -134,9 +148,41 @@ public PdfVersion Version /// The stream. It is not disposed; keep it open and unchanged until the document is disposed. /// The document. Dispose it when done. /// The file cannot be read at all. - /// ISO 32000-2 §7.5. + /// + /// ISO 32000-2 §7.5. A seekable stream is read in place as objects are used, under a lock (a is + /// memory-mapped instead); a non-seekable stream is copied first, into memory up to and + /// into a temporary file beyond it. + /// public static PdfDocument Open(Stream stream) => PdfEngine.Default.Open(stream); + /// Opens the PDF file held by , from its current position, with default options; a non-seekable stream is read asynchronously. + /// The stream. It is not disposed; a seekable stream must stay open and unchanged until the document is disposed. + /// The document. Dispose it when done. + /// The file cannot be read at all. + /// ISO 32000-2 §7.5. The same as on an engine with default options. + public static Task OpenAsync(Stream stream) => PdfEngine.Default.OpenAsync(stream, CancellationToken.None); + + /// Opens the PDF file held by , from its current position, with default options; a non-seekable stream is read asynchronously. + /// The stream. It is not disposed; a seekable stream must stay open and unchanged until the document is disposed. + /// Cancels reading a non-seekable stream. + /// The document. Dispose it when done. + /// The file cannot be read at all. + /// was canceled. + /// ISO 32000-2 §7.5. The same as on an engine with default options. + public static Task OpenAsync(Stream stream, CancellationToken cancellationToken) => + PdfEngine.Default.OpenAsync(stream, cancellationToken); + + /// Opens the PDF file held by , from its current position; a non-seekable stream is read asynchronously. + /// The stream. It is not disposed; a seekable stream must stay open and unchanged until the document is disposed. + /// The options. + /// Cancels reading a non-seekable stream. + /// The document. Dispose it when done. + /// The file cannot be read at all, or, in strict mode, deviates from ISO 32000-2. + /// was canceled. + /// ISO 32000-2 §7.5. The same as on an engine built from . + public static Task OpenAsync(Stream stream, PdfOptions options, CancellationToken cancellationToken = default) => + new PdfEngine(options).OpenAsync(stream, cancellationToken); + /// Opens the PDF file held by , from its current position. /// The stream. It is not disposed; keep it open and unchanged until the document is disposed. /// The options. @@ -146,7 +192,9 @@ public PdfVersion Version public static PdfDocument Open(Stream stream, PdfOptions options) => new PdfEngine(options).Open(stream); /// Opens the PDF file held in with default options. - /// The file. Not copied: do not change it until the document is disposed. + /// + /// The file. Not copied: do not change it while the document or any of its objects is in use; stream data refers into it. + /// /// The document. Dispose it when done. /// The file cannot be read at all. /// ISO 32000-2 §7.5. @@ -230,7 +278,7 @@ internal static PdfDocument Read(PdfSource source, EngineConfiguration configura diagnostics, value => loader is not null ? loader.Resolve(value) : value is null or CosReference ? CosNull.Instance : value); CrossReference crossReference = CrossReferenceReader.Read(source, header, streams, diagnostics) ?? Reconstruct(diagnostics); - loader = new ObjectLoader(source, header, crossReference, diagnostics, new ObjectLoaderHooks(), streams); + loader = new ObjectLoader(source, header, crossReference, diagnostics, new ObjectLoaderHooks(), streams) { Logger = configuration.Logger }; IReadOnlyList revisions = ReadRevisions(source, crossReference, diagnostics); CosDictionary catalog = ReadCatalog(loader, diagnostics); PdfLinearization? linearization = LinearizationReader.Read(source, loader, diagnostics); diff --git a/src/Broadside/PdfEngine.cs b/src/Broadside/PdfEngine.cs index cc6fecb7..ab9e8447 100644 --- a/src/Broadside/PdfEngine.cs +++ b/src/Broadside/PdfEngine.cs @@ -77,7 +77,29 @@ public PdfDocument Open(string path) public PdfDocument Open(Stream stream) { ArgumentNullException.ThrowIfNull(stream); - return PdfDocument.Read(PdfSource.FromStream(stream), _configuration); + return PdfDocument.Read(PdfSource.FromStream(stream, _configuration.StreamBufferLimit), _configuration); + } + + /// Opens the PDF file held by , from its current position, reading a non-seekable stream asynchronously. + /// + /// The stream. It is not disposed. A seekable stream is read in place as objects are used: keep it open and unchanged until the + /// document is disposed. A non-seekable stream is read to its end, asynchronously, before the file is parsed. + /// + /// Cancels reading a non-seekable stream. + /// The document. Dispose it when done. + /// + /// The file cannot be read at all, or, in strict mode, deviates from ISO 32000-2. + /// + /// was canceled. + /// + /// ISO 32000-2 §7.5. Reading is synchronous once the bytes are available (spec #33: Async only at the open and save + /// boundaries), so this differs from only in how a non-seekable stream is copied. + /// + public async Task OpenAsync(Stream stream, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(stream); + PdfSource source = await PdfSource.FromStreamAsync(stream, _configuration.StreamBufferLimit, cancellationToken).ConfigureAwait(false); + return PdfDocument.Read(source, _configuration); } /// Opens the PDF file held in . diff --git a/src/Broadside/PdfOptions.cs b/src/Broadside/PdfOptions.cs index 374d858a..30e847d4 100644 --- a/src/Broadside/PdfOptions.cs +++ b/src/Broadside/PdfOptions.cs @@ -17,8 +17,12 @@ public sealed class PdfOptions /// The default of : 1 GiB. public const long DefaultMaxDecodedStreamLength = 1L << 30; + /// The default of : 64 MiB. + public const long DefaultStreamBufferLimit = 64L << 20; + private readonly List _filters = []; private long _maxDecodedStreamLength = DefaultMaxDecodedStreamLength; + private long _streamBufferLimit = DefaultStreamBufferLimit; /// Gets or sets how deviations from the specification are treated. The default is . /// ADR 0005. @@ -94,6 +98,37 @@ public PdfOptions WithMaxDecodedStreamLength(long maxLength) return this; } + /// + /// Gets or sets how many bytes of a non-seekable stream are copied into memory when a document is opened from it; a longer stream + /// is copied into a temporary file, deleted when the document is disposed, and read from there. Default 64 MiB. + /// + /// + /// ISO 32000-2 §7.5.1: a file is read at random through its cross-reference table, starting from its end, which a non-seekable + /// stream cannot do, so it is copied once at the open boundary. A seekable stream, a path and bytes are never copied: they are + /// read in place or memory-mapped as objects are used. + /// + /// The value is negative. + public long StreamBufferLimit + { + get => _streamBufferLimit; + set + { + ArgumentOutOfRangeException.ThrowIfNegative(value); + _streamBufferLimit = value; + } + } + + /// Sets . + /// How many bytes of a non-seekable stream to copy into memory; 0 always uses a temporary file. + /// These options. + /// is negative. + /// ISO 32000-2 §7.5.1. + public PdfOptions WithStreamBufferLimit(long limit) + { + StreamBufferLimit = limit; + return this; + } + /// Gets the logger factory set by , or . /// Not a property, so configuration binding never sees it. internal ILoggerFactory? LoggerFactory { get; private set; } diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index 49b61793..67acd901 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -265,3 +265,11 @@ Broadside.PdfOptions.WithLoggerFactory(Microsoft.Extensions.Logging.ILoggerFacto Microsoft.Extensions.DependencyInjection.BroadsideServiceCollectionExtensions static Microsoft.Extensions.DependencyInjection.BroadsideServiceCollectionExtensions.AddBroadside(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! static Microsoft.Extensions.DependencyInjection.BroadsideServiceCollectionExtensions.AddBroadside(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, System.Action! configure) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! +Broadside.PdfEngine.OpenAsync(System.IO.Stream! stream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Broadside.PdfOptions.StreamBufferLimit.get -> long +Broadside.PdfOptions.StreamBufferLimit.set -> void +Broadside.PdfOptions.WithStreamBufferLimit(long limit) -> Broadside.PdfOptions! +const Broadside.PdfOptions.DefaultStreamBufferLimit = 67108864 -> long +static Broadside.PdfDocument.OpenAsync(System.IO.Stream! stream) -> System.Threading.Tasks.Task! +static Broadside.PdfDocument.OpenAsync(System.IO.Stream! stream, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +static Broadside.PdfDocument.OpenAsync(System.IO.Stream! stream, Broadside.PdfOptions! options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 332f7742..4ad163cc 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -20,6 +20,7 @@ internal static class FuzzTargets ["lexer"] = Lexer, ["object-parser"] = ObjectParser, ["document"] = Document, + ["windowed-document"] = WindowedDocument, ["hint-tables"] = HintTables, ["xref-stream"] = XrefStream, ["object-stream"] = ObjectStreamTarget, @@ -90,6 +91,59 @@ private static void Document(ReadOnlySpan data) } } + /// + /// Opens the input twice, from memory (the whole file in one view) and through a seekable stream (read in place, in windows that + /// grow while an object does not end inside them), and requires the two to read the same: the same outcome when the file cannot + /// be opened, else the same pages, the same object for every number below the trailer's Size (capped), and the same diagnostics. + /// + /// ISO 32000-2 §7.5.4: random access to indirect objects through the cross-reference table (issue #45). + private static void WindowedDocument(ReadOnlySpan data) + { + byte[] bytes = data.ToArray(); + string whole = ReadEverything(() => PdfDocument.Open(bytes)); + using var stream = new MemoryStream(bytes, writable: false); + string windowed = ReadEverything(() => PdfDocument.Open(stream)); + if (whole != windowed) + { + throw new InvalidOperationException($"Reading in windows differs from reading the whole file:\n{whole}\n---\n{windowed}"); + } + } + + private static string ReadEverything(Func open) + { + PdfDocument document; + try + { + document = open(); + } + catch (DiagnosticException exception) + { + return exception.Diagnostic.ToString(); + } + + using (document) + { + var text = new System.Text.StringBuilder(); + foreach (PdfPage page in document.Pages) + { + text.Append(page.Reference).Append(' ').Append(page.MediaBox).Append('\n'); + } + + long size = document.Trailer.TryGetValue(new CosName("Size"), out CosObject? entry) && entry is CosInteger integer ? integer.Value : 0; + for (int number = 1; number < Math.Min(size, 2048); number++) + { + text.Append(document.Resolve(new CosReference(number, 0))).Append('\n'); + } + + foreach (Diagnostic diagnostic in document.Diagnostics) + { + text.Append(diagnostic).Append('\n'); + } + + return text.ToString(); + } + } + /// /// Decodes the input as a raw stream body with one filter in lenient mode. The output must stay within /// bytes per input byte (plus one group), the most any encoding of that filter can expand. diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index e62cdaf7..ff9e7e3c 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` for a file whose cross-reference information cannot be read is the one allowed outcome until #41 reconstructs it; it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` for a file whose cross-reference information cannot be read is the one allowed outcome until #41 reconstructs it; it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in growing windows, and requires both to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. diff --git a/tests/Broadside.Tests/Document/ConcurrencyTests.cs b/tests/Broadside.Tests/Document/ConcurrencyTests.cs new file mode 100644 index 00000000..e364d249 --- /dev/null +++ b/tests/Broadside.Tests/Document/ConcurrencyTests.cs @@ -0,0 +1,161 @@ +using System.Collections.Concurrent; +using System.Security.Cryptography; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// Every source a document can be opened from, for the concurrency theory. +public enum ConcurrentSource +{ + Bytes, + Path, + FileStream, + SeekableStream, + NonSeekableStream, +} + +/// +/// The concurrency contract of (CLAUDE.md, spec #33 "Thread safety"): while nobody mutates a document, any +/// number of threads may read it at once, and they see exactly what one thread reading alone sees. Every page and every object of +/// every corpus file is read from many threads in parallel, repeatedly and in random order, through every kind of source. +/// ISO 32000-2 §7.5.4 (random access to indirect objects through the cross-reference table). +/// +public class ConcurrencyTests +{ + private const int Repetitions = 50; + + public static TheoryData FilesBySource + { + get + { + var data = new TheoryData(); + foreach (string fileName in Corpus.AllFileNames) + { + foreach (ConcurrentSource source in Enum.GetValues()) + { + data.Add(fileName, source); + } + } + + return data; + } + } + + [Theory] + [MemberData(nameof(FilesBySource))] + public void Every_page_and_object_reads_the_same_from_many_threads_as_from_one(string fileName, ConcurrentSource source) + { + Reading expected; + try + { + using PdfDocument alone = PdfDocument.Open(Corpus.Bytes(fileName)); + expected = Reading.Of(alone, References(alone)); + } + catch (DiagnosticException unreadable) + { + // A file the reader cannot open yet (cross-reference reconstruction is issue #41) fails the same way from every source. + DiagnosticException exception = Assert.Throws(() => Open(fileName, source).Dispose()); + Assert.Equal(unreadable.Diagnostic.Code, exception.Diagnostic.Code); + return; + } + + using PdfDocument document = Open(fileName, source); + var instances = new ConcurrentDictionary(); + Parallel.For(0, Repetitions, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 2 }, repetition => + { + foreach (int index in LazyLoadingTests.Shuffled(0, expected.References.Length, repetition)) + { + CosReference reference = expected.References[index]; + CosObject value = document.Resolve(reference); + Assert.Same(instances.GetOrAdd(reference, value), value); + Assert.Equal(expected.Objects[index], Reading.Describe(document, value)); + } + + Assert.Equal(expected.Pages, Reading.DescribePages(document)); + }); + + Assert.Equal(expected.Diagnostics, Reading.DistinctDiagnostics(document)); + } + + /// Every object reachable from the trailer, plus objects 1 to Size - 1 with generation 0, in a fixed order. + private static CosReference[] References(PdfDocument document) + { + var found = new HashSet(); + var pending = new Stack([document.Trailer]); + while (pending.TryPop(out CosObject? value)) + { + switch (value) + { + case CosReference reference when found.Add(reference): + pending.Push(document.Resolve(reference)); + break; + case CosArray array: + foreach (CosObject item in array) + { + pending.Push(item); + } + + break; + case CosDictionary dictionary: + foreach (KeyValuePair entry in dictionary) + { + pending.Push(entry.Value); + } + + break; + case CosStream stream: + pending.Push(stream.Dictionary); + break; + } + } + + long size = document.Trailer.TryGetValue(new CosName("Size"), out CosObject? sizeEntry) && sizeEntry is CosInteger integer ? integer.Value : 0; + for (int number = 1; number < Math.Min(size, 10_000); number++) + { + found.Add(new CosReference(number, 0)); + } + + return [.. found.OrderBy(reference => reference.ObjectNumber).ThenBy(reference => reference.Generation)]; + } + + private static PdfDocument Open(string fileName, ConcurrentSource source) => source switch + { + ConcurrentSource.Bytes => PdfDocument.Open(Corpus.Bytes(fileName)), + ConcurrentSource.Path => PdfDocument.Open(Corpus.Path(fileName)), + ConcurrentSource.FileStream => OpenFileStream(fileName), + ConcurrentSource.SeekableStream => PdfDocument.Open(new ProbeStream(Corpus.Bytes(fileName))), + _ => PdfDocument.Open(new ProbeStream(Corpus.Bytes(fileName), seekable: false)), + }; + + /// Opens through a the test then closes: the mapping outlives the caller's handle. + private static PdfDocument OpenFileStream(string fileName) + { + using FileStream stream = Corpus.Open(fileName); + return PdfDocument.Open(stream); + } + + /// What one complete read of a document saw, as values. + private sealed record Reading(CosReference[] References, string[] Objects, string Pages, string[] Diagnostics) + { + public static Reading Of(PdfDocument document, CosReference[] references) + { + string[] objects = [.. references.Select(reference => Describe(document, document.Resolve(reference)))]; + return new Reading(references, objects, DescribePages(document), DistinctDiagnostics(document)); + } + + /// The object's canonical syntax, and for a stream the hash of its decoded data. + public static string Describe(PdfDocument document, CosObject value) => value is CosStream stream + ? $"{value} decoded {Convert.ToHexString(SHA256.HashData(document.DecodeStream(stream).Span))}" + : value.ToString(); + + public static string DescribePages(PdfDocument document) => string.Join('\n', document.Pages.Select(static page => + $"{page.Reference} media {page.MediaBox} crop {page.CropBox} bleed {page.BleedBox} trim {page.TrimBox} art {page.ArtBox} " + + $"rotate {page.Rotation} unit {page.UserUnit} resources {page.Resources}")); + + // Decoding is not cached, so a filter diagnostic repeats with each decode; what must match is the set of deviations. + public static string[] DistinctDiagnostics(PdfDocument document) => + [.. document.Diagnostics.Select(static diagnostic => diagnostic.ToString()).Distinct().Order(StringComparer.Ordinal)]; + } +} diff --git a/tests/Broadside.Tests/Document/LargeFileTests.cs b/tests/Broadside.Tests/Document/LargeFileTests.cs new file mode 100644 index 00000000..48e0ab32 --- /dev/null +++ b/tests/Broadside.Tests/Document/LargeFileTests.cs @@ -0,0 +1,119 @@ +using System.Globalization; +using System.Text; +using Broadside.Objects; + +namespace Broadside.Tests.Document; + +/// +/// A file larger than 2 GiB opens and reads its last page with bounded memory: the reader keeps offsets as 64-bit values, maps the +/// file instead of reading it, and keeps stream data in the file. ISO 32000-2 §7.5.4 (the cross-reference table "permits random +/// access to indirect objects ... so that the entire PDF file need not be read"; ten-digit offsets reach 9 999 999 999). +/// +/// +/// The bound: opening, walking all pages, resolving every content stream and decoding the last one grows the managed heap by less +/// than 64 MiB, while the file is 2.1 GiB. Measured with , not the working set, which counts +/// the mapped (and reclaimable) pages of the file. +/// +public class LargeFileTests +{ + private const int PageCount = 2100; + private const int ContentLength = 1 << 20; + private const long ManagedMemoryBound = 64L << 20; + + [Fact] + public void A_file_over_2_GiB_opens_and_reads_its_last_page_in_bounded_memory() + { + string path = Path.Combine(Path.GetTempPath(), $"broadside-large-{Guid.NewGuid():N}.pdf"); + try + { + long length = WriteLargeFile(path); + Assert.True(length > (long)int.MaxValue + ContentLength, $"The file is {length} bytes."); + + ReadLastPage(() => PdfDocument.Open(path)); + + // The same file through a seekable stream that is not a FileStream: read in place in windows, not mapped. + using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096); + using var stream = new BufferedStream(file, 64 * 1024); + ReadLastPage(() => PdfDocument.Open(stream)); + } + finally + { + File.Delete(path); + } + } + + private static void ReadLastPage(Func open) + { + long before = GC.GetTotalMemory(forceFullCollection: true); + using PdfDocument document = open(); + + Assert.Equal(PageCount, document.Pages.Count); + PdfPage last = document.Pages[PageCount - 1]; + Assert.Equal(new PdfRectangle(0, 0, 612, 792), last.MediaBox); + + // Every content stream object, 2 GiB of data in all, without reading the data. + foreach (PdfPage page in document.Pages) + { + Assert.Equal(ContentLength, ((CosInteger)((CosStream)document.Resolve(page.Dictionary[new CosName("Contents")])).Dictionary[new CosName("Length")]).Value); + } + + var contents = (CosStream)document.Resolve(last.Dictionary[new CosName("Contents")]); + ReadOnlyMemory decoded = document.DecodeStream(contents); + Assert.Equal(ContentLength, decoded.Length); + Assert.True(decoded.Span.StartsWith(Encoding.ASCII.GetBytes($"q Q % page {PageCount - 1} "))); + Assert.Empty(document.Diagnostics); + + decoded = default; + long growth = GC.GetTotalMemory(forceFullCollection: true) - before; + Assert.True(growth < ManagedMemoryBound, $"The managed heap grew by {growth} bytes."); + GC.KeepAlive(document); + } + + /// Writes the file one object at a time; returns its length. + private static long WriteLargeFile(string path) + { + using var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 1 << 20); + var offsets = new long[(2 * PageCount) + 3]; + byte[] padding = new byte[ContentLength]; + padding.AsSpan().Fill((byte)'x'); + padding[^1] = (byte)'\n'; + + Write(file, "%PDF-1.7\n%âãÏÓ\n"); + offsets[1] = file.Position; + Write(file, "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n"); + offsets[2] = file.Position; + var kids = new StringBuilder(); + for (int page = 0; page < PageCount; page++) + { + kids.Append(CultureInfo.InvariantCulture, $"{3 + (2 * page)} 0 R "); + } + + Write(file, $"2 0 obj\n<< /Type /Pages /Kids [{kids}] /Count {PageCount} >>\nendobj\n"); + for (int page = 0; page < PageCount; page++) + { + int number = 3 + (2 * page); + offsets[number] = file.Position; + Write(file, $"{number} 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> /Contents {number + 1} 0 R >>\nendobj\n"); + offsets[number + 1] = file.Position; + string prefix = $"q Q % page {page} "; + Write(file, $"{number + 1} 0 obj\n<< /Length {ContentLength} >>\nstream\n{prefix}"); + file.Write(padding, prefix.Length, ContentLength - prefix.Length); + Write(file, "\nendstream\nendobj\n"); + } + + long xref = file.Position; + int size = (2 * PageCount) + 3; + var table = new StringBuilder(); + table.Append(CultureInfo.InvariantCulture, $"xref\n0 {size}\n0000000000 65535 f \n"); + for (int number = 1; number < size; number++) + { + table.Append(CultureInfo.InvariantCulture, $"{offsets[number]:D10} 00000 n \n"); + } + + table.Append(CultureInfo.InvariantCulture, $"trailer\n<< /Size {size} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n"); + Write(file, table.ToString()); + return file.Length; + } + + private static void Write(FileStream file, string text) => file.Write(Encoding.Latin1.GetBytes(text)); +} diff --git a/tests/Broadside.Tests/Document/LazyLoadingTests.cs b/tests/Broadside.Tests/Document/LazyLoadingTests.cs new file mode 100644 index 00000000..253a0ac4 --- /dev/null +++ b/tests/Broadside.Tests/Document/LazyLoadingTests.cs @@ -0,0 +1,200 @@ +using System.Collections.Concurrent; +using Broadside.Objects; +using Broadside.TestSupport; +using Broadside.Tests.Hosting; +using Microsoft.Extensions.Logging; + +namespace Broadside.Tests.Document; + +/// +/// Objects load on first use through the cross-reference table and are parsed once, whatever the number of threads reading them. +/// ISO 32000-2 §7.5.1 and §7.5.4: the cross-reference table "permits random access to indirect objects ... so that the entire PDF +/// file need not be read". The parse count is observed through the engine's trace log (event 2, ObjectParsed). +/// +public class LazyLoadingTests +{ + private const int PageCount = 40; + + [Fact] + public void Opening_a_file_parses_the_catalog_and_nothing_else() + { + using var logs = new CapturingLoggerProvider(); + using ILoggerFactory loggerFactory = TraceLogging(logs); + + using PdfDocument document = PdfDocument.Open(ManyPages(), new PdfOptions().WithLoggerFactory(loggerFactory)); + + Assert.Equal([(1, 0)], ParsedObjects(logs)); + } + + [Fact] + public void Reading_the_pages_parses_the_page_tree_but_not_the_page_contents() + { + using var logs = new CapturingLoggerProvider(); + using ILoggerFactory loggerFactory = TraceLogging(logs); + using PdfDocument document = PdfDocument.Open(ManyPages(), new PdfOptions().WithLoggerFactory(loggerFactory)); + + Assert.Equal(PageCount, document.Pages.Count); + + // Catalog, page tree root, one page object per page: no content stream, no Length object. + int[] expected = [1, 2, .. Enumerable.Range(0, PageCount).Select(page => 3 + (3 * page))]; + Assert.Equal(expected.Order(), ParsedObjects(logs).Select(parsed => parsed.Number).Order()); + } + + [Fact] + public void Every_object_is_parsed_once_however_many_threads_read_it() + { + using var logs = new CapturingLoggerProvider(); + using ILoggerFactory loggerFactory = TraceLogging(logs); + using PdfDocument document = PdfDocument.Open(ManyPages(), new PdfOptions().WithLoggerFactory(loggerFactory)); + int objectCount = 2 + (3 * PageCount); + + var seen = new ConcurrentDictionary(); + Parallel.For(0, 64, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 2 }, iteration => + { + foreach (int number in Shuffled(1, objectCount, iteration)) + { + CosObject value = document.Resolve(new CosReference(number, 0)); + Assert.Same(seen.GetOrAdd(number, value), value); + if (value is CosStream stream) + { + Assert.Equal("q Q"u8.ToArray(), document.DecodeStream(stream).ToArray()); + } + } + }); + + (int Number, int Generation)[] parsed = ParsedObjects(logs); + Assert.Equal(Enumerable.Range(1, objectCount), parsed.Select(entry => entry.Number).Order()); + Assert.All(parsed, entry => Assert.Equal(0, entry.Generation)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Resolving_an_object_already_loaded_allocates_nothing() + { + using PdfDocument document = PdfDocument.Open(ManyPages()); + CosReference[] references = [.. Enumerable.Range(1, 2 + (3 * PageCount)).Select(number => new CosReference(number, 0))]; + + // Warm up past tiered compilation, which allocates on its own. + for (int round = 0; round < 50; round++) + { + ResolveAll(document, references); + } + + long before = GC.GetAllocatedBytesForCurrentThread(); + ResolveAll(document, references); + Assert.Equal(0, GC.GetAllocatedBytesForCurrentThread() - before); + + static void ResolveAll(PdfDocument document, CosReference[] references) + { + foreach (CosReference reference in references) + { + _ = document.Resolve(reference); + } + } + } + + [Fact] + public void An_object_stream_is_decoded_once_however_many_threads_read_its_members() + { + using var logs = new CapturingLoggerProvider(); + using ILoggerFactory loggerFactory = TraceLogging(logs); + using PdfDocument document = PdfDocument.Open(Corpus.Path("object-stream.pdf"), new PdfOptions().WithLoggerFactory(loggerFactory)); + int size = (int)((CosInteger)document.Trailer[new CosName("Size")]).Value; + + Parallel.For(0, 64, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 2 }, iteration => + { + foreach (int number in Shuffled(1, size - 1, iteration)) + { + _ = document.Resolve(new CosReference(number, 0)); + } + }); + + (int Number, int Generation)[] parsed = ParsedObjects(logs); + Assert.Equal(parsed.Length, parsed.Distinct().Count()); + Assert.Single(logs.Entries, entry => entry.EventId.Name == "ObjectStreamDecoded"); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Two_streams_whose_Lengths_refer_to_each_other_read_with_a_diagnostic() + { + using PdfDocument document = PdfDocument.Open(MutualLengths()); + + var first = Assert.IsType(document.Resolve(new CosReference(4, 0))); + var second = Assert.IsType(document.Resolve(new CosReference(5, 0))); + + Assert.Equal("four"u8.ToArray(), first.EncodedData.ToArray()); + Assert.Equal("five"u8.ToArray(), second.EncodedData.ToArray()); + Assert.Contains("ObjectReferenceCycle", document.Diagnostics.Select(diagnostic => diagnostic.Code)); + } + + [Fact] + public async Task Two_threads_each_loading_a_stream_whose_Length_is_the_other_one_do_not_deadlock() + { + // Thread A holds stream 4 and needs 5; thread B holds 5 and needs 4. One of them must give up instead of waiting. + for (int attempt = 0; attempt < 200; attempt++) + { + using PdfDocument document = PdfDocument.Open(MutualLengths()); + using var start = new Barrier(2); + Task[] loads = + [ + Task.Run(() => { start.SignalAndWait(); return document.Resolve(new CosReference(4, 0)); }), + Task.Run(() => { start.SignalAndWait(); return document.Resolve(new CosReference(5, 0)); }), + ]; + + // A deadlock fails the test with a TimeoutException instead of hanging the run. + CosObject[] results = await Task.WhenAll(loads).WaitAsync(TimeSpan.FromSeconds(30), TestContext.Current.CancellationToken); + Assert.Equal("four"u8.ToArray(), Assert.IsType(results[0]).EncodedData.ToArray()); + Assert.Equal("five"u8.ToArray(), Assert.IsType(results[1]).EncodedData.ToArray()); + Assert.Same(results[0], document.Resolve(new CosReference(4, 0))); + Assert.Same(results[1], document.Resolve(new CosReference(5, 0))); + } + } + + /// A one-page file plus objects 4 and 5, streams whose Length entries refer to each other. + private static byte[] MutualLengths() => new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>", + "<< /Length 5 0 R >>\nstream\nfour\nendstream", + "<< /Length 4 0 R >>\nstream\nfive\nendstream"); + + /// A catalog, a page tree root and pages, each with a content stream whose Length is indirect. + internal static byte[] ManyPages() + { + var objects = new List + { + "<< /Type /Catalog /Pages 2 0 R >>", + $"<< /Type /Pages /Kids [{string.Join(' ', Enumerable.Range(0, PageCount).Select(page => $"{3 + (3 * page)} 0 R"))}] /Count {PageCount} >>", + }; + for (int page = 0; page < PageCount; page++) + { + int number = 3 + (3 * page); + objects.Add($"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> /Contents {number + 1} 0 R >>"); + objects.Add($"<< /Length {number + 2} 0 R >>\nstream\nq Q\nendstream"); + objects.Add("3"); + } + + return new TestPdf().Build([.. objects]); + } + + /// The numbers to + - 1 in an order fixed by . + internal static int[] Shuffled(int start, int count, int seed) + { + int[] values = [.. Enumerable.Range(start, count)]; +#pragma warning disable CA5394 // A reproducible test order, not security. + new Random(seed).Shuffle(values); +#pragma warning restore CA5394 + return values; + } + + internal static ILoggerFactory TraceLogging(CapturingLoggerProvider logs) => + LoggerFactory.Create(logging => logging.AddProvider(logs).SetMinimumLevel(LogLevel.Trace)); + + internal static (int Number, int Generation)[] ParsedObjects(CapturingLoggerProvider logs) => + [ + .. logs.Entries + .Where(entry => entry.EventId.Name == "ObjectParsed") + .Select(entry => ((int)entry.State["ObjectNumber"]!, (int)entry.State["Generation"]!)), + ]; +} diff --git a/tests/Broadside.Tests/Document/OpenDocumentTests.cs b/tests/Broadside.Tests/Document/OpenDocumentTests.cs index cc6145f8..8811388d 100644 --- a/tests/Broadside.Tests/Document/OpenDocumentTests.cs +++ b/tests/Broadside.Tests/Document/OpenDocumentTests.cs @@ -84,10 +84,9 @@ private static PdfDocument Open(string fileName, SourceKind kind) case SourceKind.Path: return PdfDocument.Open(Corpus.Path(fileName)); case SourceKind.Stream: - using (FileStream stream = Corpus.Open(fileName)) - { - return PdfDocument.Open(stream); - } + // A seekable stream is read in place, so it stays open as long as the document; a stream that is not a FileStream + // is read under a lock rather than memory-mapped. + return PdfDocument.Open(new ProbeStream(Corpus.Bytes(fileName))); default: return PdfDocument.Open(Corpus.Bytes(fileName)); diff --git a/tests/Broadside.Tests/Document/ProbeStream.cs b/tests/Broadside.Tests/Document/ProbeStream.cs new file mode 100644 index 00000000..8dd11a36 --- /dev/null +++ b/tests/Broadside.Tests/Document/ProbeStream.cs @@ -0,0 +1,87 @@ +namespace Broadside.Tests.Document; + +/// +/// A stream over bytes that is not a or (so the reader cannot take a shortcut), +/// optionally not seekable or not readable synchronously, counting the bytes read through it. +/// +internal sealed class ProbeStream(byte[] bytes, bool seekable = true, bool synchronous = true) : Stream +{ + private long _position; + private long _bytesRead; + + public long BytesRead => Interlocked.Read(ref _bytesRead); + + public bool IsDisposed { get; private set; } + + public override bool CanRead => !IsDisposed; + + public override bool CanSeek => seekable && !IsDisposed; + + public override bool CanWrite => false; + + public override long Length => seekable ? bytes.Length : throw new NotSupportedException(); + + public override long Position + { + get => seekable ? _position : throw new NotSupportedException(); + set => _position = seekable ? value : throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) + { + if (!synchronous) + { + throw new InvalidOperationException("This stream can only be read asynchronously."); + } + + return ReadCore(buffer); + } + + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) => + ValueTask.FromResult(ReadCore(buffer.Span)); + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + Task.FromResult(ReadCore(buffer.AsSpan(offset, count))); + + public override long Seek(long offset, SeekOrigin origin) + { + if (!seekable) + { + throw new NotSupportedException(); + } + + _position = origin switch + { + SeekOrigin.Begin => offset, + SeekOrigin.Current => _position + offset, + _ => bytes.Length + offset, + }; + return _position; + } + + public override void Flush() + { + } + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + IsDisposed = true; + base.Dispose(disposing); + } + + private int ReadCore(Span buffer) + { + ObjectDisposedException.ThrowIf(IsDisposed, this); + int count = (int)Math.Clamp(bytes.Length - _position, 0, buffer.Length); + bytes.AsSpan((int)_position, count).CopyTo(buffer); + _position += count; + Interlocked.Add(ref _bytesRead, count); + return count; + } +} diff --git a/tests/Broadside.Tests/Document/SourceTests.cs b/tests/Broadside.Tests/Document/SourceTests.cs new file mode 100644 index 00000000..4372a8d3 --- /dev/null +++ b/tests/Broadside.Tests/Document/SourceTests.cs @@ -0,0 +1,180 @@ +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// +/// Where a document's bytes come from: memory, a memory-mapped file, a seekable stream read in place, or a non-seekable stream +/// buffered when it is opened. ISO 32000-2 §7.5.1 (a file is read at random through its cross-reference table) and §7.5.4. +/// +public class SourceTests +{ + private const int ContentLength = 64 * 1024; + + [Fact] + public void A_seekable_stream_is_read_in_place_only_where_objects_are_needed() + { + byte[] file = LargePages(pageCount: 16); + using var stream = new ProbeStream(file); + + using PdfDocument document = PdfDocument.Open(stream); + Assert.Equal(16, document.Pages.Count); + + // The page tree is read; the sixteen 64 KB content streams are not. + Assert.True(stream.BytesRead < file.Length / 4, $"{stream.BytesRead} of {file.Length} bytes were read to open the file and walk its pages."); + + var contents = (CosStream)document.Resolve(document.Pages[15].Dictionary[new CosName("Contents")]); + Assert.Equal(Content(15), document.DecodeStream(contents).ToArray()); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void An_object_larger_than_the_first_read_of_a_stream_is_read_whole() + { + byte[] content = [.. Enumerable.Repeat((byte)'%', 300_000), (byte)'\n']; + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> /Contents 4 0 R >>", + $"<< /Length {content.Length} >>\nstream\n{System.Text.Encoding.Latin1.GetString(content)}\nendstream"); + using var stream = new ProbeStream(file); + + using PdfDocument document = PdfDocument.Open(stream); + + var contents = (CosStream)document.Resolve(new CosReference(4, 0)); + Assert.Equal(content, contents.EncodedData.ToArray()); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_stream_is_read_from_its_position_when_opened() + { + byte[] file = [.. "not part of the file"u8, .. Corpus.Bytes("page-tree-inherited.pdf")]; + using var stream = new ProbeStream(file); + stream.Position = "not part of the file"u8.Length; + + using PdfDocument document = PdfDocument.Open(stream); + using PdfDocument expected = PdfDocument.Open(Corpus.Path("page-tree-inherited.pdf")); + + Assert.Equal(DocumentProjection.Of(expected), DocumentProjection.Of(document)); + } + + [Fact] + public void The_callers_stream_is_left_open() + { + using var stream = new ProbeStream(Corpus.Bytes("empty-page.pdf")); + + PdfDocument.Open(stream).Dispose(); + + Assert.False(stream.IsDisposed); + } + + [Fact] + public void A_non_seekable_stream_is_read_whole_when_opened() + { + byte[] file = Corpus.Bytes("object-stream.pdf"); + using var stream = new ProbeStream(file, seekable: false); + + using PdfDocument document = PdfDocument.Open(stream); + using PdfDocument expected = PdfDocument.Open(file); + + Assert.Equal(file.Length, stream.BytesRead); + Assert.Equal(DocumentProjection.Of(expected), DocumentProjection.Of(document)); + } + + [Fact] + public void A_non_seekable_stream_longer_than_the_buffer_limit_is_read_through_a_temporary_file() + { + byte[] file = LargePages(pageCount: 4); + using var stream = new ProbeStream(file, seekable: false); + + using PdfDocument document = PdfDocument.Open(stream, new PdfOptions().WithStreamBufferLimit(4096)); + + Assert.Equal(4, document.Pages.Count); + var contents = (CosStream)document.Resolve(document.Pages[3].Dictionary[new CosName("Contents")]); + Assert.Equal(Content(3), document.DecodeStream(contents).ToArray()); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public async Task OpenAsync_reads_a_non_seekable_stream_asynchronously() + { + byte[] file = Corpus.Bytes("xref-stream.pdf"); + using var stream = new ProbeStream(file, seekable: false, synchronous: false); + + using PdfDocument document = await PdfDocument.OpenAsync(stream, TestContext.Current.CancellationToken); + using PdfDocument expected = PdfDocument.Open(file); + + Assert.Equal(DocumentProjection.Of(expected), DocumentProjection.Of(document)); + } + + [Fact] + public async Task OpenAsync_spills_a_long_non_seekable_stream_to_a_temporary_file_asynchronously() + { + byte[] file = LargePages(pageCount: 4); + using var stream = new ProbeStream(file, seekable: false, synchronous: false); + var engine = new PdfEngine(new PdfOptions().WithStreamBufferLimit(4096)); + + using PdfDocument document = await engine.OpenAsync(stream, TestContext.Current.CancellationToken); + + var contents = (CosStream)document.Resolve(document.Pages[2].Dictionary[new CosName("Contents")]); + Assert.Equal(Content(2), document.DecodeStream(contents).ToArray()); + } + + [Fact] + public async Task OpenAsync_honors_cancellation() + { + using var stream = new ProbeStream(Corpus.Bytes("empty-page.pdf"), seekable: false, synchronous: false); + + await Assert.ThrowsAnyAsync(() => PdfDocument.OpenAsync(stream, new CancellationToken(canceled: true))); + } + + [Fact] + public void Stream_data_of_a_disposed_document_opened_from_a_path_cannot_be_read() + { + PdfDocument document = PdfDocument.Open(Corpus.Path("flate-stream.pdf")); + var contents = (CosStream)document.Resolve(document.Pages[0].Dictionary[new CosName("Contents")]); + Assert.False(contents.EncodedData.IsEmpty); + + document.Dispose(); + + Assert.Throws(() => contents.EncodedData); + } + + [Fact] + public void Stream_data_of_a_document_opened_from_bytes_refers_to_those_bytes() + { + byte[] file = Corpus.Bytes("flate-stream.pdf"); + using PdfDocument document = PdfDocument.Open(file); + + var contents = (CosStream)document.Resolve(document.Pages[0].Dictionary[new CosName("Contents")]); + + Assert.True(System.Runtime.InteropServices.MemoryMarshal.TryGetArray(contents.EncodedData, out ArraySegment segment)); + Assert.Same(file, segment.Array); + } + + /// A file of pages, each with a content stream of bytes. + internal static byte[] LargePages(int pageCount) + { + var objects = new List + { + "<< /Type /Catalog /Pages 2 0 R >>", + $"<< /Type /Pages /Kids [{string.Join(' ', Enumerable.Range(0, pageCount).Select(page => $"{3 + (2 * page)} 0 R"))}] /Count {pageCount} >>", + }; + for (int page = 0; page < pageCount; page++) + { + objects.Add($"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> /Contents {4 + (2 * page)} 0 R >>"); + byte[] content = Content(page); + objects.Add($"<< /Length {content.Length} >>\nstream\n{System.Text.Encoding.Latin1.GetString(content)}\nendstream"); + } + + return new TestPdf().Build([.. objects]); + } + + /// A content stream that paints nothing: a save/restore pair, then a comment padding it to . + private static byte[] Content(int page) + { + byte[] prefix = System.Text.Encoding.ASCII.GetBytes($"q Q % page {page} "); + return [.. prefix, .. Enumerable.Repeat((byte)'x', ContentLength - prefix.Length - 1), (byte)'\n']; + } +} From d90f13215d1f10484705947556b715730dd41bbf Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:59:16 -0500 Subject: [PATCH 013/152] fix(cos): grow windows for cross-reference sections of any size (#45) A seekable non-FileStream source read cross-reference tables and streams in one 4 MiB window, silently truncating a larger section. Tables, xref stream objects and reconstruction trailers now parse through PdfSource.ReadGrowing: the window doubles until the parse ends inside it and the next token is whole inside it; table diagnostics are held back until the window is final. Object headers and end tokens cut by a window boundary also grow the window. The windowed-document fuzz target adds a pass with 16-byte initial windows; tests open a 6 MB table and a 5.6 MB xref stream through a seekable stream. Co-Authored-By: Claude Opus 5.5 --- src/Broadside/IO/PdfSource.cs | 44 ++++++++++++ src/Broadside/IO/StreamSource.cs | 7 +- src/Broadside/Parsing/CrossReferenceReader.cs | 42 ++++++++++- .../Parsing/CrossReferenceReconstructor.cs | 11 ++- src/Broadside/Parsing/ObjectLoader.cs | 8 ++- src/Broadside/Parsing/StructureTokens.cs | 13 ++++ src/Broadside/Parsing/XrefStreamReader.cs | 54 ++++++++++++-- tests/Broadside.Fuzz/FuzzTargets.cs | 8 +++ tests/Broadside.Fuzz/README.md | 2 +- tests/Broadside.Tests/Document/SourceTests.cs | 71 +++++++++++++++++++ 10 files changed, 246 insertions(+), 14 deletions(-) diff --git a/src/Broadside/IO/PdfSource.cs b/src/Broadside/IO/PdfSource.cs index c6fbb60c..d78f0619 100644 --- a/src/Broadside/IO/PdfSource.cs +++ b/src/Broadside/IO/PdfSource.cs @@ -3,6 +3,14 @@ namespace Broadside.IO; +/// One attempt of : parse , or ask for a larger one. +/// What the parse produces. +/// The bytes from the offset on. +/// Whether a larger window is impossible: the parse must finish, repairing what is missing. +/// The result, when the attempt succeeds. +/// to be called again with a larger window. +internal delegate bool WindowAttempt(ReadOnlySpan window, bool final, out T result); + /// The bytes of one PDF file, read by position. /// /// @@ -27,11 +35,18 @@ internal abstract class PdfSource : IDisposable private const int CopyBufferLength = 81920; + private volatile bool _disposed; /// Gets the length of the file in bytes. public abstract long Length { get; } + /// + /// Gets the first window and the object loader ask for: the most a parse usually needs. Only matters + /// for a source that reads in windows; the fuzz target windowed-document makes it tiny to exercise every growth path. + /// + public virtual int InitialWindow => 64 * 1024; + /// Creates a source over bytes the caller promises not to change while the source is in use. The bytes are not copied. /// The file. /// The source. @@ -176,6 +191,35 @@ public static async Task FromStreamAsync(Stream stream, long bufferLi /// The view, empty when is at or past the end of the file. public abstract ReadOnlyMemory GetWindow(long offset, int minimumLength); + /// + /// Parses something of unknown length at : gets a window and says whether it + /// held enough; while it does not and the window is not final (the rest of the file, or the largest span possible), the + /// window doubles. Whole-file sources pass the first window as final, so this costs them nothing. + /// + /// What the parse produces. + /// The offset of the first byte to parse. + /// + /// Parses one window; returns (reporting nothing) when the window ended before the parse could, which it + /// may only do for a window that is not final. + /// + /// The result of the attempt that succeeded. + public T ReadGrowing(long offset, WindowAttempt attempt) + { + long available = Math.Max(0, Length - offset); + int minimum = InitialWindow; + while (true) + { + ReadOnlyMemory window = GetWindow(offset, minimum); + bool final = window.Length >= available || window.Length >= Array.MaxLength / 2 || window.Length < minimum; + if (attempt(window.Span, final, out T result)) + { + return result; + } + + minimum = (int)Math.Min(Array.MaxLength, (long)window.Length * 2); + } + } + /// Creates the stream object for data at , without copying the data out of the source. /// The stream dictionary. /// The absolute offset of the first data byte. diff --git a/src/Broadside/IO/StreamSource.cs b/src/Broadside/IO/StreamSource.cs index 11d21586..763f6502 100644 --- a/src/Broadside/IO/StreamSource.cs +++ b/src/Broadside/IO/StreamSource.cs @@ -20,8 +20,10 @@ internal sealed class StreamSource : PdfSource /// Initializes a new instance of the class over from its current position. /// The stream; seekable and readable. /// Whether the source disposes the stream. - public StreamSource(Stream stream, bool ownsStream) + /// The first window a growing read asks for (). + public StreamSource(Stream stream, bool ownsStream, int initialWindow = 64 * 1024) { + InitialWindow = initialWindow; _stream = stream; _ownsStream = ownsStream; _start = stream.Position; @@ -31,6 +33,9 @@ public StreamSource(Stream stream, bool ownsStream) /// public override long Length => _length; + /// + public override int InitialWindow { get; } + /// public override int Read(long offset, Span destination) { diff --git a/src/Broadside/Parsing/CrossReferenceReader.cs b/src/Broadside/Parsing/CrossReferenceReader.cs index feed3995..7ed45179 100644 --- a/src/Broadside/Parsing/CrossReferenceReader.cs +++ b/src/Broadside/Parsing/CrossReferenceReader.cs @@ -195,7 +195,7 @@ private static bool TryReadStartxref(PdfSource source, FileHeader header, Diagno window = window[first.Start..]; } - return isTable ? XrefTableReader.Read(window, offset, diagnostics) : XrefStreamReader.Read(source, offset, streams, diagnostics); + return isTable ? ReadTable(source, offset, diagnostics) : XrefStreamReader.Read(source, offset, streams, diagnostics); } string stated = isFirst ? "startxref" : "Prev"; @@ -255,6 +255,46 @@ void Consider(long candidate) } } + /// + /// Reads the table section at in a window large enough for all of it, whatever its size: a windowed + /// source is read again in a larger window while the section does not end inside the window (issue #45). Deviations are held + /// back until the window is known to be large enough, so a window boundary is never reported as damage. + /// + private static XrefSection? ReadTable(PdfSource source, long offset, DiagnosticSink diagnostics) => + source.ReadGrowing(offset, (ReadOnlySpan window, bool final, out XrefSection? section) => + { + var attempt = new DiagnosticSink(strict: false); + DiagnosticException? failure = null; + try + { + section = XrefTableReader.Read(window, offset, attempt); + } + catch (DiagnosticException exception) + { + failure = exception; + section = null; + } + + // The token after the section must be in the window too: a trailer dictionary followed by "stream" is not a trailer. + Diagnostic[] found = attempt.Snapshot(); + if (!final && (found.Length > 0 || section is null || !StructureTokens.NextTokenEndsInside(window, (int)(section.End - offset)))) + { + return false; + } + + foreach (Diagnostic diagnostic in found) + { + diagnostics.Report(diagnostic.Code, diagnostic.Severity, diagnostic.Message, diagnostic.Offset, diagnostic.ObjectReference); + } + + if (failure is not null) + { + throw failure; + } + + return true; + }); + /// /// Reads the cross-reference stream a hybrid file's table names through its trailer's XRefStm entry (§7.5.8.4, Table 19). /// diff --git a/src/Broadside/Parsing/CrossReferenceReconstructor.cs b/src/Broadside/Parsing/CrossReferenceReconstructor.cs index 0630f33b..ba578f6c 100644 --- a/src/Broadside/Parsing/CrossReferenceReconstructor.cs +++ b/src/Broadside/Parsing/CrossReferenceReconstructor.cs @@ -210,8 +210,15 @@ private static bool AddObjectStreamMembers( var candidates = new List<(long Offset, CosDictionary Trailer)>(); foreach (long keyword in scan.TrailerKeywords) { - ReadOnlySpan window = source.GetWindow(keyword + "trailer"u8.Length).Span; - if (new CosParser(window, new CosRepairLog()).ParseObject() is CosDictionary trailer) + // A windowed source reads again in a larger window while the dictionary does not end inside it (issue #45). + CosObject parsed = source.ReadGrowing(keyword + "trailer"u8.Length, (ReadOnlySpan window, bool final, out CosObject value) => + { + var repairs = new CosRepairLog(); + var parser = new CosParser(window, repairs); + value = parser.ParseObject(); + return final || (repairs.Count == 0 && StructureTokens.NextTokenEndsInside(window, parser.Position)); + }); + if (parsed is CosDictionary trailer) { candidates.Add((keyword, trailer)); } diff --git a/src/Broadside/Parsing/ObjectLoader.cs b/src/Broadside/Parsing/ObjectLoader.cs index 55f304bd..3cafc88e 100644 --- a/src/Broadside/Parsing/ObjectLoader.cs +++ b/src/Broadside/Parsing/ObjectLoader.cs @@ -346,7 +346,7 @@ private CosObject LoadMisplaced(in ObjectLoadContext context) private CosObject ParseIndirectObject(in ObjectLoadContext context) { long available = _source.Length - context.Offset; - int minimum = InitialObjectWindow; + int minimum = Math.Min(InitialObjectWindow, _source.InitialWindow); while (true) { ReadOnlyMemory window = _source.GetWindow(context.Offset, minimum); @@ -373,7 +373,8 @@ private CosObject ParseIndirectObject(in ObjectLoadContext context) || number != context.Reference.ObjectNumber || generation != context.Reference.Generation) { - return LoadMisplaced(context); + // A header cut off by the end of a window that is not final is read again in a larger one. + return !final && lexer.Position >= window.Length ? null : LoadMisplaced(context); } lexer.SkipWhitespaceAndComments(); @@ -385,7 +386,8 @@ private CosObject ParseIndirectObject(in ObjectLoadContext context) lexer.Position = parser.Position; CosToken end = lexer.Next(); bool ended = StructureTokens.IsKeyword(window, end, "endobj"u8); - if (!final && (!ended || repairs.Count > 0)) + // Not final: read again in a larger window unless the object, and the token after it, end inside this one. + if (!final && (!ended || repairs.Count > 0 || end.End >= window.Length)) { return null; } diff --git a/src/Broadside/Parsing/StructureTokens.cs b/src/Broadside/Parsing/StructureTokens.cs index 9566940a..da7b30a5 100644 --- a/src/Broadside/Parsing/StructureTokens.cs +++ b/src/Broadside/Parsing/StructureTokens.cs @@ -6,6 +6,19 @@ namespace Broadside.Parsing; /// Reads the tokens of file structure (§7.5): unsigned integers and keywords, from a . internal static class StructureTokens { + /// + /// Returns whether the token after starts and ends inside , so what was + /// parsed up to cannot depend on bytes past the window (issue #45: windowed sources). + /// + /// The window. + /// Where the parse ended. + /// when a whole token follows inside the window. + public static bool NextTokenEndsInside(ReadOnlySpan window, int position) + { + CosToken next = new CosLexer(window, position).Next(); + return next.Kind != CosTokenKind.EndOfInput && next.End < window.Length; + } + /// Reads the next token as an unsigned decimal integer. /// The lexer; advanced past the token whether or not it is an integer. /// The value. diff --git a/src/Broadside/Parsing/XrefStreamReader.cs b/src/Broadside/Parsing/XrefStreamReader.cs index 8abd8d7f..57ea6598 100644 --- a/src/Broadside/Parsing/XrefStreamReader.cs +++ b/src/Broadside/Parsing/XrefStreamReader.cs @@ -95,7 +95,10 @@ private static CosDictionary Trailer(CosDictionary dictionary) return CosDictionary.FromOwnedEntries(trailer); } - /// Parses N G obj stream endobj at (§7.3.10). + /// + /// Parses N G obj stream endobj at (§7.3.10), in a window that grows while the object + /// does not end inside it (a windowed source, issue #45). + /// private static bool TryParseStreamObject( PdfSource source, long offset, @@ -104,10 +107,35 @@ private static bool TryParseStreamObject( out CosReference? reference, out long end) { + (bool parsed, CosStream? value, CosReference? number, long objectEnd) = source.ReadGrowing( + offset, + (ReadOnlySpan window, bool final, out (bool, CosStream?, CosReference?, long) result) => + { + bool done = TryParseStreamObject(window, final, offset, diagnostics, out bool ok, out CosStream? s, out CosReference? r, out long e); + result = (ok, s, r, e); + return done; + }); + stream = value; + reference = number; + end = objectEnd; + return parsed && stream is not null; + } + + /// One attempt of ; asks for a larger window. + private static bool TryParseStreamObject( + ReadOnlySpan window, + bool final, + long offset, + DiagnosticSink diagnostics, + out bool parsed, + out CosStream? stream, + out CosReference? reference, + out long end) + { + parsed = false; stream = null; reference = null; end = offset; - ReadOnlySpan window = source.GetWindow(offset).Span; var lexer = new CosLexer(window); if (!StructureTokens.TryReadUnsigned(ref lexer, out long number) || !StructureTokens.TryReadUnsigned(ref lexer, out long generation) @@ -115,23 +143,36 @@ private static bool TryParseStreamObject( || number is 0 or > int.MaxValue || generation > CosReference.MaxGeneration) { + if (!final && lexer.Position >= window.Length) + { + // The header is cut off by the end of the window: read again in a larger one. + return false; + } + Report(diagnostics, DiagnosticCodes.XrefSectionInvalid, DiagnosticSeverity.Error, "Expected the xref keyword or the header of a cross-reference stream object.", offset, null); - return false; + return true; } reference = new CosReference((int)number, (int)generation); var repairs = new CosRepairLog(keepAll: true); var parser = new CosParser(window, repairs, lexer.Position); CosObject value = parser.ParseObject(); + var after = new CosLexer(window, parser.Position); + CosToken next = after.Next(); + if (!final && (repairs.Count > 0 || value is not CosStream || !StructureTokens.IsKeyword(window, next, "endobj"u8) || next.End >= window.Length)) + { + return false; + } + foreach (CosRepair repair in repairs.All) { diagnostics.Report(repair.Code, DiagnosticSeverity.Warning, repair.Message, offset + repair.Offset, reference); } - if (value is not CosStream parsed) + if (value is not CosStream parsedStream) { Report(diagnostics, DiagnosticCodes.XrefSectionInvalid, DiagnosticSeverity.Error, "The object at the cross-reference offset is not a stream.", offset, reference); - return false; + return true; } lexer.Position = parser.Position; @@ -146,7 +187,8 @@ private static bool TryParseStreamObject( end = offset + parser.Position; } - stream = parsed; + stream = parsedStream; + parsed = true; return true; } diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 66dddaf9..d9abe32d 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -109,6 +109,14 @@ private static void WindowedDocument(ReadOnlySpan data) { throw new InvalidOperationException($"Reading in windows differs from reading the whole file:\n{whole}\n---\n{windowed}"); } + + // Windows that start at 16 bytes and double: every object and section is read through the growth paths. + using var tiny = new MemoryStream(bytes, writable: false); + string grown = ReadEverything(() => PdfDocument.Read(new StreamSource(tiny, ownsStream: false, initialWindow: 16), EngineConfiguration.From(new PdfOptions()))); + if (whole != grown) + { + throw new InvalidOperationException($"Reading in growing windows differs from reading the whole file:\n{whole}\n---\n{grown}"); + } } private static string ReadEverything(Func open) diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index b45b574b..831262ab 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in growing windows, and requires both to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. diff --git a/tests/Broadside.Tests/Document/SourceTests.cs b/tests/Broadside.Tests/Document/SourceTests.cs index 4372a8d3..c5d2fb1d 100644 --- a/tests/Broadside.Tests/Document/SourceTests.cs +++ b/tests/Broadside.Tests/Document/SourceTests.cs @@ -11,6 +11,9 @@ public class SourceTests { private const int ContentLength = 64 * 1024; + /// The window a windowed source first reads a structure in, before #45 grew it: 4 MiB. + private const int PdfSectionBound = 4 << 20; + [Fact] public void A_seekable_stream_is_read_in_place_only_where_objects_are_needed() { @@ -46,6 +49,56 @@ public void An_object_larger_than_the_first_read_of_a_stream_is_read_whole() Assert.Empty(document.Diagnostics); } + [Fact] + public void A_cross_reference_table_larger_than_4_MiB_is_read_whole_through_a_seekable_stream() + { + // 300 000 entries of 20 bytes: a 6 MB section, whose last entry names the object resolved here. + const int last = 300_000; + var text = new System.Text.StringBuilder("%PDF-1.7\n"); + var offsets = new int[last + 1]; + string[] bodies = [.. XrefStreamPdf.OnePage]; + for (int index = 0; index < bodies.Length; index++) + { + offsets[index + 1] = text.Length; + text.Append(System.Globalization.CultureInfo.InvariantCulture, $"{index + 1} 0 obj\n{bodies[index]}\nendobj\n"); + } + + offsets[last] = text.Length; + text.Append(System.Globalization.CultureInfo.InvariantCulture, $"{last} 0 obj\n(the last object)\nendobj\n"); + int xref = text.Length; + text.Append(System.Globalization.CultureInfo.InvariantCulture, $"xref\n0 {last + 1}\n0000000000 65535 f \n"); + for (int number = 1; number <= last; number++) + { + text.Append(offsets[number] > 0 ? $"{offsets[number]:D10} 00000 n \n" : "0000000000 00001 f \n"); + } + + text.Append(System.Globalization.CultureInfo.InvariantCulture, $"trailer\n<< /Size {last + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n"); + byte[] file = System.Text.Encoding.Latin1.GetBytes(text.ToString()); + Assert.True(file.Length - xref > PdfSectionBound, $"The section is {file.Length - xref} bytes."); + + AssertLastObjectReads(file, last); + } + + [Fact] + public void A_cross_reference_stream_larger_than_4_MiB_is_read_whole_through_a_seekable_stream() + { + // 800 000 unfiltered rows of 7 bytes: a 5.6 MB stream, whose last row places the object resolved here. + const int last = 800_000; + int[] widths = [1, 4, 2]; + var pdf = new XrefStreamPdf().AddOnePage().Add(last, "(the last object)"); + var rows = new (long Type, long Field2, long Field3)[last + 2]; + rows[0] = (0, 0, 65535); + for (int number = 1; number <= last; number++) + { + rows[number] = number is <= 3 or last ? (1, pdf.Offset(number), 0) : (0, 0, 1); + } + + rows[last + 1] = (1, pdf.Position, 0); + byte[] file = pdf.Finish(last + 1, $"/Size {last + 2} /Root 1 0 R /W [1 4 2]", widths, rows); + + AssertLastObjectReads(file, last); + } + [Fact] public void A_stream_is_read_from_its_position_when_opened() { @@ -153,6 +206,24 @@ public void Stream_data_of_a_document_opened_from_bytes_refers_to_those_bytes() Assert.Same(file, segment.Array); } + /// + /// Opens through a seekable stream that is not a (read in windows) and from + /// bytes, and requires both to resolve object with no diagnostic. + /// + private static void AssertLastObjectReads(byte[] file, int last) + { + using var stream = new ProbeStream(file); + using PdfDocument windowed = PdfDocument.Open(stream); + using PdfDocument whole = PdfDocument.Open(file); + + foreach (PdfDocument document in (PdfDocument[])[windowed, whole]) + { + Assert.Equal("the last object", Assert.IsType(document.Resolve(new CosReference(last, 0))).DecodeText()); + Assert.Single(document.Pages); + Assert.Empty(document.Diagnostics); + } + } + /// A file of pages, each with a content stream of bytes. internal static byte[] LargePages(int pageCount) { From 70140fb9e1d0695b6db92fc57e32b17a719b9413 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 15:08:47 -0500 Subject: [PATCH 014/152] feat(security): standard security handler, all revisions, AES-GCM and integrity MAC (#42) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Encrypted documents open transparently with the default user password, a user password or the owner password: ISO 32000-2 §7.6.1-7.6.4 and §7.6.6 (revisions 2-6, RC4, AES-128, AES-256, crypt filters, EncryptMetadata), ISO/TS 32003 (V 6 / R 7, AES-256-GCM) and ISO/TS 32004 (standalone and signature-attached PDF MAC tokens). - Security handler extension point (ISecurityHandler, registered through PdfOptions.UseSecurityHandler, chosen by Filter or SubFilter); the standard handler is the default and only authenticates; the engine applies Algorithm 1/1.A/GCM per string and stream in loader hook 2. - Distinct PdfPasswordException (Required/Incorrect) and PdfEncryptionNotSupportedException; PdfDocument.Security/Permissions. - RC4 managed; MD5, AES, AES-GCM from the BCL with managed fallbacks where the platform has none; RFC 3394 key wrap managed. - Corpus: R3 40-bit, crypt filters, AES-GCM, MAC (+ tampered copy), owner-key variant, and a password-protected table. - Fuzz targets encrypted-document, decrypt, mac-token; SecurityBenchmarks. - Conformance: 7.4.10, 7.6.1-7.6.7 rows; ISO/TS 32003 and 32004. Co-Authored-By: Claude Opus 5.5 --- .../SecurityBenchmarks.cs | 102 +++ docs/conformance/iso-32000-2.md | 12 +- docs/conformance/iso-ts-32003.md | 6 +- docs/conformance/iso-ts-32004.md | 18 +- src/Broadside/EngineConfiguration.cs | 8 + src/Broadside/Filters/ICryptFilterHandler.cs | 5 +- src/Broadside/Objects/CosArray.cs | 5 + src/Broadside/Objects/CosDictionary.cs | 10 + src/Broadside/Objects/CosStream.cs | 8 + src/Broadside/Objects/KnownNames.cs | 12 + src/Broadside/Objects/TextStringDecoder.cs | 3 + src/Broadside/Parsing/DiagnosticCodes.cs | 21 + src/Broadside/PdfAccessLevel.cs | 12 + src/Broadside/PdfDocument.cs | 55 +- src/Broadside/PdfEngine.cs | 51 ++ src/Broadside/PdfIntegrityStatus.cs | 21 + src/Broadside/PdfOptions.cs | 49 ++ src/Broadside/PdfPermissions.cs | 47 ++ src/Broadside/PdfSecurity.cs | 85 +++ src/Broadside/PublicAPI.Unshipped.txt | 95 +++ .../Security/Cryptography/AesCipher.cs | 134 ++++ .../Security/Cryptography/AesGcmCipher.cs | 154 +++++ .../Security/Cryptography/AesKeyWrap.cs | 89 +++ .../Cryptography/CryptographyBackend.cs | 38 ++ .../Security/Cryptography/ManagedAes.cs | 242 +++++++ src/Broadside/Security/Cryptography/Md5.cs | 135 ++++ src/Broadside/Security/Cryptography/Rc4.cs | 44 ++ src/Broadside/Security/DocumentDecryptor.cs | 626 ++++++++++++++++++ src/Broadside/Security/DocumentSecurity.cs | 173 +++++ src/Broadside/Security/ISecurityHandler.cs | 132 ++++ src/Broadside/Security/IntegrityVerifier.cs | 615 +++++++++++++++++ src/Broadside/Security/PasswordEncoding.cs | 206 ++++++ src/Broadside/Security/PdfCredentials.cs | 65 ++ .../Security/PdfPasswordException.cs | 100 +++ .../Security/SecurityHandlerRegistry.cs | 60 ++ .../Security/StandardSecurityHandler.cs | 576 ++++++++++++++++ tests/Broadside.Fuzz/FuzzTargets.cs | 112 ++++ tests/Broadside.Fuzz/README.md | 4 +- tests/Broadside.TestSupport/Corpus.cs | 20 +- .../Document/ConcurrencyTests.cs | 15 +- .../Filters/CorpusFilterTests.cs | 2 - .../Security/CryptFilterTests.cs | 174 +++++ .../Security/CryptographyTests.cs | 205 ++++++ .../Security/DecryptionAllocationTests.cs | 56 ++ .../Security/EncryptedCorpusTests.cs | 201 ++++++ .../Security/IntegrityTests.cs | 127 ++++ .../Broadside.Tests/Security/PasswordTests.cs | 145 ++++ .../SecurityHandlerExtensionPointTests.cs | 169 +++++ .../Security/SignatureIntegrityTests.cs | 184 +++++ ...pus_file_names_match_snapshot.verified.txt | 8 + tests/Broadside.Tests/Writing/SaveTests.cs | 4 +- tests/Corpus/README.md | 17 +- tests/Corpus/encrypted-aes-gcm.pdf | Bin 0 -> 1774 bytes tests/Corpus/encrypted-crypt-filters.pdf | Bin 0 -> 2158 bytes tests/Corpus/encrypted-mac-tampered.pdf | Bin 0 -> 2505 bytes tests/Corpus/encrypted-mac.pdf | Bin 0 -> 2505 bytes tests/Corpus/encrypted-owner-key-variant.pdf | Bin 0 -> 957 bytes tests/Corpus/encrypted-rc4-40-r3.pdf | Bin 0 -> 941 bytes tests/Corpus/encrypted-rc4-user-password.pdf | Bin 0 -> 1026 bytes tests/Corpus/encrypted-user-password.pdf | Bin 0 -> 1447 bytes tests/Corpus/generate.py | 340 +++++++++- tests/README.md | 2 +- 62 files changed, 5752 insertions(+), 47 deletions(-) create mode 100644 bench/Broadside.Benchmarks/SecurityBenchmarks.cs create mode 100644 src/Broadside/PdfAccessLevel.cs create mode 100644 src/Broadside/PdfIntegrityStatus.cs create mode 100644 src/Broadside/PdfPermissions.cs create mode 100644 src/Broadside/PdfSecurity.cs create mode 100644 src/Broadside/Security/Cryptography/AesCipher.cs create mode 100644 src/Broadside/Security/Cryptography/AesGcmCipher.cs create mode 100644 src/Broadside/Security/Cryptography/AesKeyWrap.cs create mode 100644 src/Broadside/Security/Cryptography/CryptographyBackend.cs create mode 100644 src/Broadside/Security/Cryptography/ManagedAes.cs create mode 100644 src/Broadside/Security/Cryptography/Md5.cs create mode 100644 src/Broadside/Security/Cryptography/Rc4.cs create mode 100644 src/Broadside/Security/DocumentDecryptor.cs create mode 100644 src/Broadside/Security/DocumentSecurity.cs create mode 100644 src/Broadside/Security/ISecurityHandler.cs create mode 100644 src/Broadside/Security/IntegrityVerifier.cs create mode 100644 src/Broadside/Security/PasswordEncoding.cs create mode 100644 src/Broadside/Security/PdfCredentials.cs create mode 100644 src/Broadside/Security/PdfPasswordException.cs create mode 100644 src/Broadside/Security/SecurityHandlerRegistry.cs create mode 100644 src/Broadside/Security/StandardSecurityHandler.cs create mode 100644 tests/Broadside.Tests/Security/CryptFilterTests.cs create mode 100644 tests/Broadside.Tests/Security/CryptographyTests.cs create mode 100644 tests/Broadside.Tests/Security/DecryptionAllocationTests.cs create mode 100644 tests/Broadside.Tests/Security/EncryptedCorpusTests.cs create mode 100644 tests/Broadside.Tests/Security/IntegrityTests.cs create mode 100644 tests/Broadside.Tests/Security/PasswordTests.cs create mode 100644 tests/Broadside.Tests/Security/SecurityHandlerExtensionPointTests.cs create mode 100644 tests/Broadside.Tests/Security/SignatureIntegrityTests.cs create mode 100644 tests/Corpus/encrypted-aes-gcm.pdf create mode 100644 tests/Corpus/encrypted-crypt-filters.pdf create mode 100644 tests/Corpus/encrypted-mac-tampered.pdf create mode 100644 tests/Corpus/encrypted-mac.pdf create mode 100644 tests/Corpus/encrypted-owner-key-variant.pdf create mode 100644 tests/Corpus/encrypted-rc4-40-r3.pdf create mode 100644 tests/Corpus/encrypted-rc4-user-password.pdf create mode 100644 tests/Corpus/encrypted-user-password.pdf diff --git a/bench/Broadside.Benchmarks/SecurityBenchmarks.cs b/bench/Broadside.Benchmarks/SecurityBenchmarks.cs new file mode 100644 index 00000000..7b6d4cb5 --- /dev/null +++ b/bench/Broadside.Benchmarks/SecurityBenchmarks.cs @@ -0,0 +1,102 @@ +using BenchmarkDotNet.Attributes; +using Broadside.Objects; +using Broadside.Security; +using Broadside.Security.Cryptography; +using Broadside.TestSupport; + +namespace Broadside.Benchmarks; + +/// +/// The decryption hot paths over 64 KB (ISO 32000-2 §7.6.3; ISO/TS 32003 §5.2): RC4 and AES-CBC with the platform's and the managed +/// AES, AES-GCM, and the revision 6 key derivation (Algorithm 2.B). RC4 and the cipher calls into a reused buffer must read +/// Allocated -; Broadside.Tests.Security.DecryptionAllocationTests fails the build otherwise. +/// +[MemoryDiagnoser] +public class SecurityBenchmarks +{ + private const int Length = 64 * 1024; + + private readonly byte[] _key = [.. Enumerable.Range(0, 32).Select(i => (byte)i)]; + private readonly byte[] _iv = new byte[16]; + private readonly byte[] _nonce = new byte[12]; + private readonly byte[] _tag = new byte[16]; + private readonly byte[] _output = new byte[Length]; + private byte[] _data = []; + private byte[] _gcmCiphertext = []; + private AesCipher? _platformAes; + private AesCipher? _managedAes; + + [GlobalSetup] + public void Setup() + { + _data = FilterEncoders.SampleData(Length, alphabet: 256); + _platformAes = AesCipher.Create(_key); + using (CryptographyBackend.ForceManaged()) + { + _managedAes = AesCipher.Create(_key); + } + + _gcmCiphertext = new byte[Length]; + AesGcmCipher.Encrypt(_key, _nonce, _data, _gcmCiphertext, _tag); + } + + [GlobalCleanup] + public void Cleanup() + { + _platformAes?.Dispose(); + _managedAes?.Dispose(); + } + + [Benchmark] + public byte Rc4Decrypt() + { + Rc4.Transform(_key.AsSpan(0, 16), _data, _output); + return _output[^1]; + } + + [Benchmark] + public byte AesCbcDecrypt() + { + _platformAes!.DecryptCbc(_data, _iv, _output); + return _output[^1]; + } + + [Benchmark] + public byte ManagedAesCbcDecrypt() + { + _managedAes!.DecryptCbc(_data, _iv, _output); + return _output[^1]; + } + + [Benchmark] + public bool AesGcmDecrypt() => AesGcmCipher.TryDecrypt(_key, _nonce, _gcmCiphertext, _tag, _output); + + [Benchmark] + public byte Revision6Hash() + { + Span hash = stackalloc byte[32]; + StandardSecurityHandler.HashRevision6("owner12345678"u8, "owner"u8, _key.AsSpan(0, 0), hash); + return hash[0]; + } +} + +/// Opening an encrypted corpus file and decrypting its content stream, end to end (ISO 32000-2 §7.6). +[MemoryDiagnoser] +public class EncryptedDocumentBenchmarks +{ + private static readonly CosName Contents = new("Contents"); + private byte[] _file = []; + + [Params("encrypted-rc4-128.pdf", "encrypted-aes-128.pdf", "encrypted-aes-256.pdf", "encrypted-aes-gcm.pdf", "encrypted-mac.pdf")] + public string File { get; set; } = string.Empty; + + [GlobalSetup] + public void Setup() => _file = System.IO.File.ReadAllBytes(Path.Combine(CorpusLocator.CorpusDirectory, File)); + + [Benchmark] + public int OpenAndDecryptContent() + { + using PdfDocument document = PdfDocument.Open(_file); + return document.DecodeStream((CosStream)document.Resolve(document.Pages[0].Dictionary[Contents])).Length; + } +} diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index 5bfb860e..ca8d4f85 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -28,16 +28,22 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.4.7 | JBIG2Decode filter | not started | | | Phase 2B (#64, #65); `FilterContext.DecodeStream` and `Resolve` serve JBIG2Globals | | 7.4.8 | DCTDecode filter | not started | | | Phase 2B (#61, #62) | | 7.4.9 | JPXDecode filter | not started | | | Phase 2B (#67, #68) | -| 7.4.10 | Crypt filter | partial | `StreamDecoder`, `ICryptFilterHandler` | `Broadside.Tests.Filters.FilterPipelineTests.The_identity_crypt_filter_passes_the_data_through`, `Broadside.Tests.Filters.FilterPipelineTests.A_crypt_filter_the_security_handler_does_not_know_leaves_the_data_encrypted_with_a_diagnostic`, `Broadside.Tests.Filters.FilterPipelineTests.A_crypt_filter_that_is_not_first_is_applied_where_it_is_with_a_diagnostic` | Slot only: Identity passes through, other crypt filter names are `CryptFilterUnsupported` until the security handler (#42) sets `StreamDecoder.CryptFilter` | +| 7.4.10 | Crypt filter | done | `StreamDecoder`, `ICryptFilterHandler`, `DocumentDecryptor` | `Broadside.Tests.Filters.FilterPipelineTests.The_identity_crypt_filter_passes_the_data_through`, `Broadside.Tests.Filters.FilterPipelineTests.A_crypt_filter_the_security_handler_does_not_know_leaves_the_data_encrypted_with_a_diagnostic`, `Broadside.Tests.Filters.FilterPipelineTests.A_crypt_filter_that_is_not_first_is_applied_where_it_is_with_a_diagnostic`, `Broadside.Tests.Security.CryptFilterTests.Each_content_stream_decrypts_with_the_crypt_filter_it_names_or_the_default_one`, `Broadside.Tests.Security.CryptFilterTests.A_stream_that_names_a_crypt_filter_the_document_does_not_define_is_left_encrypted_with_a_diagnostic` | The security handler decrypts a stream whose Filter starts with Crypt when its object loads, with the named crypt filter (DecodeParms Name, default Identity) and that filter's key used as is; for AES-128 data that does not decrypt that way, Algorithm 1's object key (what qpdf reads) is tried; the pipeline's Crypt stage then passes known names through and reports CryptFilterUnsupported for unknown ones | | 7.5.1 | General | done | `PdfDocument`, `CrossReferenceReader`, `PdfSource`, `MappedFileSource`, `StreamSource` | `Broadside.Tests.Document.OpenDocumentTests.A_file_opens_identically_from_a_path_a_stream_and_bytes_with_no_diagnostics`, `Broadside.Tests.Document.WellFormedCorpusTests.A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics`, `Broadside.Tests.Document.SourceTests.A_seekable_stream_is_read_in_place_only_where_objects_are_needed`, `Broadside.Tests.Document.SourceTests.A_non_seekable_stream_is_read_whole_when_opened`, `Broadside.Tests.Document.SourceTests.A_non_seekable_stream_longer_than_the_buffer_limit_is_read_through_a_temporary_file`, `Broadside.Tests.Document.SourceTests.OpenAsync_reads_a_non_seekable_stream_asynchronously`, `Broadside.Tests.Document.LargeFileTests.A_file_over_2_GiB_opens_and_reads_its_last_page_in_bounded_memory` | Read from the end through startxref, the cross-reference table and the trailer, never serially; linearized files read through the same path (Annex F). Sources (#45): bytes (zero-copy), paths and FileStreams memory-mapped, other seekable streams read in place under a lock in growing windows, non-seekable streams copied at open (memory up to `StreamBufferLimit`, then a temporary file; `OpenAsync` copies asynchronously); fuzz `windowed-document` | | 7.5.2 | File header | done | `FileHeader`, `PdfVersion`, `PdfDocument`, `FileWriter` | `Broadside.Tests.Document.FileStructureTests.Offsets_count_from_the_header_so_bytes_before_it_do_not_matter`, `Broadside.Tests.Document.FileStructureTests.A_file_without_a_header_opens_from_byte_0_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_header_without_a_valid_version_takes_the_catalog_version_with_a_diagnostic`, `Broadside.Tests.Document.RepairTests.Offsets_counted_from_byte_0_instead_of_the_header_are_repaired`, `Broadside.Tests.Writing.SaveTests.The_header_keeps_the_version_unless_the_layout_needs_a_later_one`, `Broadside.Tests.Writing.CreateTests.A_created_document_has_one_empty_letter_page_and_is_PDF_2_0` | Header searched in the first 1024 bytes; every stated offset is relative to it; missing header: offsets from byte 0, version 1.4 unless the catalog says otherwise; offsets a writer counted from byte 0 despite junk before the header are repaired by the nearest-section and object searches; written: `%PDF-n.m` LF, then a comment of four bytes above 127; the document version is kept and raised to 1.5 for cross-reference streams (ADR 0003); `Create` writes 2.0 (#44) | | 7.5.3 | File body | done | `ObjectLoader`, `FileWriter`, `ObjectCache`, `OnceCache` | `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_reopens_with_the_same_objects_and_no_diagnostics`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_passes_qpdf_check`, `Broadside.Tests.Document.LazyLoadingTests.Opening_a_file_parses_the_catalog_and_nothing_else`, `Broadside.Tests.Document.LazyLoadingTests.Every_object_is_parsed_once_however_many_threads_read_it`, `Broadside.Tests.Document.LazyLoadingTests.An_object_stream_is_decoded_once_however_many_threads_read_its_members`, `Broadside.Tests.Document.LazyLoadingTests.Two_threads_each_loading_a_stream_whose_Length_is_the_other_one_do_not_deadlock`, `Broadside.Tests.Document.ConcurrencyTests.Every_page_and_object_reads_the_same_from_many_threads_as_from_one` | Objects load lazily by cross-reference entry, from the file body or an object stream (7.5.7); a full save writes every in-use object of the newest revision, dropping only old cross-reference streams, object streams and linearization data that nothing refers to (#44), parsed once per (number, generation) and object streams decoded once, under the concurrency contract on `PdfDocument` (#45); stream data stays in the source and is read on access; parses traced at Trace level (`ObjectParsed`, `ObjectStreamDecoded`); `bench/Broadside.Benchmarks/LazyLoadingBenchmarks.cs` (cached resolve allocates nothing) | | 7.5.4 | Cross-reference table | done | `XrefTableReader`, `CrossReference`, `FileScan`, `CrossReferenceReconstructor`, `FileWriter` | `Broadside.Tests.Document.FileStructureTests.Entries_are_read_as_tokens_not_fixed_width_records`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_is_read_from_where_its_header_is_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation`, `Broadside.Tests.Document.RepairTests.Entries_that_are_not_20_bytes_long_are_read_with_one_diagnostic_per_section`, `Broadside.Tests.Document.RepairTests.A_subsection_numbered_from_1_whose_first_entry_is_the_free_list_head_is_renumbered_from_0`, `Broadside.Tests.Document.RepairTests.A_file_whose_line_endings_were_converted_to_crlf_opens_with_the_intact_pages`, `Broadside.Tests.Document.RepairTests.Rebuilding_an_updated_file_keeps_the_newest_copy_of_each_object_and_the_newest_trailer`, `Broadside.Tests.Document.RepairTests.A_repair_met_twice_is_recorded_once`, `Broadside.Tests.Document.BrokenCorpusTests.A_broken_file_opens_leniently_with_exactly_the_documented_diagnostics_and_the_intact_pages`, `Broadside.Tests.Document.BrokenCorpusTests.Strict_mode_throws_on_a_broken_file_with_the_code_of_its_first_diagnostic`, `Broadside.Tests.Writing.SaveTests.Startxref_gives_the_offset_of_the_cross_reference_information`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_passes_qpdf_check` | Subsections and n/f entries read as tokens; entries not 20 bytes long reported once per section (XrefEntryFormatInvalid); a subsection numbered from 1 whose first entry is the free-list head renumbered from 0 (XrefSubsectionNumberingInvalid); offset-0 in-use entries read as free; misplaced objects searched (7.3.10); an unreadable table is rebuilt by one windowed scan for N G obj headers (newest copy wins), object stream members and trailers (repair is informative, ADR 0005); comments inside a table are read silently; broken-xref-offsets.pdf, no-xref.pdf; fuzz `repair`; written as one subsection from 0 with 20-byte entries (CR LF), free entries linked from object 0 (generation 65535); offsets above ten digits refuse the table layout (#44) | -| 7.5.5 | File trailer | partial | `CrossReferenceReader`, `CrossReference`, `PdfDocument`, `CrossReferenceReconstructor`, `FileWriter` | `Broadside.Tests.Document.FileStructureTests.A_startxref_offset_on_the_white_space_before_xref_is_repaired_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_file_with_no_startxref_is_rebuilt_by_scanning_and_keeps_its_trailer`, `Broadside.Tests.Document.FileStructureTests.A_trailer_without_root_is_repaired_by_finding_the_catalog_by_scanning`, `Broadside.Tests.Document.FileStructureTests.A_prev_chain_that_loops_ends_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic`, `Broadside.Tests.Document.RepairTests.A_wrong_prev_offset_reads_the_nearest_older_section`, `Broadside.Tests.Document.RepairTests.Rebuilding_an_encrypted_file_keeps_its_encryption_dictionary_and_identifier`, `Broadside.Tests.Document.RepairTests.A_compressed_catalog_is_found_when_no_trailer_survives`, `Broadside.Tests.Document.RepairTests.A_file_with_nothing_but_junk_cannot_be_read`, `Broadside.Tests.Document.BrokenCorpusTests.A_broken_file_opens_leniently_with_exactly_the_documented_diagnostics_and_the_intact_pages`, `Broadside.Tests.Writing.SaveTests.Saving_an_updated_file_collapses_its_revisions_into_one_with_the_newest_objects`, `Broadside.Tests.Writing.SaveTests.Startxref_gives_the_offset_of_the_cross_reference_information` | Last startxref, Prev chain with loop guard, Root; trailer merged newest-first; a startxref or Prev offset at neither xref nor N G obj reads the nearest section (table wins ties, never one already read); missing or unusable startxref, or a Root that does not lead to the catalog, rebuilds the cross-reference from a scan: newest trailer or xref-stream dictionary whose Root leads to a catalog, Encrypt/ID/Info from any trailer, else the newest /Catalog (TrailerMissing or RootMissing); no catalog at all throws CatalogNotFound; startxref-wrong.pdf, no-xref.pdf; ignoring entries beyond Size is not done; Encrypt is #42; written trailer: Size, the source trailer without Size, Prev, XRefStm and ID, then ID; startxref and %%EOF (#44) | +| 7.5.5 | File trailer | partial | `CrossReferenceReader`, `CrossReference`, `PdfDocument`, `CrossReferenceReconstructor`, `FileWriter` | `Broadside.Tests.Document.FileStructureTests.A_startxref_offset_on_the_white_space_before_xref_is_repaired_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_file_with_no_startxref_is_rebuilt_by_scanning_and_keeps_its_trailer`, `Broadside.Tests.Document.FileStructureTests.A_trailer_without_root_is_repaired_by_finding_the_catalog_by_scanning`, `Broadside.Tests.Document.FileStructureTests.A_prev_chain_that_loops_ends_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic`, `Broadside.Tests.Document.RepairTests.A_wrong_prev_offset_reads_the_nearest_older_section`, `Broadside.Tests.Document.RepairTests.Rebuilding_an_encrypted_file_keeps_its_encryption_dictionary_and_identifier`, `Broadside.Tests.Document.RepairTests.A_compressed_catalog_is_found_when_no_trailer_survives`, `Broadside.Tests.Document.RepairTests.A_file_with_nothing_but_junk_cannot_be_read`, `Broadside.Tests.Document.BrokenCorpusTests.A_broken_file_opens_leniently_with_exactly_the_documented_diagnostics_and_the_intact_pages`, `Broadside.Tests.Writing.SaveTests.Saving_an_updated_file_collapses_its_revisions_into_one_with_the_newest_objects`, `Broadside.Tests.Writing.SaveTests.Startxref_gives_the_offset_of_the_cross_reference_information` | Last startxref, Prev chain with loop guard, Root; trailer merged newest-first; a startxref or Prev offset at neither xref nor N G obj reads the nearest section (table wins ties, never one already read); missing or unusable startxref, or a Root that does not lead to the catalog, rebuilds the cross-reference from a scan: newest trailer or xref-stream dictionary whose Root leads to a catalog, Encrypt/ID/Info from any trailer, else the newest /Catalog (TrailerMissing or RootMissing); no catalog at all throws CatalogNotFound; startxref-wrong.pdf, no-xref.pdf; ignoring entries beyond Size is not done; Encrypt and ID are read from the newest trailer (#42); written trailer: Size, the source trailer without Size, Prev, XRefStm and ID, then ID; startxref and %%EOF (#44) | | 7.5.6 | Incremental updates | done | `CrossReference`, `RevisionReader`, `PdfRevision`, `PdfDocument` | `Broadside.Tests.Document.IncrementalUpdateTests.An_updated_file_has_one_revision_per_update_and_the_first_is_the_original_file`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_is_the_file_as_it_was_after_that_save`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_has_its_own_trailer`, `Broadside.Tests.Document.IncrementalUpdateTests.A_hybrid_file_has_its_main_section_and_its_update_section_as_two_revisions`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_earlier_revision_without_its_end_of_file_marker_ends_after_its_startxref_offset_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`, `Broadside.Tests.Writing.SaveTests.Saving_an_updated_file_collapses_its_revisions_into_one_with_the_newest_objects` | Revisions oldest first, each the byte prefix up to its %%EOF and end-of-line; newest section decides per object number, free hides older copies, a reference must match the live generation; Root, Info, Encrypt and ID missing from the newest trailer are taken from an older one with TrailerEntryFromOlderRevision; a linearized pair is one revision; a hybrid XRefStm stream joins its table's revision; a full save collapses the revisions into one (#44); writing an incremental update is Phase 4 | | 7.5.7 | Object streams | done | `ObjectStream`, `ObjectLoader`, `FileWriter` | `Broadside.Tests.Document.ObjectStreamTests.The_catalog_page_tree_and_page_resolve_from_an_object_stream`, `Broadside.Tests.Document.ObjectStreamTests.A_reference_to_a_member_with_a_generation_other_than_0_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.Members_need_no_white_space_between_them`, `Broadside.Tests.Document.ObjectStreamTests.A_member_at_another_index_than_its_entry_says_is_found_by_its_object_number`, `Broadside.Tests.Document.ObjectStreamTests.Offsets_out_of_order_bound_each_member_by_the_next_offset_in_sorted_order`, `Broadside.Tests.Document.ObjectStreamTests.A_member_the_object_stream_does_not_hold_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_whose_N_is_one_of_its_own_members_resolves_its_members_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_listed_as_compressed_itself_is_not_read`, `Broadside.Tests.Document.ObjectStreamTests.A_type_2_entry_naming_an_object_that_is_not_a_stream_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.A_flate_encoded_object_stream_is_decoded_through_the_filters`, `Broadside.Tests.Document.ObjectStreamTests.Members_of_one_object_stream_resolve_to_the_same_instances_from_concurrent_threads`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file`, `Broadside.Tests.Document.RepairTests.Objects_in_object_streams_survive_a_damaged_cross_reference_stream`, `Broadside.Tests.Writing.SaveTests.Objects_that_were_not_changed_keep_their_source_bytes_in_any_layout`, `Broadside.Tests.Writing.SaveTests.The_information_dictionary_of_a_hybrid_file_survives_from_its_object_stream` | Members located by type 2 entries (index checked against the header, searched by number when wrong, with ObjectStreamIndexMismatch); each member parsed over exactly the bytes up to the next offset (NOTE 7); out-of-order offsets sorted; container decoded once per document and shared, decrypted as a whole (members skip hooks 1 and 2); nested containers and self-referencing N/First/Filter end with ObjectStreamNested/ObjectStreamCycle; /Extends ignored (grouping only); object-stream.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `object-stream`; written by `PdfCrossReferenceLayout.StreamWithObjectStreams`: every object with generation 0 that is not a stream or a bare reference, at most 100 per Flate-encoded object stream; unchanged members keep their bytes (#44); a rebuilt cross-reference indexes the members of every object stream found by scanning (#41) | | 7.5.8 | Cross-reference streams | done | `XrefStreamReader`, `CrossReferenceReader`, `CrossReference`, `FileWriter`, `PdfCrossReferenceLayout` | `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file`, `Broadside.Tests.Document.CrossReferenceStreamTests.Strict_mode_opens_a_file_with_compressed_structures`, `Broadside.Tests.Document.CrossReferenceStreamTests.The_trailer_of_a_cross_reference_stream_is_its_dictionary_without_the_entries_that_describe_the_stream`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_type_field_makes_every_entry_type_1`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_generation_field_defaults_to_generation_0`, `Broadside.Tests.Document.CrossReferenceStreamTests.Index_with_two_subsections_numbers_the_entries_of_each_from_its_first_object_number`, `Broadside.Tests.Document.CrossReferenceStreamTests.Wide_fields_are_read_big_endian`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_entry_of_an_unknown_type_is_a_reference_to_the_null_object`, `Broadside.Tests.Document.CrossReferenceStreamTests.Data_shorter_than_the_entries_ends_the_section_where_the_data_ends`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_without_type_XRef_is_read_with_a_diagnostic`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_whose_W_cannot_be_read_is_not_a_cross_reference_section_so_the_file_is_rebuilt_by_scanning`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_update_written_as_a_cross_reference_stream_overrides_the_original_section`, `Broadside.Tests.Document.HybridFileTests.An_object_only_the_XRefStm_stream_lists_is_found`, `Broadside.Tests.Document.HybridFileTests.An_in_use_entry_in_the_table_of_a_section_takes_precedence_over_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.A_free_entry_in_the_table_of_a_section_gives_way_to_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.The_XRefStm_streams_dictionary_is_not_the_trailer_and_its_Prev_is_not_followed`, `Broadside.Tests.Document.HybridFileTests.An_XRefStm_offset_that_names_no_stream_is_reported_and_the_table_is_still_read`, `Broadside.Tests.Document.LinearizationTests.A_linearized_file_with_cross_reference_streams_has_its_first_page_and_main_streams_as_one_revision`, `Broadside.Tests.Writing.SaveTests.Startxref_gives_the_offset_of_the_cross_reference_information`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_passes_qpdf_check` | 7.5.8.1 to 7.5.8.4. W (0 to 8 bytes per field, W[0] = 0 means type 1), Index (default [0 Size]), Size, Prev; entries big-endian into long; type 0/1/2, other types are the null object; dictionary minus Type, Length, W, Index, Filter, DecodeParms, DL, F, FFilter, FDecodeParms is the trailer; data decoded through the filter pipeline under the engine's decoded-length limit, never decrypted; hybrid XRefStm read after its table and before Prev, its entries replacing the table's free entries (an in-use table entry wins), its own Prev not followed and its dictionary not a trailer; xref-stream.pdf, object-stream.pdf, png-predictor.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `xref-stream`; written by `PdfCrossReferenceLayout.Stream` and `StreamWithObjectStreams`: W [1 n 2] with n the fewest bytes for the largest offset, an entry for the stream itself, Flate with Predictor 12, trailer keys in its dictionary; hybrid files are not written (#44) | -| 7.6 | Encryption | not started | | | | +| 7.6.1 | General | done | `PdfDocument`, `PdfSecurity` | `Broadside.Tests.Security.EncryptedCorpusTests.An_encrypted_file_opens_with_the_empty_user_password_and_its_content_stream_decrypts`, `Broadside.Tests.Security.EncryptedCorpusTests.An_unencrypted_document_permits_everything` | An encrypted file opens transparently: `PdfDocument.IsEncrypted`, `PdfDocument.Security`, `PdfDocument.Permissions` | +| 7.6.2 | Application of encryption | done | `DocumentSecurity`, `DocumentDecryptor`, `SecurityHandlerRegistry`, `ISecurityHandler`, `SecurityHandlerContext`, `SecurityHandlerResult`, `PdfEncryptionNotSupportedException` | `Broadside.Tests.Security.EncryptedCorpusTests.Strings_are_decrypted_with_the_key_of_the_object_that_holds_them`, `Broadside.Tests.Security.EncryptedCorpusTests.The_encryption_dictionary_and_the_file_identifier_are_not_decrypted`, `Broadside.Tests.Security.EncryptedCorpusTests.Decrypting_marks_nothing_dirty`, `Broadside.Tests.Security.EncryptedCorpusTests.Concurrent_readers_see_the_same_decrypted_content`, `Broadside.Tests.Security.EncryptedCorpusTests.A_document_rebuilt_because_its_root_is_unusable_is_still_decrypted`, `Broadside.Tests.Security.EncryptedCorpusTests.A_document_whose_cross_reference_is_unreadable_is_rebuilt_and_decrypted`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.The_standard_handler_is_registered_by_default`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_handler_registered_for_standard_replaces_the_default`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.Two_engines_with_different_handlers_do_not_interfere`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_handler_that_supplies_the_key_another_way_decrypts_the_document`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_handler_is_chosen_by_subfilter_when_no_handler_has_the_filter_name`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_document_whose_handler_is_not_registered_is_not_supported` | Every string and stream is decrypted as its indirect object loads (hook 2), never the Encrypt dictionary, the trailer (ID, AuthCode), object-stream members (their container is decrypted), cross-reference streams or a signature dictionary's Contents; decryption never marks objects dirty; handler chosen by Filter, else by SubFilter (`PdfOptions.UseSecurityHandler`, standard handler by default); V 1-6 (V 3 read as V 2 with a diagnostic); newest trailer's Encrypt and ID; a missing ID is an empty identifier with EncryptionIdMissing; an Encrypt entry that does not resolve rebuilds the cross-reference (#41); fuzz `encrypted-document` | +| 7.6.3 | General encryption algorithm | done | `DocumentDecryptor`, `Rc4`, `AesCipher`, `ManagedAes`, `Md5`, `ManagedMd5`, `CryptographyBackend` | `Broadside.Tests.Security.EncryptedCorpusTests.The_managed_cryptography_decrypts_like_the_platform_cryptography`, `Broadside.Tests.Security.CryptFilterTests.Aes_data_with_a_damaged_pad_is_kept_whole_with_a_diagnostic`, `Broadside.Tests.Security.CryptographyTests.Managed_md5_matches_rfc_1321`, `Broadside.Tests.Security.CryptographyTests.Managed_md5_agrees_with_the_platform_at_every_padding_boundary`, `Broadside.Tests.Security.CryptographyTests.Managed_aes_matches_fips_197_appendix_c`, `Broadside.Tests.Security.CryptographyTests.Managed_aes_cbc_agrees_with_the_platform`, `Broadside.Tests.Security.CryptographyTests.Rc4_matches_the_published_vectors`, `Broadside.Tests.Security.DecryptionAllocationTests.Rc4_allocates_nothing`, `Broadside.Tests.Security.DecryptionAllocationTests.Aes_cbc_into_a_buffer_allocates_nothing_per_block` | 7.6.3.1 to 7.6.3.3. Algorithm 1 (RC4, AES-128-CBC with "sAlT") and 1.A (AES-256-CBC), IV prefix, PKCS#5 padding; damaged AES data repaired like pdf.js with EncryptedDataInvalid (too short: nothing; partial block dropped; bad pad kept); RC4 managed; MD5 and AES from the BCL, with managed MD5 and AES selected at run time where the platform has none (browser); `SecurityBenchmarks`; fuzz `decrypt` | +| 7.6.4 | Standard security handler | done | `StandardSecurityHandler`, `PasswordEncoding`, `PdfPassword`, `PdfCredentials`, `PdfPasswordException`, `PdfPermissions`, `PdfAccessLevel`, `PdfSecurity` | `Broadside.Tests.Security.EncryptedCorpusTests.An_encrypted_file_opens_with_the_owner_password_and_gives_owner_access`, `Broadside.Tests.Security.EncryptedCorpusTests.An_encrypted_file_opens_in_strict_mode`, `Broadside.Tests.Security.EncryptedCorpusTests.The_security_describes_the_algorithm_revision_and_key_length`, `Broadside.Tests.Security.PasswordTests.A_document_with_a_user_password_needs_a_password`, `Broadside.Tests.Security.PasswordTests.A_wrong_password_is_reported_as_incorrect`, `Broadside.Tests.Security.PasswordTests.The_user_password_opens_the_document_with_user_access`, `Broadside.Tests.Security.PasswordTests.The_owner_password_opens_the_document_with_owner_access`, `Broadside.Tests.Security.PasswordTests.User_access_has_the_permissions_the_document_grants`, `Broadside.Tests.Security.PasswordTests.A_revision_6_password_maps_soft_hyphens_to_nothing`, `Broadside.Tests.Security.PasswordTests.A_legacy_password_can_be_given_as_bytes_in_a_code_page`, `Broadside.Tests.Security.PasswordTests.A_wrong_password_for_a_document_without_a_user_password_is_still_incorrect`, `Broadside.Tests.Security.PasswordTests.The_password_given_to_open_overrides_the_one_on_the_options`, `Broadside.Tests.Security.PasswordTests.An_owner_password_computed_by_rehashing_only_the_key_length_is_accepted_with_a_diagnostic`, `Broadside.Tests.Security.PasswordTests.The_owner_key_variant_throws_in_strict_mode`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.The_standard_handler_reads_permissions_by_revision`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.An_undefined_revision_is_an_unsupported_algorithm`, `Broadside.Tests.Security.CryptographyTests.Saslprep_maps_like_rfc_4013`, `Broadside.Tests.Security.CryptographyTests.Saslprep_rejects_prohibited_characters` | 7.6.4.1 to 7.6.4.4. Revisions 2, 3, 4, 6 (and the deprecated 5, read with EncryptionRevisionInvalid); Algorithms 2, 2.A, 2.B, 3-7, 11-13; default user password first, then user, then owner (`PdfPasswordFailure.Required` / `Incorrect`); PDFDocEncoding then Latin-1 for R2-4, SASLprep + UTF-8 (127 bytes) then plain UTF-8 for R6 (bidi check not applied; NFKC needs platform globalization data); O/U/OE/UE/Perms lengths repaired with EncryptionEntryLengthInvalid; Algorithm 3 rehash-first-n variant accepted with OwnerPasswordKeyVariant (encrypted-owner-key-variant.pdf); Perms checked (EncryptionPermissionsMismatch, Perms wins); permissions by revision (Table 22); corpus encrypted-rc4-40, -rc4-128, -rc4-40-r3, -aes-128, -aes-256, -user-password, -rc4-user-password; writing encrypted files is Phase 4 | +| 7.6.5 | Public-key security handlers | not started | | | #43, through `ISecurityHandler` (`PdfCredentials` for certificates, `SecurityHandlerResult.CryptFilterKeys` for crypt filters with their own recipients) | +| 7.6.6 | Crypt filters | done | `DocumentDecryptor`, `CryptFilter`, `CryptMethod` | `Broadside.Tests.Security.CryptFilterTests.An_embedded_file_is_decrypted_with_eff_which_defaults_to_stmf`, `Broadside.Tests.Security.CryptFilterTests.Each_content_stream_decrypts_with_the_crypt_filter_it_names_or_the_default_one`, `Broadside.Tests.Security.CryptFilterTests.Metadata_is_left_as_it_is_when_encrypt_metadata_is_false`, `Broadside.Tests.Security.CryptFilterTests.The_owner_password_opens_a_document_whose_metadata_is_not_encrypted`, `Broadside.Tests.Security.CryptFilterTests.A_stream_that_names_a_crypt_filter_the_document_does_not_define_is_left_encrypted_with_a_diagnostic`, `Broadside.Tests.Security.CryptFilterTests.Metadata_in_plaintext_although_encrypt_metadata_is_true_is_read_as_it_is_with_a_diagnostic`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.An_unknown_crypt_filter_method_is_an_unsupported_algorithm` | CF, StmF, StrF, EFF (default StmF), Identity, CFM V2/AESV2/AESV3 (and AESV4, ISO/TS 32003); CFM None leaves data as is with CryptFilterMethodInvalid; AESV2 under V 5 read as AESV3 with a diagnostic; unknown CFM for StmF/StrF/EFF throws `PdfEncryptionNotSupportedException`; EncryptMetadata false leaves /Type /Metadata streams alone (plaintext XMP under EncryptMetadata true read with MetadataNotEncrypted); crypt filter Length not used (keys come from the handler); encrypted-crypt-filters.pdf | +| 7.6.7 | Unencrypted wrapper document | not started | | | Collections of encrypted payloads (PDF 2.0); a wrapper opens as an ordinary unencrypted document | | 7.7.1 | General | n/a | | | Introductory text | | 7.7.2 | Document catalog dictionary | partial | `PdfDocument`, `PdfVersion` | `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_catalog_version_written_as_a_number_is_read_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.A_malformed_catalog_version_is_ignored_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_catalog_without_its_type_is_read_with_a_diagnostic` | Type, Version (effective version = later of header and catalog) and Pages; the other Table 29 entries arrive with their features (outlines, names, AcroForm, ...) | | 7.7.3 | Page tree | done | `PdfPage`, `PdfPageCollection`, `PageTreeReader` | `Broadside.Tests.Document.OpenDocumentTests.Page_tree_inherited_pdf_pages_inherit_media_box_and_resources_from_the_intermediate_node`, `Broadside.Tests.Document.PageTreeTests.Pages_come_in_kids_order_depth_first_across_intermediate_nodes`, `Broadside.Tests.Document.PageTreeTests.The_nearest_ancestor_wins_and_values_are_inherited_as_is_without_merging`, `Broadside.Tests.Document.PageTreeTests.A_change_to_an_ancestor_node_shows_through_the_pages_that_inherit_from_it`, `Broadside.Tests.Document.PageTreeTests.Page_count_comes_from_the_kids_not_the_count_entry_which_is_checked`, `Broadside.Tests.Document.PageTreeTests.A_node_referenced_twice_is_read_once_with_a_diagnostic`, `Broadside.Tests.Document.PageAttributeTests.Crop_bleed_trim_and_art_boxes_default_to_the_media_box_through_the_crop_box`, `Broadside.Tests.Document.PageAttributeTests.Rotation_is_a_multiple_of_90_normalized_into_0_to_270` | 7.7.3.1 to 7.7.3.4: Kids walk with cycle guard, Count checked not trusted, Resources/MediaBox/CropBox/Rotate inherited as-is from the nearest node; page boxes, Rotate and UserUnit from Table 31; other Table 31 entries arrive with their features | diff --git a/docs/conformance/iso-ts-32003.md b/docs/conformance/iso-ts-32003.md index a7e9230b..d2daa5cd 100644 --- a/docs/conformance/iso-ts-32003.md +++ b/docs/conformance/iso-ts-32003.md @@ -4,6 +4,6 @@ Clause titles verified against the document's table of contents. Split rows to d | Clause | Title | Status | Implementing types | Tests | Notes | |---|---|---|---|---|---| -| 4 | Extension schema details | not started | | | | -| 5.1 | Encrypt dictionary (AESV4, revision 7) | not started | | | | -| 5.2 | Encryption of data using AES-GCM in PDF objects | not started | | | | +| 4 | Extension schema details | done | `DocumentSecurity` | `Broadside.Tests.Security.EncryptedCorpusTests.A_revision_7_document_without_the_32003_extension_is_read_with_a_diagnostic`, `Broadside.Tests.Security.EncryptedCorpusTests.Strings_are_decrypted_with_the_key_of_the_object_that_holds_them` | Reading checks that a V 6 document declares ExtensionLevel 32003 under ISO_ (EncryptionExtensionMissing, read anyway); writing is Phase 4 | +| 5.1 | Encrypt dictionary (AESV4, revision 7) | done | `StandardSecurityHandler`, `DocumentDecryptor` | `Broadside.Tests.Security.EncryptedCorpusTests.An_encrypted_file_opens_with_the_empty_user_password_and_its_content_stream_decrypts`, `Broadside.Tests.Security.EncryptedCorpusTests.An_encrypted_file_opens_with_the_owner_password_and_gives_owner_access`, `Broadside.Tests.Security.EncryptedCorpusTests.The_security_describes_the_algorithm_revision_and_key_length` | V 6, R 7 with the revision 6 password algorithms, CFM AESV4 (AESV4 under V 5 read with a diagnostic); encrypted-aes-gcm.pdf (no reference reader supports R 7: qpdf 12.4.2 and poppler refuse it; vectors self-tested in generate.py) | +| 5.2 | Encryption of data using AES-GCM in PDF objects | done | `DocumentDecryptor`, `AesGcmCipher` | `Broadside.Tests.Security.CryptFilterTests.Aes_gcm_data_that_fails_authentication_decrypts_to_nothing_with_an_error`, `Broadside.Tests.Security.CryptFilterTests.Damaged_ciphertext_throws_in_strict_mode`, `Broadside.Tests.Security.CryptographyTests.Managed_aes_gcm_matches_the_gcm_specification_test_cases_13_and_14`, `Broadside.Tests.Security.CryptographyTests.Managed_aes_gcm_agrees_with_the_platform_and_rejects_a_changed_tag` | 12-byte IV, ciphertext, 16-byte tag, no AAD, the file key for every object; a tag that does not authenticate decrypts to nothing with EncryptedDataAuthenticationFailed (Error); BCL AesGcm, managed GCM where the platform has none (browser, iOS/tvOS before 13); fuzz `decrypt` | diff --git a/docs/conformance/iso-ts-32004.md b/docs/conformance/iso-ts-32004.md index 52bca80b..e7d79150 100644 --- a/docs/conformance/iso-ts-32004.md +++ b/docs/conformance/iso-ts-32004.md @@ -4,12 +4,12 @@ Clause titles verified against the document's table of contents. Split rows to d | Clause | Title | Status | Implementing types | Tests | Notes | |---|---|---|---|---|---| -| 4 | Extension schema details | not started | | | | -| 5.1 | Encrypt dictionary additions (KDFSalt, MAC) | not started | | | | -| 5.2 | File trailer additions and AuthCode dictionary | not started | | | | -| 6.1 | Composing PDF MAC tokens: general | not started | | | | -| 6.2 | PdfMacIntegrityInfo data type | not started | | | | -| 6.3 | CMS structure of a PDF MAC token | not started | | | | -| 6.4 | Key derivation function | not started | | | | -| 6.5 | Location of PDF MAC tokens (unsigned and signed revisions) | not started | | | | -| 6.6 | Computing the digests in a PDF MAC token | not started | | | | +| 4 | Extension schema details | done | `DocumentSecurity` | `Broadside.Tests.Security.SignatureIntegrityTests.A_mac_attached_to_a_signature_is_verified` | A document with a MAC is checked for ExtensionLevel 32004 under ISO_ (EncryptionExtensionMissing, read anyway) | +| 5.1 | Encrypt dictionary additions (KDFSalt, MAC) | done | `IntegrityVerifier`, `PdfSecurity` | `Broadside.Tests.Security.IntegrityTests.A_standalone_mac_that_covers_the_whole_file_is_verified`, `Broadside.Tests.Security.IntegrityTests.A_tampered_file_opens_with_a_mismatch_diagnostic_in_lenient_mode`, `Broadside.Tests.Security.IntegrityTests.A_tampered_file_throws_in_strict_mode`, `Broadside.Tests.Security.IntegrityTests.A_missing_mac_that_the_permissions_require_is_reported`, `Broadside.Tests.Security.IntegrityTests.A_mac_with_the_wrong_key_derivation_salt_does_not_unwrap` | KDFSalt (32 bytes) required for a MAC; P bit 13 clear requires a token (`PdfSecurity.RequiresIntegrityCode`; missing: IntegrityCodeMissing); a V below 5 with AuthCode is IntegrityCodeInvalid | +| 5.2 | File trailer additions and AuthCode dictionary | done | `IntegrityVerifier` | `Broadside.Tests.Security.IntegrityTests.A_standalone_mac_that_covers_the_whole_file_is_verified`, `Broadside.Tests.Security.IntegrityTests.A_tampered_file_opens_with_a_mismatch_diagnostic_in_lenient_mode`, `Broadside.Tests.Security.IntegrityTests.A_tampered_file_throws_in_strict_mode`, `Broadside.Tests.Security.IntegrityTests.A_byte_range_that_does_not_frame_the_mac_string_is_invalid`, `Broadside.Tests.Security.IntegrityTests.A_mac_whose_location_is_unknown_is_not_verified_and_only_noted` | The newest trailer's AuthCode only (B.1); Standalone (ByteRange [0 L1 S L2] framing exactly ) and AttachedToSig (SigObjRef); MAC strings are never decrypted (the trailer does not pass through the loader); unknown MACLocation: IntegrityCodeNotVerified (Information) | +| 6.1 | Composing PDF MAC tokens: general | partial | `IntegrityVerifier` | `Broadside.Tests.Security.IntegrityTests.A_standalone_mac_that_covers_the_whole_file_is_verified`, `Broadside.Tests.Security.IntegrityTests.A_tampered_file_opens_with_a_mismatch_diagnostic_in_lenient_mode`, `Broadside.Tests.Security.IntegrityTests.A_tampered_file_throws_in_strict_mode` | Validation only; composing tokens (writing) is Phase 4 | +| 6.2 | PdfMacIntegrityInfo data type | done | `IntegrityVerifier` | `Broadside.Tests.Security.IntegrityTests.A_standalone_mac_that_covers_the_whole_file_is_verified`, `Broadside.Tests.Security.IntegrityTests.A_tampered_file_opens_with_a_mismatch_diagnostic_in_lenient_mode`, `Broadside.Tests.Security.IntegrityTests.A_tampered_file_throws_in_strict_mode`, `Broadside.Tests.Security.SignatureIntegrityTests.A_mac_attached_to_a_signature_is_verified` | version 0, dataDigest, signatureDigest [0] (present only for a token attached to a signature) | +| 6.3 | CMS structure of a PDF MAC token | done | `IntegrityVerifier` | `Broadside.Tests.Security.IntegrityTests.A_standalone_mac_that_covers_the_whole_file_is_verified`, `Broadside.Tests.Security.IntegrityTests.A_tampered_file_opens_with_a_mismatch_diagnostic_in_lenient_mode`, `Broadside.Tests.Security.IntegrityTests.A_tampered_file_throws_in_strict_mode`, `Broadside.Tests.Security.IntegrityTests.A_mac_whose_token_was_changed_is_reported` | id-ct-authData; exactly one PasswordRecipientInfo with pdfMacWrapKdf and AES-256 key wrap (RFC 3394, managed `AesKeyWrap`: the BCL has only RFC 5649); HMAC-SHA-256 over the DER SET OF authenticated attributes; exactly one content-type and one message-digest attribute; no unauthenticated attributes; SHA-256/384/512 and SHA3 (SHA3 where the platform has it, else IntegrityCodeNotVerified); fuzz `mac-token` | +| 6.4 | Key derivation function | done | `IntegrityVerifier`, `AesKeyWrap` | `Broadside.Tests.Security.IntegrityTests.A_mac_with_the_wrong_key_derivation_salt_does_not_unwrap`, `Broadside.Tests.Security.CryptographyTests.The_key_wrap_matches_rfc_3394`, `Broadside.Tests.Security.CryptographyTests.A_wrapped_key_that_fails_the_integrity_check_does_not_unwrap` | HKDF-SHA-256(file encryption key, KDFSalt, "PDFMAC", 32); for public-key handlers the DefaultCryptFilter key is #43's | +| 6.5 | Location of PDF MAC tokens (unsigned and signed revisions) | done | `IntegrityVerifier` | `Broadside.Tests.Security.IntegrityTests.A_standalone_mac_that_covers_the_whole_file_is_verified`, `Broadside.Tests.Security.IntegrityTests.A_tampered_file_opens_with_a_mismatch_diagnostic_in_lenient_mode`, `Broadside.Tests.Security.IntegrityTests.A_tampered_file_throws_in_strict_mode`, `Broadside.Tests.Security.SignatureIntegrityTests.A_mac_attached_to_a_signature_is_verified`, `Broadside.Tests.Security.SignatureIntegrityTests.A_mac_attached_to_a_different_signature_value_does_not_match` | Standalone in the trailer; AttachedToSig as the pdfMacData unsigned attribute of the signature's first SignerInfo (SignedCms) | +| 6.6 | Computing the digests in a PDF MAC token | done | `IntegrityVerifier` | `Broadside.Tests.Security.IntegrityTests.A_standalone_mac_that_covers_the_whole_file_is_verified`, `Broadside.Tests.Security.IntegrityTests.A_tampered_file_opens_with_a_mismatch_diagnostic_in_lenient_mode`, `Broadside.Tests.Security.IntegrityTests.A_tampered_file_throws_in_strict_mode`, `Broadside.Tests.Security.IntegrityTests.Bytes_appended_after_the_covered_range_make_the_mac_incomplete`, `Broadside.Tests.Security.SignatureIntegrityTests.A_mac_attached_to_a_different_signature_value_does_not_match` | dataDigest over the byte range, read in 64 KB windows; signatureDigest over the SignerInfo signature value; a byte range short of the end of the file is IntegrityCodeIncomplete (B.2.2.2, B.2.3.2); encrypted-mac.pdf, encrypted-mac-tampered.pdf | diff --git a/src/Broadside/EngineConfiguration.cs b/src/Broadside/EngineConfiguration.cs index 9ef361d1..0a451b27 100644 --- a/src/Broadside/EngineConfiguration.cs +++ b/src/Broadside/EngineConfiguration.cs @@ -1,5 +1,6 @@ using Broadside.Diagnostics; using Broadside.Filters; +using Broadside.Security; using Microsoft.Extensions.Logging; namespace Broadside; @@ -36,6 +37,11 @@ internal sealed class EngineConfiguration /// Gets the most bytes one stream may decode to (issue #38). public long MaxDecodedStreamLength { get; private init; } = PdfOptions.DefaultMaxDecodedStreamLength; + /// Gets the security handlers: the standard handler with the options' registrations applied (issue #42). + public SecurityHandlerRegistry SecurityHandlers { get; private init; } = SecurityHandlerRegistry.Default; + + /// Gets the credentials offered to encrypted documents opened without their own (issue #42). + public PdfCredentials? Credentials { get; private init; } /// Gets how many bytes of a non-seekable stream are copied into memory before a temporary file is used (issue #45). public long StreamBufferLimit { get; private init; } = PdfOptions.DefaultStreamBufferLimit; @@ -49,6 +55,8 @@ internal sealed class EngineConfiguration Logger = ObjectLog.CreateLogger(options.LoggerFactory ?? hostLoggerFactory), Filters = FilterRegistry.Create(options.Filters), MaxDecodedStreamLength = options.MaxDecodedStreamLength, + SecurityHandlers = options.SecurityHandlers.Count == 0 ? SecurityHandlerRegistry.Default : SecurityHandlerRegistry.Create(options.SecurityHandlers), + Credentials = options.Credentials, StreamBufferLimit = options.StreamBufferLimit, }; } diff --git a/src/Broadside/Filters/ICryptFilterHandler.cs b/src/Broadside/Filters/ICryptFilterHandler.cs index 0bdc9b08..474c4462 100644 --- a/src/Broadside/Filters/ICryptFilterHandler.cs +++ b/src/Broadside/Filters/ICryptFilterHandler.cs @@ -9,8 +9,9 @@ namespace Broadside.Filters; /// decodes only the Identity crypt filter. /// /// -/// A stream whose chain starts with Crypt is decrypted here with the named crypt filter's key used as is (§7.4.10), so the -/// object decryptor (hook 2 of the object loader) must leave such a stream's data alone. +/// The standard implementation (issue #42, DocumentDecryptor) decrypts a stream whose chain starts with Crypt when the +/// stream's object loads (it needs the object number for Algorithm 1), with the named crypt filter; this stage then passes the data +/// of a crypt filter the document defines through and returns for an unknown one. /// internal interface ICryptFilterHandler { diff --git a/src/Broadside/Objects/CosArray.cs b/src/Broadside/Objects/CosArray.cs index 580d2c8f..7a9e9367 100644 --- a/src/Broadside/Objects/CosArray.cs +++ b/src/Broadside/Objects/CosArray.cs @@ -132,6 +132,11 @@ public void Clear() /// IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + /// Replaces the element at as part of loading (decryption), without marking the array dirty. + /// The element's position. + /// The loaded value. + internal void ReplaceLoaded(int index, CosObject value) => _items[index] = value; + /// Wraps a list the caller gives up ownership of, without copying it and without marking the array dirty. internal static CosArray FromOwnedList(List items) => new(items, owned: true); } diff --git a/src/Broadside/Objects/CosDictionary.cs b/src/Broadside/Objects/CosDictionary.cs index 9898b3ec..b9157f57 100644 --- a/src/Broadside/Objects/CosDictionary.cs +++ b/src/Broadside/Objects/CosDictionary.cs @@ -159,6 +159,16 @@ bool ICollection>.Remove(KeyValuePairReplaces the value at as part of loading (decryption), without marking the dictionary dirty. + /// The entry's position. + /// The loaded value; not . + internal void ReplaceLoaded(int index, CosObject value) => _entries.SetAt(index, value); + + /// Gets the entry at in insertion order. + /// The entry's position. + /// The entry. + internal KeyValuePair GetAt(int index) => _entries.GetAt(index); + /// Wraps entries the caller gives up ownership of, without copying them and without marking the dictionary dirty. internal static CosDictionary FromOwnedEntries(OrderedDictionary entries) => new(entries); } diff --git a/src/Broadside/Objects/CosStream.cs b/src/Broadside/Objects/CosStream.cs index 918dc392..25329f40 100644 --- a/src/Broadside/Objects/CosStream.cs +++ b/src/Broadside/Objects/CosStream.cs @@ -53,6 +53,14 @@ public ReadOnlyMemory EncodedData } } + /// Replaces the encoded data as part of loading (decryption), without marking the stream dirty. + /// The data. + internal void ReplaceLoadedData(ReadOnlyMemory encodedData) + { + _encodedData = encodedData; + _deferred = null; + } + /// Gets the length of without reading it. internal int EncodedLength => _deferred is { } deferred ? deferred.Length : _encodedData.Length; diff --git a/src/Broadside/Objects/KnownNames.cs b/src/Broadside/Objects/KnownNames.cs index c23a8e68..9e835a0f 100644 --- a/src/Broadside/Objects/KnownNames.cs +++ b/src/Broadside/Objects/KnownNames.cs @@ -71,4 +71,16 @@ internal static class KnownNames /// /ID, the trailer's file identifier (§7.5.5, Table 15). public static readonly CosName ID = new("ID"); + + /// The encryption dictionary's algorithm code (§7.6.2, Table 20). + public static readonly CosName V = new("V"); + + /// The catalog's extensions dictionary (§7.12). + public static readonly CosName Extensions = new("Extensions"); + + /// The ISO prefix of the extensions dictionary (§7.12.3). + public static readonly CosName IsoPrefix = new("ISO_"); + + /// A developer extensions dictionary's level (§7.12.3, Table 49). + public static readonly CosName ExtensionLevel = new("ExtensionLevel"); } diff --git a/src/Broadside/Objects/TextStringDecoder.cs b/src/Broadside/Objects/TextStringDecoder.cs index 5d1e4fca..84b05320 100644 --- a/src/Broadside/Objects/TextStringDecoder.cs +++ b/src/Broadside/Objects/TextStringDecoder.cs @@ -14,6 +14,9 @@ internal static class TextStringDecoder /// private static readonly char[] PdfDocEncoding = BuildPdfDocEncoding(); + /// Gets the PDFDocEncoding table (Annex D, Table D.3): the character each byte stands for. + public static ReadOnlySpan PdfDocEncodingTable => PdfDocEncoding; + public static string Decode(ReadOnlySpan bytes) { if (bytes.StartsWith((ReadOnlySpan)[0xFE, 0xFF])) diff --git a/src/Broadside/Parsing/DiagnosticCodes.cs b/src/Broadside/Parsing/DiagnosticCodes.cs index d04a5535..fe1e1e0e 100644 --- a/src/Broadside/Parsing/DiagnosticCodes.cs +++ b/src/Broadside/Parsing/DiagnosticCodes.cs @@ -81,6 +81,27 @@ internal static class DiagnosticCodes public const string StreamDecodedLengthExceeded = nameof(StreamDecodedLengthExceeded); public const string StreamDecodingTooDeep = nameof(StreamDecodingTooDeep); + // Encryption (§7.6; ISO/TS 32003; ISO/TS 32004). + public const string EncryptDictionaryInvalid = nameof(EncryptDictionaryInvalid); + public const string EncryptionIdMissing = nameof(EncryptionIdMissing); + public const string EncryptionVersionInvalid = nameof(EncryptionVersionInvalid); + public const string EncryptionRevisionInvalid = nameof(EncryptionRevisionInvalid); + public const string EncryptionKeyLengthInvalid = nameof(EncryptionKeyLengthInvalid); + public const string EncryptionEntryLengthInvalid = nameof(EncryptionEntryLengthInvalid); + public const string EncryptionPermissionsMismatch = nameof(EncryptionPermissionsMismatch); + public const string EncryptionExtensionMissing = nameof(EncryptionExtensionMissing); + public const string OwnerPasswordKeyVariant = nameof(OwnerPasswordKeyVariant); + public const string CryptFilterMissing = nameof(CryptFilterMissing); + public const string CryptFilterMethodInvalid = nameof(CryptFilterMethodInvalid); + public const string EncryptedDataInvalid = nameof(EncryptedDataInvalid); + public const string EncryptedDataAuthenticationFailed = nameof(EncryptedDataAuthenticationFailed); + public const string MetadataNotEncrypted = nameof(MetadataNotEncrypted); + public const string IntegrityCodeMissing = nameof(IntegrityCodeMissing); + public const string IntegrityCodeInvalid = nameof(IntegrityCodeInvalid); + public const string IntegrityCodeMismatch = nameof(IntegrityCodeMismatch); + public const string IntegrityCodeIncomplete = nameof(IntegrityCodeIncomplete); + public const string IntegrityCodeNotVerified = nameof(IntegrityCodeNotVerified); + // Document catalog (§7.7.2). public const string CatalogTypeInvalid = nameof(CatalogTypeInvalid); public const string CatalogVersionNotName = nameof(CatalogVersionNotName); diff --git a/src/Broadside/PdfAccessLevel.cs b/src/Broadside/PdfAccessLevel.cs new file mode 100644 index 00000000..e92874de --- /dev/null +++ b/src/Broadside/PdfAccessLevel.cs @@ -0,0 +1,12 @@ +namespace Broadside; + +/// Which credential opened an encrypted document. +/// ISO 32000-2 §7.6.4.1: the owner password gives full access; the user password (or the default, empty one) gives the access the permissions allow. +public enum PdfAccessLevel +{ + /// User access: the document's permissions apply. + User, + + /// Owner access: every operation is permitted. + Owner, +} diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 008d3921..61b5949a 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -4,6 +4,7 @@ using Broadside.IO; using Broadside.Objects; using Broadside.Parsing; +using Broadside.Security; using Broadside.Writing; namespace Broadside; @@ -59,8 +60,10 @@ private PdfDocument( StreamDecoder streams, CosDictionary catalog, IReadOnlyList revisions, - PdfLinearization? linearization) + PdfLinearization? linearization, + PdfSecurity? security) { + Security = security; _source = source; _diagnostics = diagnostics; _loader = loader; @@ -132,6 +135,24 @@ public PdfVersion Version /// ISO 32000-2 Annex F, F.3.3. public PdfLinearization? Linearization { get; } + /// Gets a value indicating whether the document is encrypted (its trailer has an Encrypt entry). + /// + /// ISO 32000-2 §7.6. An encrypted document opens transparently: strings and streams read through it are decrypted, so its COS + /// objects hold plaintext. + /// + public bool IsEncrypted => Security is not null; + + /// Gets how the document is encrypted and what the credential that opened it allows, or when it is not encrypted. + /// ISO 32000-2 §7.6; ISO/TS 32003; ISO/TS 32004. + public PdfSecurity? Security { get; } + + /// + /// Gets the operations the document permits: when it is not encrypted or was opened with the + /// owner password, otherwise those its security handler grants. + /// + /// ISO 32000-2 §7.6.4.2, Table 22, and §7.6.5.2, Table 24. Readers are expected to respect them; PDF does not enforce them. + public PdfPermissions Permissions => Security?.Permissions ?? PdfPermissions.All; + /// Gets the deviations found so far, in the order they were found. Empty for a well-formed file. /// /// ADR 0005. A snapshot: objects load lazily, so reading more of the document can add diagnostics, which a later call returns. @@ -400,8 +421,9 @@ private FileWriter PlanSave(PdfSaveOptions options) /// The open path shared by every entry point: header, cross-reference information, trailer, catalog. /// The file; owned by the document, disposed if opening fails. /// The engine's configuration. + /// The credentials for an encrypted document; for the configuration's. /// The document. - internal static PdfDocument Read(PdfSource source, EngineConfiguration configuration) + internal static PdfDocument Read(PdfSource source, EngineConfiguration configuration, PdfCredentials? credentials = null) { try { @@ -421,23 +443,40 @@ internal static PdfDocument Read(PdfSource source, EngineConfiguration configura bool reconstructed = crossReference is null; crossReference ??= Reconstruct(source, header, scan.Value, streams, diagnostics, reportMissingTrailer: true); loader = new ObjectLoader(source, header, crossReference, diagnostics, new ObjectLoaderHooks(), streams) { Scan = scan, Logger = configuration.Logger }; - CosDictionary? catalog = ReadCatalog(loader, diagnostics, reportUnusableRoot: reconstructed); + + // Decryption is installed on the loader before the catalog loads (§7.6.2): the Encrypt dictionary loads undecrypted, + // everything after it decrypted. A rebuilt loader gets it installed again. + PdfCredentials? offered = credentials ?? configuration.Credentials; + PdfSecurity? security = DocumentSecurity.Open( + source, loader, streams, configuration.SecurityHandlers, offered, diagnostics, reportUnusable: reconstructed, out bool encryptUnusable); + CosDictionary? catalog = encryptUnusable ? null : ReadCatalog(loader, diagnostics, reportUnusableRoot: reconstructed); if (catalog is null) { - // §7.5.5: the trailer's Root shall lead to the catalog. When it does not, the cross-reference information is not - // trusted either: rebuild it by scanning, which also finds a catalog no trailer names. + // §7.5.5: the trailer's Root shall lead to the catalog (and its Encrypt to the encryption dictionary). When it does + // not, the cross-reference information is not trusted either: rebuild it by scanning, which also finds a catalog no + // trailer names. diagnostics.Report( - DiagnosticCodes.RootMissing, + encryptUnusable ? DiagnosticCodes.EncryptDictionaryInvalid : DiagnosticCodes.RootMissing, DiagnosticSeverity.Warning, - "The trailer has no Root entry that resolves to the catalog dictionary; the cross-reference information is rebuilt by scanning the file."); + encryptUnusable + ? "The trailer's Encrypt entry does not resolve to the encryption dictionary; the cross-reference information is rebuilt by scanning the file." + : "The trailer has no Root entry that resolves to the catalog dictionary; the cross-reference information is rebuilt by scanning the file."); crossReference = Reconstruct(source, header, scan.Value, streams, diagnostics, reportMissingTrailer: false); loader = new ObjectLoader(source, header, crossReference, diagnostics, new ObjectLoaderHooks(), streams) { Scan = scan, Logger = configuration.Logger }; + streams.CryptFilter = IdentityCryptFilterHandler.Instance; + security = DocumentSecurity.Open( + source, loader, streams, configuration.SecurityHandlers, offered, diagnostics, reportUnusable: true, out _); catalog = ReadCatalog(loader, diagnostics, reportUnusableRoot: true)!; } IReadOnlyList revisions = ReadRevisions(source, crossReference, diagnostics); + if (security is not null) + { + DocumentSecurity.CheckExtensions(security, catalog, loader.Resolve, diagnostics); + } + PdfLinearization? linearization = LinearizationReader.Read(source, loader, diagnostics); - return new PdfDocument(source, diagnostics, loader, streams, catalog, revisions, linearization); + return new PdfDocument(source, diagnostics, loader, streams, catalog, revisions, linearization, security); } catch { diff --git a/src/Broadside/PdfEngine.cs b/src/Broadside/PdfEngine.cs index c8cec21d..ae6769bc 100644 --- a/src/Broadside/PdfEngine.cs +++ b/src/Broadside/PdfEngine.cs @@ -1,4 +1,5 @@ using Broadside.IO; +using Broadside.Security; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -111,6 +112,56 @@ public async Task OpenAsync(Stream stream, CancellationToken cancel /// ISO 32000-2 §7.5. public PdfDocument Open(ReadOnlyMemory bytes) => PdfDocument.Read(PdfSource.FromMemory(bytes), _configuration); + /// Opens the encrypted PDF file at with . + /// The file path. + /// The credentials, such as a ; they override those set on the options. + /// The document. Dispose it when done. + /// + /// The file cannot be read at all, or, in strict mode, deviates from ISO 32000-2. + /// + /// The document is encrypted and the credentials do not open it. + /// The document is encrypted in a way this engine cannot decrypt. + /// ISO 32000-2 §7.5 and §7.6. For an unencrypted file the credentials are ignored. + public PdfDocument Open(string path, PdfCredentials credentials) + { + ArgumentException.ThrowIfNullOrEmpty(path); + ArgumentNullException.ThrowIfNull(credentials); + return PdfDocument.Read(PdfSource.FromFile(path), _configuration, credentials); + } + + /// Opens the encrypted PDF file held by , from its current position, with . + /// The stream. It is not disposed; keep it open and unchanged until the document is disposed. + /// The credentials, such as a ; they override those set on the options. + /// The document. Dispose it when done. + /// + /// The file cannot be read at all, or, in strict mode, deviates from ISO 32000-2. + /// + /// The document is encrypted and the credentials do not open it. + /// The document is encrypted in a way this engine cannot decrypt. + /// ISO 32000-2 §7.5 and §7.6. For an unencrypted file the credentials are ignored. + public PdfDocument Open(Stream stream, PdfCredentials credentials) + { + ArgumentNullException.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(credentials); + return PdfDocument.Read(PdfSource.FromStream(stream, _configuration.StreamBufferLimit), _configuration, credentials); + } + + /// Opens the encrypted PDF file held in with . + /// The file. Not copied: do not change it until the document is disposed. + /// The credentials, such as a ; they override those set on the options. + /// The document. Dispose it when done. + /// + /// The file cannot be read at all, or, in strict mode, deviates from ISO 32000-2. + /// + /// The document is encrypted and the credentials do not open it. + /// The document is encrypted in a way this engine cannot decrypt. + /// ISO 32000-2 §7.5 and §7.6. For an unencrypted file the credentials are ignored. + public PdfDocument Open(ReadOnlyMemory bytes, PdfCredentials credentials) + { + ArgumentNullException.ThrowIfNull(credentials); + return PdfDocument.Read(PdfSource.FromMemory(bytes), _configuration, credentials); + } + /// Creates a new document with one empty US Letter page (612 by 792 points). /// The document. Dispose it when done. /// diff --git a/src/Broadside/PdfIntegrityStatus.cs b/src/Broadside/PdfIntegrityStatus.cs new file mode 100644 index 00000000..ceae41e5 --- /dev/null +++ b/src/Broadside/PdfIntegrityStatus.cs @@ -0,0 +1,21 @@ +namespace Broadside; + +/// The outcome of checking an encrypted document's integrity MAC. +/// ISO/TS 32004, Annex B. +public enum PdfIntegrityStatus +{ + /// The document carries no PDF MAC token (and its permissions do not require one). + None, + + /// The PDF MAC token is valid and covers the whole file. + Verified, + + /// The PDF MAC token is invalid, does not match the file, or does not cover all of it; the diagnostics say why. + Failed, + + /// A token is present or required but cannot be checked here (an unavailable digest, a location not supported). + NotVerified, + + /// The permissions require a PDF MAC token and the document has none. + Missing, +} diff --git a/src/Broadside/PdfOptions.cs b/src/Broadside/PdfOptions.cs index 30e847d4..84fa3fef 100644 --- a/src/Broadside/PdfOptions.cs +++ b/src/Broadside/PdfOptions.cs @@ -1,5 +1,6 @@ using Broadside.Filters; using Broadside.Objects; +using Broadside.Security; using Microsoft.Extensions.Logging; namespace Broadside; @@ -21,6 +22,7 @@ public sealed class PdfOptions public const long DefaultStreamBufferLimit = 64L << 20; private readonly List _filters = []; + private readonly List _securityHandlers = []; private long _maxDecodedStreamLength = DefaultMaxDecodedStreamLength; private long _streamBufferLimit = DefaultStreamBufferLimit; @@ -150,4 +152,51 @@ public PdfOptions WithLoggerFactory(ILoggerFactory? loggerFactory) LoggerFactory = loggerFactory; return this; } + + /// Gets the security handlers registered with , in order. + /// Not public, so configuration binding never sees it. + internal IReadOnlyList SecurityHandlers => _securityHandlers; + + /// Gets the credentials set by or , or . + /// Not public, so configuration binding never sees a password. + internal PdfCredentials? Credentials { get; private set; } + + /// + /// Uses for encrypted documents whose encryption dictionary's Filter is + /// , or whose SubFilter it lists, replacing the default of that name + /// ( for Standard). A later registration of the same name wins. + /// + /// The handler. Shared by every document and thread of the engine: it must keep no state between calls. + /// These options. + /// ISO 32000-2 §7.6.2, Table 20. The security handler extension point (ADR 0001). + public PdfOptions UseSecurityHandler(ISecurityHandler handler) + { + ArgumentNullException.ThrowIfNull(handler); + _ = handler.Filter ?? throw new ArgumentException("The security handler has no Filter name.", nameof(handler)); + _securityHandlers.Add(handler); + return this; + } + + /// Offers to every encrypted document opened without credentials of its own. + /// The user or owner password; or empty for the default user password only. + /// These options. + /// + /// ISO 32000-2 §7.6.4.1. To give each document its own password, pass it to + /// instead. A password that opens neither as the user nor as the owner password makes opening throw . + /// + public PdfOptions WithPassword(string? password) + { + Credentials = string.IsNullOrEmpty(password) ? null : new PdfPassword(password); + return this; + } + + /// Offers to every encrypted document opened without credentials of its own. + /// The credentials, or for none. + /// These options. + /// ISO 32000-2 §7.6.4 and §7.6.5: a password for the standard security handler, a certificate for a public-key handler. + public PdfOptions WithCredentials(PdfCredentials? credentials) + { + Credentials = credentials; + return this; + } } diff --git a/src/Broadside/PdfPermissions.cs b/src/Broadside/PdfPermissions.cs new file mode 100644 index 00000000..ee4164d3 --- /dev/null +++ b/src/Broadside/PdfPermissions.cs @@ -0,0 +1,47 @@ +namespace Broadside; + +/// The operations a user may perform on a document, as its security handler grants them. +/// +/// +/// ISO 32000-2 §7.6.4.2, Table 22 (standard security handler) and §7.6.5.2, Table 24 (public-key security handlers). Each value is +/// the bit of the P entry that grants it (bit 3 is 1 << 2), so a P value of a revision 3 or later handler +/// masked with is the set of permissions it grants. +/// +/// +/// A document opened with the owner password, and an unencrypted document, has . For a revision 2 handler, which +/// controls only bits 3 to 6, follows , follows +/// and follows . PDF readers "should behave as if" +/// were granted when they provide content to assistive technology (Table 22, bit 5); bit 10 is ignored (PDF 2.0). +/// Readers are expected to respect these permissions; nothing in PDF enforces them (§7.6.4.1). +/// +/// +[Flags] +public enum PdfPermissions +{ + /// No permission. + None = 0, + + /// Print the document, possibly at degraded quality unless is also granted (bit 3). + Print = 1 << 2, + + /// Modify the contents by operations other than annotating, filling forms and assembling (bit 4). + Modify = 1 << 3, + + /// Copy or otherwise extract text and graphics (bit 5). + Extract = 1 << 4, + + /// Add or modify text annotations and fill in form fields; with , create or modify form fields (bit 6). + Annotate = 1 << 5, + + /// Fill in existing form fields, signature fields included, even without (bit 9). + FillForms = 1 << 8, + + /// Assemble the document: insert, rotate or delete pages, create outline items or thumbnails (bit 11). + Assemble = 1 << 10, + + /// Print to a representation from which a faithful digital copy could be generated (bit 12). + PrintHighQuality = 1 << 11, + + /// Every permission: the access of the owner, and of anyone to an unencrypted document. + All = Print | Modify | Extract | Annotate | FillForms | Assemble | PrintHighQuality, +} diff --git a/src/Broadside/PdfSecurity.cs b/src/Broadside/PdfSecurity.cs new file mode 100644 index 00000000..a109f076 --- /dev/null +++ b/src/Broadside/PdfSecurity.cs @@ -0,0 +1,85 @@ +using Broadside.Objects; + +namespace Broadside; + +/// How an encrypted document is protected and what the credential that opened it allows. +/// +/// ISO 32000-2 §7.6 (Table 20 and Table 21); ISO/TS 32003 (version 6, revision 7); ISO/TS 32004 (integrity MAC). Read once, when the +/// document is opened; is the live encryption dictionary. +/// +public sealed class PdfSecurity +{ + internal PdfSecurity( + CosDictionary encryptionDictionary, + CosName handler, + CosName? subFilter, + int version, + int? revision, + int keyLength, + PdfAccessLevel access, + PdfPermissions permissions, + int rawPermissions, + bool encryptsMetadata, + PdfIntegrityStatus integrity) + { + EncryptionDictionary = encryptionDictionary; + Handler = handler; + SubFilter = subFilter; + Version = version; + Revision = revision; + KeyLength = keyLength; + Access = access; + Permissions = permissions; + RawPermissions = rawPermissions; + EncryptsMetadata = encryptsMetadata; + Integrity = integrity; + } + + /// Gets the encryption dictionary (the trailer's Encrypt entry), whose strings are never encrypted. + /// ISO 32000-2 §7.6.2, Table 20. + public CosDictionary EncryptionDictionary { get; } + + /// Gets the name of the security handler that opened the document, such as Standard. + /// ISO 32000-2 §7.6.2, Table 20, Filter; a handler may also be chosen by SubFilter. + public CosName Handler { get; } + + /// Gets the encryption dictionary's SubFilter, or . + /// ISO 32000-2 §7.6.2, Table 20. + public CosName? SubFilter { get; } + + /// Gets the algorithm code V: 1 to 4 (deprecated), 5 (AES-256) or 6 (AES-GCM, ISO/TS 32003). + /// ISO 32000-2 §7.6.2, Table 20; ISO/TS 32003 §5.1, Table 2. + public int Version { get; } + + /// Gets the standard security handler's revision R (2 to 7), or for another handler. + /// ISO 32000-2 §7.6.4.2, Table 21; ISO/TS 32003 §5.1, Table 3. + public int? Revision { get; } + + /// Gets the length of the file encryption key, in bits. + /// ISO 32000-2 §7.6.2: 40 to 128 bits for V 1 to 4, 256 bits for 5 and 6. + public int KeyLength { get; } + + /// Gets which credential opened the document. + /// ISO 32000-2 §7.6.4.1. + public PdfAccessLevel Access { get; } + + /// Gets the permissions that apply: for the owner, the granted ones for a user. + /// ISO 32000-2 §7.6.4.2, Table 22. + public PdfPermissions Permissions { get; } + + /// Gets the user access permissions word as the document states it (the P entry, or the value in Perms). + /// ISO 32000-2 §7.6.4.2: an unsigned 32-bit quantity stored as a signed integer; bit 1 is the low-order bit. + public int RawPermissions { get; } + + /// Gets a value indicating whether the document-level metadata stream is encrypted (EncryptMetadata). + /// ISO 32000-2 §7.6.4.2, Table 21: meaningful for V 4 and later, default . + public bool EncryptsMetadata { get; } + + /// Gets a value indicating whether the permissions require a PDF MAC token in every revision (bit 13 clear). + /// ISO/TS 32004 §5.1.2, Table 3; meaningful for V 5 and later. + public bool RequiresIntegrityCode => Version >= 5 && (RawPermissions & (1 << 12)) == 0; + + /// Gets the outcome of checking the document's integrity MAC when it was opened. + /// ISO/TS 32004, Annex B. A failure is also recorded as a diagnostic, and throws in strict mode. + public PdfIntegrityStatus Integrity { get; } +} diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index 38f38c07..6f88a918 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -266,6 +266,101 @@ Broadside.PdfOptions.WithLoggerFactory(Microsoft.Extensions.Logging.ILoggerFacto Microsoft.Extensions.DependencyInjection.BroadsideServiceCollectionExtensions static Microsoft.Extensions.DependencyInjection.BroadsideServiceCollectionExtensions.AddBroadside(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! static Microsoft.Extensions.DependencyInjection.BroadsideServiceCollectionExtensions.AddBroadside(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, System.Action! configure) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! +Broadside.PdfAccessLevel +Broadside.PdfAccessLevel.Owner = 1 -> Broadside.PdfAccessLevel +Broadside.PdfAccessLevel.User = 0 -> Broadside.PdfAccessLevel +Broadside.PdfDocument.IsEncrypted.get -> bool +Broadside.PdfDocument.Permissions.get -> Broadside.PdfPermissions +Broadside.PdfDocument.Security.get -> Broadside.PdfSecurity? +Broadside.PdfEngine.Open(string! path, Broadside.Security.PdfCredentials! credentials) -> Broadside.PdfDocument! +Broadside.PdfEngine.Open(System.IO.Stream! stream, Broadside.Security.PdfCredentials! credentials) -> Broadside.PdfDocument! +Broadside.PdfEngine.Open(System.ReadOnlyMemory bytes, Broadside.Security.PdfCredentials! credentials) -> Broadside.PdfDocument! +Broadside.PdfIntegrityStatus +Broadside.PdfIntegrityStatus.Failed = 2 -> Broadside.PdfIntegrityStatus +Broadside.PdfIntegrityStatus.Missing = 4 -> Broadside.PdfIntegrityStatus +Broadside.PdfIntegrityStatus.None = 0 -> Broadside.PdfIntegrityStatus +Broadside.PdfIntegrityStatus.NotVerified = 3 -> Broadside.PdfIntegrityStatus +Broadside.PdfIntegrityStatus.Verified = 1 -> Broadside.PdfIntegrityStatus +Broadside.PdfOptions.UseSecurityHandler(Broadside.Security.ISecurityHandler! handler) -> Broadside.PdfOptions! +Broadside.PdfOptions.WithCredentials(Broadside.Security.PdfCredentials? credentials) -> Broadside.PdfOptions! +Broadside.PdfOptions.WithPassword(string? password) -> Broadside.PdfOptions! +Broadside.PdfPermissions +Broadside.PdfPermissions.All = Broadside.PdfPermissions.Print | Broadside.PdfPermissions.Modify | Broadside.PdfPermissions.Extract | Broadside.PdfPermissions.Annotate | Broadside.PdfPermissions.FillForms | Broadside.PdfPermissions.Assemble | Broadside.PdfPermissions.PrintHighQuality -> Broadside.PdfPermissions +Broadside.PdfPermissions.Annotate = 32 -> Broadside.PdfPermissions +Broadside.PdfPermissions.Assemble = 1024 -> Broadside.PdfPermissions +Broadside.PdfPermissions.Extract = 16 -> Broadside.PdfPermissions +Broadside.PdfPermissions.FillForms = 256 -> Broadside.PdfPermissions +Broadside.PdfPermissions.Modify = 8 -> Broadside.PdfPermissions +Broadside.PdfPermissions.None = 0 -> Broadside.PdfPermissions +Broadside.PdfPermissions.Print = 4 -> Broadside.PdfPermissions +Broadside.PdfPermissions.PrintHighQuality = 2048 -> Broadside.PdfPermissions +Broadside.PdfSecurity +Broadside.PdfSecurity.Access.get -> Broadside.PdfAccessLevel +Broadside.PdfSecurity.EncryptionDictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfSecurity.EncryptsMetadata.get -> bool +Broadside.PdfSecurity.Handler.get -> Broadside.Objects.CosName! +Broadside.PdfSecurity.Integrity.get -> Broadside.PdfIntegrityStatus +Broadside.PdfSecurity.KeyLength.get -> int +Broadside.PdfSecurity.Permissions.get -> Broadside.PdfPermissions +Broadside.PdfSecurity.RawPermissions.get -> int +Broadside.PdfSecurity.RequiresIntegrityCode.get -> bool +Broadside.PdfSecurity.Revision.get -> int? +Broadside.PdfSecurity.SubFilter.get -> Broadside.Objects.CosName? +Broadside.PdfSecurity.Version.get -> int +Broadside.Security.ISecurityHandler +Broadside.Security.ISecurityHandler.Authenticate(Broadside.Security.SecurityHandlerContext! context) -> Broadside.Security.SecurityHandlerResult! +Broadside.Security.ISecurityHandler.Filter.get -> Broadside.Objects.CosName! +Broadside.Security.ISecurityHandler.SubFilters.get -> System.Collections.Generic.IReadOnlyCollection! +Broadside.Security.PdfCredentials +Broadside.Security.PdfCredentials.PdfCredentials() -> void +Broadside.Security.PdfEncryptionNotSupportedException +Broadside.Security.PdfEncryptionNotSupportedException.PdfEncryptionNotSupportedException() -> void +Broadside.Security.PdfEncryptionNotSupportedException.PdfEncryptionNotSupportedException(Broadside.Security.PdfEncryptionNotSupportedReason reason, string? message) -> void +Broadside.Security.PdfEncryptionNotSupportedException.PdfEncryptionNotSupportedException(string? message) -> void +Broadside.Security.PdfEncryptionNotSupportedException.PdfEncryptionNotSupportedException(string? message, System.Exception? innerException) -> void +Broadside.Security.PdfEncryptionNotSupportedException.Reason.get -> Broadside.Security.PdfEncryptionNotSupportedReason +Broadside.Security.PdfEncryptionNotSupportedReason +Broadside.Security.PdfEncryptionNotSupportedReason.Algorithm = 1 -> Broadside.Security.PdfEncryptionNotSupportedReason +Broadside.Security.PdfEncryptionNotSupportedReason.Handler = 0 -> Broadside.Security.PdfEncryptionNotSupportedReason +Broadside.Security.PdfEncryptionNotSupportedReason.Platform = 2 -> Broadside.Security.PdfEncryptionNotSupportedReason +Broadside.Security.PdfPassword +Broadside.Security.PdfPassword.IsEmpty.get -> bool +Broadside.Security.PdfPassword.PdfPassword(string! password) -> void +Broadside.Security.PdfPassword.PdfPassword(System.ReadOnlySpan password) -> void +Broadside.Security.PdfPassword.Text.get -> string? +Broadside.Security.PdfPasswordException +Broadside.Security.PdfPasswordException.Failure.get -> Broadside.Security.PdfPasswordFailure +Broadside.Security.PdfPasswordException.PdfPasswordException() -> void +Broadside.Security.PdfPasswordException.PdfPasswordException(Broadside.Security.PdfPasswordFailure failure) -> void +Broadside.Security.PdfPasswordException.PdfPasswordException(string? message) -> void +Broadside.Security.PdfPasswordException.PdfPasswordException(string? message, System.Exception? innerException) -> void +Broadside.Security.PdfPasswordFailure +Broadside.Security.PdfPasswordFailure.Incorrect = 1 -> Broadside.Security.PdfPasswordFailure +Broadside.Security.PdfPasswordFailure.Required = 0 -> Broadside.Security.PdfPasswordFailure +Broadside.Security.SecurityHandlerContext +Broadside.Security.SecurityHandlerContext.Credentials.get -> Broadside.Security.PdfCredentials? +Broadside.Security.SecurityHandlerContext.DocumentId.get -> System.ReadOnlyMemory +Broadside.Security.SecurityHandlerContext.EncryptionDictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Security.SecurityHandlerContext.ReadingMode.get -> Broadside.PdfReadingMode +Broadside.Security.SecurityHandlerContext.Report(string! code, Broadside.Diagnostics.DiagnosticSeverity severity, string! message) -> void +Broadside.Security.SecurityHandlerContext.Resolve(Broadside.Objects.CosObject? value) -> Broadside.Objects.CosObject! +Broadside.Security.SecurityHandlerResult +Broadside.Security.SecurityHandlerResult.Access.get -> Broadside.PdfAccessLevel +Broadside.Security.SecurityHandlerResult.CryptFilterKeys.get -> System.Collections.Generic.IReadOnlyDictionary>? +Broadside.Security.SecurityHandlerResult.CryptFilterKeys.init -> void +Broadside.Security.SecurityHandlerResult.FileEncryptionKey.get -> System.ReadOnlyMemory +Broadside.Security.SecurityHandlerResult.Permissions.get -> Broadside.PdfPermissions +Broadside.Security.SecurityHandlerResult.RawPermissions.get -> int +Broadside.Security.SecurityHandlerResult.Revision.get -> int? +Broadside.Security.SecurityHandlerResult.Revision.init -> void +Broadside.Security.SecurityHandlerResult.SecurityHandlerResult(System.ReadOnlySpan fileEncryptionKey, Broadside.PdfAccessLevel access, Broadside.PdfPermissions permissions, int rawPermissions) -> void +Broadside.Security.StandardSecurityHandler +Broadside.Security.StandardSecurityHandler.Authenticate(Broadside.Security.SecurityHandlerContext! context) -> Broadside.Security.SecurityHandlerResult! +Broadside.Security.StandardSecurityHandler.Filter.get -> Broadside.Objects.CosName! +Broadside.Security.StandardSecurityHandler.StandardSecurityHandler() -> void +Broadside.Security.StandardSecurityHandler.SubFilters.get -> System.Collections.Generic.IReadOnlyCollection! +override Broadside.Security.PdfPassword.ToString() -> string! +static Broadside.Security.StandardSecurityHandler.UserPermissions(int rawPermissions, int revision) -> Broadside.PdfPermissions Broadside.PdfEngine.OpenAsync(System.IO.Stream! stream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! Broadside.PdfOptions.StreamBufferLimit.get -> long Broadside.PdfOptions.StreamBufferLimit.set -> void diff --git a/src/Broadside/Security/Cryptography/AesCipher.cs b/src/Broadside/Security/Cryptography/AesCipher.cs new file mode 100644 index 00000000..9c5fdefc --- /dev/null +++ b/src/Broadside/Security/Cryptography/AesCipher.cs @@ -0,0 +1,134 @@ +using System.Diagnostics.CodeAnalysis; +using System.Security.Cryptography; + +namespace Broadside.Security.Cryptography; + +/// +/// AES with one key, in the CBC and ECB modes ISO 32000-2 uses, always without padding (the caller strips PKCS#5 padding itself so +/// a damaged pad can be repaired rather than rejected). +/// +/// +/// ISO 32000-2 §7.6.3 (AES-CBC for strings and streams), §7.6.4.3.3-7.6.4.3.4 (CBC with a zero IV for OE and UE, CBC for the +/// Algorithm 2.B hash), §7.6.4.4.12 (ECB for Perms); RFC 3394 (ECB blocks for the key wrap). The base class library's AES where the +/// platform has it, elsewhere. Not thread-safe: create one per use. +/// +[SuppressMessage("Security", "CA5358:Review cipher mode usage with cryptography experts", Justification = "ISO 32000-2 §7.6.4.4.12 and RFC 3394 prescribe ECB on single blocks.")] +internal sealed class AesCipher : IDisposable +{ + private readonly Aes? _aes; + private readonly ManagedAes? _managed; + + private AesCipher(ReadOnlySpan key) + { + if (CryptographyBackend.UseManaged) + { + _managed = new ManagedAes(key); + } + else + { + _aes = Aes.Create(); + _aes.Key = key.ToArray(); + } + } + + /// The block size in bytes. + public const int BlockSize = 16; + + /// Creates a cipher for . + /// 16, 24 or 32 bytes. + /// The cipher. Dispose it. + public static AesCipher Create(ReadOnlySpan key) => new(key); + + /// Decrypts whole blocks in CBC mode without removing any padding. + /// A multiple of 16 bytes. + /// 16 bytes. + /// At least as long as . + public void DecryptCbc(ReadOnlySpan ciphertext, ReadOnlySpan iv, Span destination) + { + if (_aes is not null) + { + _aes.DecryptCbc(ciphertext, iv, destination, PaddingMode.None); + return; + } + + Span previous = stackalloc byte[BlockSize]; + Span current = stackalloc byte[BlockSize]; + iv[..BlockSize].CopyTo(previous); + for (int offset = 0; offset < ciphertext.Length; offset += BlockSize) + { + ReadOnlySpan block = ciphertext.Slice(offset, BlockSize); + block.CopyTo(current); + Span output = destination.Slice(offset, BlockSize); + _managed!.DecryptBlock(block, output); + for (int i = 0; i < BlockSize; i++) + { + output[i] ^= previous[i]; + } + + current.CopyTo(previous); + } + } + + /// Encrypts whole blocks in CBC mode without adding padding. + /// A multiple of 16 bytes. + /// 16 bytes. + /// At least as long as . + public void EncryptCbc(ReadOnlySpan plaintext, ReadOnlySpan iv, Span destination) + { + if (_aes is not null) + { + _aes.EncryptCbc(plaintext, iv, destination, PaddingMode.None); + return; + } + + Span chain = stackalloc byte[BlockSize]; + iv[..BlockSize].CopyTo(chain); + for (int offset = 0; offset < plaintext.Length; offset += BlockSize) + { + for (int i = 0; i < BlockSize; i++) + { + chain[i] ^= plaintext[offset + i]; + } + + _managed!.EncryptBlock(chain, chain); + chain.CopyTo(destination.Slice(offset, BlockSize)); + } + } + + /// Decrypts whole blocks in ECB mode. + /// A multiple of 16 bytes. + /// At least as long as . + public void DecryptEcb(ReadOnlySpan ciphertext, Span destination) + { + if (_aes is not null) + { + _aes.DecryptEcb(ciphertext, destination, PaddingMode.None); + return; + } + + for (int offset = 0; offset < ciphertext.Length; offset += BlockSize) + { + _managed!.DecryptBlock(ciphertext.Slice(offset, BlockSize), destination.Slice(offset, BlockSize)); + } + } + + /// Encrypts whole blocks in ECB mode. + /// A multiple of 16 bytes. + /// At least as long as . + public void EncryptEcb(ReadOnlySpan plaintext, Span destination) + { + if (_aes is not null) + { + _aes.EncryptEcb(plaintext, destination, PaddingMode.None); + return; + } + + for (int offset = 0; offset < plaintext.Length; offset += BlockSize) + { + _managed!.EncryptBlock(plaintext.Slice(offset, BlockSize), destination.Slice(offset, BlockSize)); + } + } + + /// + public void Dispose() => _aes?.Dispose(); +} diff --git a/src/Broadside/Security/Cryptography/AesGcmCipher.cs b/src/Broadside/Security/Cryptography/AesGcmCipher.cs new file mode 100644 index 00000000..3d8b4dc0 --- /dev/null +++ b/src/Broadside/Security/Cryptography/AesGcmCipher.cs @@ -0,0 +1,154 @@ +using System.Buffers.Binary; +using System.Security.Cryptography; + +namespace Broadside.Security.Cryptography; + +/// AES-GCM (NIST SP 800-38D) with a 12-byte IV, a 16-byte tag and no additional authenticated data, as ISO/TS 32003 uses it. +/// +/// ISO/TS 32003 §5.2. The base class library's where the platform has it (not the browser, not iOS or tvOS before +/// 13), the managed implementation below elsewhere (). +/// +internal static class AesGcmCipher +{ + /// The IV length ISO/TS 32003 prescribes. + public const int NonceSize = 12; + + /// The tag length ISO/TS 32003 prescribes. + public const int TagSize = 16; + + /// Decrypts and authenticates. + /// 16, 24 or 32 bytes. + /// 12 bytes. + /// The ciphertext. + /// 16 bytes. + /// As long as ; cleared when authentication fails. + /// when the tag does not authenticate the ciphertext. + public static bool TryDecrypt(ReadOnlySpan key, ReadOnlySpan nonce, ReadOnlySpan ciphertext, ReadOnlySpan tag, Span plaintext) + { + if (!CryptographyBackend.UseManagedGcm) + { + using var gcm = new AesGcm(key, TagSize); + try + { + gcm.Decrypt(nonce, ciphertext, tag, plaintext); + return true; + } + catch (AuthenticationTagMismatchException) + { + return false; + } + } + + var aes = new ManagedAes(key); + Span expected = stackalloc byte[TagSize]; + ComputeTag(aes, nonce, ciphertext, expected); + if (!CryptographicOperations.FixedTimeEquals(expected, tag)) + { + plaintext[..ciphertext.Length].Clear(); + return false; + } + + Counter(aes, nonce, ciphertext, plaintext); + return true; + } + + /// Encrypts and computes the tag (writers and tests). + /// 16, 24 or 32 bytes. + /// 12 bytes. + /// The plaintext. + /// As long as . + /// 16 bytes. + public static void Encrypt(ReadOnlySpan key, ReadOnlySpan nonce, ReadOnlySpan plaintext, Span ciphertext, Span tag) + { + if (!CryptographyBackend.UseManagedGcm) + { + using var gcm = new AesGcm(key, TagSize); + gcm.Encrypt(nonce, plaintext, ciphertext, tag); + return; + } + + var aes = new ManagedAes(key); + Counter(aes, nonce, plaintext, ciphertext); + ComputeTag(aes, nonce, ciphertext[..plaintext.Length], tag); + } + + /// GCTR from inc32(J0) (SP 800-38D §6.5, §7.1 step 3 and §7.2 step 4). + private static void Counter(ManagedAes aes, ReadOnlySpan nonce, ReadOnlySpan input, Span output) + { + Span counter = stackalloc byte[16]; + Span keystream = stackalloc byte[16]; + nonce[..NonceSize].CopyTo(counter); + uint block = 1; + for (int offset = 0; offset < input.Length; offset += 16) + { + block++; + BinaryPrimitives.WriteUInt32BigEndian(counter[12..], block); + aes.EncryptBlock(counter, keystream); + int count = Math.Min(16, input.Length - offset); + for (int i = 0; i < count; i++) + { + output[offset + i] = (byte)(input[offset + i] ^ keystream[i]); + } + } + } + + /// T = E(K, J0) xor GHASH_H(C ‖ pad ‖ [0]64 ‖ [len(C)]64), with J0 = IV ‖ 0^31 ‖ 1 (SP 800-38D §7.1). + private static void ComputeTag(ManagedAes aes, ReadOnlySpan nonce, ReadOnlySpan ciphertext, Span tag) + { + Span h = stackalloc byte[16]; + h.Clear(); + aes.EncryptBlock(h, h); + ulong hHigh = BinaryPrimitives.ReadUInt64BigEndian(h); + ulong hLow = BinaryPrimitives.ReadUInt64BigEndian(h[8..]); + + ulong yHigh = 0; + ulong yLow = 0; + Span block = stackalloc byte[16]; + for (int offset = 0; offset < ciphertext.Length; offset += 16) + { + block.Clear(); + ciphertext.Slice(offset, Math.Min(16, ciphertext.Length - offset)).CopyTo(block); + yHigh ^= BinaryPrimitives.ReadUInt64BigEndian(block); + yLow ^= BinaryPrimitives.ReadUInt64BigEndian(block[8..]); + (yHigh, yLow) = Multiply(yHigh, yLow, hHigh, hLow); + } + + yLow ^= (ulong)ciphertext.Length * 8; + (yHigh, yLow) = Multiply(yHigh, yLow, hHigh, hLow); + + Span j0 = stackalloc byte[16]; + nonce[..NonceSize].CopyTo(j0); + BinaryPrimitives.WriteUInt32BigEndian(j0[12..], 1); + aes.EncryptBlock(j0, j0); + BinaryPrimitives.WriteUInt64BigEndian(tag, yHigh ^ BinaryPrimitives.ReadUInt64BigEndian(j0)); + BinaryPrimitives.WriteUInt64BigEndian(tag[8..], yLow ^ BinaryPrimitives.ReadUInt64BigEndian(j0[8..])); + } + + /// Multiplication in GF(2^128) with the GCM bit order (SP 800-38D §6.3, Algorithm 1). + private static (ulong High, ulong Low) Multiply(ulong xHigh, ulong xLow, ulong yHigh, ulong yLow) + { + ulong zHigh = 0; + ulong zLow = 0; + ulong vHigh = yHigh; + ulong vLow = yLow; + for (int i = 0; i < 128; i++) + { + ulong bit = i < 64 ? (xHigh >> (63 - i)) & 1 : (xLow >> (127 - i)) & 1; + if (bit != 0) + { + zHigh ^= vHigh; + zLow ^= vLow; + } + + bool carry = (vLow & 1) != 0; + vLow = (vLow >> 1) | (vHigh << 63); + vHigh >>= 1; + if (carry) + { + vHigh ^= 0xE100000000000000UL; + } + } + + return (zHigh, zLow); + } +} diff --git a/src/Broadside/Security/Cryptography/AesKeyWrap.cs b/src/Broadside/Security/Cryptography/AesKeyWrap.cs new file mode 100644 index 00000000..abee0e10 --- /dev/null +++ b/src/Broadside/Security/Cryptography/AesKeyWrap.cs @@ -0,0 +1,89 @@ +using System.Buffers.Binary; +using System.Security.Cryptography; + +namespace Broadside.Security.Cryptography; + +/// The AES key wrap of RFC 3394 (without padding), which ISO/TS 32004 uses to protect the MAC key. +/// +/// ISO/TS 32004 §6.3.3, Table 7. The base class library implements only the padded variant of RFC 5649 (a different initial value +/// and a length prefix), so the wrap is built here on single AES blocks (). +/// +internal static class AesKeyWrap +{ + private const ulong DefaultInitialValue = 0xA6A6A6A6A6A6A6A6UL; + + /// Unwraps a key (RFC 3394 §2.2.2, index-based) and checks its integrity (§2.2.3.1). + /// The KEK: 16, 24 or 32 bytes. + /// The wrapped key: a multiple of 8 bytes, at least 24. + /// The key, or when the input is malformed or fails the integrity check. + public static byte[]? Unwrap(ReadOnlySpan keyEncryptionKey, ReadOnlySpan wrapped) + { + if (wrapped.Length < 24 || wrapped.Length % 8 != 0) + { + return null; + } + + int n = (wrapped.Length / 8) - 1; + ulong a = BinaryPrimitives.ReadUInt64BigEndian(wrapped); + byte[] r = wrapped[8..].ToArray(); + Span block = stackalloc byte[16]; + using AesCipher aes = AesCipher.Create(keyEncryptionKey); + for (int j = 5; j >= 0; j--) + { + for (int i = n; i >= 1; i--) + { + ulong t = (ulong)((n * j) + i); + BinaryPrimitives.WriteUInt64BigEndian(block, a ^ t); + r.AsSpan((i - 1) * 8, 8).CopyTo(block[8..]); + aes.DecryptEcb(block, block); + a = BinaryPrimitives.ReadUInt64BigEndian(block); + block[8..].CopyTo(r.AsSpan((i - 1) * 8, 8)); + } + } + + Span check = stackalloc byte[8]; + Span expected = stackalloc byte[8]; + BinaryPrimitives.WriteUInt64BigEndian(check, a); + BinaryPrimitives.WriteUInt64BigEndian(expected, DefaultInitialValue); + if (!CryptographicOperations.FixedTimeEquals(check, expected)) + { + CryptographicOperations.ZeroMemory(r); + return null; + } + + return r; + } + + /// Wraps a key (RFC 3394 §2.2.1, index-based); used by writers and tests. + /// The KEK: 16, 24 or 32 bytes. + /// The key to wrap: a multiple of 8 bytes, at least 16. + /// The wrapped key, 8 bytes longer. + public static byte[] Wrap(ReadOnlySpan keyEncryptionKey, ReadOnlySpan key) + { + if (key.Length < 16 || key.Length % 8 != 0) + { + throw new ArgumentException("RFC 3394 wraps keys of at least 16 bytes, in multiples of 8.", nameof(key)); + } + + int n = key.Length / 8; + ulong a = DefaultInitialValue; + byte[] output = new byte[key.Length + 8]; + key.CopyTo(output.AsSpan(8)); + Span block = stackalloc byte[16]; + using AesCipher aes = AesCipher.Create(keyEncryptionKey); + for (int j = 0; j <= 5; j++) + { + for (int i = 1; i <= n; i++) + { + BinaryPrimitives.WriteUInt64BigEndian(block, a); + output.AsSpan(i * 8, 8).CopyTo(block[8..]); + aes.EncryptEcb(block, block); + a = BinaryPrimitives.ReadUInt64BigEndian(block) ^ (ulong)((n * j) + i); + block[8..].CopyTo(output.AsSpan(i * 8, 8)); + } + } + + BinaryPrimitives.WriteUInt64BigEndian(output, a); + return output; + } +} diff --git a/src/Broadside/Security/Cryptography/CryptographyBackend.cs b/src/Broadside/Security/Cryptography/CryptographyBackend.cs new file mode 100644 index 00000000..952afe6b --- /dev/null +++ b/src/Broadside/Security/Cryptography/CryptographyBackend.cs @@ -0,0 +1,38 @@ +using System.Security.Cryptography; + +namespace Broadside.Security.Cryptography; + +/// +/// Chooses, at run time, between the base class library's implementation of a primitive and the managed one in this folder. +/// +/// +/// ADR 0001 and the WebAssembly commitment of the specification: the base class library has no MD5, AES or AES-GCM in the browser, +/// no AES-GCM before iOS and tvOS 13, and no RFC 3394 key wrap anywhere. Every primitive the security handlers use goes through the +/// facades here (, , , , ), which +/// use the base class library where the platform supports it and the managed implementation elsewhere. SHA-2, HMAC and HKDF are +/// available on every platform and are called directly. +/// +internal static class CryptographyBackend +{ + private static readonly AsyncLocal ForcedManaged = new(); + + /// Gets a value indicating whether MD5 and AES use the managed implementations. + public static bool UseManaged => ForcedManaged.Value || OperatingSystem.IsBrowser(); + + /// Gets a value indicating whether AES-GCM uses the managed implementation. + public static bool UseManagedGcm => UseManaged || !AesGcm.IsSupported; + + /// Makes the current asynchronous flow use the managed implementations until the result is disposed (tests). + /// The scope. + public static IDisposable ForceManaged() + { + bool previous = ForcedManaged.Value; + ForcedManaged.Value = true; + return new Scope(previous); + } + + private sealed class Scope(bool previous) : IDisposable + { + public void Dispose() => ForcedManaged.Value = previous; + } +} diff --git a/src/Broadside/Security/Cryptography/ManagedAes.cs b/src/Broadside/Security/Cryptography/ManagedAes.cs new file mode 100644 index 00000000..3aa04f20 --- /dev/null +++ b/src/Broadside/Security/Cryptography/ManagedAes.cs @@ -0,0 +1,242 @@ +namespace Broadside.Security.Cryptography; + +/// A managed AES block cipher (FIPS 197) for platforms whose base class library has none (the browser). +/// +/// A direct transcription of FIPS 197 §5 with byte-wide S-box lookups. It is not hardened against cache-timing attacks; it reads +/// documents on platforms that offer nothing else, and the base class library's AES is used wherever it exists. +/// +internal sealed class ManagedAes +{ + private static readonly byte[] SBox = BuildSBox(); + private static readonly byte[] InverseSBox = BuildInverseSBox(SBox); + private static readonly byte[] Times9 = BuildProducts(9); + private static readonly byte[] Times11 = BuildProducts(11); + private static readonly byte[] Times13 = BuildProducts(13); + private static readonly byte[] Times14 = BuildProducts(14); + + private readonly byte[] _roundKeys; + private readonly int _rounds; + + /// Initializes a new instance of the class: key expansion (FIPS 197 §5.2). + /// 16, 24 or 32 bytes. + public ManagedAes(ReadOnlySpan key) + { + if (key.Length is not (16 or 24 or 32)) + { + throw new ArgumentException("An AES key is 16, 24 or 32 bytes long.", nameof(key)); + } + + int nk = key.Length / 4; + _rounds = nk + 6; + int words = 4 * (_rounds + 1); + _roundKeys = new byte[words * 4]; + key.CopyTo(_roundKeys); + Span temp = stackalloc byte[4]; + byte rcon = 1; + for (int i = nk; i < words; i++) + { + _roundKeys.AsSpan((i - 1) * 4, 4).CopyTo(temp); + if (i % nk == 0) + { + byte first = temp[0]; + temp[0] = (byte)(SBox[temp[1]] ^ rcon); + temp[1] = SBox[temp[2]]; + temp[2] = SBox[temp[3]]; + temp[3] = SBox[first]; + rcon = XTime(rcon); + } + else if (nk > 6 && i % nk == 4) + { + for (int b = 0; b < 4; b++) + { + temp[b] = SBox[temp[b]]; + } + } + + for (int b = 0; b < 4; b++) + { + _roundKeys[(i * 4) + b] = (byte)(_roundKeys[((i - nk) * 4) + b] ^ temp[b]); + } + } + } + + /// Encrypts one 16-byte block (FIPS 197 §5.1). + /// 16 bytes. + /// 16 bytes; may be the same memory as . + public void EncryptBlock(ReadOnlySpan input, Span output) + { + Span state = stackalloc byte[16]; + input[..16].CopyTo(state); + AddRoundKey(state, 0); + for (int round = 1; round <= _rounds; round++) + { + for (int i = 0; i < 16; i++) + { + state[i] = SBox[state[i]]; + } + + ShiftRows(state); + if (round != _rounds) + { + MixColumns(state); + } + + AddRoundKey(state, round); + } + + state.CopyTo(output); + } + + /// Decrypts one 16-byte block (FIPS 197 §5.3). + /// 16 bytes. + /// 16 bytes; may be the same memory as . + public void DecryptBlock(ReadOnlySpan input, Span output) + { + Span state = stackalloc byte[16]; + input[..16].CopyTo(state); + AddRoundKey(state, _rounds); + for (int round = _rounds - 1; round >= 0; round--) + { + InverseShiftRows(state); + for (int i = 0; i < 16; i++) + { + state[i] = InverseSBox[state[i]]; + } + + AddRoundKey(state, round); + if (round != 0) + { + InverseMixColumns(state); + } + } + + state.CopyTo(output); + } + + private static byte XTime(byte value) => (byte)((value << 1) ^ ((value & 0x80) != 0 ? 0x1B : 0)); + + private static byte Multiply(byte a, byte b) + { + byte product = 0; + while (b != 0) + { + if ((b & 1) != 0) + { + product ^= a; + } + + a = XTime(a); + b >>= 1; + } + + return product; + } + + // The state is column-major: byte r + 4c is row r of column c (FIPS 197 §3.4). + private static void ShiftRows(Span state) + { + Span copy = stackalloc byte[16]; + state.CopyTo(copy); + for (int column = 0; column < 4; column++) + { + for (int row = 1; row < 4; row++) + { + state[row + (4 * column)] = copy[row + (4 * ((column + row) & 3))]; + } + } + } + + private static void InverseShiftRows(Span state) + { + Span copy = stackalloc byte[16]; + state.CopyTo(copy); + for (int column = 0; column < 4; column++) + { + for (int row = 1; row < 4; row++) + { + state[row + (4 * ((column + row) & 3))] = copy[row + (4 * column)]; + } + } + } + + private static void MixColumns(Span state) + { + for (int c = 0; c < 16; c += 4) + { + byte a0 = state[c], a1 = state[c + 1], a2 = state[c + 2], a3 = state[c + 3]; + state[c] = (byte)(XTime(a0) ^ XTime(a1) ^ a1 ^ a2 ^ a3); + state[c + 1] = (byte)(a0 ^ XTime(a1) ^ XTime(a2) ^ a2 ^ a3); + state[c + 2] = (byte)(a0 ^ a1 ^ XTime(a2) ^ XTime(a3) ^ a3); + state[c + 3] = (byte)(XTime(a0) ^ a0 ^ a1 ^ a2 ^ XTime(a3)); + } + } + + private static void InverseMixColumns(Span state) + { + for (int c = 0; c < 16; c += 4) + { + byte a0 = state[c], a1 = state[c + 1], a2 = state[c + 2], a3 = state[c + 3]; + state[c] = (byte)(Times14[a0] ^ Times11[a1] ^ Times13[a2] ^ Times9[a3]); + state[c + 1] = (byte)(Times9[a0] ^ Times14[a1] ^ Times11[a2] ^ Times13[a3]); + state[c + 2] = (byte)(Times13[a0] ^ Times9[a1] ^ Times14[a2] ^ Times11[a3]); + state[c + 3] = (byte)(Times11[a0] ^ Times13[a1] ^ Times9[a2] ^ Times14[a3]); + } + } + + private static byte[] BuildSBox() + { + // FIPS 197 §5.1.1: multiplicative inverse in GF(2^8) followed by the affine transformation. + var box = new byte[256]; + for (int value = 0; value < 256; value++) + { + byte inverse = 0; + for (int candidate = 1; candidate < 256 && value != 0; candidate++) + { + if (Multiply((byte)value, (byte)candidate) == 1) + { + inverse = (byte)candidate; + break; + } + } + + int s = inverse; + int result = s ^ RotateLeft(s, 1) ^ RotateLeft(s, 2) ^ RotateLeft(s, 3) ^ RotateLeft(s, 4) ^ 0x63; + box[value] = (byte)result; + } + + return box; + + static int RotateLeft(int x, int shift) => ((x << shift) | (x >> (8 - shift))) & 0xFF; + } + + private static byte[] BuildProducts(byte factor) + { + var products = new byte[256]; + for (int i = 0; i < 256; i++) + { + products[i] = Multiply((byte)i, factor); + } + + return products; + } + + private static byte[] BuildInverseSBox(byte[] box) + { + var inverse = new byte[256]; + for (int i = 0; i < 256; i++) + { + inverse[box[i]] = (byte)i; + } + + return inverse; + } + + private void AddRoundKey(Span state, int round) + { + ReadOnlySpan key = _roundKeys.AsSpan(round * 16, 16); + for (int i = 0; i < 16; i++) + { + state[i] ^= key[i]; + } + } +} diff --git a/src/Broadside/Security/Cryptography/Md5.cs b/src/Broadside/Security/Cryptography/Md5.cs new file mode 100644 index 00000000..3e59334e --- /dev/null +++ b/src/Broadside/Security/Cryptography/Md5.cs @@ -0,0 +1,135 @@ +using System.Buffers.Binary; +using System.Diagnostics.CodeAnalysis; +using System.Security.Cryptography; + +namespace Broadside.Security.Cryptography; + +/// MD5 (RFC 1321), which the deprecated standard security handler revisions 2 to 4 require for key derivation. +/// +/// ISO 32000-2 §7.6.3.1: "Encrypt versions 1-4 ... make use of the MD5 message-digest algorithm for key generation purposes". Used only +/// to read such files, never to protect anything new. The base class library's MD5 where the platform has it, the managed +/// implementation below elsewhere (). +/// +[SuppressMessage("Security", "CA5351:Do Not Use Broken Cryptographic Algorithms", Justification = "ISO 32000-2 §7.6.3.2 and §7.6.4.3.2 prescribe MD5 for reading revision 2-4 files.")] +internal static class Md5 +{ + /// The digest length in bytes. + public const int HashSize = 16; + + /// Hashes into the first 16 bytes of . + /// The data. + /// At least 16 bytes. + public static void HashData(ReadOnlySpan source, Span destination) + { + if (CryptographyBackend.UseManaged) + { + ManagedMd5.HashData(source, destination); + } + else + { + MD5.HashData(source, destination); + } + } +} + +/// A managed MD5 (RFC 1321 §3), for platforms whose base class library has none. +internal static class ManagedMd5 +{ + private static readonly uint[] Sines = BuildSines(); + + private static readonly int[] Shifts = + [ + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, + ]; + + /// Hashes into the first 16 bytes of . + /// The data. + /// At least 16 bytes. + public static void HashData(ReadOnlySpan source, Span destination) + { + Span state = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]; + int full = source.Length & ~63; + for (int offset = 0; offset < full; offset += 64) + { + Transform(state, source.Slice(offset, 64)); + } + + // Step 1 and 2: append a 1 bit, zeros to 56 mod 64, then the bit length, low-order byte first. + Span tail = stackalloc byte[128]; + tail.Clear(); + ReadOnlySpan rest = source[full..]; + rest.CopyTo(tail); + tail[rest.Length] = 0x80; + int tailLength = rest.Length < 56 ? 64 : 128; + BinaryPrimitives.WriteUInt64LittleEndian(tail[(tailLength - 8)..], (ulong)source.Length * 8); + for (int offset = 0; offset < tailLength; offset += 64) + { + Transform(state, tail.Slice(offset, 64)); + } + + for (int i = 0; i < 4; i++) + { + BinaryPrimitives.WriteUInt32LittleEndian(destination[(i * 4)..], state[i]); + } + } + + private static void Transform(Span state, ReadOnlySpan block) + { + Span x = stackalloc uint[16]; + for (int i = 0; i < 16; i++) + { + x[i] = BinaryPrimitives.ReadUInt32LittleEndian(block[(i * 4)..]); + } + + uint a = state[0], b = state[1], c = state[2], d = state[3]; + for (int i = 0; i < 64; i++) + { + uint f; + int g; + switch (i >> 4) + { + case 0: + f = (b & c) | (~b & d); + g = i; + break; + case 1: + f = (d & b) | (~d & c); + g = ((5 * i) + 1) & 15; + break; + case 2: + f = b ^ c ^ d; + g = ((3 * i) + 5) & 15; + break; + default: + f = c ^ (b | ~d); + g = (7 * i) & 15; + break; + } + + uint rotated = uint.RotateLeft(a + f + Sines[i] + x[g], Shifts[i]); + a = d; + d = c; + c = b; + b += rotated; + } + + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; + } + + private static uint[] BuildSines() + { + var sines = new uint[64]; + for (int i = 0; i < 64; i++) + { + sines[i] = (uint)(long)Math.Floor(Math.Abs(Math.Sin(i + 1)) * 4294967296.0); + } + + return sines; + } +} diff --git a/src/Broadside/Security/Cryptography/Rc4.cs b/src/Broadside/Security/Cryptography/Rc4.cs new file mode 100644 index 00000000..c1ee7c32 --- /dev/null +++ b/src/Broadside/Security/Cryptography/Rc4.cs @@ -0,0 +1,44 @@ +namespace Broadside.Security.Cryptography; + +/// The RC4 stream cipher, implemented in managed code (the base class library has none). +/// +/// ISO 32000-2 §7.6.3.1: RC4 is a symmetric stream cipher, the same operation encrypts and decrypts, and the length of the data does +/// not change. Deprecated in PDF 2.0; used here only to read files that use it. The state lives on the stack: no allocation per call. +/// +internal static class Rc4 +{ + /// Encrypts or decrypts into , which may be the same memory. + /// The key, 1 to 256 bytes. + /// The data. + /// At least as long as . + public static void Transform(ReadOnlySpan key, ReadOnlySpan input, Span output) + { + if (key.IsEmpty) + { + throw new ArgumentException("The RC4 key cannot be empty.", nameof(key)); + } + + Span state = stackalloc byte[256]; + for (int i = 0; i < 256; i++) + { + state[i] = (byte)i; + } + + int j = 0; + for (int i = 0; i < 256; i++) + { + j = (j + state[i] + key[i % key.Length]) & 0xFF; + (state[i], state[j]) = (state[j], state[i]); + } + + int x = 0; + int y = 0; + for (int k = 0; k < input.Length; k++) + { + x = (x + 1) & 0xFF; + y = (y + state[x]) & 0xFF; + (state[x], state[y]) = (state[y], state[x]); + output[k] = (byte)(input[k] ^ state[(state[x] + state[y]) & 0xFF]); + } + } +} diff --git a/src/Broadside/Security/DocumentDecryptor.cs b/src/Broadside/Security/DocumentDecryptor.cs new file mode 100644 index 00000000..c41d7592 --- /dev/null +++ b/src/Broadside/Security/DocumentDecryptor.cs @@ -0,0 +1,626 @@ +using System.Buffers; +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Filters; +using Broadside.Objects; +using Broadside.Parsing; +using Broadside.Security.Cryptography; + +namespace Broadside.Security; + +/// How a crypt filter decrypts (§7.6.6, Table 25; ISO/TS 32003 Table 4). +internal enum CryptMethod +{ + /// No decryption (the Identity crypt filter, Table 26). + Identity, + + /// RC4 with a per-object key (Algorithm 1; V 1-3, CFM V2). + Rc4, + + /// AES-128-CBC with a per-object key (Algorithm 1 with "sAlT"; CFM AESV2). + AesV2, + + /// AES-256-CBC with the file key (Algorithm 1.A; CFM AESV3). + AesV3, + + /// AES-256-GCM with the file key (ISO/TS 32003 §5.2; CFM AESV4). + AesV4, +} + +/// A crypt filter of the document: its method and key. +/// The name it has in CF, or Identity, or the name the document's V 1-3 encryption is given. +/// How it decrypts. +/// The key: the file encryption key, or the filter's own. +internal sealed record CryptFilter(CosName Name, CryptMethod Method, byte[] Key); + +/// +/// Decrypts the strings and streams of one encrypted document as objects load (hook 2 of the object loader) and serves the +/// Crypt filter of the stream pipeline. +/// +/// +/// +/// ISO 32000-2 §7.6.2 (what is encrypted), §7.6.3 (Algorithms 1 and 1.A), §7.6.6 (crypt filters), §7.4.10 (the Crypt filter); +/// ISO/TS 32003 §5.2 (AES-GCM). Every string is decrypted with StrF and every stream with StmF, an embedded file with +/// EFF (§7.6.2 Table 20), except: strings in the encryption dictionary (it loads before this hook is set), the trailer's +/// ID and AuthCode (the trailer never loads through the loader), strings inside streams and object-stream members (the +/// container is decrypted as a whole; members never reach this hook), cross-reference streams, the Contents string of a +/// signature dictionary, and metadata streams when EncryptMetadata is false. +/// +/// +/// A stream whose Filter starts with Crypt is decrypted here too, with the crypt filter its DecodeParms name +/// (default Identity) and that filter's key used as is (§7.4.10), not with StmF; the pipeline's Crypt stage then +/// passes the already decrypted data through. So of every loaded stream holds plaintext. For an +/// AES-128 crypt filter whose data does not decrypt with the key as is, Algorithm 1's per-object key (what Table 25 describes for +/// AESV2, and what qpdf uses) is tried before the data is reported damaged. +/// +/// +/// Damaged ciphertext is repaired the way pdf.js does, with a diagnostic: AES data too short for an IV and a block decrypts to nothing, +/// a trailing partial block is dropped, an invalid PKCS#5 pad is kept; AES-GCM data that fails authentication decrypts to nothing. +/// Decryption never marks anything dirty (ADR 0004). Thread-safe: the key material is immutable and every call has its own cipher. +/// +/// +internal sealed class DocumentDecryptor : IObjectDecryptor, ICryptFilterHandler +{ + private static readonly CosName CF = new("CF"); + private static readonly CosName StmF = new("StmF"); + private static readonly CosName StrF = new("StrF"); + private static readonly CosName EFF = new("EFF"); + private static readonly CosName CFM = new("CFM"); + private static readonly CosName EncryptMetadataName = new("EncryptMetadata"); + private static readonly CosName None = new("None"); + private static readonly CosName V2 = new("V2"); + private static readonly CosName AESV2 = new("AESV2"); + private static readonly CosName AESV3 = new("AESV3"); + private static readonly CosName AESV4 = new("AESV4"); + private static readonly CosName XRef = new("XRef"); + private static readonly CosName Metadata = new("Metadata"); + private static readonly CosName EmbeddedFile = new("EmbeddedFile"); + private static readonly CosName Sig = new("Sig"); + private static readonly CosName DocTimeStamp = new("DocTimeStamp"); + private static readonly CosName Contents = new("Contents"); + private static readonly CosName ByteRange = new("ByteRange"); + private static readonly CosName StandardFilterName = new("StdCF"); + + private readonly CryptFilter _strings; + private readonly CryptFilter _streams; + private readonly CryptFilter _embeddedFiles; + private readonly Dictionary _named; + private readonly DiagnosticSink _diagnostics; + private readonly Func _resolve; + + private DocumentDecryptor( + CryptFilter strings, + CryptFilter streams, + CryptFilter embeddedFiles, + Dictionary named, + bool encryptMetadata, + DiagnosticSink diagnostics, + Func resolve) + { + _strings = strings; + _streams = streams; + _embeddedFiles = embeddedFiles; + _named = named; + EncryptMetadata = encryptMetadata; + _diagnostics = diagnostics; + _resolve = resolve; + } + + /// Gets a value indicating whether metadata streams are encrypted (Table 21). + public bool EncryptMetadata { get; } + + /// Gets the crypt filter strings are decrypted with. + public CryptFilter Strings => _strings; + + /// Gets the crypt filter streams are decrypted with by default. + public CryptFilter Streams => _streams; + + /// Reads the crypt filters of an encryption dictionary (Table 20, §7.6.6) for the key a handler returned. + /// The encryption dictionary. + /// Its V. + /// What the handler returned. + /// Where to report deviations. + /// Resolves references without decryption. + /// The decryptor. + /// A method the document uses for its strings or streams is unknown. + public static DocumentDecryptor Create( + CosDictionary encryption, + int version, + SecurityHandlerResult result, + DiagnosticSink diagnostics, + Func resolve) + { + byte[] fileKey = result.FileEncryptionKey.ToArray(); + var identity = new CryptFilter(FilterNames.Identity, CryptMethod.Identity, []); + switch (version) + { + case 1 or 2 or 3: + { + if (version == 3) + { + diagnostics.Report( + DiagnosticCodes.EncryptionVersionInvalid, + DiagnosticSeverity.Warning, + "V 3 (an unpublished algorithm) shall not appear in a conforming file; it is read as V 2, RC4 with the Length key."); + } + + var rc4 = new CryptFilter(StandardFilterName, CryptMethod.Rc4, fileKey); + return new DocumentDecryptor(rc4, rc4, rc4, [], encryptMetadata: true, diagnostics, resolve); + } + + case 4 or 5 or 6: + { + var named = new Dictionary(); + var unsupported = new Dictionary(); + if (resolve(encryption.TryGetValue(CF, out CosObject? cf) ? cf : null) is CosDictionary filters) + { + for (int index = 0; index < filters.Count; index++) + { + (CosName name, CosObject entry) = filters.GetAt(index); + if (name.Equals(FilterNames.Identity)) + { + continue; // Table 20: standard crypt filter names in CF shall be ignored. + } + + byte[] key = result.CryptFilterKeys is { } keys && keys.TryGetValue(name, out ReadOnlyMemory own) ? own.ToArray() : fileKey; + if (ReadFilter(name, resolve(entry) as CosDictionary, version, key, diagnostics, resolve, out string? problem) is { } filter) + { + named[name] = filter; + } + else + { + unsupported[name] = problem!; + } + } + } + + CryptFilter Select(CosName key, CosName? fallback) + { + CosName? name = resolve(encryption.TryGetValue(key, out CosObject? entry) ? entry : null) as CosName ?? fallback; + if (name is null || name.Equals(FilterNames.Identity)) + { + return identity; + } + + if (named.TryGetValue(name, out CryptFilter? filter)) + { + return filter; + } + + if (unsupported.TryGetValue(name, out string? problem)) + { + throw new PdfEncryptionNotSupportedException(PdfEncryptionNotSupportedReason.Algorithm, problem); + } + + diagnostics.Report( + DiagnosticCodes.CryptFilterMissing, + DiagnosticSeverity.Error, + $"{key.Value} names the crypt filter /{name.Value}, which the CF dictionary does not define; that data is left as it is."); + return identity; + } + + CryptFilter streams = Select(StmF, null); + CryptFilter strings = Select(StrF, null); + CryptFilter embedded = encryption.ContainsKey(EFF) ? Select(EFF, null) : streams; + bool encryptMetadata = resolve(encryption.TryGetValue(EncryptMetadataName, out CosObject? flag) ? flag : null) is not CosBoolean { Value: false }; + return new DocumentDecryptor(strings, streams, embedded, named, encryptMetadata, diagnostics, resolve); + } + + default: + throw new PdfEncryptionNotSupportedException( + PdfEncryptionNotSupportedReason.Algorithm, + string.Create(CultureInfo.InvariantCulture, $"The encryption algorithm V {version} is not defined.")); + } + } + + /// + public CosObject Decrypt(CosObject value, in ObjectLoadContext context) + { + if (context.Origin != ObjectOrigin.FileBody) + { + return value; + } + + CosReference id = context.Reference; + switch (value) + { + case CosString text: + return DecryptString(text, id); + case CosStream stream: + DecryptStream(stream, id); + return stream; + case CosDictionary dictionary: + DecryptStrings(dictionary, id); + return dictionary; + case CosArray array: + DecryptStrings(array, id); + return array; + default: + return value; + } + } + + /// + /// The loader decrypted the stream already (see the class remarks); a known crypt filter passes the data through. + public bool TryDecrypt(CosName cryptFilterName, ReadOnlySpan data, IBufferWriter output, FilterContext context) + { + if (!cryptFilterName.Equals(FilterNames.Identity) && !_named.ContainsKey(cryptFilterName)) + { + return false; + } + + output.Write(data); + return true; + } + + /// Decrypts data with a crypt filter, outside any object (tests, fuzzing, and the integrity check's own needs). + /// The crypt filter. + /// The encrypted data. + /// The object the data belongs to. + /// The plaintext. + public ReadOnlyMemory Apply(CryptFilter filter, ReadOnlySpan data, CosReference id) => Apply(filter, data, id, perObjectKey: true); + + private static CryptFilter? ReadFilter( + CosName name, + CosDictionary? dictionary, + int version, + byte[] key, + DiagnosticSink diagnostics, + Func resolve, + out string? problem) + { + problem = null; + CosName method = resolve(dictionary?.TryGetValue(CFM, out CosObject? entry) == true ? entry : null) as CosName ?? None; + if (method.Equals(None)) + { + diagnostics.Report( + DiagnosticCodes.CryptFilterMethodInvalid, + DiagnosticSeverity.Warning, + $"The crypt filter /{name.Value} has the method None, which leaves decryption to the security handler; this handler has no method of its own, so the data is left as it is."); + return new CryptFilter(name, CryptMethod.Identity, []); + } + + if (method.Equals(V2)) + { + return new CryptFilter(name, CryptMethod.Rc4, key); + } + + if (method.Equals(AESV2)) + { + if (version >= 5) + { + diagnostics.Report( + DiagnosticCodes.CryptFilterMethodInvalid, + DiagnosticSeverity.Warning, + $"The crypt filter /{name.Value} uses AESV2 with a 256-bit file key (V {version}); it is read as AESV3, as other readers do."); + return Aes256(name, CryptMethod.AesV3, key, out problem); + } + + return new CryptFilter(name, CryptMethod.AesV2, Fit(name, key, 16, diagnostics)); + } + + if (method.Equals(AESV3)) + { + return Aes256(name, CryptMethod.AesV3, key, out problem); + } + + if (method.Equals(AESV4)) + { + if (version < 6) + { + diagnostics.Report( + DiagnosticCodes.CryptFilterMethodInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The crypt filter /{name.Value} uses AESV4, which goes with V 6 (ISO/TS 32003); the dictionary has V {version}. It is read as AES-GCM.")); + } + + return Aes256(name, CryptMethod.AesV4, key, out problem); + } + + problem = $"The crypt filter /{name.Value} uses the method /{method.Value}, which this engine does not support (§7.6.6, Table 25)."; + return null; + } + + private static CryptFilter? Aes256(CosName name, CryptMethod method, byte[] key, out string? problem) + { + if (key.Length != 32) + { + problem = string.Create(CultureInfo.InvariantCulture, $"The crypt filter /{name.Value} needs a 256-bit key; the security handler's key has {key.Length * 8} bits."); + return null; + } + + problem = null; + return new CryptFilter(name, method, key); + } + + private static byte[] Fit(CosName name, byte[] key, int length, DiagnosticSink diagnostics) + { + if (key.Length == length) + { + return key; + } + + diagnostics.Report( + DiagnosticCodes.EncryptionKeyLengthInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The crypt filter /{name.Value} needs a {length * 8}-bit key; the {key.Length * 8}-bit key is {(key.Length < length ? "padded with zeros" : "truncated")}.")); + byte[] fitted = new byte[length]; + key.AsSpan(0, Math.Min(length, key.Length)).CopyTo(fitted); + return fitted; + } + + private static bool IsType(CosDictionary dictionary, CosName type) => + dictionary.TryGetValue(KnownNames.Type, out CosObject? value) && type.Equals(value); + + /// A signature dictionary's Contents is never encrypted (§7.6.2): Type Sig or DocTimeStamp, or Contents with ByteRange. + private static bool IsSignature(CosDictionary dictionary) => + IsType(dictionary, Sig) || IsType(dictionary, DocTimeStamp) + || (dictionary.TryGetValue(Contents, out CosObject? contents) && contents is CosString && dictionary.TryGetValue(ByteRange, out CosObject? range) && range is CosArray); + + private CosString DecryptString(CosString text, CosReference id) + { + if (_strings.Method == CryptMethod.Identity) + { + return text; + } + + ReadOnlyMemory plain = Apply(_strings, text.Bytes, id, perObjectKey: true); + return CosString.FromOwnedBytes(plain.ToArray(), text.IsHexadecimal); + } + + private void DecryptStrings(CosDictionary dictionary, CosReference id) + { + bool signature = IsSignature(dictionary); + for (int index = 0; index < dictionary.Count; index++) + { + (CosName key, CosObject value) = dictionary.GetAt(index); + switch (value) + { + case CosString text when !(signature && key.Equals(Contents)): + dictionary.ReplaceLoaded(index, DecryptString(text, id)); + break; + case CosDictionary inner: + DecryptStrings(inner, id); + break; + case CosArray inner: + DecryptStrings(inner, id); + break; + default: + break; + } + } + } + + private void DecryptStrings(CosArray array, CosReference id) + { + for (int index = 0; index < array.Count; index++) + { + switch (array[index]) + { + case CosString text: + array.ReplaceLoaded(index, DecryptString(text, id)); + break; + case CosDictionary inner: + DecryptStrings(inner, id); + break; + case CosArray inner: + DecryptStrings(inner, id); + break; + default: + break; + } + } + } + + private void DecryptStream(CosStream stream, CosReference id) + { + CosDictionary dictionary = stream.Dictionary; + if (IsType(dictionary, XRef)) + { + return; // §7.5.8.2: cross-reference streams are never encrypted, nor their dictionaries' strings. + } + + DecryptStrings(dictionary, id); + CryptFilter filter; + bool perObjectKey = true; + if (TryReadCryptFilterName(dictionary, out CosName? cryptFilterName)) + { + if (cryptFilterName.Equals(FilterNames.Identity) || !_named.TryGetValue(cryptFilterName, out CryptFilter? named)) + { + return; // Identity, or unknown: the pipeline reports CryptFilterUnsupported when the stream is decoded. + } + + filter = named; + perObjectKey = false; // §7.4.10: the crypt filter's key is used as is. + } + else if (IsType(dictionary, Metadata) && !EncryptMetadata) + { + return; + } + else + { + filter = IsType(dictionary, EmbeddedFile) ? _embeddedFiles : _streams; + } + + if (filter.Method == CryptMethod.Identity || stream.EncodedLength == 0) + { + return; + } + + // A stream opened from a file reads its data from the source on every access (#45): read it once, store the plaintext. + ReadOnlyMemory data = stream.EncodedData; + if (IsType(dictionary, Metadata) && data.Span.StartsWith("Reads the crypt filter a stream names when its first filter is Crypt (§7.4.10, Table 14; default Identity). + private bool TryReadCryptFilterName(CosDictionary dictionary, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out CosName? name) + { + name = null; + CosObject filters = _resolve(dictionary.TryGetValue(FilterNames.Filter, out CosObject? filter) ? filter : null); + bool first = filters switch + { + CosName single => single.Equals(FilterNames.Crypt), + CosArray { Count: > 0 } array => FilterNames.Crypt.Equals(_resolve(array[0])), + _ => false, + }; + if (!first) + { + return false; + } + + CosObject parameters = _resolve(dictionary.TryGetValue(FilterNames.DecodeParms, out CosObject? entry) ? entry : null); + if (parameters is CosArray { Count: > 0 } list) + { + parameters = _resolve(list[0]); + } + + name = parameters is CosDictionary decodeParms && _resolve(decodeParms.TryGetValue(FilterNames.Name, out CosObject? value) ? value : null) is CosName named + ? named + : FilterNames.Identity; + return true; + } + + private ReadOnlyMemory Apply(CryptFilter filter, ReadOnlySpan data, CosReference id, bool perObjectKey) + { + switch (filter.Method) + { + case CryptMethod.Identity: + return data.ToArray(); + case CryptMethod.Rc4: + { + byte[] output = new byte[data.Length]; + Rc4.Transform(perObjectKey ? ObjectKey(filter.Key, id, aes: false) : filter.Key, data, output); + return output; + } + + case CryptMethod.AesV2: + { + byte[] key = perObjectKey ? ObjectKey(filter.Key, id, aes: true) : filter.Key; + ReadOnlyMemory plain = DecryptCbc(key, data, out string? problem); + if (problem is not null && !perObjectKey) + { + ReadOnlyMemory salted = DecryptCbc(ObjectKey(filter.Key, id, aes: true), data, out string? saltedProblem); + if (saltedProblem is null) + { + return salted; + } + } + + Report(problem, id); + return plain; + } + + case CryptMethod.AesV3: + { + ReadOnlyMemory plain = DecryptCbc(filter.Key, data, out string? problem); + Report(problem, id); + return plain; + } + + default: + return DecryptGcm(filter.Key, data, id); + } + } + + /// Algorithm 1 steps b-d: MD5 of the key, the low 3 bytes of the object number, the low 2 of the generation, "sAlT" for AES. + private static byte[] ObjectKey(byte[] fileKey, CosReference id, bool aes) + { + Span input = stackalloc byte[fileKey.Length + 9]; + fileKey.CopyTo(input); + int offset = fileKey.Length; + input[offset] = (byte)id.ObjectNumber; + input[offset + 1] = (byte)(id.ObjectNumber >> 8); + input[offset + 2] = (byte)(id.ObjectNumber >> 16); + input[offset + 3] = (byte)id.Generation; + input[offset + 4] = (byte)(id.Generation >> 8); + int length = offset + 5; + if (aes) + { + "sAlT"u8.CopyTo(input[length..]); + length += 4; + } + + Span digest = stackalloc byte[Md5.HashSize]; + Md5.HashData(input[..length], digest); + return digest[..Math.Min(fileKey.Length + 5, 16)].ToArray(); + } + + /// AES-CBC with the IV in the first 16 bytes and PKCS#5 padding (§7.6.3.1), repaired the way pdf.js repairs it. + private static ReadOnlyMemory DecryptCbc(ReadOnlySpan key, ReadOnlySpan data, out string? problem) + { + problem = null; + if (data.Length < 32) + { + problem = string.Create(CultureInfo.InvariantCulture, $"AES-encrypted data shall hold a 16-byte IV and at least one 16-byte block; {data.Length} bytes decrypt to nothing."); + return ReadOnlyMemory.Empty; + } + + int body = (data.Length - 16) & ~15; + if (body != data.Length - 16) + { + problem = "AES-encrypted data is not a whole number of 16-byte blocks; the partial block at the end is dropped."; + } + + byte[] plain = new byte[body]; + using (AesCipher aes = AesCipher.Create(key)) + { + aes.DecryptCbc(data.Slice(16, body), data[..16], plain); + } + + int pad = plain[^1]; + bool valid = pad is >= 1 and <= 16; + for (int i = 1; valid && i <= pad; i++) + { + valid = plain[^i] == pad; + } + + if (!valid) + { + problem ??= "AES-decrypted data does not end with a valid PKCS#5 pad; it is kept whole."; + return plain; + } + + return plain.AsMemory(0, body - pad); + } + + private ReadOnlyMemory DecryptGcm(ReadOnlySpan key, ReadOnlySpan data, CosReference id) + { + const int overhead = AesGcmCipher.NonceSize + AesGcmCipher.TagSize; + if (data.Length < overhead) + { + Report(string.Create(CultureInfo.InvariantCulture, $"AES-GCM data shall hold a 12-byte IV and a 16-byte tag; {data.Length} bytes decrypt to nothing."), id); + return ReadOnlyMemory.Empty; + } + + byte[] plain = new byte[data.Length - overhead]; + if (!AesGcmCipher.TryDecrypt(key, data[..AesGcmCipher.NonceSize], data[AesGcmCipher.NonceSize..^AesGcmCipher.TagSize], data[^AesGcmCipher.TagSize..], plain)) + { + _diagnostics.Report( + DiagnosticCodes.EncryptedDataAuthenticationFailed, + DiagnosticSeverity.Error, + "The AES-GCM authentication tag does not match: the data was changed or damaged after it was encrypted; it decrypts to nothing.", + objectReference: id); + return ReadOnlyMemory.Empty; + } + + return plain; + } + + private void Report(string? problem, CosReference id) + { + if (problem is not null) + { + _diagnostics.Report(DiagnosticCodes.EncryptedDataInvalid, DiagnosticSeverity.Warning, problem, objectReference: id); + } + } +} diff --git a/src/Broadside/Security/DocumentSecurity.cs b/src/Broadside/Security/DocumentSecurity.cs new file mode 100644 index 00000000..bd2dcb41 --- /dev/null +++ b/src/Broadside/Security/DocumentSecurity.cs @@ -0,0 +1,173 @@ +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Filters; +using Broadside.IO; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Security; + +/// Opens the encryption of a document while it opens: handler, authentication, decryption hooks, integrity check. +/// +/// ISO 32000-2 §7.6.2: a document is encrypted when its trailer has an Encrypt entry. Runs after the cross-reference +/// information is read and before the catalog loads, so the encryption dictionary (and anything it refers to) loads undecrypted and +/// every object loaded afterwards is decrypted. The newest trailer's Encrypt and ID apply (§7.6.2: the entry "should be +/// identical in all copies of the trailer"). +/// +internal static class DocumentSecurity +{ + private static readonly CosName SubFilterName = new("SubFilter"); + private static readonly CosName StandardName = new("Standard"); + private static readonly CosName R = new("R"); + + /// Reads the trailer's Encrypt entry and, for an encrypted document, installs decryption on the loader and pipeline. + /// The file. + /// The document's loader; its decryptor hook is set. + /// The document's pipeline; its crypt filter slot is set. + /// The engine's security handlers. + /// The credentials offered, or . + /// Where to report deviations. + /// + /// Whether an Encrypt entry that does not resolve to a dictionary is reported and the document read as not encrypted; + /// otherwise it sets so the caller can rebuild the cross-reference information first. + /// + /// Set when the Encrypt entry does not resolve and is false. + /// The document's security, or when it is not encrypted. + /// The credentials do not open the document. + /// No handler or method for the document's encryption. + public static PdfSecurity? Open( + PdfSource source, + ObjectLoader loader, + StreamDecoder streams, + SecurityHandlerRegistry handlers, + PdfCredentials? credentials, + DiagnosticSink diagnostics, + bool reportUnusable, + out bool unusable) + { + unusable = false; + CosDictionary trailer = loader.CrossReference.Trailer; + if (!trailer.TryGetValue(KnownNames.Encrypt, out CosObject? entry)) + { + return null; + } + + if (loader.Resolve(entry) is not CosDictionary encryption) + { + if (!reportUnusable) + { + unusable = true; + return null; + } + + diagnostics.Report( + DiagnosticCodes.EncryptDictionaryInvalid, + DiagnosticSeverity.Error, + "The trailer's Encrypt entry is not a dictionary; the document is read as not encrypted."); + return null; + } + + CosName? filter = loader.Resolve(encryption.TryGetValue(FilterNames.Filter, out CosObject? named) ? named : null) as CosName; + CosName? subFilter = loader.Resolve(encryption.TryGetValue(SubFilterName, out CosObject? sub) ? sub : null) as CosName; + if (filter is null && encryption.ContainsKey(R)) + { + diagnostics.Report( + DiagnosticCodes.EncryptDictionaryInvalid, + DiagnosticSeverity.Warning, + "The encryption dictionary has no Filter entry; its R entry marks it as the standard security handler's."); + filter = StandardName; + } + + ISecurityHandler handler = handlers.Find(filter, subFilter) ?? throw new PdfEncryptionNotSupportedException( + PdfEncryptionNotSupportedReason.Handler, + $"The document is encrypted by the security handler /{filter?.Value ?? "(none)"}{(subFilter is null ? string.Empty : $" (format /{subFilter.Value})")}, which no registered handler implements."); + + int version = loader.Resolve(encryption.TryGetValue(KnownNames.V, out CosObject? v) ? v : null) is CosInteger { Value: >= 0 and <= int.MaxValue } integer + ? (int)integer.Value + : 0; + ReadOnlyMemory documentId = ReadDocumentId(trailer, diagnostics); + var context = new SecurityHandlerContext(encryption, documentId, credentials, diagnostics, loader.Resolve); + SecurityHandlerResult result = handler.Authenticate(context); + if (version == 0) + { + version = result.Revision switch { 2 => 1, 3 => 2, 4 => 4, 7 => 6, _ => 5 }; + } + + DocumentDecryptor decryptor = DocumentDecryptor.Create(encryption, version, result, diagnostics, loader.Resolve); + loader.Hooks.Decryptor = decryptor; + streams.CryptFilter = decryptor; + + PdfIntegrityStatus integrity = IntegrityVerifier.Verify(source, loader, version, result, diagnostics); + return new PdfSecurity( + encryption, + handler.Filter, + subFilter, + version, + result.Revision, + result.FileEncryptionKey.Length * 8, + result.Access, + result.Permissions, + result.RawPermissions, + decryptor.EncryptMetadata, + integrity); + } + + /// + /// Checks, once the catalog is loaded, that a document using ISO/TS 32003 or ISO/TS 32004 declares the extension (their clause 4: + /// the developer extensions dictionary "shall be included"). + /// + /// The document's security. + /// The catalog. + /// Resolves references. + /// Where to report deviations. + public static void CheckExtensions(PdfSecurity security, CosDictionary catalog, Func resolve, DiagnosticSink diagnostics) + { + if (security.Version >= 6) + { + CheckExtension(32003, catalog, resolve, diagnostics); + } + + if (security.Integrity != PdfIntegrityStatus.None) + { + CheckExtension(32004, catalog, resolve, diagnostics); + } + } + + private static void CheckExtension(int level, CosDictionary catalog, Func resolve, DiagnosticSink diagnostics) + { + if (resolve(catalog.TryGetValue(KnownNames.Extensions, out CosObject? extensions) ? extensions : null) is CosDictionary dictionary + && resolve(dictionary.TryGetValue(KnownNames.IsoPrefix, out CosObject? iso) ? iso : null) is CosObject entries) + { + IEnumerable list = entries is CosArray array ? array : [entries]; + foreach (CosObject item in list) + { + if (resolve(item) is CosDictionary extension + && resolve(extension.TryGetValue(KnownNames.ExtensionLevel, out CosObject? value) ? value : null) is CosInteger { Value: var found } + && found == level) + { + return; + } + } + } + + diagnostics.Report( + DiagnosticCodes.EncryptionExtensionMissing, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The document uses ISO/TS {level} but its catalog's Extensions dictionary has no ISO_ entry with ExtensionLevel {level} (clause 4); it is read anyway.")); + } + + /// The first element of the trailer's ID array (§7.5.5 Table 15: required when the document is encrypted). + private static ReadOnlyMemory ReadDocumentId(CosDictionary trailer, DiagnosticSink diagnostics) + { + if (trailer.TryGetValue(KnownNames.ID, out CosObject? id) && id is CosArray { Count: >= 1 } array && array[0] is CosString first) + { + return first.Bytes.ToArray(); + } + + diagnostics.Report( + DiagnosticCodes.EncryptionIdMissing, + DiagnosticSeverity.Warning, + "The trailer of an encrypted document shall have an ID array of two strings; an empty identifier is used."); + return ReadOnlyMemory.Empty; + } +} diff --git a/src/Broadside/Security/ISecurityHandler.cs b/src/Broadside/Security/ISecurityHandler.cs new file mode 100644 index 00000000..1480cba3 --- /dev/null +++ b/src/Broadside/Security/ISecurityHandler.cs @@ -0,0 +1,132 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Security; + +/// +/// A security handler: given a document's encryption dictionary and the reader's credentials, it authenticates them and yields the +/// file encryption key and the permissions. The extension point every encrypted document opens through. +/// +/// +/// +/// ISO 32000-2 §7.6.2 (Table 20) and §7.6.3. A handler is registered with ; the engine +/// picks the one whose is the document's Filter, else one that lists the document's SubFilter in +/// . is registered by default; registering another handler for +/// Standard replaces it. +/// +/// +/// The handler only authenticates. The engine applies the encryption the dictionary describes (V, Length, CF, +/// StmF, StrF, EFF, EncryptMetadata) with the key the handler returns: Algorithm 1 (RC4 and AES-128 with +/// per-object keys), Algorithm 1.A (AES-256) and AES-GCM (ISO/TS 32003), the crypt filters of §7.6.6, and the integrity MAC of +/// ISO/TS 32004. Handlers are shared by every document an engine opens, from any thread: keep them stateless. +/// +/// +public interface ISecurityHandler +{ + /// Gets the handler name a document's Filter entry selects it by, such as Standard. + CosName Filter { get; } + + /// Gets the SubFilter formats the handler implements, by which it may open documents another handler encrypted. + IReadOnlyCollection SubFilters { get; } + + /// Authenticates the credentials against the encryption dictionary. + /// The encryption dictionary, the file identifier, the credentials and the diagnostics. + /// The file encryption key, the access level and the permissions. + /// The credentials do not open the document. + /// The handler does not implement what the dictionary asks for. + /// The dictionary is too damaged to authenticate against. + SecurityHandlerResult Authenticate(SecurityHandlerContext context); +} + +/// What a security handler authenticates against. +/// ISO 32000-2 §7.6.2. Created by the engine for one document while it opens. +public sealed class SecurityHandlerContext +{ + private readonly DiagnosticSink _diagnostics; + private readonly Func _resolve; + + internal SecurityHandlerContext( + CosDictionary encryptionDictionary, + ReadOnlyMemory documentId, + PdfCredentials? credentials, + DiagnosticSink diagnostics, + Func resolve) + { + EncryptionDictionary = encryptionDictionary; + DocumentId = documentId; + Credentials = credentials; + _diagnostics = diagnostics; + _resolve = resolve; + } + + /// Gets the encryption dictionary. Its strings are never encrypted (§7.6.2). + public CosDictionary EncryptionDictionary { get; } + + /// Gets the first element of the trailer's ID array, or empty when the trailer has none. + /// ISO 32000-2 §7.5.5, Table 15; Algorithm 2 step e. + public ReadOnlyMemory DocumentId { get; } + + /// Gets the credentials the reader offered, or for none (try the default user password). + public PdfCredentials? Credentials { get; } + + /// Gets the reading mode; in strict mode throws. + public PdfReadingMode ReadingMode => _diagnostics.IsStrict ? PdfReadingMode.Strict : PdfReadingMode.Lenient; + + /// Records a deviation found in the encryption dictionary. In strict mode, throws it as a . + /// A PascalCase code. + /// The severity. + /// What deviates and what was done about it. + public void Report(string code, DiagnosticSeverity severity, string message) => _diagnostics.Report(code, severity, message); + + /// Returns , or the object it refers to, read without decryption. + /// An entry of the encryption dictionary, or . + /// The direct object; for an absent entry. + public CosObject Resolve(CosObject? value) => _resolve(value); +} + +/// What a security handler returns when the credentials open the document. +/// ISO 32000-2 §7.6.3: the file encryption key the handler computes, from which every string and stream key derives. +public sealed class SecurityHandlerResult +{ + private readonly byte[] _fileEncryptionKey; + + /// Initializes a new instance of the class. + /// The file encryption key, copied. + /// Which credential opened the document. + /// The permissions that apply to that access ( for the owner). + /// The permissions word as the document states it. + public SecurityHandlerResult(ReadOnlySpan fileEncryptionKey, PdfAccessLevel access, PdfPermissions permissions, int rawPermissions) + { + if (fileEncryptionKey.IsEmpty) + { + throw new ArgumentException("The file encryption key cannot be empty.", nameof(fileEncryptionKey)); + } + + _fileEncryptionKey = fileEncryptionKey.ToArray(); + Access = access; + Permissions = permissions; + RawPermissions = rawPermissions; + } + + /// Gets the file encryption key. + public ReadOnlyMemory FileEncryptionKey => _fileEncryptionKey; + + /// Gets which credential opened the document. + public PdfAccessLevel Access { get; } + + /// Gets the permissions that apply. + public PdfPermissions Permissions { get; } + + /// Gets the permissions word as the document states it. + public int RawPermissions { get; } + + /// Gets the handler's revision, for the standard security handler the R entry; otherwise . + public int? Revision { get; init; } + + /// + /// Gets keys for named crypt filters that do not use the file encryption key, such as a public-key handler's crypt filters with + /// their own recipients (§7.6.6, Table 27); when every crypt filter uses the file encryption key. + /// + public IReadOnlyDictionary>? CryptFilterKeys { get; init; } +} diff --git a/src/Broadside/Security/IntegrityVerifier.cs b/src/Broadside/Security/IntegrityVerifier.cs new file mode 100644 index 00000000..a950d482 --- /dev/null +++ b/src/Broadside/Security/IntegrityVerifier.cs @@ -0,0 +1,615 @@ +using System.Formats.Asn1; +using System.Globalization; +using System.Security.Cryptography; +using System.Security.Cryptography.Pkcs; +using System.Text; +using Broadside.Diagnostics; +using Broadside.IO; +using Broadside.Objects; +using Broadside.Parsing; +using Broadside.Security.Cryptography; + +namespace Broadside.Security; + +/// Verifies the integrity MAC of an encrypted document (ISO/TS 32004). +/// +/// +/// ISO/TS 32004 §5.2.3 (the trailer's AuthCode dictionary), §6.3-6.6 (the PDF MAC token: a CMS AuthenticatedData with one +/// password recipient, the key derived with pdfMacWrapKdf, wrapped with AES-256 key wrap, HMAC-SHA-256 over the authenticated +/// attributes) and Annex B (validation). Only the newest revision's AuthCode counts (B.1). A standalone token is checked +/// against the byte range it states, which must cover the whole file except the token itself (B.2.2); a token attached to a +/// signature is checked against the signature's byte range and signature value (B.2.3). +/// +/// +/// Outcomes are diagnostics: a token that is malformed is IntegrityCodeInvalid, one that does not match the file is +/// IntegrityCodeMismatch, one whose byte range stops short of the end of the file is IntegrityCodeIncomplete, a +/// missing token the permissions require is IntegrityCodeMissing, and one that cannot be checked here (a SHA-3 digest the +/// platform lacks) is IntegrityCodeNotVerified. Strict mode throws on any of them. The file is digested in windows, so a large +/// file is never held in memory for this. +/// +/// +internal static class IntegrityVerifier +{ + private const string AuthenticatedDataOid = "1.2.840.113549.1.9.16.1.2"; + private const string IntegrityInfoOid = "1.0.32004.1.0"; + private const string WrapKdfOid = "1.0.32004.1.1"; + private const string MacDataAttributeOid = "1.0.32004.1.2"; + private const string Aes256WrapOid = "2.16.840.1.101.3.4.1.45"; + private const string HmacSha256Oid = "1.2.840.113549.2.9"; + private const string ContentTypeAttributeOid = "1.2.840.113549.1.9.3"; + private const string MessageDigestAttributeOid = "1.2.840.113549.1.9.4"; + + private static readonly CosName AuthCode = new("AuthCode"); + private static readonly CosName MacLocation = new("MACLocation"); + private static readonly CosName Standalone = new("Standalone"); + private static readonly CosName AttachedToSig = new("AttachedToSig"); + private static readonly CosName ByteRange = new("ByteRange"); + private static readonly CosName SigObjRef = new("SigObjRef"); + private static readonly CosName KdfSalt = new("KDFSalt"); + private static readonly CosName Contents = new("Contents"); + + /// Checks the document's PDF MAC token, if it has or needs one. + /// The file. + /// The loader, decryption installed. + /// The encryption dictionary's V. + /// The security handler's result: the file encryption key and the permissions. + /// Where to report the outcome. + /// The outcome. + public static PdfIntegrityStatus Verify(PdfSource source, ObjectLoader loader, int version, SecurityHandlerResult result, DiagnosticSink diagnostics) + { + CosDictionary trailer = loader.CrossReference.Sections[0].Trailer; + bool required = version >= 5 && (result.RawPermissions & (1 << 12)) == 0; + if (!trailer.TryGetValue(AuthCode, out CosObject? entry)) + { + if (!required) + { + return PdfIntegrityStatus.None; + } + + diagnostics.Report( + DiagnosticCodes.IntegrityCodeMissing, + DiagnosticSeverity.Warning, + "Permission bit 13 is clear, so a PDF MAC token is required (ISO/TS 32004 Table 3), but the trailer has no AuthCode dictionary."); + return PdfIntegrityStatus.Missing; + } + + var verifier = new Verification(source, loader, diagnostics); + return verifier.Run(entry, version, result.FileEncryptionKey.Span); + } + + /// Parses a PDF MAC token and checks its structure (§6.3) without any key: the parser the fuzz target drives. + /// The DER-encoded token. + /// Why the token is invalid, or . + /// when the token is structurally valid. + internal static bool TryParseToken(byte[] der, out string? problem) + { + try + { + problem = MacToken.Parse(der).Problem; + } + catch (AsnContentException exception) + { + problem = exception.Message; + } + catch (CryptographicException exception) + { + problem = exception.Message; + } + + return problem is null; + } + + /// The checks of one document, with its diagnostics. + private sealed class Verification(PdfSource source, ObjectLoader loader, DiagnosticSink diagnostics) + { + public PdfIntegrityStatus Run(CosObject entry, int version, ReadOnlySpan fileKey) + { + if (loader.Resolve(entry) is not CosDictionary authCode) + { + return Invalid("The trailer's AuthCode entry shall be a dictionary."); + } + + if (version < 5) + { + return Invalid(string.Create(CultureInfo.InvariantCulture, $"An AuthCode dictionary requires an encryption dictionary with V 5 or later (ISO/TS 32004 Table 5); this one has V {version}.")); + } + + if (Encryption() is not { } encryption + || loader.Resolve(encryption.TryGetValue(KdfSalt, out CosObject? salt) ? salt : null) is not CosString { Bytes.Length: 32 } kdfSalt) + { + return Invalid("The encryption dictionary shall have a 32-byte KDFSalt string when the document has a PDF MAC token (ISO/TS 32004 Table 2)."); + } + + CosObject location = loader.Resolve(authCode.TryGetValue(MacLocation, out CosObject? named) ? named : null); + if (Standalone.Equals(location)) + { + return VerifyStandalone(authCode, fileKey, kdfSalt.Bytes); + } + + if (AttachedToSig.Equals(location)) + { + return VerifyAttached(authCode, fileKey, kdfSalt.Bytes); + } + + if (location is CosName other) + { + diagnostics.Report( + DiagnosticCodes.IntegrityCodeNotVerified, + DiagnosticSeverity.Information, + $"The PDF MAC token's location /{other.Value} is not one ISO/TS 32004 defines; the token is not checked."); + return PdfIntegrityStatus.NotVerified; + } + + return Invalid("The AuthCode dictionary has no MACLocation, which indicates an invalid MAC (ISO/TS 32004 B.2.1)."); + } + + private CosDictionary? Encryption() => + loader.Resolve(loader.CrossReference.Trailer.TryGetValue(KnownNames.Encrypt, out CosObject? encrypt) ? encrypt : null) as CosDictionary; + + private PdfIntegrityStatus VerifyStandalone(CosDictionary authCode, ReadOnlySpan fileKey, ReadOnlySpan kdfSalt) + { + if (!TryReadByteRange(authCode, out long[] range)) + { + return Invalid("The AuthCode ByteRange shall be four nonnegative integers [0 L1 S L2] with S greater than L1, inside the file."); + } + + long baseOffset = loader.Header.Offset; + long gapStart = range[1]; + long gapEnd = range[2]; + if (!TryReadHexToken(baseOffset + gapStart, gapEnd - gapStart, out byte[]? token)) + { + return Invalid("The bytes the AuthCode ByteRange leaves out shall be exactly the MAC string: '<', an even number of hexadecimal digits, '>'."); + } + + return CheckCoverage(VerifyToken(token, fileKey, kdfSalt, range, signatureValue: null), range); + } + + /// B.2.2.2 and B.2.3.2: a valid token whose byte range stops short of the end of the file leaves the rest unprotected. + private PdfIntegrityStatus CheckCoverage(PdfIntegrityStatus status, long[] range) + { + if (status == PdfIntegrityStatus.Verified && range[2] + range[3] != source.Length - loader.Header.Offset) + { + diagnostics.Report( + DiagnosticCodes.IntegrityCodeIncomplete, + DiagnosticSeverity.Warning, + "The PDF MAC token is valid but its byte range does not reach the end of the file: what follows is not protected (a stale MAC after an update, or tampering; ISO/TS 32004 B.2.2.2, B.2.3.2)."); + return PdfIntegrityStatus.Failed; + } + + return status; + } + + private PdfIntegrityStatus VerifyAttached(CosDictionary authCode, ReadOnlySpan fileKey, ReadOnlySpan kdfSalt) + { + if (!authCode.TryGetValue(SigObjRef, out CosObject? reference) + || loader.Resolve(reference) is not CosDictionary signature + || loader.Resolve(signature.TryGetValue(Contents, out CosObject? contents) ? contents : null) is not CosString container) + { + return Invalid("The AuthCode SigObjRef shall refer to a signature dictionary with a Contents string (ISO/TS 32004 Table 6)."); + } + + if (!TryReadByteRange(signature, out long[] range)) + { + return Invalid("The signature dictionary the PDF MAC token is attached to has no valid ByteRange."); + } + + byte[]? token = null; + byte[] signatureValue; + try + { + var signed = new SignedCms(); + signed.Decode(TrimTrailingZeros(container.Bytes)); + SignerInfo signer = signed.SignerInfos[0]; + signatureValue = signer.GetSignature(); + foreach (CryptographicAttributeObject attribute in signer.UnsignedAttributes) + { + if (attribute.Oid.Value == MacDataAttributeOid) + { + if (token is not null || attribute.Values.Count != 1) + { + return Invalid("The signature shall carry exactly one pdfMacData attribute with exactly one value (ISO/TS 32004 §6.5.2)."); + } + + token = attribute.Values[0].RawData; + } + } + } + catch (CryptographicException exception) + { + return Invalid($"The signature container the PDF MAC token is attached to cannot be decoded ({exception.Message})."); + } + catch (ArgumentOutOfRangeException) + { + return Invalid("The signature container the PDF MAC token is attached to has no signer."); + } + + if (token is null) + { + return Invalid("The signature the AuthCode dictionary points to carries no pdfMacData attribute (ISO/TS 32004 §6.5.2)."); + } + + return CheckCoverage(VerifyToken(token, fileKey, kdfSalt, range, signatureValue), range); + } + + /// Validates the token's CMS structure (§6.3, B.3) and its binding to the file (B.2). + private PdfIntegrityStatus VerifyToken(byte[] token, ReadOnlySpan fileKey, ReadOnlySpan kdfSalt, long[] range, byte[]? signatureValue) + { + MacToken parsed; + try + { + parsed = MacToken.Parse(token); + } + catch (AsnContentException exception) + { + return Invalid($"The PDF MAC token is not a valid DER-encoded AuthenticatedData ({exception.Message})."); + } + catch (CryptographicException exception) + { + return Invalid($"The PDF MAC token is not a valid DER-encoded AuthenticatedData ({exception.Message})."); + } + + if (parsed.Problem is { } problem) + { + return Invalid(problem); + } + + if (!TryCreateDigest(parsed.DigestAlgorithm, out HashAlgorithmName digestName)) + { + diagnostics.Report( + DiagnosticCodes.IntegrityCodeNotVerified, + DiagnosticSeverity.Information, + $"The PDF MAC token's digest algorithm {parsed.DigestAlgorithm} is not available on this platform; the document's integrity is not checked."); + return PdfIntegrityStatus.NotVerified; + } + + // §6.4: KEK = HKDF-SHA-256(file encryption key, KDFSalt, "PDFMAC"); then unwrap the MAC key (RFC 3394). + byte[] keyEncryptionKey = HKDF.DeriveKey(HashAlgorithmName.SHA256, fileKey.ToArray(), 32, kdfSalt.ToArray(), "PDFMAC"u8.ToArray()); + byte[]? macKey = AesKeyWrap.Unwrap(keyEncryptionKey, parsed.EncryptedKey); + if (macKey is null) + { + return Mismatch("The PDF MAC token's key does not unwrap with the document's key: the token was not made for this document's key, or was changed."); + } + + // RFC 5652 §9.2: the MAC covers the DER of the authenticated attributes with the SET OF tag. + byte[] attributes = parsed.AuthenticatedAttributes.ToArray(); + attributes[0] = 0x31; + byte[] mac = HMACSHA256.HashData(macKey, attributes); + if (!CryptographicOperations.FixedTimeEquals(mac, parsed.Mac)) + { + return Mismatch("The PDF MAC token's MAC does not match its authenticated attributes: the token was changed."); + } + + if (!CryptographicOperations.FixedTimeEquals(Hash(digestName, parsed.Content), parsed.MessageDigest)) + { + return Mismatch("The PDF MAC token's messageDigest attribute does not match its content."); + } + + if (signatureValue is null && parsed.SignatureDigest is not null) + { + return Invalid("A standalone PDF MAC token shall not have a signatureDigest (ISO/TS 32004 §6.6.2)."); + } + + if (signatureValue is not null + && (parsed.SignatureDigest is null || !CryptographicOperations.FixedTimeEquals(Hash(digestName, signatureValue), parsed.SignatureDigest))) + { + return Mismatch("The PDF MAC token's signatureDigest does not match the signature it is attached to (ISO/TS 32004 §6.6.3)."); + } + + if (!CryptographicOperations.FixedTimeEquals(DigestRange(digestName, range), parsed.DataDigest)) + { + return Mismatch("The file's bytes do not match the PDF MAC token's dataDigest: the document was changed after the MAC was computed."); + } + + return PdfIntegrityStatus.Verified; + } + + private bool TryReadByteRange(CosDictionary dictionary, out long[] range) + { + range = new long[4]; + if (loader.Resolve(dictionary.TryGetValue(ByteRange, out CosObject? entry) ? entry : null) is not CosArray { Count: 4 } array) + { + return false; + } + + for (int i = 0; i < 4; i++) + { + if (loader.Resolve(array[i]) is not CosInteger { Value: >= 0 } value) + { + return false; + } + + range[i] = value.Value; + } + + long length = source.Length - loader.Header.Offset; + return range[0] == 0 && range[2] > range[1] && range[1] <= length && range[2] <= length && range[3] <= length - range[2]; + } + + private bool TryReadHexToken(long offset, long length, out byte[] token) + { + token = []; + if (length < 2 || length > 1 << 20) + { + return false; + } + + byte[] region = new byte[length]; + if (source.Read(offset, region) != region.Length || region[0] != (byte)'<' || region[^1] != (byte)'>' || (region.Length - 2) % 2 != 0) + { + return false; + } + + try + { + token = Convert.FromHexString(Encoding.ASCII.GetString(region, 1, region.Length - 2)); + return true; + } + catch (FormatException) + { + return false; + } + } + + private byte[] DigestRange(HashAlgorithmName name, long[] range) + { + using var hash = IncrementalHash.CreateHash(name); + long baseOffset = loader.Header.Offset; + byte[] buffer = new byte[64 * 1024]; + for (int part = 0; part < 4; part += 2) + { + long position = baseOffset + range[part]; + long remaining = range[part + 1]; + while (remaining > 0) + { + int read = source.Read(position, buffer.AsSpan(0, (int)Math.Min(buffer.Length, remaining))); + if (read <= 0) + { + break; + } + + hash.AppendData(buffer, 0, read); + position += read; + remaining -= read; + } + } + + return hash.GetHashAndReset(); + } + + private PdfIntegrityStatus Invalid(string message) + { + diagnostics.Report(DiagnosticCodes.IntegrityCodeInvalid, DiagnosticSeverity.Error, message); + return PdfIntegrityStatus.Failed; + } + + private PdfIntegrityStatus Mismatch(string message) + { + diagnostics.Report(DiagnosticCodes.IntegrityCodeMismatch, DiagnosticSeverity.Error, message); + return PdfIntegrityStatus.Failed; + } + + private static byte[] TrimTrailingZeros(ReadOnlySpan container) + { + // Signature containers are padded with zeros to fill their reserved space (ISO 32000-2 §12.8.3.3.1). + int end = container.Length; + while (end > 0 && container[end - 1] == 0) + { + end--; + } + + return container[..end].ToArray(); + } + + private static byte[] Hash(HashAlgorithmName name, ReadOnlySpan data) => name.Name switch + { + "SHA256" => SHA256.HashData(data), + "SHA384" => SHA384.HashData(data), + "SHA512" => SHA512.HashData(data), + "SHA3-256" => SHA3_256.HashData(data), + "SHA3-384" => SHA3_384.HashData(data), + _ => SHA3_512.HashData(data), + }; + + /// ISO/TS 32004 Table 8. + private static bool TryCreateDigest(string oid, out HashAlgorithmName name) + { + (name, bool supported) = oid switch + { + "2.16.840.1.101.3.4.2.1" => (HashAlgorithmName.SHA256, true), + "2.16.840.1.101.3.4.2.2" => (HashAlgorithmName.SHA384, true), + "2.16.840.1.101.3.4.2.3" => (HashAlgorithmName.SHA512, true), + "2.16.840.1.101.3.4.2.8" => (HashAlgorithmName.SHA3_256, SHA3_256.IsSupported), + "2.16.840.1.101.3.4.2.9" => (HashAlgorithmName.SHA3_384, SHA3_384.IsSupported), + "2.16.840.1.101.3.4.2.10" => (HashAlgorithmName.SHA3_512, SHA3_512.IsSupported), + _ => (default, false), + }; + return supported; + } + } + + /// The parts of a PDF MAC token the validation needs (RFC 5652 §9.1, ISO/TS 32004 §6.2-6.3). + private sealed class MacToken + { + public string? Problem { get; private set; } + + public string DigestAlgorithm { get; private set; } = string.Empty; + + public byte[] EncryptedKey { get; private set; } = []; + + public ReadOnlyMemory AuthenticatedAttributes { get; private set; } + + public byte[] Mac { get; private set; } = []; + + public byte[] Content { get; private set; } = []; + + public byte[] MessageDigest { get; private set; } = []; + + public byte[] DataDigest { get; private set; } = []; + + public byte[]? SignatureDigest { get; private set; } + + public static MacToken Parse(byte[] der) + { + var token = new MacToken(); + var contentInfo = new AsnReader(der, AsnEncodingRules.DER).ReadSequence(); + if (contentInfo.ReadObjectIdentifier() != AuthenticatedDataOid) + { + return token.Fail("The PDF MAC token's content type shall be id-ct-authData (ISO/TS 32004 §6.3.1)."); + } + + AsnReader data = contentInfo.ReadSequence(new Asn1Tag(TagClass.ContextSpecific, 0, isConstructed: true)).ReadSequence(); + _ = data.ReadInteger(); + if (data.PeekTag().HasSameClassAndValue(new Asn1Tag(TagClass.ContextSpecific, 0))) + { + data.ReadEncodedValue(); // originatorInfo + } + + if (token.ReadRecipient(data.ReadSetOf()) is { } recipientProblem) + { + return token.Fail(recipientProblem); + } + + if (ReadAlgorithm(data) != HmacSha256Oid) + { + return token.Fail("The PDF MAC token's MAC algorithm shall be HMAC with SHA-256 (ISO/TS 32004 Table 9)."); + } + + if (!data.PeekTag().HasSameClassAndValue(new Asn1Tag(TagClass.ContextSpecific, 1))) + { + return token.Fail("The PDF MAC token shall name its digest algorithm (ISO/TS 32004 §6.3.4)."); + } + + token.DigestAlgorithm = ReadAlgorithm(data, new Asn1Tag(TagClass.ContextSpecific, 1, isConstructed: true)); + + AsnReader encapsulated = data.ReadSequence(); + if (encapsulated.ReadObjectIdentifier() != IntegrityInfoOid) + { + return token.Fail("The PDF MAC token's encapsulated content type shall be id-ct-pdfMacIntegrityInfo (ISO/TS 32004 §6.3.2)."); + } + + token.Content = encapsulated.ReadSequence(new Asn1Tag(TagClass.ContextSpecific, 0, isConstructed: true)).ReadOctetString(); + if (token.ReadIntegrityInfo() is { } infoProblem) + { + return token.Fail(infoProblem); + } + + var attributesTag = new Asn1Tag(TagClass.ContextSpecific, 2, isConstructed: true); + if (!data.PeekTag().HasSameClassAndValue(attributesTag)) + { + return token.Fail("The PDF MAC token shall have authenticated attributes (ISO/TS 32004 §6.3.6.1)."); + } + + token.AuthenticatedAttributes = data.ReadEncodedValue(); + if (token.ReadAttributes(attributesTag) is { } attributeProblem) + { + return token.Fail(attributeProblem); + } + + token.Mac = data.ReadOctetString(); + if (data.HasData) + { + return token.Fail("The PDF MAC token shall have no unauthenticated attributes (ISO/TS 32004 §6.3.7)."); + } + + return token; + } + + private static string ReadAlgorithm(AsnReader reader, Asn1Tag? tag = null) + { + AsnReader algorithm = tag is { } implicitTag ? reader.ReadSequence(implicitTag) : reader.ReadSequence(); + return algorithm.ReadObjectIdentifier(); + } + + private string? ReadRecipient(AsnReader recipients) + { + var passwordRecipient = new Asn1Tag(TagClass.ContextSpecific, 3, isConstructed: true); + if (!recipients.HasData || !recipients.PeekTag().HasSameClassAndValue(passwordRecipient)) + { + return "The PDF MAC token shall have exactly one recipient, of type PasswordRecipientInfo (ISO/TS 32004 §6.3.3)."; + } + + AsnReader recipient = recipients.ReadSequence(passwordRecipient); + if (recipients.HasData) + { + return "The PDF MAC token shall have exactly one recipient (ISO/TS 32004 §6.3.3)."; + } + + _ = recipient.ReadInteger(); + var kdfTag = new Asn1Tag(TagClass.ContextSpecific, 0, isConstructed: true); + if (!recipient.PeekTag().HasSameClassAndValue(kdfTag) || ReadAlgorithm(recipient, kdfTag) != WrapKdfOid) + { + return "The PDF MAC token's key derivation algorithm shall be pdfMacWrapKdf (ISO/TS 32004 §6.4)."; + } + + if (ReadAlgorithm(recipient) != Aes256WrapOid) + { + return "The PDF MAC token's key encryption algorithm shall be AES-256 key wrap without padding (ISO/TS 32004 Table 7)."; + } + + EncryptedKey = recipient.ReadOctetString(); + return null; + } + + private string? ReadIntegrityInfo() + { + AsnReader info = new AsnReader(Content, AsnEncodingRules.DER).ReadSequence(); + if (info.ReadInteger() != 0) + { + return "The PdfMacIntegrityInfo version shall be 0 (ISO/TS 32004 §6.6.1)."; + } + + DataDigest = info.ReadOctetString(); + if (info.HasData) + { + SignatureDigest = info.ReadOctetString(new Asn1Tag(TagClass.ContextSpecific, 0)); + } + + return null; + } + + private string? ReadAttributes(Asn1Tag tag) + { + AsnReader attributes = new AsnReader(AuthenticatedAttributes, AsnEncodingRules.DER).ReadSetOf(tag); + int contentTypes = 0; + int digests = 0; + while (attributes.HasData) + { + AsnReader attribute = attributes.ReadSequence(); + string type = attribute.ReadObjectIdentifier(); + AsnReader values = attribute.ReadSetOf(); + switch (type) + { + case ContentTypeAttributeOid: + contentTypes++; + if (values.ReadObjectIdentifier() != IntegrityInfoOid || values.HasData) + { + return "The PDF MAC token's content-type attribute shall be id-ct-pdfMacIntegrityInfo (ISO/TS 32004 §6.3.6.2)."; + } + + break; + case MessageDigestAttributeOid: + digests++; + MessageDigest = values.ReadOctetString(); + if (values.HasData) + { + return "The PDF MAC token's message-digest attribute shall have exactly one value (ISO/TS 32004 §6.3.6.3)."; + } + + break; + default: + break; + } + } + + return contentTypes == 1 && digests == 1 + ? null + : "The PDF MAC token shall have exactly one content-type and one message-digest attribute (ISO/TS 32004 §6.3.6)."; + } + + private MacToken Fail(string problem) + { + Problem = problem; + return this; + } + } +} diff --git a/src/Broadside/Security/PasswordEncoding.cs b/src/Broadside/Security/PasswordEncoding.cs new file mode 100644 index 00000000..7f1de948 --- /dev/null +++ b/src/Broadside/Security/PasswordEncoding.cs @@ -0,0 +1,206 @@ +using System.Text; +using Broadside.Objects; + +namespace Broadside.Security; + +/// Turns a into the byte strings the standard security handler tries, by revision. +/// +/// ISO 32000-2 §7.6.4.3.2 step a (revisions 2-4: PDFDocEncoding, at most 32 bytes) and §7.6.4.1 with §7.6.4.3.3 steps a-b (revision 6 +/// and later: SASLprep of RFC 4013 with the Normalize option, UTF-8, at most 127 bytes). Readers disagree with the letter of both +/// rules in ways that matter for real files, and so does this one: for revisions 2-4 a password that PDFDocEncoding cannot represent, +/// or that fails, is retried as Latin-1 (what pdf.js and PDFBox send); for revision 6 a password SASLprep rejects or changes is also +/// tried as plain UTF-8 (pdf.js). The bidirectional-text check of RFC 3454 §6 is not applied (pdf.js does not either). The +/// deprecated revision 5 uses plain UTF-8. +/// +internal static class PasswordEncoding +{ + /// The longest legacy password (§7.6.4.3.2 step a). + public const int MaxLegacyLength = 32; + + /// The longest revision 6 password (§7.6.4.3.3 step b). + public const int MaxUnicodeLength = 127; + + private static readonly Dictionary PdfDocBytes = BuildPdfDocBytes(); + + /// Returns the byte strings to try for revisions 2 to 4, most likely first, each at most 32 bytes. + /// The password, or for the empty one. + /// One or two candidates. + public static List Legacy(PdfPassword? password) + { + if (password is null || password.IsEmpty) + { + return [[]]; + } + + if (password.IsRaw) + { + return [Truncate(password.RawBytes, MaxLegacyLength)]; + } + + string text = password.Text!; + var candidates = new List(2); + if (TryEncodePdfDoc(text, out byte[]? pdfDoc)) + { + candidates.Add(Truncate(pdfDoc, MaxLegacyLength)); + } + + byte[] latin1 = Truncate(Encoding.Latin1.GetBytes(text), MaxLegacyLength); + if (candidates.Count == 0 || !candidates[0].AsSpan().SequenceEqual(latin1)) + { + candidates.Add(latin1); + } + + return candidates; + } + + /// Returns the byte strings to try for revision 6 and later, most likely first, each at most 127 bytes. + /// The password, or for the empty one. + /// One or two candidates. + public static List Unicode(PdfPassword? password) + { + if (password is null || password.IsEmpty) + { + return [[]]; + } + + if (password.IsRaw) + { + return [Truncate(password.RawBytes, MaxUnicodeLength)]; + } + + string text = password.Text!; + byte[] plain = Truncate(Encoding.UTF8.GetBytes(text), MaxUnicodeLength); + string? prepared = SaslPrep(text); + if (prepared is null) + { + return [plain]; + } + + byte[] preparedBytes = Truncate(Encoding.UTF8.GetBytes(prepared), MaxUnicodeLength); + return preparedBytes.AsSpan().SequenceEqual(plain) ? [preparedBytes] : [preparedBytes, plain]; + } + + /// Returns the byte string to try for the deprecated revision 5: UTF-8, at most 127 bytes. + /// The password, or for the empty one. + /// One candidate. + public static List Utf8(PdfPassword? password) => + password is null || password.IsEmpty ? [[]] : [Truncate(password.Utf8(), MaxUnicodeLength)]; + + /// + /// The SASLprep profile (RFC 4013) of stringprep (RFC 3454): map non-ASCII spaces to SPACE and the characters of table B.1 to + /// nothing, normalize with NFKC, reject the prohibited characters. Returns for a prohibited character. + /// + /// The password. + /// The prepared password, or . + public static string? SaslPrep(string text) + { + var mapped = new StringBuilder(text.Length); + for (int i = 0; i < text.Length; i++) + { + int codePoint = ReadCodePoint(text, i, out int width); + i += width - 1; + if (IsNonAsciiSpace(codePoint)) + { + mapped.Append(' '); + } + else if (!IsMappedToNothing(codePoint)) + { + mapped.Append(text, i - width + 1, width); + } + } + + string normalized; + try + { + normalized = mapped.ToString().Normalize(NormalizationForm.FormKC); + } + catch (ArgumentException) + { + // An unpaired surrogate: prohibited (RFC 3454 table C.5). + return null; + } + + for (int i = 0; i < normalized.Length; i++) + { + if (char.IsSurrogate(normalized[i]) && !char.IsSurrogatePair(normalized, i)) + { + return null; + } + + int codePoint = ReadCodePoint(normalized, i, out int width); + i += width - 1; + if (IsProhibited(codePoint)) + { + return null; + } + } + + return normalized; + } + + private static int ReadCodePoint(string text, int index, out int width) + { + if (char.IsHighSurrogate(text[index]) && index + 1 < text.Length && char.IsLowSurrogate(text[index + 1])) + { + width = 2; + return char.ConvertToUtf32(text[index], text[index + 1]); + } + + width = 1; + return text[index]; + } + + /// RFC 3454 table C.1.2. + private static bool IsNonAsciiSpace(int c) => + c is 0x00A0 or 0x1680 or (>= 0x2000 and <= 0x200B) or 0x202F or 0x205F or 0x3000; + + /// RFC 3454 table B.1. + private static bool IsMappedToNothing(int c) => + c is 0x00AD or 0x034F or 0x1806 or (>= 0x180B and <= 0x180D) or (>= 0x200B and <= 0x200D) or 0x2060 + or (>= 0xFE00 and <= 0xFE0F) or 0xFEFF; + + /// RFC 4013 §2.3: RFC 3454 tables C.1.2, C.2.1, C.2.2, C.3, C.4, C.5, C.6, C.7, C.8 and C.9. + private static bool IsProhibited(int c) => + IsNonAsciiSpace(c) + || c is <= 0x1F or 0x7F + || c is (>= 0x80 and <= 0x9F) or 0x06DD or 0x070F or 0x180E or 0x200C or 0x200D or 0x2028 or 0x2029 + or (>= 0x2060 and <= 0x2063) or (>= 0x206A and <= 0x206F) or 0xFEFF or (>= 0xFFF9 and <= 0xFFFC) + or (>= 0x1D173 and <= 0x1D17A) + || c is (>= 0xE000 and <= 0xF8FF) or (>= 0xF0000 and <= 0xFFFFD) or (>= 0x100000 and <= 0x10FFFD) + || c is (>= 0xFDD0 and <= 0xFDEF) || (c & 0xFFFE) == 0xFFFE + || c is (>= 0xD800 and <= 0xDFFF) + || c is (>= 0xFFF9 and <= 0xFFFD) + || c is (>= 0x2FF0 and <= 0x2FFB) + || c is 0x0340 or 0x0341 or 0x200E or 0x200F or (>= 0x202A and <= 0x202E) + || c is 0xE0001 or (>= 0xE0020 and <= 0xE007F); + + private static bool TryEncodePdfDoc(string text, out byte[] bytes) + { + bytes = new byte[text.Length]; + for (int i = 0; i < text.Length; i++) + { + if (!PdfDocBytes.TryGetValue(text[i], out byte value)) + { + return false; + } + + bytes[i] = value; + } + + return true; + } + + private static byte[] Truncate(ReadOnlySpan bytes, int length) => bytes[..Math.Min(bytes.Length, length)].ToArray(); + + private static Dictionary BuildPdfDocBytes() + { + ReadOnlySpan table = TextStringDecoder.PdfDocEncodingTable; + var bytes = new Dictionary(table.Length); + for (int i = 0; i < table.Length; i++) + { + bytes.TryAdd(table[i], (byte)i); + } + + return bytes; + } +} diff --git a/src/Broadside/Security/PdfCredentials.cs b/src/Broadside/Security/PdfCredentials.cs new file mode 100644 index 00000000..7f6689bc --- /dev/null +++ b/src/Broadside/Security/PdfCredentials.cs @@ -0,0 +1,65 @@ +using System.Text; + +namespace Broadside.Security; + +/// What a reader offers a security handler to open an encrypted document: a password, a certificate, or another secret. +/// +/// ISO 32000-2 §7.6.4 (passwords for the standard security handler) and §7.6.5 (certificates for public-key handlers). A handler +/// accepts the kinds it understands and treats others as no credential. +/// +public abstract class PdfCredentials +{ + /// Initializes a new instance of the class. + protected PdfCredentials() + { + } +} + +/// A password for the standard security handler, the user or the owner password. +/// +/// +/// ISO 32000-2 §7.6.4. Given as text, the password is encoded the way the document's revision requires: PDFDocEncoding for revisions +/// 2 to 4 (§7.6.4.3.2, step a; when that fails, Latin-1, as other readers do), SASLprep and UTF-8 truncated to 127 bytes for revision 6 +/// and later (§7.6.4.1), UTF-8 for the deprecated revision 5. Given as bytes, it is used as is, for passwords in a legacy code page. +/// +/// +/// SASLprep's normalization (NFKC) uses the platform's Unicode data; in an application built with invariant globalization it is not +/// available, so a revision 6 password must then be given in its normalized form (what keyboards produce for most scripts). The +/// mapping steps (non-ASCII spaces to SPACE, soft hyphens and joiners to nothing) apply everywhere. +/// +/// The empty password is the default user password, which readers always try first. +/// +public sealed class PdfPassword : PdfCredentials +{ + private readonly byte[]? _bytes; + + /// Initializes a new instance of the class from text. + /// The password. + public PdfPassword(string password) + { + ArgumentNullException.ThrowIfNull(password); + Text = password; + } + + /// Initializes a new instance of the class from bytes, used without any encoding. + /// The password's bytes, copied. + public PdfPassword(ReadOnlySpan password) => _bytes = password.ToArray(); + + /// Gets the password as text, or when it was given as bytes. + public string? Text { get; } + + /// Gets a value indicating whether this is the empty password. + public bool IsEmpty => Text is { Length: 0 } || _bytes is { Length: 0 }; + + /// Gets the bytes the password was given as, or when it was given as text. + internal ReadOnlySpan RawBytes => _bytes; + + /// Gets a value indicating whether the password was given as bytes. + internal bool IsRaw => _bytes is not null; + + /// + public override string ToString() => "PdfPassword"; + + /// Encodes text as UTF-8 (used when no handler-specific encoding applies). + internal byte[] Utf8() => _bytes ?? Encoding.UTF8.GetBytes(Text!); +} diff --git a/src/Broadside/Security/PdfPasswordException.cs b/src/Broadside/Security/PdfPasswordException.cs new file mode 100644 index 00000000..b339943f --- /dev/null +++ b/src/Broadside/Security/PdfPasswordException.cs @@ -0,0 +1,100 @@ +namespace Broadside.Security; + +/// Why an encrypted document did not open with the password given. +/// ISO 32000-2 §7.6.4.1. +public enum PdfPasswordFailure +{ + /// No password, or the empty one, was given and the document has a user password: ask for one. + Required, + + /// The password given is neither the user nor the owner password. + Incorrect, +} + +/// The exception thrown when an encrypted document cannot be opened with the password given. +/// +/// ISO 32000-2 §7.6.4.1: a reader first tries the default (empty) user password and, when that fails, should prompt for a password. +/// tells the two cases apart, so a caller can prompt on and report a +/// typing mistake on . +/// +public sealed class PdfPasswordException : Exception +{ + /// Initializes a new instance of the class. + /// Why the password did not open the document. + public PdfPasswordException(PdfPasswordFailure failure) + : base(failure == PdfPasswordFailure.Required + ? "The document is encrypted with a user password; open it with the user or the owner password." + : "The password is neither the document's user password nor its owner password.") => Failure = failure; + + /// Initializes a new instance of the class. + public PdfPasswordException() + : this(PdfPasswordFailure.Required) + { + } + + /// Initializes a new instance of the class. + /// The message. + public PdfPasswordException(string? message) + : this(message, null) + { + } + + /// Initializes a new instance of the class. + /// The message. + /// The cause. + public PdfPasswordException(string? message, Exception? innerException) + : base(message, innerException) => Failure = PdfPasswordFailure.Incorrect; + + /// Gets why the password did not open the document. + public PdfPasswordFailure Failure { get; } +} + +/// What about a document's encryption this engine cannot handle. +public enum PdfEncryptionNotSupportedReason +{ + /// No registered security handler implements the encryption dictionary's Filter or SubFilter. + Handler, + + /// The handler does not implement the algorithm, revision or crypt filter method the document uses. + Algorithm, + + /// The algorithm is not available on this platform. + Platform, +} + +/// The exception thrown when a document is encrypted in a way this engine cannot decrypt. +/// +/// ISO 32000-2 §7.6.2 (Table 20: only the handler a document names, or one implementing its SubFilter, may open it) and §7.6.6 +/// (Table 25: a reader that meets an unknown crypt filter method "shall report that the file is encrypted with an unsupported +/// algorithm"). Distinct from : no password will open the document with this engine. +/// +public sealed class PdfEncryptionNotSupportedException : NotSupportedException +{ + /// Initializes a new instance of the class. + /// What is not supported. + /// The message. + public PdfEncryptionNotSupportedException(PdfEncryptionNotSupportedReason reason, string? message) + : base(message) => Reason = reason; + + /// Initializes a new instance of the class. + public PdfEncryptionNotSupportedException() + : this(PdfEncryptionNotSupportedReason.Algorithm, "The document's encryption is not supported.") + { + } + + /// Initializes a new instance of the class. + /// The message. + public PdfEncryptionNotSupportedException(string? message) + : this(PdfEncryptionNotSupportedReason.Algorithm, message) + { + } + + /// Initializes a new instance of the class. + /// The message. + /// The cause. + public PdfEncryptionNotSupportedException(string? message, Exception? innerException) + : base(message, innerException) => Reason = PdfEncryptionNotSupportedReason.Algorithm; + + /// Gets what is not supported. + public PdfEncryptionNotSupportedReason Reason { get; } +} diff --git a/src/Broadside/Security/SecurityHandlerRegistry.cs b/src/Broadside/Security/SecurityHandlerRegistry.cs new file mode 100644 index 00000000..3914b0c8 --- /dev/null +++ b/src/Broadside/Security/SecurityHandlerRegistry.cs @@ -0,0 +1,60 @@ +using Broadside.Objects; + +namespace Broadside.Security; + +/// The security handlers of one engine, by Filter name and by SubFilter format. Immutable once built. +/// +/// ISO 32000-2 §7.6.2, Table 20: the handler a document's Filter names opens it; when SubFilter is present, any handler +/// implementing that format may. is the default for Standard; a handler registered later +/// for the same name replaces an earlier one. +/// +internal sealed class SecurityHandlerRegistry +{ + private readonly Dictionary _byFilter = []; + private readonly Dictionary _bySubFilter = []; + + private SecurityHandlerRegistry() + { + } + + /// Gets the registry of an engine with no handlers of its own: the standard handler only. + public static SecurityHandlerRegistry Default { get; } = Create([]); + + /// Builds a registry from the defaults and the handlers registered on the options, in order. + /// The registered handlers. + /// The registry. + public static SecurityHandlerRegistry Create(IEnumerable handlers) + { + var registry = new SecurityHandlerRegistry(); + registry.Add(new StandardSecurityHandler()); + foreach (ISecurityHandler handler in handlers) + { + registry.Add(handler); + } + + return registry; + } + + /// Finds the handler for a document: by , else by . + /// The encryption dictionary's Filter. + /// Its SubFilter, or . + /// The handler, or . + public ISecurityHandler? Find(CosName? filter, CosName? subFilter) + { + if (filter is not null && _byFilter.TryGetValue(filter, out ISecurityHandler? handler)) + { + return handler; + } + + return subFilter is not null && _bySubFilter.TryGetValue(subFilter, out handler) ? handler : null; + } + + private void Add(ISecurityHandler handler) + { + _byFilter[handler.Filter] = handler; + foreach (CosName subFilter in handler.SubFilters) + { + _bySubFilter[subFilter] = handler; + } + } +} diff --git a/src/Broadside/Security/StandardSecurityHandler.cs b/src/Broadside/Security/StandardSecurityHandler.cs new file mode 100644 index 00000000..9495918d --- /dev/null +++ b/src/Broadside/Security/StandardSecurityHandler.cs @@ -0,0 +1,576 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.Globalization; +using System.Security.Cryptography; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; +using Broadside.Security.Cryptography; + +namespace Broadside.Security; + +/// The standard password-based security handler, revisions 2 to 7. Registered by default. +/// +/// +/// ISO 32000-2 §7.6.4: Algorithms 2, 3, 6 and 7 for revisions 2 to 4 (RC4 and AES-128, MD5 key derivation), Algorithms 2.A, 2.B, +/// 11, 12 and 13 for revision 6 (AES-256), the same for revision 7 (ISO/TS 32003, AES-GCM: its password algorithms are those of +/// revision 6), and the deprecated revision 5 (an Adobe extension: SHA-256 instead of Algorithm 2.B) for reading only. +/// +/// +/// Without a password the default (empty) user password is tried (§7.6.4.1); a document it does not open throws +/// with . A password is tried as the user password, then +/// as the owner password; one that is neither throws . The owner password grants +/// . +/// +/// +/// Repairs, each recorded as a diagnostic: O and U longer than the revision's length are truncated and shorter ones +/// padded with zeros; a Length outside 40 to 128 bits is clamped (one that looks like a byte count is read as one); for a +/// revision 3 or 4 key shorter than 128 bits whose owner password fails Algorithm 3 as written, the variant that rehashes only the +/// first n bytes in step c (which PDFBox writes) is tried; a revision 6 Perms that disagrees with P wins over it +/// (it is the tamper-resistant copy, ISO/TS 32004 §5.1.2 NOTE 2). +/// +/// +public sealed class StandardSecurityHandler : ISecurityHandler +{ + /// The 32-byte padding string of Algorithm 2 step a (§7.6.4.3.2). + internal static ReadOnlySpan PasswordPadding => + [ + 0x28, 0xBF, 0x4E, 0x5E, 0x4E, 0x75, 0x8A, 0x41, 0x64, 0x00, 0x4E, 0x56, 0xFF, 0xFA, 0x01, 0x08, + 0x2E, 0x2E, 0x00, 0xB6, 0xD0, 0x68, 0x3E, 0x80, 0x2F, 0x0C, 0xA9, 0xFE, 0x64, 0x53, 0x69, 0x7A, + ]; + + private static readonly CosName StandardName = new("Standard"); + private static readonly CosName V = new("V"); + private static readonly CosName R = new("R"); + private static readonly CosName O = new("O"); + private static readonly CosName U = new("U"); + private static readonly CosName OE = new("OE"); + private static readonly CosName UE = new("UE"); + private static readonly CosName P = new("P"); + private static readonly CosName Perms = new("Perms"); + private static readonly CosName LengthName = new("Length"); + private static readonly CosName EncryptMetadata = new("EncryptMetadata"); + + /// Gets Standard, the name of the built-in password-based handler (Table 20). + public CosName Filter => StandardName; + + /// Gets no formats: the standard handler is chosen by Filter only. + public IReadOnlyCollection SubFilters => []; + + /// Computes the permissions a user has from the P entry, the way the revision defines them (Table 22). + /// The P entry. + /// The revision R. + /// The permissions. + /// ISO 32000-2 §7.6.4.2, Table 22. + public static PdfPermissions UserPermissions(int rawPermissions, int revision) + { + var bits = (PdfPermissions)rawPermissions; + bool print = bits.HasFlag(PdfPermissions.Print); + bool modify = bits.HasFlag(PdfPermissions.Modify); + bool annotate = bits.HasFlag(PdfPermissions.Annotate); + PdfPermissions permissions = bits & (PdfPermissions.Print | PdfPermissions.Modify | PdfPermissions.Extract | PdfPermissions.Annotate); + if (revision < 3) + { + // Revision 2 controls bits 3-6 only; what later revisions split out follows the bit that covered it. + permissions |= (annotate ? PdfPermissions.FillForms : 0) | (modify ? PdfPermissions.Assemble : 0) | (print ? PdfPermissions.PrintHighQuality : 0); + return permissions; + } + + if (annotate || bits.HasFlag(PdfPermissions.FillForms)) + { + permissions |= PdfPermissions.FillForms; + } + + if (bits.HasFlag(PdfPermissions.Assemble)) + { + permissions |= PdfPermissions.Assemble; + } + + if (print && bits.HasFlag(PdfPermissions.PrintHighQuality)) + { + permissions |= PdfPermissions.PrintHighQuality; + } + + return permissions; + } + + /// + public SecurityHandlerResult Authenticate(SecurityHandlerContext context) + { + ArgumentNullException.ThrowIfNull(context); + CosDictionary dictionary = context.EncryptionDictionary; + int revision = ReadInteger(context, dictionary, R) ?? throw Fail(context, "The standard encryption dictionary has no R (revision) entry."); + if (revision is < 2 or > 7) + { + throw new PdfEncryptionNotSupportedException( + PdfEncryptionNotSupportedReason.Algorithm, + string.Create(CultureInfo.InvariantCulture, $"Revision {revision} of the standard security handler is not defined.")); + } + + int version = ReadInteger(context, dictionary, V) ?? DefaultVersion(context, revision); + int rawPermissions = ReadInteger(context, dictionary, P) ?? throw Fail(context, "The standard encryption dictionary has no P (permissions) entry."); + PdfPassword? password = context.Credentials as PdfPassword; + if (revision == 5) + { + context.Report( + DiagnosticCodes.EncryptionRevisionInvalid, + DiagnosticSeverity.Warning, + "Revision 5 of the standard security handler shall not be used (Table 21: a deprecated Adobe extension); it is read as such."); + } + + return revision <= 4 + ? AuthenticateLegacy(context, dictionary, password, version, revision, rawPermissions) + : AuthenticateModern(context, dictionary, password, revision, rawPermissions); + } + + /// Algorithm 2.B (§7.6.4.3.4): the revision 6 hash, written into the first 32 bytes of . + /// The password, a salt and (owner) the 48-byte U. + /// The UTF-8 password. + /// The 48-byte U when checking the owner password; otherwise empty. + /// At least 32 bytes. + internal static void HashRevision6(ReadOnlySpan input, ReadOnlySpan password, ReadOnlySpan userKey, Span output) + { + Span k = stackalloc byte[64]; + int kLength = SHA256.HashData(input, k); + int maxSequence = password.Length + 64 + userKey.Length; + byte[] k1 = ArrayPool.Shared.Rent(maxSequence * 64); + byte[] e = ArrayPool.Shared.Rent(maxSequence * 64); + try + { + for (int round = 1; ; round++) + { + // a) K1 = 64 repetitions of password ‖ K ‖ U. + int sequence = password.Length + kLength + userKey.Length; + Span first = k1.AsSpan(0, sequence); + password.CopyTo(first); + k[..kLength].CopyTo(first[password.Length..]); + userKey.CopyTo(first[(password.Length + kLength)..]); + int length = sequence * 64; + for (int offset = sequence; offset < length; offset += sequence) + { + first.CopyTo(k1.AsSpan(offset, sequence)); + } + + // b) E = AES-128-CBC(key K[0..16], IV K[16..32], no padding). + using (AesCipher aes = AesCipher.Create(k[..16])) + { + aes.EncryptCbc(k1.AsSpan(0, length), k[16..32], e); + } + + // c) The first 16 bytes of E as a big-endian integer, modulo 3: since 256 ≡ 1 (mod 3), the sum of the bytes. + int sum = 0; + for (int i = 0; i < 16; i++) + { + sum += e[i]; + } + + // d) The next K. + ReadOnlySpan encrypted = e.AsSpan(0, length); + kLength = (sum % 3) switch + { + 0 => SHA256.HashData(encrypted, k), + 1 => SHA384.HashData(encrypted, k), + _ => SHA512.HashData(encrypted, k), + }; + + // e)-f) After round 63 (the 64th), stop once the last byte of E is at most the round number - 32. + if (round >= 64 && e[length - 1] <= round - 32) + { + break; + } + } + + k[..32].CopyTo(output); + } + finally + { + ArrayPool.Shared.Return(k1); + ArrayPool.Shared.Return(e); + } + } + + private static SecurityHandlerResult AuthenticateLegacy( + SecurityHandlerContext context, + CosDictionary dictionary, + PdfPassword? password, + int version, + int revision, + int rawPermissions) + { + int keyLength = LegacyKeyLength(context, dictionary, version, revision); + bool encryptMetadata = version < 4 || revision < 4 || (ReadBoolean(context, dictionary, EncryptMetadata) ?? true); + byte[] owner = ReadEntry(context, dictionary, O, 32, required: true)!; + byte[] user = ReadEntry(context, dictionary, U, 32, required: true)!; + var legacy = new LegacyKeys(revision, keyLength, owner, user, rawPermissions, context.DocumentId.Span.ToArray(), encryptMetadata); + + PdfPermissions userPermissions = UserPermissions(rawPermissions, revision); + foreach (byte[] candidate in PasswordEncoding.Legacy(password)) + { + if (legacy.TryUser(candidate) is { } userKey) + { + return new SecurityHandlerResult(userKey, PdfAccessLevel.User, userPermissions, rawPermissions) { Revision = revision }; + } + + if (candidate.Length > 0 && legacy.TryOwner(candidate, context) is { } ownerKey) + { + return new SecurityHandlerResult(ownerKey, PdfAccessLevel.Owner, PdfPermissions.All, rawPermissions) { Revision = revision }; + } + } + + throw new PdfPasswordException(password is null || password.IsEmpty ? PdfPasswordFailure.Required : PdfPasswordFailure.Incorrect); + } + + private static SecurityHandlerResult AuthenticateModern( + SecurityHandlerContext context, + CosDictionary dictionary, + PdfPassword? password, + int revision, + int rawPermissions) + { + byte[] owner = ReadEntry(context, dictionary, O, 48, required: true)!; + byte[] user = ReadEntry(context, dictionary, U, 48, required: true)!; + byte[] ownerEncryption = ReadEntry(context, dictionary, OE, 32, required: true)!; + byte[] userEncryption = ReadEntry(context, dictionary, UE, 32, required: true)!; + byte[]? permissionsEntry = ReadEntry(context, dictionary, Perms, 16, required: revision >= 6); + bool encryptMetadata = ReadBoolean(context, dictionary, EncryptMetadata) ?? true; + + List candidates = revision == 5 ? PasswordEncoding.Utf8(password) : PasswordEncoding.Unicode(password); + foreach (byte[] candidate in candidates) + { + PdfAccessLevel? access = null; + byte[]? key = TryModernUser(revision, candidate, user, userEncryption); + if (key is not null) + { + access = PdfAccessLevel.User; + } + else if (candidate.Length > 0 && (key = TryModernOwner(revision, candidate, owner, user, ownerEncryption)) is not null) + { + access = PdfAccessLevel.Owner; + } + + if (access is { } level) + { + int permissions = permissionsEntry is null + ? rawPermissions + : ValidatePermissions(context, key!, permissionsEntry, rawPermissions, encryptMetadata); + PdfPermissions granted = level == PdfAccessLevel.Owner ? PdfPermissions.All : UserPermissions(permissions, revision); + return new SecurityHandlerResult(key, level, granted, permissions) { Revision = revision }; + } + } + + throw new PdfPasswordException(password is null || password.IsEmpty ? PdfPasswordFailure.Required : PdfPasswordFailure.Incorrect); + } + + /// Algorithm 11, then Algorithm 2.A step e. + private static byte[]? TryModernUser(int revision, byte[] password, byte[] user, byte[] userEncryption) + { + Span hash = stackalloc byte[32]; + ModernHash(revision, [.. password, .. user.AsSpan(32, 8)], password, [], hash); + if (!CryptographicOperations.FixedTimeEquals(hash, user.AsSpan(0, 32))) + { + return null; + } + + ModernHash(revision, [.. password, .. user.AsSpan(40, 8)], password, [], hash); + return DecryptFileKey(hash, userEncryption); + } + + /// Algorithm 12, then Algorithm 2.A step d. + private static byte[]? TryModernOwner(int revision, byte[] password, byte[] owner, byte[] user, byte[] ownerEncryption) + { + Span hash = stackalloc byte[32]; + ModernHash(revision, [.. password, .. owner.AsSpan(32, 8), .. user], password, user, hash); + if (!CryptographicOperations.FixedTimeEquals(hash, owner.AsSpan(0, 32))) + { + return null; + } + + ModernHash(revision, [.. password, .. owner.AsSpan(40, 8), .. user], password, user, hash); + return DecryptFileKey(hash, ownerEncryption); + } + + private static void ModernHash(int revision, ReadOnlySpan input, ReadOnlySpan password, ReadOnlySpan userKey, Span output) + { + if (revision == 5) + { + SHA256.HashData(input, output); + } + else + { + HashRevision6(input, password, userKey, output); + } + } + + /// AES-256 in CBC mode with a zero IV and no padding over OE or UE (Algorithm 2.A steps d and e). + private static byte[] DecryptFileKey(ReadOnlySpan intermediateKey, byte[] encryptedKey) + { + byte[] fileKey = new byte[32]; + using AesCipher aes = AesCipher.Create(intermediateKey); + aes.DecryptCbc(encryptedKey.AsSpan(0, 32), stackalloc byte[16], fileKey); + return fileKey; + } + + /// Algorithm 13 (and 2.A step f): decrypt Perms, check "adb", compare with P and EncryptMetadata. + private static int ValidatePermissions(SecurityHandlerContext context, byte[] fileKey, byte[] permissionsEntry, int rawPermissions, bool encryptMetadata) + { + Span block = stackalloc byte[16]; + using (AesCipher aes = AesCipher.Create(fileKey)) + { + aes.DecryptEcb(permissionsEntry.AsSpan(0, 16), block); + } + + if (!block.Slice(9, 3).SequenceEqual("adb"u8)) + { + context.Report( + DiagnosticCodes.EncryptionPermissionsMismatch, + DiagnosticSeverity.Warning, + "The Perms entry does not decrypt to a permissions block (bytes 9-11 are not \"adb\"); the P entry is used."); + return rawPermissions; + } + + int permissions = BinaryPrimitives.ReadInt32LittleEndian(block); + if (permissions != rawPermissions) + { + context.Report( + DiagnosticCodes.EncryptionPermissionsMismatch, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The permissions in Perms ({permissions}) shall match the P entry ({rawPermissions}); the value in Perms is used.")); + } + + if (block[8] != (encryptMetadata ? (byte)'T' : (byte)'F')) + { + context.Report( + DiagnosticCodes.EncryptionPermissionsMismatch, + DiagnosticSeverity.Warning, + "Byte 8 of Perms does not match EncryptMetadata (Algorithm 13); EncryptMetadata is used."); + } + + return permissions; + } + + /// The file encryption key length n in bytes for revisions 2 to 4 (Table 20, Algorithm 2 step i). + private static int LegacyKeyLength(SecurityHandlerContext context, CosDictionary dictionary, int version, int revision) + { + if (revision == 2 || version == 1) + { + return 5; + } + + if (version >= 4) + { + return 16; + } + + int? bits = ReadInteger(context, dictionary, LengthName); + switch (bits) + { + case null: + return 5; + case >= 40 and <= 128 when bits % 8 == 0: + return bits.Value / 8; + case >= 5 and <= 16: + context.Report( + DiagnosticCodes.EncryptionKeyLengthInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The Length entry shall be a bit count from 40 to 128; {bits} is read as a byte count.")); + return bits.Value; + default: + int clamped = Math.Clamp(bits.Value, 40, 128) / 8; + context.Report( + DiagnosticCodes.EncryptionKeyLengthInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The Length entry shall be a multiple of 8 from 40 to 128; {bits} is read as {clamped * 8}.")); + return clamped; + } + } + + private static int DefaultVersion(SecurityHandlerContext context, int revision) + { + int version = revision switch { 2 => 1, 3 => 2, 4 => 4, 7 => 6, _ => 5 }; + context.Report( + DiagnosticCodes.EncryptDictionaryInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The encryption dictionary has no V entry; it is read as {version}, the value revision {revision} goes with.")); + return version; + } + + private static int? ReadInteger(SecurityHandlerContext context, CosDictionary dictionary, CosName key) + { + if (!dictionary.TryGetValue(key, out CosObject? entry)) + { + return null; + } + + switch (context.Resolve(entry)) + { + case CosInteger integer when integer.Value is >= int.MinValue and <= uint.MaxValue: + // P is an unsigned 32-bit quantity some writers store unsigned (§7.6.4.2). + return unchecked((int)integer.Value); + case CosReal real: + context.Report( + DiagnosticCodes.EncryptDictionaryInvalid, + DiagnosticSeverity.Warning, + $"The encryption dictionary's {key.Value} entry shall be an integer; the real number is truncated."); + return (int)real.Value; + default: + return null; + } + } + + private static bool? ReadBoolean(SecurityHandlerContext context, CosDictionary dictionary, CosName key) => + dictionary.TryGetValue(key, out CosObject? entry) && context.Resolve(entry) is CosBoolean boolean ? boolean.Value : null; + + /// Reads a byte-string entry, truncating a longer one and zero-padding a shorter one, with a diagnostic. + private static byte[]? ReadEntry(SecurityHandlerContext context, CosDictionary dictionary, CosName key, int length, bool required) + { + if (!dictionary.TryGetValue(key, out CosObject? entry) || context.Resolve(entry) is not CosString value) + { + return required + ? throw Fail(context, $"The standard encryption dictionary has no {key.Value} string, which the revision requires.") + : null; + } + + ReadOnlySpan bytes = value.Bytes; + if (bytes.Length == length) + { + return bytes.ToArray(); + } + + context.Report( + DiagnosticCodes.EncryptionEntryLengthInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The {key.Value} entry shall be {length} bytes long; it has {bytes.Length}, read as its first {length} bytes{(bytes.Length < length ? " padded with zeros" : string.Empty)}.")); + byte[] fixedLength = new byte[length]; + bytes[..Math.Min(length, bytes.Length)].CopyTo(fixedLength); + return fixedLength; + } + + private static DiagnosticException Fail(SecurityHandlerContext context, string message) + { + var diagnostic = new Diagnostic(DiagnosticCodes.EncryptDictionaryInvalid, DiagnosticSeverity.Error, message); + context.Report(diagnostic.Code, diagnostic.Severity, diagnostic.Message); + return new DiagnosticException(diagnostic); + } + + /// The key computations of revisions 2 to 4 for one encryption dictionary. + private sealed class LegacyKeys(int revision, int keyLength, byte[] owner, byte[] user, int permissions, byte[] documentId, bool encryptMetadata) + { + /// Algorithm 6: computes the key from a user password with Algorithm 2 and checks it against U. + public byte[]? TryUser(ReadOnlySpan password) + { + byte[] key = FileKey(password); + Span check = stackalloc byte[32]; + if (revision == 2) + { + // Algorithm 4. + Rc4.Transform(key, PasswordPadding, check); + return CryptographicOperations.FixedTimeEquals(check, user.AsSpan(0, 32)) ? key : null; + } + + // Algorithm 5: compare the first 16 bytes. + Span buffer = stackalloc byte[32 + documentId.Length]; + PasswordPadding.CopyTo(buffer); + documentId.CopyTo(buffer[32..]); + Md5.HashData(buffer, check); + Span value = check[..16]; + Rc4.Transform(key, value, value); + Span roundKey = stackalloc byte[key.Length]; + for (int i = 1; i <= 19; i++) + { + for (int b = 0; b < key.Length; b++) + { + roundKey[b] = (byte)(key[b] ^ i); + } + + Rc4.Transform(roundKey, value, value); + } + + return CryptographicOperations.FixedTimeEquals(value, user.AsSpan(0, 16)) ? key : null; + } + + /// Algorithm 7: recovers the user password from O with the owner password and authenticates it. + public byte[]? TryOwner(ReadOnlySpan password, SecurityHandlerContext context) + { + if (TryOwner(password, rehashWholeDigest: true) is { } key) + { + return key; + } + + if (revision < 3 || keyLength >= 16 || TryOwner(password, rehashWholeDigest: false) is not { } variantKey) + { + return null; + } + + context.Report( + DiagnosticCodes.OwnerPasswordKeyVariant, + DiagnosticSeverity.Warning, + "The O entry was computed by rehashing only the first n bytes in Algorithm 3 step c, not the whole digest; the owner password is accepted."); + return variantKey; + } + + private byte[]? TryOwner(ReadOnlySpan password, bool rehashWholeDigest) + { + // Algorithm 3 steps a-d. + Span digest = stackalloc byte[16]; + Md5.HashData(Pad(password), digest); + if (revision >= 3) + { + for (int i = 0; i < 50; i++) + { + Md5.HashData(rehashWholeDigest ? digest : digest[..keyLength], digest); + } + } + + ReadOnlySpan rc4Key = digest[..keyLength]; + Span userPassword = stackalloc byte[32]; + if (revision == 2) + { + Rc4.Transform(rc4Key, owner.AsSpan(0, 32), userPassword); + } + else + { + owner.AsSpan(0, 32).CopyTo(userPassword); + Span roundKey = stackalloc byte[keyLength]; + for (int i = 19; i >= 0; i--) + { + for (int b = 0; b < keyLength; b++) + { + roundKey[b] = (byte)(rc4Key[b] ^ i); + } + + Rc4.Transform(roundKey, userPassword, userPassword); + } + } + + // The result is the padded user password; padding a 32-byte string leaves it as is. + return TryUser(userPassword); + } + + /// Algorithm 2: the file encryption key from a user password. + private byte[] FileKey(ReadOnlySpan password) + { + byte[] input = [.. Pad(password), .. owner.AsSpan(0, 32), 0, 0, 0, 0, .. documentId, .. revision >= 4 && !encryptMetadata ? [0xFF, 0xFF, 0xFF, 0xFF] : Array.Empty()]; + BinaryPrimitives.WriteInt32LittleEndian(input.AsSpan(64), permissions); + Span digest = stackalloc byte[16]; + Md5.HashData(input, digest); + if (revision >= 3) + { + for (int i = 0; i < 50; i++) + { + Md5.HashData(digest[..keyLength], digest); + } + } + + return digest[..keyLength].ToArray(); + } + + private static byte[] Pad(ReadOnlySpan password) + { + byte[] padded = new byte[32]; + int length = Math.Min(32, password.Length); + password[..length].CopyTo(padded); + PasswordPadding[..(32 - length)].CopyTo(padded.AsSpan(length)); + return padded; + } + } +} diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index d9abe32d..2fc9f2d0 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -4,6 +4,7 @@ using Broadside.IO; using Broadside.Objects; using Broadside.Parsing; +using Broadside.Security; using SharpFuzz; namespace Broadside.Fuzz; @@ -32,9 +33,13 @@ internal static class FuzzTargets ["filter-flate"] = data => Filter(new FlateDecodeFilter(), data, parameters: null, maxRatio: 1100), ["filter-runlength"] = data => Filter(new RunLengthDecodeFilter(), data, parameters: null, maxRatio: 128), ["filter-predictor"] = PredictorTarget, + ["encrypted-document"] = EncryptedDocument, + ["decrypt"] = Decrypt, + ["mac-token"] = MacToken, }; private static readonly CosName ContentsKey = new("Contents"); + private static readonly CosName InfoKey = new("Info"); /// /// Opens the input as a whole file in lenient mode and reads everything the document model exposes: version, trailer, every @@ -130,6 +135,14 @@ private static string ReadEverything(Func open) { return exception.Diagnostic.ToString(); } + catch (PdfPasswordException exception) + { + return exception.Failure.ToString(); + } + catch (PdfEncryptionNotSupportedException exception) + { + return exception.Reason.ToString(); + } using (document) { @@ -418,8 +431,107 @@ private static void ObjectStreamTarget(ReadOnlySpan data) { return null; } + catch (PdfPasswordException) + { + return null; + } + catch (PdfEncryptionNotSupportedException) + { + return null; + } } + /// + /// Opens the input as an encrypted file with the corpus owner password owner (so mutations of the encrypted corpus files + /// get past authentication) and decodes every page's content streams and the Info dictionary's strings. A password or + /// unsupported-encryption exception is a documented outcome; anything else is a finding. A decoded stream is never longer than + /// the engine's limit. + /// + /// ISO 32000-2 §7.6; ISO/TS 32003; ISO/TS 32004. + private static void EncryptedDocument(ReadOnlySpan data) + { + PdfDocument document; + try + { + document = new PdfEngine().Open(data.ToArray(), new PdfPassword("owner")); + } + catch (DiagnosticException) + { + return; + } + catch (PdfPasswordException) + { + return; + } + catch (PdfEncryptionNotSupportedException) + { + return; + } + + using (document) + { + _ = (document.Permissions, document.Security?.Integrity); + foreach (PdfPage page in document.Pages) + { + CosObject contents = document.Resolve(page.Dictionary.TryGetValue(ContentsKey, out CosObject? value) ? value : null); + IEnumerable streams = contents is CosArray array ? array : [contents]; + foreach (CosObject item in streams) + { + if (document.Resolve(item) is CosStream stream && document.DecodeStream(stream).Length > PdfOptions.DefaultMaxDecodedStreamLength) + { + throw new InvalidOperationException("A decoded stream exceeds the decoded-length limit."); + } + } + } + + if (document.Resolve(document.Trailer.TryGetValue(InfoKey, out CosObject? info) ? info : null) is CosDictionary dictionary) + { + foreach (KeyValuePair entry in dictionary) + { + _ = (document.Resolve(entry.Value) as CosString)?.DecodeText(); + } + } + } + } + + /// + /// Decrypts the input as a string of object 1 0 with the crypt filter method its first byte selects (RC4, AES-128-CBC with + /// Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and a fixed key, in lenient mode. The plaintext is never longer than the + /// ciphertext. + /// + /// ISO 32000-2 §7.6.3 Algorithms 1 and 1.A; ISO/TS 32003 §5.2. + private static void Decrypt(ReadOnlySpan data) + { + if (data.IsEmpty) + { + return; + } + + (int version, string method) = (data[0] % 4) switch + { + 0 => (4, "V2"), + 1 => (4, "AESV2"), + 2 => (5, "AESV3"), + _ => (6, "AESV4"), + }; + byte[] key = new byte[version == 4 ? 16 : 32]; + key.AsSpan().Fill(0x42); + var encryption = (CosDictionary)CosObject.Parse(System.Text.Encoding.ASCII.GetBytes( + $"<< /V {version} /CF << /StdCF << /CFM /{method} >> >> /StmF /StdCF /StrF /StdCF >>")); + var diagnostics = new DiagnosticSink(strict: false); + DocumentDecryptor decryptor = DocumentDecryptor.Create( + encryption, version, new SecurityHandlerResult(key, PdfAccessLevel.User, PdfPermissions.All, -4), diagnostics, value => value ?? CosNull.Instance); + ReadOnlyMemory plain = decryptor.Apply(decryptor.Strings, data[1..], new CosReference(1, 0)); + if (plain.Length > data.Length - 1) + { + throw new InvalidOperationException($"{plain.Length} bytes of plaintext from {data.Length - 1} bytes of ciphertext."); + } + } + + /// Parses the input as a DER-encoded PDF MAC token (a CMS AuthenticatedData) and checks its structure. + /// ISO/TS 32004 §6.2-6.3; RFC 5652 §9. + private static void MacToken(ReadOnlySpan data) => _ = IntegrityVerifier.TryParseToken(data.ToArray(), out _); + /// /// Tokenizes the whole input. Every token must lie inside the input and start at or after the previous one's end, and the lexer /// must reach the end of input. diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index 831262ab..c203e85c 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. @@ -40,6 +40,8 @@ mkdir -p artifacts/fuzz/seeds-xref-stream artifacts/fuzz/seeds-object-stream { printf '\003\016'; qpdf --show-object=4 --filtered-stream-data tests/Corpus/object-stream.pdf; } > artifacts/fuzz/seeds-object-stream/object-stream.bin ``` +`mac-token` takes a DER token: seed it with the one in `encrypted-mac.pdf` (`python3 -c "import re,sys; d=open('tests/Corpus/encrypted-mac.pdf','rb').read(); sys.stdout.buffer.write(bytes.fromhex(re.search(rb'/MAC <([0-9A-F]+)>', d).group(1).decode()))" > artifacts/fuzz/seeds/mac-token.bin`). `decrypt` takes a selector byte and ciphertext: prefix the content stream of an encrypted corpus file with `\001` (AES-128) or `\003` (GCM). + For the `filter-*` targets whole files are weak seeds too (a whole PDF as a stream body); for real fuzzing extract stream bodies, for example `qpdf --show-object=4 --raw-stream-data tests/Corpus/lzw-stream.pdf > artifacts/fuzz/seeds/lzw.bin`. Smoke mode is a regression net, not a fuzzer: it has no coverage feedback and finds only shallow bugs. Use a real fuzzer for anything that parses. diff --git a/tests/Broadside.TestSupport/Corpus.cs b/tests/Broadside.TestSupport/Corpus.cs index 8c9cb728..14474402 100644 --- a/tests/Broadside.TestSupport/Corpus.cs +++ b/tests/Broadside.TestSupport/Corpus.cs @@ -29,6 +29,10 @@ public static class Corpus "encrypted-rc4-128.pdf", "encrypted-aes-128.pdf", "encrypted-aes-256.pdf", + "encrypted-rc4-40-r3.pdf", + "encrypted-crypt-filters.pdf", + "encrypted-aes-gcm.pdf", + "encrypted-mac.pdf", "inline-image.pdf", "page-tree-inherited.pdf", "annotations-link.pdf", @@ -44,6 +48,14 @@ public static class Corpus "wrong-stream-length.pdf", "no-xref.pdf", "startxref-wrong.pdf", + "encrypted-mac-tampered.pdf", + "encrypted-owner-key-variant.pdf", + ]; + + private static readonly (string FileName, string UserPassword)[] PasswordProtected = + [ + ("encrypted-user-password.pdf", "p\u00e4sswort"), + ("encrypted-rc4-user-password.pdf", "caf\u00e9"), ]; /// The absolute path of tests/Corpus/, found by walking up from the running assembly to the directory that holds Broadside.slnx. @@ -55,8 +67,14 @@ public static class Corpus /// Names of the files in the "Deliberately broken files" table of the corpus README. public static IReadOnlyList MalformedFileNames => Malformed; + /// Names of the files in the "Password-protected files" table: well-formed, but they open only with a password. + public static IReadOnlyList PasswordProtectedFileNames { get; } = [.. PasswordProtected.Select(file => file.FileName)]; + /// Names of every file in the corpus, well-formed first. - public static IReadOnlyList AllFileNames { get; } = [.. WellFormed, .. Malformed]; + public static IReadOnlyList AllFileNames { get; } = [.. WellFormed, .. Malformed, .. PasswordProtected.Select(file => file.FileName)]; + + /// Theory data over the password-protected files: the file name and its user password (the owner password is owner). + public static TheoryData PasswordProtectedFiles => new(PasswordProtected.Select(file => (file.FileName, file.UserPassword))); /// Theory data over . public static TheoryData WellFormedFiles => new(WellFormed); diff --git a/tests/Broadside.Tests/Document/ConcurrencyTests.cs b/tests/Broadside.Tests/Document/ConcurrencyTests.cs index fefaac93..37adb5ec 100644 --- a/tests/Broadside.Tests/Document/ConcurrencyTests.cs +++ b/tests/Broadside.Tests/Document/ConcurrencyTests.cs @@ -27,6 +27,9 @@ public class ConcurrencyTests { private const int Repetitions = 50; + /// The owner password of the encrypted corpus files, so the password-protected ones open too (ignored elsewhere). + private static readonly PdfOptions Options = new PdfOptions().WithPassword("owner"); + public static TheoryData FilesBySource { get @@ -51,7 +54,7 @@ public void Every_page_and_object_reads_the_same_from_many_threads_as_from_one(s Reading expected; try { - using PdfDocument alone = PdfDocument.Open(Corpus.Bytes(fileName)); + using PdfDocument alone = PdfDocument.Open(Corpus.Bytes(fileName), Options); expected = Reading.Of(alone, References(alone)); } catch (DiagnosticException unreadable) @@ -123,18 +126,18 @@ private static CosReference[] References(PdfDocument document) private static PdfDocument Open(string fileName, ConcurrentSource source) => source switch { - ConcurrentSource.Bytes => PdfDocument.Open(Corpus.Bytes(fileName)), - ConcurrentSource.Path => PdfDocument.Open(Corpus.Path(fileName)), + ConcurrentSource.Bytes => PdfDocument.Open(Corpus.Bytes(fileName), Options), + ConcurrentSource.Path => PdfDocument.Open(Corpus.Path(fileName), Options), ConcurrentSource.FileStream => OpenFileStream(fileName), - ConcurrentSource.SeekableStream => PdfDocument.Open(new ProbeStream(Corpus.Bytes(fileName))), - _ => PdfDocument.Open(new ProbeStream(Corpus.Bytes(fileName), seekable: false)), + ConcurrentSource.SeekableStream => PdfDocument.Open(new ProbeStream(Corpus.Bytes(fileName)), Options), + _ => PdfDocument.Open(new ProbeStream(Corpus.Bytes(fileName), seekable: false), Options), }; /// Opens through a the test then closes: the mapping outlives the caller's handle. private static PdfDocument OpenFileStream(string fileName) { using FileStream stream = Corpus.Open(fileName); - return PdfDocument.Open(stream); + return PdfDocument.Open(stream, Options); } /// What one complete read of a document saw, as values. diff --git a/tests/Broadside.Tests/Filters/CorpusFilterTests.cs b/tests/Broadside.Tests/Filters/CorpusFilterTests.cs index d9d4f34e..8c357d4b 100644 --- a/tests/Broadside.Tests/Filters/CorpusFilterTests.cs +++ b/tests/Broadside.Tests/Filters/CorpusFilterTests.cs @@ -49,8 +49,6 @@ public void Decoding_into_a_buffer_writer_gives_the_same_bytes(string fileName, [MemberData(nameof(Corpus.WellFormedFiles), MemberType = typeof(Corpus))] public void Every_page_content_stream_of_a_well_formed_file_decodes_with_no_diagnostics(string fileName) { - Assert.SkipWhen(fileName.StartsWith("encrypted-", StringComparison.Ordinal), "Needs decryption (#42)."); - using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName)); foreach (PdfPage page in document.Pages) { diff --git a/tests/Broadside.Tests/Security/CryptFilterTests.cs b/tests/Broadside.Tests/Security/CryptFilterTests.cs new file mode 100644 index 00000000..ea90c15f --- /dev/null +++ b/tests/Broadside.Tests/Security/CryptFilterTests.cs @@ -0,0 +1,174 @@ +using System.Text; +using System.Text.RegularExpressions; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Tests.Document; +using Broadside.TestSupport; + +namespace Broadside.Tests.Security; + +/// +/// Crypt filters: StmF and StrF, the Identity crypt filter, a stream that names its own crypt filter, and +/// EncryptMetadata false; and how damaged ciphertext is repaired. ISO 32000-2 §7.4.10, §7.6.3, §7.6.6; ISO/TS 32003 §5.2. +/// +public class CryptFilterTests +{ + [Fact] + public void Each_content_stream_decrypts_with_the_crypt_filter_it_names_or_the_default_one() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("encrypted-crypt-filters.pdf")); + var contents = (CosArray)document.Pages[0].Dictionary[new CosName("Contents")]; + + string[] texts = [.. contents.Select(reference => Encoding.Latin1.GetString(document.DecodeStream((CosStream)document.Resolve(reference)).Span))]; + + Assert.Equal( + [ + "BT /F1 24 Tf 72 700 Td (StmF StdCF) Tj ET", + "BT /F1 24 Tf 72 660 Td (Identity crypt filter) Tj ET", + "BT /F1 24 Tf 72 620 Td (StdCF crypt filter) Tj ET", + ], + texts); + Assert.Equal("Crypt filters", EncryptedCorpusTests.InfoTitle(document)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Metadata_is_left_as_it_is_when_encrypt_metadata_is_false() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("encrypted-crypt-filters.pdf")); + var metadata = (CosStream)document.Resolve(document.Catalog[new CosName("Metadata")]); + + Assert.False(document.Security!.EncryptsMetadata); + Assert.StartsWith(">", "/DecodeParms << /Type /CryptFilterDecodeParms /Name /XyzCF >>", StringComparison.Ordinal); + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + var stream = (CosStream)document.Resolve(((CosArray)document.Pages[0].Dictionary[new CosName("Contents")])[2]); + + ReadOnlyMemory decoded = document.DecodeStream(stream); + + Assert.True(decoded.Span.SequenceEqual(stream.EncodedData.Span)); + Assert.Equal("CryptFilterUnsupported", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void Metadata_in_plaintext_although_encrypt_metadata_is_true_is_read_as_it_is_with_a_diagnostic() + { + byte[] original = Corpus.Bytes("encrypted-aes-256.pdf"); + string id = Regex.Match(Encoding.Latin1.GetString(original), "/ID \\[<[0-9a-f]+> <[0-9a-f]+>\\]").Value; + const string xmp = ""; + byte[] file = TestPdf.AppendUpdate( + original, + $"/Size 9 /Root 1 0 R /Encrypt 6 0 R {id}", + (1, 0, "<< /Type /Catalog /Pages 2 0 R /Metadata 8 0 R >>"), + (8, 0, $"<< /Type /Metadata /Subtype /XML /Length {xmp.Length} >>\nstream\n{xmp}\nendstream")); + + using PdfDocument document = PdfDocument.Open(file); + var metadata = (CosStream)document.Resolve(document.Catalog[new CosName("Metadata")]); + + Assert.StartsWith(" diagnostic.Code == "MetadataNotEncrypted"); + } + + [Fact] + public void Aes_gcm_data_that_fails_authentication_decrypts_to_nothing_with_an_error() + { + byte[] file = Corpus.Bytes("encrypted-aes-gcm.pdf"); + int data = IndexOf(file, "4 0 obj\n<< /Length "u8) is var start and >= 0 ? IndexOf(file, "stream\n"u8, start) + "stream\n".Length : -1; + file[data + 20] ^= 0x01; + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal(string.Empty, EncryptedCorpusTests.ContentText(document)); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("EncryptedDataAuthenticationFailed", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity); + Assert.Equal(new CosReference(4, 0), diagnostic.ObjectReference); + } + + [Fact] + public void Aes_data_with_a_damaged_pad_is_kept_whole_with_a_diagnostic() + { + byte[] file = Corpus.Bytes("encrypted-aes-256.pdf"); + int start = IndexOf(file, "4 0 obj\n"u8); + int end = IndexOf(file, "\nendstream"u8, start); + file[end - 1] ^= 0x55; + + using PdfDocument document = PdfDocument.Open(file); + string text = EncryptedCorpusTests.ContentText(document); + + Assert.StartsWith("BT /F1 24 Tf 72 700 Td (AES-256", text, StringComparison.Ordinal); + Assert.Equal(48, text.Length); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("EncryptedDataInvalid", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); + } + + [Fact] + public void Damaged_ciphertext_throws_in_strict_mode() + { + byte[] file = Corpus.Bytes("encrypted-aes-gcm.pdf"); + int start = IndexOf(file, "4 0 obj\n"u8); + file[IndexOf(file, "stream\n"u8, start) + 30] ^= 0x01; + + using PdfDocument document = PdfDocument.Open(file, new PdfOptions().UseStrict()); + + var exception = Assert.Throws(() => EncryptedCorpusTests.ContentText(document)); + Assert.Equal("EncryptedDataAuthenticationFailed", exception.Diagnostic.Code); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void An_embedded_file_is_decrypted_with_eff_which_defaults_to_stmf(bool effIdentity) + { + byte[] original = Corpus.Bytes("encrypted-aes-256.pdf"); + string text = Encoding.Latin1.GetString(original); + byte[] payload = "embedded file payload"u8.ToArray(); + byte[] data = payload; + if (!effIdentity) + { + using var aes = System.Security.Cryptography.Aes.Create(); + aes.Key = System.Security.Cryptography.SHA256.HashData("broadside-corpus:encrypted-aes-256:file-key:0"u8); + byte[] iv = new byte[16]; + data = [.. iv, .. aes.EncryptCbc(payload, iv)]; + } + + int start = text.IndexOf("6 0 obj\n", StringComparison.Ordinal) + "6 0 obj\n".Length; + string encryption = text[start..text.IndexOf("\nendobj", start, StringComparison.Ordinal)]; + int idStart = text.IndexOf("/ID [", StringComparison.Ordinal); + string id = text[idStart..(text.IndexOf(']', idStart) + 1)]; + byte[] file = TestPdf.AppendUpdate( + original, + $"/Size 9 /Root 1 0 R /Encrypt 6 0 R {id}", + (6, 0, effIdentity ? encryption[..^2] + " /EFF /Identity >>" : encryption), + (8, 0, $"<< /Type /EmbeddedFile /Length {data.Length} >>\nstream\n{Encoding.Latin1.GetString(data)}\nendstream")); + + using PdfDocument document = PdfDocument.Open(file); + var stream = (CosStream)document.Resolve(new CosReference(8, 0)); + + Assert.Equal(payload, document.DecodeStream(stream).ToArray()); + Assert.Empty(document.Diagnostics); + } + + private static int IndexOf(byte[] haystack, ReadOnlySpan needle, int start = 0) + { + int index = haystack.AsSpan(start).IndexOf(needle); + return index < 0 ? -1 : start + index; + } +} diff --git a/tests/Broadside.Tests/Security/CryptographyTests.cs b/tests/Broadside.Tests/Security/CryptographyTests.cs new file mode 100644 index 00000000..e83acc1f --- /dev/null +++ b/tests/Broadside.Tests/Security/CryptographyTests.cs @@ -0,0 +1,205 @@ +using System.Security.Cryptography; +using System.Text; +using Broadside.Security; +using Broadside.Security.Cryptography; +using Broadside.TestSupport; + +namespace Broadside.Tests.Security; + +/// +/// The primitives behind the security handlers, each through its facade: the published test vectors (RFC 1321, FIPS 197, NIST +/// SP 800-38D, RFC 3394, RFC 4013) for the managed implementations the browser uses, and agreement with the base class library on +/// random data where the platform has it. +/// +public class CryptographyTests +{ + public static TheoryData Md5Vectors => new() + { + { string.Empty, "d41d8cd98f00b204e9800998ecf8427e" }, + { "a", "0cc175b9c0f1b6a831c399e269772661" }, + { "abc", "900150983cd24fb0d6963f7d28e17f72" }, + { "message digest", "f96b697d7cb7938d525a2f31aaf161d0" }, + { "abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b" }, + { "12345678901234567890123456789012345678901234567890123456789012345678901234567890", "57edf4a22be3c955ac49da2e2107b67a" }, + }; + + public static TheoryData AesVectors => new() + { + { "000102030405060708090a0b0c0d0e0f", "69c4e0d86a7b0430d8cdb78070b4c55a" }, + { "000102030405060708090a0b0c0d0e0f1011121314151617", "dda97ca4864cdfe06eaf70a0ec0d7191" }, + { "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", "8ea2b7ca516745bfeafc49904b496089" }, + }; + + public static TheoryData Rc4Vectors => new() + { + { "Key", "Plaintext", "bbf316e8d940af0ad3" }, + { "Wiki", "pedia", "1021bf0420" }, + { "Secret", "Attack at dawn", "45a01f645fc35b383552544b9bf5" }, + }; + + [Theory] + [MemberData(nameof(Md5Vectors))] + public void Managed_md5_matches_rfc_1321(string message, string digest) + { + using IDisposable managed = CryptographyBackend.ForceManaged(); + byte[] output = new byte[16]; + + Md5.HashData(Encoding.ASCII.GetBytes(message), output); + + Assert.Equal(digest, Convert.ToHexStringLower(output)); + } + + [Fact] + public void Managed_md5_agrees_with_the_platform_at_every_padding_boundary() + { + byte[] data = RandomBytes(300, seed: 1); + for (int length = 0; length <= data.Length; length++) + { + byte[] managed = new byte[16]; + ManagedMd5.HashData(data.AsSpan(0, length), managed); +#pragma warning disable CA5351 // The reference implementation the managed one is checked against. + Assert.Equal(MD5.HashData(data.AsSpan(0, length)), managed); +#pragma warning restore CA5351 + } + } + + [Theory] + [MemberData(nameof(AesVectors))] + public void Managed_aes_matches_fips_197_appendix_c(string key, string ciphertext) + { + using IDisposable managed = CryptographyBackend.ForceManaged(); + using AesCipher aes = AesCipher.Create(Convert.FromHexString(key)); + byte[] plaintext = Convert.FromHexString("00112233445566778899aabbccddeeff"); + byte[] output = new byte[16]; + + aes.EncryptEcb(plaintext, output); + Assert.Equal(ciphertext, Convert.ToHexStringLower(output)); + + aes.DecryptEcb(output, output); + Assert.Equal(plaintext, output); + } + + [Theory] + [InlineData(16)] + [InlineData(24)] + [InlineData(32)] + public void Managed_aes_cbc_agrees_with_the_platform(int keyLength) + { + byte[] key = RandomBytes(keyLength, seed: keyLength); + byte[] iv = RandomBytes(16, seed: 99); + byte[] plaintext = RandomBytes(16 * 37, seed: 7); + byte[] expected = new byte[plaintext.Length]; + byte[] actual = new byte[plaintext.Length]; + using (AesCipher platform = AesCipher.Create(key)) + { + platform.EncryptCbc(plaintext, iv, expected); + } + + using (CryptographyBackend.ForceManaged()) + using (AesCipher managed = AesCipher.Create(key)) + { + managed.EncryptCbc(plaintext, iv, actual); + Assert.Equal(expected, actual); + managed.DecryptCbc(actual, iv, actual); + } + + Assert.Equal(plaintext, actual); + } + + [Fact] + public void Managed_aes_gcm_matches_the_gcm_specification_test_cases_13_and_14() + { + using IDisposable managed = CryptographyBackend.ForceManaged(); + byte[] tag = new byte[16]; + byte[] ciphertext = new byte[16]; + + AesGcmCipher.Encrypt(new byte[32], new byte[12], [], [], tag); + Assert.Equal("530f8afbc74536b9a963b4f1c4cb738b", Convert.ToHexStringLower(tag)); + + AesGcmCipher.Encrypt(new byte[32], new byte[12], new byte[16], ciphertext, tag); + Assert.Equal("cea7403d4d606b6e074ec5d3baf39d18", Convert.ToHexStringLower(ciphertext)); + Assert.Equal("d0d1c8a799996bf0265b98b5d48ab919", Convert.ToHexStringLower(tag)); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(16)] + [InlineData(33)] + [InlineData(1000)] + public void Managed_aes_gcm_agrees_with_the_platform_and_rejects_a_changed_tag(int length) + { + Assert.SkipUnless(AesGcm.IsSupported, "The platform has no AES-GCM to compare with."); + byte[] key = RandomBytes(32, seed: 5); + byte[] nonce = RandomBytes(12, seed: 6); + byte[] plaintext = RandomBytes(length, seed: length); + byte[] expected = new byte[length]; + byte[] expectedTag = new byte[16]; + AesGcmCipher.Encrypt(key, nonce, plaintext, expected, expectedTag); + + using IDisposable managed = CryptographyBackend.ForceManaged(); + byte[] actual = new byte[length]; + byte[] tag = new byte[16]; + AesGcmCipher.Encrypt(key, nonce, plaintext, actual, tag); + Assert.Equal(expected, actual); + Assert.Equal(expectedTag, tag); + + byte[] decrypted = new byte[length]; + Assert.True(AesGcmCipher.TryDecrypt(key, nonce, actual, tag, decrypted)); + Assert.Equal(plaintext, decrypted); + tag[^1] ^= 1; + Assert.False(AesGcmCipher.TryDecrypt(key, nonce, actual, tag, decrypted)); + } + + [Theory] + [InlineData("000102030405060708090a0b0c0d0e0f", "00112233445566778899aabbccddeeff", "1fa68b0a8112b447aef34bd8fb5a7b829d3e862371d2cfe5")] + [InlineData("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", "00112233445566778899aabbccddeeff000102030405060708090a0b0c0d0e0f", "28c9f404c4b810f4cbccb35cfb87f8263f5786e2d80ed326cbc7f0e71a99f43bfb988b9b7a02dd21")] + public void The_key_wrap_matches_rfc_3394(string keyEncryptionKey, string key, string wrapped) + { + foreach (bool forceManaged in new[] { false, true }) + { + using IDisposable? managed = forceManaged ? CryptographyBackend.ForceManaged() : null; + byte[] kek = Convert.FromHexString(keyEncryptionKey); + + Assert.Equal(wrapped, Convert.ToHexStringLower(AesKeyWrap.Wrap(kek, Convert.FromHexString(key)))); + Assert.Equal(key, Convert.ToHexStringLower(AesKeyWrap.Unwrap(kek, Convert.FromHexString(wrapped))!)); + } + } + + [Fact] + public void A_wrapped_key_that_fails_the_integrity_check_does_not_unwrap() + { + byte[] wrapped = Convert.FromHexString("1fa68b0a8112b447aef34bd8fb5a7b829d3e862371d2cfe5"); + wrapped[10] ^= 1; + + Assert.Null(AesKeyWrap.Unwrap(Convert.FromHexString("000102030405060708090a0b0c0d0e0f"), wrapped)); + Assert.Null(AesKeyWrap.Unwrap(new byte[16], new byte[12])); + } + + [Theory] + [MemberData(nameof(Rc4Vectors))] + public void Rc4_matches_the_published_vectors(string key, string plaintext, string ciphertext) + { + byte[] output = Encoding.ASCII.GetBytes(plaintext); + + Rc4.Transform(Encoding.ASCII.GetBytes(key), output, output); + + Assert.Equal(ciphertext, Convert.ToHexStringLower(output)); + } + + [Theory] + [InlineData("I\u00adX", "IX")] + [InlineData("user", "user")] + [InlineData("USER", "USER")] + [InlineData("a\u00a0b\u3000c", "a b c")] + [InlineData("zero\u2060width", "zerowidth")] + public void Saslprep_maps_like_rfc_4013(string input, string output) => Assert.Equal(output, PasswordEncoding.SaslPrep(input)); + + [Theory] + [InlineData("\u0007")] + [InlineData("private\ue000use")] + [InlineData("\ud800")] + public void Saslprep_rejects_prohibited_characters(string input) => Assert.Null(PasswordEncoding.SaslPrep(input)); + + private static byte[] RandomBytes(int length, int seed) => FilterEncoders.SampleData(length, alphabet: 256, seed: seed); +} diff --git a/tests/Broadside.Tests/Security/DecryptionAllocationTests.cs b/tests/Broadside.Tests/Security/DecryptionAllocationTests.cs new file mode 100644 index 00000000..9387b87d --- /dev/null +++ b/tests/Broadside.Tests/Security/DecryptionAllocationTests.cs @@ -0,0 +1,56 @@ +using Broadside.Security.Cryptography; +using Broadside.TestSupport; + +namespace Broadside.Tests.Security; + +/// +/// The decryption hot paths allocate nothing per call into a caller's buffer (CLAUDE.md, hot paths; the benchmarks are +/// SecurityBenchmarks). ISO 32000-2 §7.6.3. +/// +[Collection("Heavy")] +public class DecryptionAllocationTests +{ + private static readonly byte[] Key = [.. Enumerable.Range(0, 32).Select(i => (byte)i)]; + + [Fact] + public void Rc4_allocates_nothing() + { + byte[] data = FilterEncoders.SampleData(64 * 1024, alphabet: 256); + byte[] output = new byte[data.Length]; + + Assert.Equal(0, Measure(() => Rc4.Transform(Key.AsSpan(0, 16), data, output))); + } + + [Fact] + public void Aes_cbc_into_a_buffer_allocates_nothing_per_block() + { + byte[] data = FilterEncoders.SampleData(64 * 1024, alphabet: 256); + byte[] output = new byte[data.Length]; + byte[] iv = new byte[16]; + using AesCipher platform = AesCipher.Create(Key); + AesCipher managed; + using (CryptographyBackend.ForceManaged()) + { + managed = AesCipher.Create(Key); + } + + using (managed) + { + // The platform cipher costs a small constant per call (its one-shot transform object), whatever the data length. + Assert.InRange(Measure(() => platform.DecryptCbc(data, iv, output)), 0, 256); + Assert.Equal(0, Measure(() => managed.DecryptCbc(data, iv, output))); + } + } + + private static long Measure(Action action) + { + for (int i = 0; i < 40; i++) + { + action(); // past tiered compilation + } + + long before = GC.GetAllocatedBytesForCurrentThread(); + action(); + return GC.GetAllocatedBytesForCurrentThread() - before; + } +} diff --git a/tests/Broadside.Tests/Security/EncryptedCorpusTests.cs b/tests/Broadside.Tests/Security/EncryptedCorpusTests.cs new file mode 100644 index 00000000..2b12846a --- /dev/null +++ b/tests/Broadside.Tests/Security/EncryptedCorpusTests.cs @@ -0,0 +1,201 @@ +using System.Text; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Security; +using Broadside.Security.Cryptography; +using Broadside.TestSupport; + +namespace Broadside.Tests.Security; + +/// +/// The encrypted corpus files open with the empty user password and with the owner password owner, and their strings and +/// content streams decrypt to what tests/Corpus/generate.py encrypted. ISO 32000-2 §7.6; ISO/TS 32003. +/// +public class EncryptedCorpusTests +{ + public static TheoryData EncryptedFiles => new() + { + { "encrypted-rc4-40.pdf", "RC4 40-bit (R2)" }, + { "encrypted-rc4-128.pdf", "RC4 128-bit (R3)" }, + { "encrypted-rc4-40-r3.pdf", "RC4 40-bit (R3)" }, + { "encrypted-aes-128.pdf", "AES-128 (R4)" }, + { "encrypted-aes-256.pdf", "AES-256 (R6)" }, + { "encrypted-aes-gcm.pdf", "AES-256-GCM (R7)" }, + { "encrypted-mac.pdf", "Integrity MAC (R6)" }, + }; + + public static TheoryData EncryptionParameters => new() + { + { "encrypted-rc4-40.pdf", 1, 2, 40 }, + { "encrypted-rc4-128.pdf", 2, 3, 128 }, + { "encrypted-rc4-40-r3.pdf", 2, 3, 40 }, + { "encrypted-aes-128.pdf", 4, 4, 128 }, + { "encrypted-aes-256.pdf", 5, 6, 256 }, + { "encrypted-aes-gcm.pdf", 6, 7, 256 }, + }; + + [Theory] + [MemberData(nameof(EncryptedFiles))] + public void An_encrypted_file_opens_with_the_empty_user_password_and_its_content_stream_decrypts(string fileName, string text) + { + using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName)); + + Assert.Equal($"BT /F1 24 Tf 72 700 Td ({text}) Tj ET", ContentText(document)); + Assert.True(document.IsEncrypted); + Assert.Equal(PdfAccessLevel.User, document.Security!.Access); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [MemberData(nameof(EncryptedFiles))] + public void An_encrypted_file_opens_with_the_owner_password_and_gives_owner_access(string fileName, string text) + { + using PdfDocument document = new PdfEngine().Open(Corpus.Bytes(fileName), new PdfPassword("owner")); + + Assert.Equal($"BT /F1 24 Tf 72 700 Td ({text}) Tj ET", ContentText(document)); + Assert.Equal(PdfAccessLevel.Owner, document.Security!.Access); + Assert.Equal(PdfPermissions.All, document.Permissions); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [MemberData(nameof(EncryptedFiles))] + public void An_encrypted_file_opens_in_strict_mode(string fileName, string text) + { + using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName), new PdfOptions().UseStrict()); + + Assert.Equal($"BT /F1 24 Tf 72 700 Td ({text}) Tj ET", ContentText(document)); + } + + [Theory] + [MemberData(nameof(EncryptedFiles))] + public void The_managed_cryptography_decrypts_like_the_platform_cryptography(string fileName, string text) + { + using IDisposable managed = CryptographyBackend.ForceManaged(); + using PdfDocument document = new PdfEngine().Open(Corpus.Bytes(fileName), new PdfPassword("owner")); + + Assert.Equal($"BT /F1 24 Tf 72 700 Td ({text}) Tj ET", ContentText(document)); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [MemberData(nameof(EncryptionParameters))] + public void The_security_describes_the_algorithm_revision_and_key_length(string fileName, int version, int revision, int keyLength) + { + using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName)); + PdfSecurity security = document.Security!; + + Assert.Equal(new CosName("Standard"), security.Handler); + Assert.Null(security.SubFilter); + Assert.Equal(version, security.Version); + Assert.Equal(revision, security.Revision); + Assert.Equal(keyLength, security.KeyLength); + Assert.Equal(-4, security.RawPermissions); + Assert.Equal(PdfPermissions.All, security.Permissions); + Assert.True(security.EncryptsMetadata); + Assert.False(security.RequiresIntegrityCode); + Assert.Equal(PdfIntegrityStatus.None, security.Integrity); + } + + [Fact] + public void Strings_are_decrypted_with_the_key_of_the_object_that_holds_them() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("encrypted-aes-gcm.pdf")); + + Assert.Equal("AES-GCM", InfoTitle(document)); + var extension = (CosDictionary)((CosArray)((CosDictionary)document.Catalog[new CosName("Extensions")])[new CosName("ISO_")])[0]; + Assert.Equal(":2023", ((CosString)extension[new CosName("ExtensionRevision")]).DecodeText()); + Assert.Equal("https://www.iso.org/standard/45876.html", ((CosString)extension[new CosName("URL")]).DecodeText()); + } + + [Fact] + public void Decrypting_marks_nothing_dirty() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("encrypted-aes-gcm.pdf")); + + _ = ContentText(document); + _ = InfoTitle(document); + + Assert.False(document.Catalog.IsDirty); + Assert.False(document.Resolve(document.Trailer[new CosName("Info")]).IsDirty); + Assert.False(document.Resolve(document.Pages[0].Dictionary[new CosName("Contents")]).IsDirty); + } + + [Fact] + public void The_encryption_dictionary_and_the_file_identifier_are_not_decrypted() + { + byte[] file = Corpus.Bytes("encrypted-aes-256.pdf"); + using PdfDocument document = PdfDocument.Open(file); + + var owner = (CosString)document.Security!.EncryptionDictionary[new CosName("O")]; + Assert.Contains(Convert.ToHexStringLower(owner.Bytes), Encoding.Latin1.GetString(file), StringComparison.Ordinal); + var id = (CosString)((CosArray)document.Trailer[new CosName("ID")])[0]; + Assert.Equal(16, id.Bytes.Length); + Assert.Contains(Convert.ToHexStringLower(id.Bytes), Encoding.Latin1.GetString(file), StringComparison.Ordinal); + } + + [Fact] + public void Concurrent_readers_see_the_same_decrypted_content() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("encrypted-aes-128.pdf")); + string[] texts = new string[32]; + + Parallel.For(0, texts.Length, index => texts[index] = ContentText(document)); + + Assert.All(texts, text => Assert.Equal("BT /F1 24 Tf 72 700 Td (AES-128 (R4)) Tj ET", text)); + } + + [Fact] + public void An_unencrypted_document_permits_everything() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("text-standard14.pdf")); + + Assert.False(document.IsEncrypted); + Assert.Null(document.Security); + Assert.Equal(PdfPermissions.All, document.Permissions); + } + + [Fact] + public void A_document_rebuilt_because_its_root_is_unusable_is_still_decrypted() + { + string text = Encoding.Latin1.GetString(Corpus.Bytes("encrypted-aes-256.pdf")).Replace("/Root 1 0 R", "/Root 9 0 R", StringComparison.Ordinal); + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + + Assert.Equal("BT /F1 24 Tf 72 700 Td (AES-256 (R6)) Tj ET", ContentText(document)); + Assert.Contains(document.Diagnostics, diagnostic => diagnostic.Code == "RootMissing"); + } + + [Fact] + public void A_document_whose_cross_reference_is_unreadable_is_rebuilt_and_decrypted() + { + string text = Encoding.Latin1.GetString(Corpus.Bytes("encrypted-aes-gcm.pdf")).Replace("startxref", "startxrex", StringComparison.Ordinal); + + using PdfDocument document = new PdfEngine().Open(Encoding.Latin1.GetBytes(text), new PdfPassword("owner")); + + Assert.Equal("BT /F1 24 Tf 72 700 Td (AES-256-GCM (R7)) Tj ET", ContentText(document)); + Assert.Equal("AES-GCM", InfoTitle(document)); + Assert.Equal(PdfAccessLevel.Owner, document.Security!.Access); + } + + [Fact] + public void A_revision_7_document_without_the_32003_extension_is_read_with_a_diagnostic() + { + string text = Encoding.Latin1.GetString(Corpus.Bytes("encrypted-aes-gcm.pdf")).Replace("/ExtensionLevel 32003", "/ExtensionLevel 32009", StringComparison.Ordinal); + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + + Assert.Equal("BT /F1 24 Tf 72 700 Td (AES-256-GCM (R7)) Tj ET", ContentText(document)); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("EncryptionExtensionMissing", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); + } + + internal static CosStream ContentStream(PdfDocument document) => + Assert.IsType(document.Resolve(document.Pages[0].Dictionary[new CosName("Contents")])); + + internal static string ContentText(PdfDocument document) => Encoding.Latin1.GetString(document.DecodeStream(ContentStream(document)).Span); + + internal static string InfoTitle(PdfDocument document) => + ((CosString)((CosDictionary)document.Resolve(document.Trailer[new CosName("Info")]))[new CosName("Title")]).DecodeText(); +} diff --git a/tests/Broadside.Tests/Security/IntegrityTests.cs b/tests/Broadside.Tests/Security/IntegrityTests.cs new file mode 100644 index 00000000..187df09e --- /dev/null +++ b/tests/Broadside.Tests/Security/IntegrityTests.cs @@ -0,0 +1,127 @@ +using System.Globalization; +using System.Text; +using Broadside.Diagnostics; +using Broadside.TestSupport; + +namespace Broadside.Tests.Security; + +/// The integrity MAC of an encrypted document. ISO/TS 32004 §5, §6, Annex B. +public class IntegrityTests +{ + [Fact] + public void A_standalone_mac_that_covers_the_whole_file_is_verified() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("encrypted-mac.pdf")); + + Assert.Equal(PdfIntegrityStatus.Verified, document.Security!.Integrity); + Assert.True(document.Security.RequiresIntegrityCode); + Assert.Equal(-4100, document.Security.RawPermissions); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void The_mac_is_verified_whichever_password_opens_the_document() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("encrypted-mac.pdf"), new PdfOptions().WithPassword("owner")); + + Assert.Equal(PdfIntegrityStatus.Verified, document.Security!.Integrity); + } + + [Fact] + public void A_tampered_file_opens_with_a_mismatch_diagnostic_in_lenient_mode() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("encrypted-mac-tampered.pdf")); + + Assert.Equal(PdfIntegrityStatus.Failed, document.Security!.Integrity); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("IntegrityCodeMismatch", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity); + Assert.Equal("BT /F1 24 Tf 72 700 Td (Integrity MAC (R6)) Tj ET", EncryptedCorpusTests.ContentText(document)); + } + + [Fact] + public void A_tampered_file_throws_in_strict_mode() + { + var exception = Assert.Throws(() => PdfDocument.Open(Corpus.Path("encrypted-mac-tampered.pdf"), new PdfOptions().UseStrict())); + + Assert.Equal("IntegrityCodeMismatch", exception.Diagnostic.Code); + } + + [Fact] + public void Bytes_appended_after_the_covered_range_make_the_mac_incomplete() + { + byte[] file = [.. Corpus.Bytes("encrypted-mac.pdf"), .. "% appended\n"u8]; + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal(PdfIntegrityStatus.Failed, document.Security!.Integrity); + Assert.Equal("IntegrityCodeIncomplete", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_missing_mac_that_the_permissions_require_is_reported() + { + string text = Encoding.Latin1.GetString(Corpus.Bytes("encrypted-mac.pdf")).Replace("/AuthCode", "/AuthCodX", StringComparison.Ordinal); + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + + Assert.Equal(PdfIntegrityStatus.Missing, document.Security!.Integrity); + Assert.Equal("IntegrityCodeMissing", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_mac_whose_token_was_changed_is_reported() + { + string text = Encoding.Latin1.GetString(Corpus.Bytes("encrypted-mac.pdf")); + int mac = text.IndexOf("/MAC <", StringComparison.Ordinal) + "/MAC <".Length; + int end = text.IndexOf('>', mac); + char[] chars = text.ToCharArray(); + chars[end - 1] = chars[end - 1] == '0' ? '1' : '0'; // the last byte of the HMAC value + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(chars)); + + Assert.Equal(PdfIntegrityStatus.Failed, document.Security!.Integrity); + Assert.Equal("IntegrityCodeMismatch", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_mac_with_the_wrong_key_derivation_salt_does_not_unwrap() + { + string text = Encoding.Latin1.GetString(Corpus.Bytes("encrypted-mac.pdf")); + int salt = text.IndexOf("/KDFSalt <", StringComparison.Ordinal) + "/KDFSalt <".Length; + char[] chars = text.ToCharArray(); + chars[salt] = chars[salt] == '0' ? '1' : '0'; + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(chars)); + + Assert.Equal(PdfIntegrityStatus.Failed, document.Security!.Integrity); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("IntegrityCodeMismatch", diagnostic.Code); + Assert.Contains("unwrap", diagnostic.Message, StringComparison.Ordinal); + } + + [Fact] + public void A_byte_range_that_does_not_frame_the_mac_string_is_invalid() + { + string text = Encoding.Latin1.GetString(Corpus.Bytes("encrypted-mac.pdf")); + int range = text.IndexOf("/ByteRange [0 ", StringComparison.Ordinal) + "/ByteRange [0 ".Length; + long l1 = long.Parse(text.AsSpan(range, 10), CultureInfo.InvariantCulture); + text = string.Concat(text.AsSpan(0, range), (l1 - 1).ToString("D10", CultureInfo.InvariantCulture), text.AsSpan(range + 10)); // one byte short + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text)); + + Assert.Equal(PdfIntegrityStatus.Failed, document.Security!.Integrity); + Assert.Equal("IntegrityCodeInvalid", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_mac_whose_location_is_unknown_is_not_verified_and_only_noted() + { + string text = Encoding.Latin1.GetString(Corpus.Bytes("encrypted-mac.pdf")).Replace("/MACLocation /Standalone", "/MACLocation /Elsewhere ", StringComparison.Ordinal); + + using PdfDocument document = PdfDocument.Open(Encoding.Latin1.GetBytes(text), new PdfOptions().UseStrict()); + + Assert.Equal(PdfIntegrityStatus.NotVerified, document.Security!.Integrity); + Assert.Equal(DiagnosticSeverity.Information, Assert.Single(document.Diagnostics).Severity); + } +} diff --git a/tests/Broadside.Tests/Security/PasswordTests.cs b/tests/Broadside.Tests/Security/PasswordTests.cs new file mode 100644 index 00000000..d6e8aba4 --- /dev/null +++ b/tests/Broadside.Tests/Security/PasswordTests.cs @@ -0,0 +1,145 @@ +using Broadside.Diagnostics; +using Broadside.Security; +using Broadside.TestSupport; + +namespace Broadside.Tests.Security; + +/// +/// Passwords: the default user password, user and owner passwords, their encodings by revision, and the distinct errors for a +/// missing or wrong password. ISO 32000-2 §7.6.4.1-7.6.4.4. +/// +public class PasswordTests +{ + public static TheoryData ProtectedContent => new() + { + { "encrypted-user-password.pdf", "p\u00e4sswort", "User password (R6)" }, + { "encrypted-rc4-user-password.pdf", "café", "User password (R3)" }, + }; + + [Theory] + [MemberData(nameof(Corpus.PasswordProtectedFiles), MemberType = typeof(Corpus))] + public void A_document_with_a_user_password_needs_a_password(string fileName, string userPassword) + { + Assert.NotEmpty(userPassword); + + var exception = Assert.Throws(() => PdfDocument.Open(Corpus.Path(fileName))); + + Assert.Equal(PdfPasswordFailure.Required, exception.Failure); + } + + [Theory] + [MemberData(nameof(Corpus.PasswordProtectedFiles), MemberType = typeof(Corpus))] + public void A_wrong_password_is_reported_as_incorrect(string fileName, string userPassword) + { + var exception = Assert.Throws(() => new PdfEngine().Open(Corpus.Path(fileName), new PdfPassword(userPassword + "x"))); + + Assert.Equal(PdfPasswordFailure.Incorrect, exception.Failure); + } + + [Theory] + [MemberData(nameof(ProtectedContent))] + public void The_user_password_opens_the_document_with_user_access(string fileName, string userPassword, string text) + { + using PdfDocument document = new PdfEngine().Open(Corpus.Path(fileName), new PdfPassword(userPassword)); + + Assert.Equal($"BT /F1 24 Tf 72 700 Td ({text}) Tj ET", EncryptedCorpusTests.ContentText(document)); + Assert.Equal("Protected", EncryptedCorpusTests.InfoTitle(document)); + Assert.Equal(PdfAccessLevel.User, document.Security!.Access); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [MemberData(nameof(ProtectedContent))] + public void The_owner_password_opens_the_document_with_owner_access(string fileName, string userPassword, string text) + { + Assert.NotEmpty(userPassword); + using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName), new PdfOptions().WithPassword("owner")); + + Assert.Equal($"BT /F1 24 Tf 72 700 Td ({text}) Tj ET", EncryptedCorpusTests.ContentText(document)); + Assert.Equal(PdfAccessLevel.Owner, document.Security!.Access); + Assert.Equal(PdfPermissions.All, document.Permissions); + } + + [Fact] + public void User_access_has_the_permissions_the_document_grants() + { + using PdfDocument document = new PdfEngine().Open(Corpus.Path("encrypted-user-password.pdf"), new PdfPassword("p\u00e4sswort")); + + Assert.Equal(-3372, document.Security!.RawPermissions); + Assert.Equal(PdfPermissions.Print | PdfPermissions.Extract, document.Permissions); + } + + [Fact] + public void A_revision_6_password_maps_soft_hyphens_to_nothing() + { + using PdfDocument document = new PdfEngine().Open(Corpus.Path("encrypted-user-password.pdf"), new PdfPassword("p\u00e4ss\u00adwort")); + + Assert.Equal(PdfAccessLevel.User, document.Security!.Access); + } + + [Fact] + public void A_legacy_password_can_be_given_as_bytes_in_a_code_page() + { + using PdfDocument document = new PdfEngine().Open(Corpus.Path("encrypted-rc4-user-password.pdf"), new PdfPassword([0x63, 0x61, 0x66, 0xE9])); + + Assert.Equal(PdfAccessLevel.User, document.Security!.Access); + } + + [Fact] + public void A_wrong_password_for_a_document_without_a_user_password_is_still_incorrect() + { + var exception = Assert.Throws( + () => new PdfEngine().Open(Corpus.Path("encrypted-aes-256.pdf"), new PdfPassword("not the owner"))); + + Assert.Equal(PdfPasswordFailure.Incorrect, exception.Failure); + } + + [Fact] + public void The_password_given_to_open_overrides_the_one_on_the_options() + { + var engine = new PdfEngine(new PdfOptions().WithPassword("wrong")); + + using PdfDocument document = engine.Open(Corpus.Path("encrypted-user-password.pdf"), new PdfPassword("owner")); + + Assert.Equal(PdfAccessLevel.Owner, document.Security!.Access); + } + + [Fact] + public void A_password_is_ignored_for_an_unencrypted_document() + { + using PdfDocument document = new PdfEngine().Open(Corpus.Path("empty-page.pdf"), new PdfPassword("anything")); + + Assert.False(document.IsEncrypted); + } + + [Fact] + public void An_owner_password_computed_by_rehashing_only_the_key_length_is_accepted_with_a_diagnostic() + { + using PdfDocument document = new PdfEngine().Open(Corpus.Path("encrypted-owner-key-variant.pdf"), new PdfPassword("owner")); + + Assert.Equal(PdfAccessLevel.Owner, document.Security!.Access); + Assert.Equal("BT /F1 24 Tf 72 700 Td (RC4 40-bit (R3), qpdf owner key) Tj ET", EncryptedCorpusTests.ContentText(document)); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("OwnerPasswordKeyVariant", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); + } + + [Fact] + public void The_owner_key_variant_throws_in_strict_mode() + { + var engine = new PdfEngine(new PdfOptions().UseStrict()); + + var exception = Assert.Throws(() => engine.Open(Corpus.Path("encrypted-owner-key-variant.pdf"), new PdfPassword("owner"))); + + Assert.Equal("OwnerPasswordKeyVariant", exception.Diagnostic.Code); + } + + [Fact] + public void The_owner_key_variant_opens_with_the_empty_user_password_without_a_diagnostic() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("encrypted-owner-key-variant.pdf")); + + Assert.Equal(PdfAccessLevel.User, document.Security!.Access); + Assert.Empty(document.Diagnostics); + } +} diff --git a/tests/Broadside.Tests/Security/SecurityHandlerExtensionPointTests.cs b/tests/Broadside.Tests/Security/SecurityHandlerExtensionPointTests.cs new file mode 100644 index 00000000..82de5191 --- /dev/null +++ b/tests/Broadside.Tests/Security/SecurityHandlerExtensionPointTests.cs @@ -0,0 +1,169 @@ +using System.Security.Cryptography; +using System.Text; +using Broadside.Objects; +using Broadside.Security; +using Broadside.Tests.Document; +using Broadside.TestSupport; + +namespace Broadside.Tests.Security; + +/// +/// The security handler extension point: handlers chosen by Filter or SubFilter, the standard handler as the +/// default, and the errors for encryption no handler implements. ISO 32000-2 §7.6.2, Table 20; §7.6.6, Table 25. +/// +public class SecurityHandlerExtensionPointTests +{ + /// The file encryption key generate.py fixed for encrypted-aes-256.pdf. + private static readonly byte[] Aes256FileKey = SHA256.HashData("broadside-corpus:encrypted-aes-256:file-key:0"u8); + + [Fact] + public void The_standard_handler_is_registered_by_default() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("encrypted-aes-256.pdf")); + + Assert.Equal(new StandardSecurityHandler().Filter, document.Security!.Handler); + } + + [Fact] + public void A_handler_registered_for_standard_replaces_the_default() + { + var handler = new CountingHandler(new StandardSecurityHandler()); + + using PdfDocument document = PdfDocument.Open(Corpus.Path("encrypted-aes-256.pdf"), new PdfOptions().UseSecurityHandler(handler)); + + Assert.Equal(1, handler.Calls); + Assert.Equal("BT /F1 24 Tf 72 700 Td (AES-256 (R6)) Tj ET", EncryptedCorpusTests.ContentText(document)); + } + + [Fact] + public void Two_engines_with_different_handlers_do_not_interfere() + { + var handler = new CountingHandler(new StandardSecurityHandler()); + var custom = new PdfEngine(new PdfOptions().UseSecurityHandler(handler)); + + using (PdfDocument document = PdfDocument.Open(Corpus.Path("encrypted-aes-256.pdf"))) + { + Assert.NotNull(document.Security); + } + + using (PdfDocument document = custom.Open(Corpus.Path("encrypted-aes-256.pdf"))) + { + Assert.NotNull(document.Security); + } + + Assert.Equal(1, handler.Calls); + } + + [Fact] + public void A_handler_that_supplies_the_key_another_way_decrypts_the_document() + { + var escrow = new KeyEscrowHandler(new CosName("Escrow"), [], Aes256FileKey); + + using PdfDocument document = PdfDocument.Open(WithEncryption("encrypted-aes-256.pdf", "/Filter /Standard", "/Filter /Escrow"), new PdfOptions().UseSecurityHandler(escrow)); + + Assert.Equal("BT /F1 24 Tf 72 700 Td (AES-256 (R6)) Tj ET", EncryptedCorpusTests.ContentText(document)); + Assert.Equal(new CosName("Escrow"), document.Security!.Handler); + Assert.Null(document.Security.Revision); + Assert.Equal(PdfPermissions.Print, document.Permissions); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_handler_is_chosen_by_subfilter_when_no_handler_has_the_filter_name() + { + var escrow = new KeyEscrowHandler(new CosName("Escrow"), [new CosName("x.escrow")], Aes256FileKey); + + using PdfDocument document = PdfDocument.Open( + WithEncryption("encrypted-aes-256.pdf", "/Filter /Standard", "/Filter /Vendor /SubFilter /x.escrow"), + new PdfOptions().UseSecurityHandler(escrow)); + + Assert.Equal(new CosName("Escrow"), document.Security!.Handler); + Assert.Equal(new CosName("x.escrow"), document.Security.SubFilter); + } + + [Fact] + public void A_document_whose_handler_is_not_registered_is_not_supported() + { + var exception = Assert.Throws( + () => PdfDocument.Open(WithEncryption("encrypted-aes-256.pdf", "/Filter /Standard", "/Filter /Vendor"))); + + Assert.Equal(PdfEncryptionNotSupportedReason.Handler, exception.Reason); + } + + [Fact] + public void An_unknown_crypt_filter_method_is_an_unsupported_algorithm() + { + string text = Encoding.Latin1.GetString(Corpus.Bytes("encrypted-aes-256.pdf")).Replace("/CFM /AESV3", "/CFM /AESV9", StringComparison.Ordinal); + + var exception = Assert.Throws(() => PdfDocument.Open(Encoding.Latin1.GetBytes(text))); + + Assert.Equal(PdfEncryptionNotSupportedReason.Algorithm, exception.Reason); + } + + [Fact] + public void An_undefined_revision_is_an_unsupported_algorithm() + { + string text = Encoding.Latin1.GetString(Corpus.Bytes("encrypted-aes-256.pdf")).Replace("/R 6", "/R 9", StringComparison.Ordinal); + + var exception = Assert.Throws(() => PdfDocument.Open(Encoding.Latin1.GetBytes(text))); + + Assert.Equal(PdfEncryptionNotSupportedReason.Algorithm, exception.Reason); + } + + [Fact] + public void Registering_no_handler_is_an_argument_error() => + Assert.Throws(() => new PdfOptions().UseSecurityHandler(null!)); + + [Fact] + public void The_standard_handler_reads_permissions_by_revision() + { + // Table 22: revision 2 knows bits 3-6 only; later bits follow the one that covered them. + Assert.Equal(PdfPermissions.All, StandardSecurityHandler.UserPermissions(-4, 2)); + Assert.Equal(PdfPermissions.Print | PdfPermissions.PrintHighQuality, StandardSecurityHandler.UserPermissions(-60, 2)); + Assert.Equal(PdfPermissions.Print | PdfPermissions.Extract, StandardSecurityHandler.UserPermissions(-3372, 3)); + Assert.Equal(PdfPermissions.Annotate | PdfPermissions.FillForms, StandardSecurityHandler.UserPermissions(unchecked((int)0xFFFFF0E0), 3)); + Assert.Equal(PdfPermissions.FillForms | PdfPermissions.Assemble, StandardSecurityHandler.UserPermissions(unchecked((int)0xFFFFF5C0), 4)); + Assert.Equal(PdfPermissions.None, StandardSecurityHandler.UserPermissions(unchecked((int)0xFFFFF8C0) & ~(1 << 11), 6)); + } + + /// Replaces the encryption dictionary (object 6) through an incremental update: its strings are never encrypted. + private static byte[] WithEncryption(string fileName, string find, string replace) + { + byte[] original = Corpus.Bytes(fileName); + string text = Encoding.Latin1.GetString(original); + int start = text.IndexOf("6 0 obj\n", StringComparison.Ordinal) + "6 0 obj\n".Length; + string encryption = text[start..text.IndexOf("\nendobj", start, StringComparison.Ordinal)]; + int idStart = text.IndexOf("/ID [", StringComparison.Ordinal); + string id = text[idStart..(text.IndexOf(']', idStart) + 1)]; + return TestPdf.AppendUpdate(original, $"/Size 7 /Root 1 0 R /Encrypt 6 0 R {id}", (6, 0, encryption.Replace(find, replace, StringComparison.Ordinal))); + } + + private sealed class CountingHandler(ISecurityHandler inner) : ISecurityHandler + { + public int Calls { get; private set; } + + public CosName Filter => inner.Filter; + + public IReadOnlyCollection SubFilters => inner.SubFilters; + + public SecurityHandlerResult Authenticate(SecurityHandlerContext context) + { + Calls++; + return inner.Authenticate(context); + } + } + + private sealed class KeyEscrowHandler(CosName filter, IReadOnlyCollection subFilters, byte[] key) : ISecurityHandler + { + public CosName Filter => filter; + + public IReadOnlyCollection SubFilters => subFilters; + + public SecurityHandlerResult Authenticate(SecurityHandlerContext context) + { + Assert.NotNull(context.EncryptionDictionary); + Assert.Equal(16, context.DocumentId.Length); + return new SecurityHandlerResult(key, PdfAccessLevel.User, PdfPermissions.Print, -4); + } + } +} diff --git a/tests/Broadside.Tests/Security/SignatureIntegrityTests.cs b/tests/Broadside.Tests/Security/SignatureIntegrityTests.cs new file mode 100644 index 00000000..f4d2a293 --- /dev/null +++ b/tests/Broadside.Tests/Security/SignatureIntegrityTests.cs @@ -0,0 +1,184 @@ +using System.Formats.Asn1; +using System.Globalization; +using System.Security.Cryptography; +using System.Security.Cryptography.Pkcs; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using Broadside.Diagnostics; +using Broadside.Security.Cryptography; +using Broadside.Tests.Document; +using Broadside.TestSupport; + +namespace Broadside.Tests.Security; + +/// +/// A PDF MAC token attached to a signature as an unsigned attribute (ISO/TS 32004 §6.5.2, §6.6.3, B.2.3), built in the test: an +/// incremental update of encrypted-aes-256.pdf adds a KDFSalt, a signature dictionary signed with a throwaway +/// certificate, and the trailer's AuthCode pointing at it. +/// +public class SignatureIntegrityTests +{ + private const string IntegrityInfoOid = "1.0.32004.1.0"; + + [Fact] + public void A_mac_attached_to_a_signature_is_verified() + { + using PdfDocument document = PdfDocument.Open(SignedFile(tamperSignature: false)); + + Assert.Equal(PdfIntegrityStatus.Verified, document.Security!.Integrity); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_mac_attached_to_a_different_signature_value_does_not_match() + { + using PdfDocument document = PdfDocument.Open(SignedFile(tamperSignature: true)); + + Assert.Equal(PdfIntegrityStatus.Failed, document.Security!.Integrity); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("IntegrityCodeMismatch", diagnostic.Code); + Assert.Contains("signatureDigest", diagnostic.Message, StringComparison.Ordinal); + } + + private static byte[] SignedFile(bool tamperSignature) + { + byte[] original = Corpus.Bytes("encrypted-aes-256.pdf"); + string text = Encoding.Latin1.GetString(original); + int start = text.IndexOf("6 0 obj\n", StringComparison.Ordinal) + "6 0 obj\n".Length; + string encryption = text[start..text.IndexOf("\nendobj", start, StringComparison.Ordinal)]; + int idStart = text.IndexOf("/ID [", StringComparison.Ordinal); + string id = text[idStart..(text.IndexOf(']', idStart) + 1)]; + byte[] salt = [.. Enumerable.Repeat((byte)0x11, 32)]; + string placeholder = "<" + new string('0', 2 * 4096) + ">"; + const string rangePlaceholder = "[0 0000000000 0000000000 0000000000]"; + + byte[] file = TestPdf.AppendUpdate( + original, + $"/Size 10 /Root 1 0 R /Encrypt 6 0 R {id} /AuthCode << /MACLocation /AttachedToSig /SigObjRef 9 0 R >>", + (1, 0, "<< /Type /Catalog /Pages 2 0 R /Extensions << /ISO_ [<< /Type /DeveloperExtensions /BaseVersion /2.0 /ExtensionLevel 32004 >>] >> >>"), + (6, 0, encryption[..^2] + $" /KDFSalt <{Convert.ToHexString(salt)}> >>"), + (9, 0, $"<< /Type /Sig /Filter /Adobe.PPKLite /SubFilter /adbe.pkcs7.detached /ByteRange {rangePlaceholder} /Contents {placeholder} >>")); + + string updated = Encoding.Latin1.GetString(file); + int l1 = updated.IndexOf(placeholder, StringComparison.Ordinal); + int s = l1 + placeholder.Length; + string range = string.Create(CultureInfo.InvariantCulture, $"[0 {l1:D10} {s:D10} {file.Length - s:D10}]"); + updated = updated.Replace(rangePlaceholder, range, StringComparison.Ordinal); + file = Encoding.Latin1.GetBytes(updated); + byte[] covered = [.. file.AsSpan(0, l1), .. file.AsSpan(s)]; + + using var rsa = RSA.Create(2048); + var request = new CertificateRequest("CN=Broadside test signer", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + using X509Certificate2 certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); + var signed = new SignedCms(new ContentInfo(covered), detached: true); + signed.ComputeSignature(new CmsSigner(certificate)); + byte[] signatureValue = signed.SignerInfos[0].GetSignature(); + if (tamperSignature) + { + signatureValue[0] ^= 0x01; + } + + byte[] fileKey = SHA256.HashData("broadside-corpus:encrypted-aes-256:file-key:0"u8); + byte[] token = Token(fileKey, salt, SHA256.HashData(covered), SHA256.HashData(signatureValue)); + signed.SignerInfos[0].AddUnsignedAttribute(new AsnEncodedData("1.0.32004.1.2", token)); + string contents = Convert.ToHexString(signed.Encode()).PadRight(2 * 4096, '0'); + Encoding.Latin1.GetBytes(contents).CopyTo(file, l1 + 1); + return file; + } + + /// ISO/TS 32004 §6.3: the AuthenticatedData token, written with the base class library's ASN.1 writer. + private static byte[] Token(byte[] fileKey, byte[] salt, byte[] dataDigest, byte[] signatureDigest) + { + byte[] macKey = [.. Enumerable.Range(1, 32).Select(i => (byte)i)]; + var infoWriter = new AsnWriter(AsnEncodingRules.DER); + using (infoWriter.PushSequence()) + { + infoWriter.WriteInteger(0); + infoWriter.WriteOctetString(dataDigest); + infoWriter.WriteOctetString(signatureDigest, new Asn1Tag(TagClass.ContextSpecific, 0)); + } + + byte[] info = infoWriter.Encode(); + byte[] contentType = Attribute("1.2.840.113549.1.9.3", writer => writer.WriteObjectIdentifier(IntegrityInfoOid)); + byte[] messageDigest = Attribute("1.2.840.113549.1.9.4", writer => writer.WriteOctetString(SHA256.HashData(info))); + + var setWriter = new AsnWriter(AsnEncodingRules.DER); + using (setWriter.PushSetOf()) + { + setWriter.WriteEncodedValue(contentType); + setWriter.WriteEncodedValue(messageDigest); + } + + byte[] attributesAsSet = setWriter.Encode(); + byte[] mac = HMACSHA256.HashData(macKey, attributesAsSet); + byte[] keyEncryptionKey = HKDF.DeriveKey(HashAlgorithmName.SHA256, fileKey, 32, salt, "PDFMAC"u8.ToArray()); + + var writer = new AsnWriter(AsnEncodingRules.DER); + using (writer.PushSequence()) + { + writer.WriteObjectIdentifier("1.2.840.113549.1.9.16.1.2"); + using (writer.PushSequence(new Asn1Tag(TagClass.ContextSpecific, 0, isConstructed: true))) + using (writer.PushSequence()) + { + writer.WriteInteger(0); + using (writer.PushSetOf()) + using (writer.PushSequence(new Asn1Tag(TagClass.ContextSpecific, 3, isConstructed: true))) + { + writer.WriteInteger(0); + using (writer.PushSequence(new Asn1Tag(TagClass.ContextSpecific, 0, isConstructed: true))) + { + writer.WriteObjectIdentifier("1.0.32004.1.1"); + } + + using (writer.PushSequence()) + { + writer.WriteObjectIdentifier("2.16.840.1.101.3.4.1.45"); + } + + writer.WriteOctetString(AesKeyWrap.Wrap(keyEncryptionKey, macKey)); + } + + using (writer.PushSequence()) + { + writer.WriteObjectIdentifier("1.2.840.113549.2.9"); + } + + using (writer.PushSequence(new Asn1Tag(TagClass.ContextSpecific, 1, isConstructed: true))) + { + writer.WriteObjectIdentifier("2.16.840.1.101.3.4.2.1"); + } + + using (writer.PushSequence()) + { + writer.WriteObjectIdentifier(IntegrityInfoOid); + using (writer.PushSequence(new Asn1Tag(TagClass.ContextSpecific, 0, isConstructed: true))) + { + writer.WriteOctetString(info); + } + } + + byte[] implicitAttributes = [.. attributesAsSet]; + implicitAttributes[0] = 0xA2; + writer.WriteEncodedValue(implicitAttributes); + writer.WriteOctetString(mac); + } + } + + return writer.Encode(); + } + + private static byte[] Attribute(string type, Action value) + { + var writer = new AsnWriter(AsnEncodingRules.DER); + using (writer.PushSequence()) + { + writer.WriteObjectIdentifier(type); + using (writer.PushSetOf()) + { + value(writer); + } + } + + return writer.Encode(); + } +} diff --git a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt index 9bdfc25e..745e6669 100644 --- a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt +++ b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt @@ -6,8 +6,16 @@ empty-page.pdf, encrypted-aes-128.pdf, encrypted-aes-256.pdf, + encrypted-aes-gcm.pdf, + encrypted-crypt-filters.pdf, + encrypted-mac-tampered.pdf, + encrypted-mac.pdf, + encrypted-owner-key-variant.pdf, encrypted-rc4-128.pdf, + encrypted-rc4-40-r3.pdf, encrypted-rc4-40.pdf, + encrypted-rc4-user-password.pdf, + encrypted-user-password.pdf, filter-chain.pdf, flate-stream.pdf, hybrid-xref.pdf, diff --git a/tests/Broadside.Tests/Writing/SaveTests.cs b/tests/Broadside.Tests/Writing/SaveTests.cs index e2b923f1..4709e47c 100644 --- a/tests/Broadside.Tests/Writing/SaveTests.cs +++ b/tests/Broadside.Tests/Writing/SaveTests.cs @@ -27,13 +27,13 @@ public static TheoryData FilesAndLayouts } } - /// Every deliberately broken corpus file with every layout. + /// Every unencrypted deliberately broken corpus file with every layout (encrypted files cannot be saved yet). public static TheoryData BrokenFilesAndLayouts { get { var data = new TheoryData(); - foreach (string file in Corpus.MalformedFileNames) + foreach (string file in Corpus.MalformedFileNames.Where(name => !name.StartsWith("encrypted-", StringComparison.Ordinal))) { foreach (PdfCrossReferenceLayout layout in Layouts) { diff --git a/tests/Corpus/README.md b/tests/Corpus/README.md index 9c22c2cf..caa4f3ec 100644 --- a/tests/Corpus/README.md +++ b/tests/Corpus/README.md @@ -22,7 +22,7 @@ qpdf --linearize --deterministic-id --object-streams=generate --compress-streams `--object-streams=disable` keeps classic cross-reference tables (no cross-reference streams); `--object-streams=generate` writes cross-reference streams and one object stream instead. `--compress-streams=n` leaves every stream, the hint stream and the cross-reference streams included, unfiltered. `generate.py` does not write or delete either file. -`generate.py` self-tests its codecs against known answers before writing anything (the LZW example in clause 7.4.4.2, FIPS-197 AES vectors, an RC4 vector). +`generate.py` self-tests its codecs against known answers before writing anything (the LZW example in clause 7.4.4.2, FIPS-197 AES vectors, an RC4 vector, the McGrew-Viega GCM test cases 13 and 14, the RFC 3394 4.6 key wrap vector and the RFC 5869 A.1 HKDF vector). Clause numbers below refer to ISO 32000-2:2020. @@ -53,6 +53,10 @@ Verification was run with qpdf 12.4.2 (`qpdf --check`), poppler (`pdfinfo`, `pdf | `encrypted-rc4-128.pdf` | R3 (`/V 2 /Length 128`, 128-bit RC4). | as above plus 7.6.4.4.4 Algorithm 5 | as above; `pdftotext` prints `RC4 128-bit (R3)` | clean; `R = 3` | | `encrypted-aes-128.pdf` | R4 (`/V 4`, crypt filter `/StdCF` with `/CFM /AESV2`, AES-128-CBC, IV prefixed, PKCS#5 padding, `sAlT` in the object key). | as above plus 7.6.5 Tables 25-27 | as above; `pdftotext` prints `AES-128 (R4)` | clean; `R = 4`, `AESv2` | | `encrypted-aes-256.pdf` | R6 (`/V 5`, `/CFM /AESV3`, AES-256, `/O /U /OE /UE /Perms`), `%PDF-2.0`. | 7.6.3.3 Algorithm 1.A, 7.6.4.3.3-7.6.4.3.4 Algorithms 2.A and 2.B, 7.6.4.4.7-7.6.4.4.9 Algorithms 8-10 | as above; `pdftotext` prints `AES-256 (R6)` | clean; `R = 6`, `AESv3` | +| `encrypted-rc4-40-r3.pdf` | R3 (`/V 2 /Length 40`): a 40-bit key with the revision 3 loops, so Algorithm 3 step c (rehash the whole digest) and Algorithm 2 step h (rehash the first n bytes) differ. `O` follows the letter of Algorithm 3. | 7.6.4.3.2 Algorithm 2, 7.6.4.4.2 Algorithm 3, 7.6.4.4.6 Algorithm 7 | `qpdf --check`, `qpdf --show-encryption`; `pdftotext` prints `RC4 40-bit (R3)` | clean with the empty user password; `qpdf --password=owner` reports `Incorrect password supplied` because qpdf (like PDFBox) rehashes only the first n bytes in Algorithm 3 step c; `encrypted-owner-key-variant.pdf` is the qpdf form | +| `encrypted-crypt-filters.pdf` | R4 (`/V 4`) crypt filters: `/StmF /StdCF` and `/StrF /StdCF` (`AESV2`), `/EncryptMetadata false` (Algorithm 2 step f appends `FF FF FF FF`; the catalog's `/Metadata` stream is plaintext), page `/Contents [4 0 R 7 0 R 10 0 R]`: object 4 by `StmF`, object 7 `/Filter /Crypt` with `/Name /Identity` (plaintext), object 10 `/Filter /Crypt` with `/Name /StdCF`, encrypted with the Algorithm 1 object key (what qpdf reads; 7.4.10 says "the key as is"), and an encrypted `/Info /Title`. | 7.4.10 Table 14, 7.6.2, 7.6.4.3.2 step f, 7.6.6 Tables 25-26 | `qpdf --check`, `qpdf --show-object=7 --filtered-stream-data`, `--show-object=10 ...`, `pdfinfo` | clean; qpdf decodes objects 7 and 10 (`Identity crypt filter`, `StdCF crypt filter`) and reports `AESv2` for streams, strings and files; pdfinfo `Title: Crypt filters`; pdftotext prints `StmF StdCF` and `Identity crypt filter` but not object 10 (poppler reads neither key form for a named crypt filter) | +| `encrypted-aes-gcm.pdf` | ISO/TS 32003: `/V 6 /R 7`, `/CFM /AESV4` (AES-256-GCM: 12-byte IV, ciphertext, 16-byte tag, no AAD), revision 6 password algorithms, catalog `/Extensions << /ISO_ [<< ... /ExtensionLevel 32003 >>] >>` with encrypted strings, encrypted `/Info /Title`. `%PDF-2.0`. | ISO/TS 32003 4, 5.1, 5.2 | `generate.py` self-tests GCM against the McGrew-Viega test cases 13 and 14 | neither qpdf 12.4.2 (`Unsupported /R or /V ... R = 7 (max 6), V = 6 (max 5)`) nor poppler (`Invalid encryption key length. version: 6 - revision: 7`) supports revision 7; verified by Broadside's reader only (no reference implementation exists) | +| `encrypted-mac.pdf` | ISO/TS 32004: R6 with `/KDFSalt`, `/P -4100` (bit 13 clear: a MAC token is required), trailer `/AuthCode << /MACLocation /Standalone /ByteRange [0 L1 S L2] /MAC <...> >>` covering the whole file except the token; the token is a CMS AuthenticatedData (one PasswordRecipientInfo, pdfMacWrapKdf, AES-256 key wrap, HMAC-SHA-256, SHA-256 digests, CMSAlgorithmProtection), catalog `/Extensions` with level 32004. `%PDF-2.0`. | ISO/TS 32004 4, 5.1, 5.2, 6.2-6.6 | `qpdf --check`, `qpdf --show-encryption`; `pdftotext` prints `Integrity MAC (R6)`; `generate.py` self-tests RFC 3394 4.6, RFC 5869 A.1 | clean (qpdf and poppler ignore `/AuthCode`); the MAC is verified by Broadside's reader only | | `inline-image.pdf` | Content stream with a 2x2 8-bit DeviceGray inline image (`BI /W 2 /H 2 /CS /G /BPC 8 ID ... EI`) scaled to 100x100 at (72, 600). | 8.9.7 | `pdftoppm` renders a checkerboard (black top-left and bottom-right) | clean | | `page-tree-inherited.pdf` | Root `/Pages` (2) with one intermediate `/Pages` node (3) that carries `/MediaBox` and `/Resources`; the two leaf pages (4, 5) have neither. | 7.7.3.2, 7.7.3.4 | `pdfinfo` shows 2 Letter pages; `pdftotext` prints `Page 1` and `Page 2` (the font comes from the inherited resources) | clean | | `annotations-link.pdf` | One `/Link` annotation with a `/URI` action in the page's `/Annots`. | 12.5.2, 12.5.6.5, 12.6.4.8 | `qpdf --check`; `qpdf --json --json-key=qpdf` shows the `/Link` dictionary | clean | @@ -73,6 +77,17 @@ Each file is `empty-page.pdf` (or `text-standard14.pdf`) with exactly one defect | `wrong-stream-length.pdf` | The content stream says `/Length 10` but holds 46 bytes of data followed by the end-of-line marker before `endstream` (7.3.8.1: the marker is not part of the data, so qpdf's 47 counts one byte too many); `endstream` is at the correct place. | 7.3.8.2 | qpdf (exit 3): `(object 4 0, offset 284): expected endstream`, `attempting to recover stream length`, `recovered stream length: 47`. pdftotext prints `Length is wrong` and then `Syntax Error (331): Missing 'endstream' or incorrect stream length`. | Recover the length by searching for `endstream` (46 bytes, without the end-of-line marker), record `StreamLengthInvalid` for object 4 at offset 267 (the `stream` keyword); the `/Length` entry is left as stored. `pdftotext`-equivalent output is `Length is wrong`. | | `no-xref.pdf` | No `xref`, `trailer` or `startxref` at all; the objects are followed by `%%EOF`. | 7.5.4, 7.5.5 | qpdf (exit 3): `can't find startxref`, `Attempting to reconstruct cross-reference table`, `unable to find trailer dictionary while recovering damaged file`, then opens the document (it finds the catalog by scanning). pdfinfo and pdftotext fail (exit 1): `Couldn't find trailer dictionary`, `Couldn't read xref table`. | Reconstruct the table by scanning, locate the catalog by scanning for `/Type /Catalog`, record `StartxrefMissing` and `TrailerMissing` (neither has an offset or object); the document opens with one Letter page. | | `startxref-wrong.pdf` | `startxref` points 100 bytes past the real `xref` keyword (into the table body). | 7.5.5 | qpdf (exit 3): `(offset 303): xref not found`, `Attempting to reconstruct cross-reference table`. pdfinfo: clean. | Read the cross-reference section nearest to the stated offset (the `xref` keyword at 203), record `StartxrefInvalid` at offset 303; the document opens with one Letter page. | +| `encrypted-mac-tampered.pdf` | `encrypted-mac.pdf` with one byte of a comment inside the MAC's byte range changed (`original` -> `Original`) after the MAC was computed. | ISO/TS 32004 6.6.2, B.2.2.3 | qpdf and poppler: clean (they do not check the MAC). | Open (the document is intact), record `IntegrityCodeMismatch` (Error, no offset or object): the file's digest does not match the token's `dataDigest`; `PdfSecurity.Integrity` is `Failed`. Strict mode throws it at open. | +| `encrypted-owner-key-variant.pdf` | R3 40-bit RC4 whose `O` entry was computed rehashing only the first n bytes in Algorithm 3 step c (what qpdf and PDFBox write), not the whole digest the clause describes. | 7.6.4.4.2 Algorithm 3 step c | qpdf: clean, and `qpdf --password=owner` accepts the owner password. | Opens with the empty user password with no diagnostic. Opened with the owner password `owner`, record `OwnerPasswordKeyVariant` (Warning) and grant owner access. | + +## Password-protected files + +Well-formed encrypted files with a non-empty user password: they open only with a password, so the theories over the well-formed table leave them out. The owner password is `owner`. + +| File | Feature | User password | Clauses | How to verify | Result | +|---|---|---|---|---|---| +| `encrypted-user-password.pdf` | R6 (`/V 5`, AES-256) with a non-ASCII user password and restricted permissions: `/P -3372` grants printing (bit 3) and copying (bit 5) only. Encrypted `/Info /Title`. `%PDF-2.0`. | `pässwort` (UTF-8; SASLprep leaves it unchanged, and maps its decomposed form to it) | 7.6.4.1, 7.6.4.2 Table 22, 7.6.4.3.3, 7.6.4.4.10-7.6.4.4.12 | `qpdf --password=pässwort --check`, `pdfinfo -upw`, `pdftotext -upw` | clean; pdftotext prints `User password (R6)`; pdfinfo `Title: Protected`, `print:yes copy:yes change:no addNotes:no` | +| `encrypted-rc4-user-password.pdf` | R3 (`/V 2 /Length 128`, RC4) with a user password outside ASCII, in PDFDocEncoding. Encrypted `/Info /Title`. | `café` (PDFDocEncoding `63 61 66 E9`) | 7.6.4.3.2 step a, 7.6.4.4.4-7.6.4.4.6 Algorithms 5-7 | `qpdf --password=owner --show-encryption` | clean; qpdf recovers the user password (`caf` and the byte `E9`) from `O` with the owner password | ## Adding a file diff --git a/tests/Corpus/encrypted-aes-gcm.pdf b/tests/Corpus/encrypted-aes-gcm.pdf new file mode 100644 index 0000000000000000000000000000000000000000..7982b26f46998aa5efba054ff228aee87e903982 GIT binary patch literal 1774 zcmah~J8v9S6s}o`l8Ol3#!W;#_x%tnOMdK%2uHTO!3dcM-N(7k27AVu9b1n7KqwHR zqoJj71Qk-C011##3X~L3Q6VDeQh<j$p4jfOZa7t@sISLtC^+g)Zl;tQR~HoKi6--GZa>6x}yTawRCE)FhFBGv#DT z;B<0|Clh^iT3Hj4_9iIiJ(wIVWh^-ssQ1(?k?PH@b<&qMG0%i|)==uG^M+GFBTpek z2|f#mHU}Oww-CAHRvD!@H{409DNk7?!6O96vQdeFc4*%Ou*wQel~7JZp0gDKSm2Q= z@3>8t0u2Uz3KunJ7|qhsExhsSL7hs*OJbkR{8_@QH^yl~c0|ehEi6ZKSa*cYDVCk* z6-&KZK<8@ zoflsD;_a93Uw!|(D}P*l@%~Gvqeox;bMNV2pMLP(YybXv`taM6{a+XVUi{?A>VuEg z9-KV-xTI=kb(XXe)3e_`jkp>ehHlEqv~u7gb(ty#ktwQZ;0*aogQi|% zyU~bVHU^}RvB`vugWYDMWKkxigR;~pp=CA#9ClL@h9-%=kmoil115Q|txt)SV9|_n z#i?^9DGX9i_u4yb7a z^GY*nFk?DvX)V_(A#!y%CGV(9v!~VJ4N@%+M%!4R<-_jw;Hb1nwbsOq1Hh>?Be38| z;BsND_lM=T7{I^w{N;ioW{x5^$K4)~eiFh055Tj?%rYw}&YF~>)! zxFkcD&&dqM*>MSHoVzSzNZ<=u*ZT1uw9^A*G(G`hu|t}sjI8N=xnAc68|Lf~sbhQh zpu;9Q+gigT#QG3Jat0zKowznao4|x{HklLy*8l$@WwPS<@ohIv8^gr*78V8@!`^?} Cv-frY literal 0 HcmV?d00001 diff --git a/tests/Corpus/encrypted-crypt-filters.pdf b/tests/Corpus/encrypted-crypt-filters.pdf new file mode 100644 index 0000000000000000000000000000000000000000..07823a613b5ef8c8ac37a16b3e56c73876a31101 GIT binary patch literal 2158 zcmb_dO^6&t6xLg4y#)l(m~z63uIyG<|MxgEVgDw(WH*~+#zfo*sqU)Y?QBo?&|Qe-63W4Aa%GUVZiI zdtbdbba=8lLPjlR=;vR)+)xNoQR1CaN+pErt4)sZ1Qj$&77;#77kP#>a5#$a92b0>CTne+(FuYU!n@ z$KZsF25>nffP+>W9R+spj-2dxZg#+jXai!NVGvR%R&!-`SvR#!A{(!RlnK%dR1c7? zAN|xcZ)h*-PFQ{N2I6{ZZnn>f?&kNhE6>vYc9Z(c zTp*7xhH<%Y>-`T4C}icradS?cYfkW`aC$A}wY5Wae{I=!Sz&)gDYc93MzaA`0<{}a zoE6*U0)+y>i!hdET&O6hl(L|Bbh6s@fv<95Nr+|<$=1_l?3zXOJ(%eJ~kk z?yxCPdH&o61OQ>U&lr64Ifvp$iW}^TS)a_r7>z`iXP*U;FMeefh{6*ROtZ<)4q(gYV659Q^V4j&Y1?eN3vF$i&2V?(Incjl+4NtS5==wRz*7iGu`5=|B_j)>0%p1ANX*qJ@(0d8Vye ry5kckFbVZ7lM>B?l5W`n(Lo}2cF8+wCTJ>h(ur-k%Fxi%d{y}m@Q#fi literal 0 HcmV?d00001 diff --git a/tests/Corpus/encrypted-mac-tampered.pdf b/tests/Corpus/encrypted-mac-tampered.pdf new file mode 100644 index 0000000000000000000000000000000000000000..36b2caa2aa80bb580ac4c9b63c9c934cc6807008 GIT binary patch literal 2505 zcmai0J&avP6>cJmhlGM6x(E%3rE}hy{~5HbxWB}Tt+jT8DNGd2ojJ39$@)F(zH7%0 zRisEsmkuFC6evVAG!%59q9=-?q)lQfDmtJ+aOUo2y~{ev)BCwIbAG?`oilIeM%!Nz z&%t8n(ceD&c)=O4&G5=%cb6?+e0UexvI$c--W;*zjc|lpCP?6bExQL3uD7erddrIF z)x-Ul*{#P)E#AlD&0QSN$t~-!#hW-5Ew&_==d4^S@=OWJkxwoDeKc`qu zE-RKgjYy)Wg}RPu73$3cb_+<}aKWq>v%NJ{aN06e9I)j9Za4SFNEI$s>^Ed#e&9^c z0&~pgyce}o?`(Mu*GJQB=AZ~{rxC-Qh5FBLU-a*M_>*7YN5A{k7jOLW+u!=;pML+r z({FwL-G6@XzlZO9{}1CUPrdhz>D@=q{`LK*e){)k9{u1S?{8oJ@h4Y5{mZ)_{JQz< zwe8#3{qWzfUisI1Z~o?&-}!UF>(ulqawV{f0L)=85AO}rOx;3Y&Su`7oIH=m_i&Q!1=xyUHuA%O^xNa3xf>L6{h*R}67j8lrQ;5QRxb|kWD@4w zyFg}c;CP2lqs8>GGVMyp;Z>S^FGo@8Dg0qO+Pop;gn9Fn*KUlR^8!ENk8|d+ui-rcFT4X z_wOQ2xYMSPf|{bdi8^=s@?8wj&v>?Y%(xwPmD=)XTul#Iyp8cyHihvBrysHXados> zhvUVA5%U6=UBKCk8Lg#enVs!%>W%VZ>$5%SF7GKtQ{w;Rv~idAjQ5xJtf%()Qg<4| z>KMoQ+BjUjj?7YPY&K~|I6k~PQM1g;t1Vp?ZU7w|mt~MTr4R=&R3<0gKy%m0 zJ@)k?G{_3{%_iYoo$FO|Z4<*ZUoj`Gdc0ZFEml9A@F1*@aGry6+}!cgtbjORPm-Y% z;m9f(B8E|G09OhO)S_}mIcItcEfB4#$2o{o6S~OCq$~86hh*Z97 zt*Mpjs&dQNs&~5S`$~1TZj98{OVg3JioCfCISB9-8GS+&6tx6O>0-=eg2s*#R)Wwc znb8VlZMCm^ip^JTUyj?Zu6)BOG>Su4yb_IvN=nO}?Ud}h+P1dUt!%xab72JyJze6s z5FcSoLGVl15m2Jwc}bea66bXppkIM5pzD-TZD+fdlIy&! zp>=gza|*ws3RB73Mv~`>YNKdbQ|_iyR58;T-juq6({(RYFGWvepkmoZ5(gb`6`55~ s^WMcJmhlGM6x(E%3rE}hy{~5HbxWB}Tt+jT8DNGd2ojJ39$@)F(zH7%0 zRisEsmkuFC6evVAG!%59q9=-?q)lQfDmtJ+aOUo2y~{ev)BCwIbAG?`oilIeM%!Nz z&%t8n(ceD&c)=O4&G5=%cb6?+e0UexvI$c--W;*zjc|lpCP?6bExQL3uD7erddrIF z)x-Ul*{#P)E#AlD&0QSN$t~-!#hW-5Ew&_==d4^S@=OWJkxwoDeKc`qu zE-RKgjYy)Wg}RPu73$3cb_+<}aKWq>v%NJ{aN06e9I)j9Za4SFNEI$s>^Ed#e&9^c z0&~pgyce}o?`(Mu*GJQB=AZ~{rxC-Qh5FBLU-a*M_>*7YN5A{k7jOLW+u!=;pML+r z({FwL-G6@XzlZO9{}1CUPrdhz>D@=q{`LK*e){)k9{u1S?{8oJ@h4Y5{mZ)_{JQz< zwe8#3{qWzfUisI1Z~o?&-}!UF>(ulqawV{f0L)=85AO}rOx;3Y&Su`7oIH=m_i&Q!1=xyUHuA%O^xNa3xf>L6{h*R}67j8lrQ;5QRxb|kWD@4w zyFg}c;CP2lqs8>GGVMyp;Z>S^FGo@8Dg0qO+Pop;gn9Fn*KUlR^8!ENk8|d+ui-rcFT4X z_wOQ2xYMSPf|{bdi8^=s@?8wj&v>?Y%(xwPmD=)XTul#Iyp8cyHihvBrysG+xH?*` z!|~$5hC_YsXL8f zb&TVDZ5*y%M`o!tHk&fAPOgh}93S4Ds9EOa)s`*`H-HX~%Q8rvQiuZ>DwC6LptIP87ONjlco5b{IM2a3ZtnPLRzMuEC&|!> zaAcJX5yPl8fGY(CYEe0(oHM_pQjEgC6Q<(is$L@M94 z*3?RMRk>ws)jQqveWf~EH%4mfrRm69Mc&+n90d4^j6NX>idq7tbTMW!L1RY=D?#X! z%xDF&w%XS{#pbKFFUM_HSH9sC8pWY2UWvv-C8g!gc1reLZCl&wR<_>Ixv+wUo-T1* zh>tL)AowNh2q;nTyd+IyiSxP)(62z3@~Xs>kszD>lWY>gT+lob&~?hFwzFMJ$#ve= z(7L*ADxHm!c;!P_b+yiGz-}ip(mg sd2i@njqio8ou%sa#kA-t>Q1}1YvwUB->_kv<~hKXwu_yeZogmr559n!-2eap literal 0 HcmV?d00001 diff --git a/tests/Corpus/encrypted-owner-key-variant.pdf b/tests/Corpus/encrypted-owner-key-variant.pdf new file mode 100644 index 0000000000000000000000000000000000000000..aff775c2651e1e9acdaaec5b17d922fe368c1011 GIT binary patch literal 957 zcmaizzi-qq6vtucl8vPx!SI&bDE<-0zQE}uN_!MRY1M;vI2Fl>?KaglsS+P*5gRKj z1OGrL*pL_)7yyY5h=BnKm_Q6HNKA+gJ6H9t?a)lg^XI+q^Y^_p7H2wBTjT>*8#613Za&XouK_u+&ghi+!7f?nwHRad1L zbMMZ6p?#lx8;7r3 zH;KA~#MVB0w+WzWS?S@)obKP(HcKU-**q;&mb)RWWck&+$_@gfLGUqwPS&@&1k|-M zSF%*j9|#Zb$*^-7rWl|FXvI`Z7N;^+X%Zz8F6*D8n?2AVoUujW z_qtv}HMel<+8)6l2eLFte`Skcf70YCR=1AzwVrK&z*CxTboPW1$vEptzW;t{O~CF zP$rMPb{oju{apj(rm|{K_JM4wzNsNVz!r2mo+-2gy6=;OF^;U}x`rNe@Ey!j4hsu( zhUj+YiB6_62p#K?HKTL2Snfg3N4%r~gmKX1D=fll;7$O@mZ{5Om12Re@@|P4nimS9 z0dzVjJ)`bu6LlbWOwqTGfJ+CcZDrIGZ~f)y=f_V+Z{EE+Xj8eaPI{tLY(;GWKSNiDT-_l6WjRe+@(MkRc*#QD`xQ2 z*gRE0mW#C1d4Z-s$cr0AogW9L#>*LjZa%Q40 z!!Qe|(NqM9U|E=$*gs=omiyS^>1p;VlX*Ub-joPZ2qqwd;}}I#-GX8oli0~qF&f|$ zpNa)MoQp9&&*glEYb%uxOx64h+xasCAsSnjZjPIw!>&~OyB1t4a0YKJL9ZRjRHQN0 nv1GAgXe-O`$+Y4uNLfNVa5iLTJcp{XjV+RgUaPgd(e?fV5Ag%Y literal 0 HcmV?d00001 diff --git a/tests/Corpus/encrypted-rc4-user-password.pdf b/tests/Corpus/encrypted-rc4-user-password.pdf new file mode 100644 index 0000000000000000000000000000000000000000..0de8beb1fe6a954053a45ab2f1cc556e2d976fe0 GIT binary patch literal 1026 zcmah|J#W-N5ET>@PD4PVKomo9f+p;)ch_D^)=7lqAOe)=5(v^M#oD{Rb9C6j-pkj2 zK=k|vglG^A9ipM2K;j4R(IN2{*!4vhCqc?q_S-k}X5P$p)|Pq;S82L@U!dO}j%n1PM>$;p&sV&e|-Yac}=7Rul z2;HugZmGMlBXvNJbTKp|V38x#rqc4c_xIhcx!qsU_dl0zT$q1*?fQrNqbpZ$&%fBa z_-yov-hA`<T|Pj4RR z@vb&`DgiAQX{qwU`o5VLcZ)io0mt44ErDJ>Ho5||Ze*ckr2sv(9-=NtOPXMoW+BFbw9-+++X4HP&O8jl zJ63^!bIKuu8Aj|F+=1d43+(t$VZ^tqe+u)NE$I|S|AR4hHebM7`AjAAv96j|wVoep zu!HEArF#&~_O29J39fy+$#%}w!HxkpT>HDS1cO*+T4V{uB;b)wu_DU%LmFa^xuAAX ZUF+0&l&$G<%gQviSxdc6XL+^f{R5&y6c_*i literal 0 HcmV?d00001 diff --git a/tests/Corpus/encrypted-user-password.pdf b/tests/Corpus/encrypted-user-password.pdf new file mode 100644 index 0000000000000000000000000000000000000000..80a261988283f0ee3fe1cd3c63910be455a95c11 GIT binary patch literal 1447 zcmah}O^6&t6b6qYo&=9l9`>TduK%i*VI;dVgGS>HJ247Ng!*~48JX=~dV0fd$XUI6 z5(KYaa`)gtJgDT7g9-_VND@KzC=!Ao`f6sFo$Ma$LwDD!@4c_;dp{ea{_p~Sm3B5B zJiPm3hY?C@|6!-wCB>EF10cngYu&WoBgM$=!HjSO?2uls169nxynfnYfh*pc#2MKY z8Ga3;)Q43|*qUSBIq#Th8bIiRr??Dp;x_9evP%)K87HRX^LSN@uo;n=fD}70s}Gxi z2h1lQ))-;_!-$##dOf6GW6y3&c2c|z)n0p@SegN|wgI=_`Tff~&;NV!?WaFK^Vx&v zZnLjD_y2h9;?*mN^k?7RWf z8_-UIBgLQ!b(~a~miH#r#cDQL8BSB9*9eA_X$uW0#;vQOYa%JGqB6w}(W~ooh5sXR zK?uW1u}!*y2c<0o$BooJQqGx8QUd2vQ)#s^oNFtXPd+eKda9^m#%XOS3ml{_oi z2G1NAP%cFwgYq(Y1SMppUOQa-;LE6m3COZNAYD(RqnB%Cm1dVqVi76AKMU}N!Z?vNZQil@T!K5u8qLmVgB(kzG z?1lW0>eQyOMbFq6$MJN=#wA|hj7=DO&L+({4o3N!t!><73e9}-jVCvOSZt5F&O>WH zVcx7#O|n=xZLryzj^2T6$*!d4yQJbRx literal 0 HcmV?d00001 diff --git a/tests/Corpus/generate.py b/tests/Corpus/generate.py index bc82c8ff..5cfed2df 100644 --- a/tests/Corpus/generate.py +++ b/tests/Corpus/generate.py @@ -16,6 +16,7 @@ from __future__ import annotations import hashlib +import hmac import os import struct import sys @@ -362,21 +363,24 @@ def pad_password(pw: bytes) -> bytes: return (pw + PASSWORD_PAD)[:32] -def legacy_file_key(user_pw: bytes, o_entry: bytes, p: int, id0: bytes, r: int, n: int) -> bytes: +def legacy_file_key(user_pw: bytes, o_entry: bytes, p: int, id0: bytes, r: int, n: int, + encrypt_metadata: bool = True) -> bytes: """7.6.4.3.2 Algorithm 2 (R2..R4); ``n`` is the key length in bytes.""" - h = hashlib.md5(pad_password(user_pw) + o_entry + struct.pack("= 4 and not encrypt_metadata else b"" # step (f) + h = hashlib.md5(pad_password(user_pw) + o_entry + struct.pack("= 3: for _ in range(50): h = hashlib.md5(h[:n]).digest() return h[:n] -def legacy_o_entry(owner_pw: bytes, user_pw: bytes, r: int, n: int) -> bytes: - """7.6.4.4.2 Algorithm 3.""" +def legacy_o_entry(owner_pw: bytes, user_pw: bytes, r: int, n: int, rehash_first_n: bool = False) -> bytes: + """7.6.4.4.2 Algorithm 3. ``rehash_first_n`` rehashes only the first n bytes in step (c), as qpdf + and PDFBox do (the same as the spec for 128-bit keys).""" k = hashlib.md5(pad_password(owner_pw or user_pw)).digest() if r >= 3: for _ in range(50): - k = hashlib.md5(k).digest() + k = hashlib.md5(k[:n] if rehash_first_n else k).digest() k = k[:n] o = rc4(k, pad_password(user_pw)) if r >= 3: @@ -415,6 +419,125 @@ def hash_2b(data: bytes, password: bytes, udata: bytes) -> bytes: return k[:32] +def gcm_encrypt(key: bytes, iv: bytes, data: bytes) -> tuple[bytes, bytes]: + """NIST SP 800-38D AES-GCM with a 96-bit IV and no AAD (ISO/TS 32003 5.2); returns (ciphertext, tag).""" + rk = _aes_round_keys(key) + h = int.from_bytes(aes_encrypt_block(rk, bytes(16)), "big") + out = bytearray() + for i in range(0, len(data), 16): + ks = aes_encrypt_block(rk, iv + (i // 16 + 2).to_bytes(4, "big")) + out += bytes(a ^ b for a, b in zip(data[i:i + 16], ks)) + + def mul(x: int, y: int) -> int: # GF(2^128), SP 800-38D 6.3 Algorithm 1 + z, v = 0, y + for bit in range(128): + if (x >> (127 - bit)) & 1: + z ^= v + v = (v >> 1) ^ (0xE1 << 120) if v & 1 else v >> 1 + return z + + y = 0 + for i in range(0, len(out), 16): + y = mul(y ^ int.from_bytes(bytes(out[i:i + 16]).ljust(16, b"\0"), "big"), h) + y = mul(y ^ (len(out) * 8), h) # len(A) = 0 in the high 64 bits + tag = y ^ int.from_bytes(aes_encrypt_block(rk, iv + b"\0\0\0\1"), "big") + return bytes(out), tag.to_bytes(16, "big") + + +def aes_key_wrap(kek: bytes, key: bytes) -> bytes: + """RFC 3394 2.2.1 key wrap (index-based), the key wrapping ISO/TS 32004 Table 7 uses.""" + rk = _aes_round_keys(kek) + n = len(key) // 8 + a = bytes.fromhex("A6A6A6A6A6A6A6A6") + r = [key[8 * i:8 * i + 8] for i in range(n)] + for j in range(6): + for i in range(n): + b = aes_encrypt_block(rk, a + r[i]) + a = (int.from_bytes(b[:8], "big") ^ (n * j + i + 1)).to_bytes(8, "big") + r[i] = b[8:] + return a + b"".join(r) + + +def hkdf_sha256(ikm: bytes, salt: bytes, info: bytes, length: int) -> bytes: + """RFC 5869 HKDF with SHA-256 (ISO/TS 32004 6.4 pdfMacWrapKdf).""" + prk = hmac.new(salt, ikm, hashlib.sha256).digest() + okm, t, i = b"", b"", 1 + while len(okm) < length: + t = hmac.new(prk, t + info + bytes([i]), hashlib.sha256).digest() + okm += t + i += 1 + return okm[:length] + + +def der(tag: int, content: bytes) -> bytes: + """ITU-T X.690 DER tag-length-value.""" + n = len(content) + if n < 0x80: + return bytes([tag, n]) + content + length = n.to_bytes((n.bit_length() + 7) // 8, "big") + return bytes([tag, 0x80 | len(length)]) + length + content + + +def der_oid(dotted: str) -> bytes: + arcs = [int(x) for x in dotted.split(".")] + body = bytearray([40 * arcs[0] + arcs[1]]) + for arc in arcs[2:]: + chunk = [arc & 0x7F] + arc >>= 7 + while arc: + chunk.append(0x80 | (arc & 0x7F)) + arc >>= 7 + body += bytes(reversed(chunk)) + return der(0x06, bytes(body)) + + +def der_seq(*items: bytes) -> bytes: + return der(0x30, b"".join(items)) + + +def der_set(*items: bytes) -> bytes: + return der(0x31, b"".join(sorted(items))) # DER: SET OF sorted by encoding + + +OID_AUTH_DATA = "1.2.840.113549.1.9.16.1.2" +OID_PDF_MAC_INTEGRITY_INFO = "1.0.32004.1.0" +OID_PDF_MAC_WRAP_KDF = "1.0.32004.1.1" +OID_AES256_WRAP = "2.16.840.1.101.3.4.1.45" +OID_HMAC_SHA256 = "1.2.840.113549.2.9" +OID_SHA256 = "2.16.840.1.101.3.4.2.1" +OID_CONTENT_TYPE = "1.2.840.113549.1.9.3" +OID_MESSAGE_DIGEST = "1.2.840.113549.1.9.4" +OID_CMS_ALGORITHM_PROTECTION = "1.2.840.113549.1.9.52" + + +def pdf_mac_token(file_key: bytes, kdf_salt: bytes, mac_key: bytes, data_digest: bytes) -> bytes: + """ISO/TS 32004 6.2-6.4: a CMS AuthenticatedData (RFC 5652 9) over PdfMacIntegrityInfo, one + PasswordRecipientInfo with pdfMacWrapKdf and AES-256 key wrap, HMAC-SHA-256, SHA-256 digests.""" + sha256_alg = der_seq(der_oid(OID_SHA256)) + hmac_alg = der_seq(der_oid(OID_HMAC_SHA256)) + info = der_seq(der(0x02, b"\0"), der(0x04, data_digest)) # version 0, dataDigest + encap = der_seq(der_oid(OID_PDF_MAC_INTEGRITY_INFO), der(0xA0, der(0x04, info))) + attrs = sorted([ + der_seq(der_oid(OID_CONTENT_TYPE), der_set(der_oid(OID_PDF_MAC_INTEGRITY_INFO))), + der_seq(der_oid(OID_MESSAGE_DIGEST), der_set(der(0x04, hashlib.sha256(info).digest()))), + der_seq(der_oid(OID_CMS_ALGORITHM_PROTECTION), + der_set(der_seq(sha256_alg, der(0xA2, der_oid(OID_HMAC_SHA256))))), # RFC 6211, macAlgorithm [2] + ]) + mac = hmac.new(mac_key, der(0x31, b"".join(attrs)), hashlib.sha256).digest() # RFC 5652 9.2 + kek = hkdf_sha256(file_key, kdf_salt, b"PDFMAC", 32) + pwri = der(0xA3, der(0x02, b"\0") + der(0xA0, der_oid(OID_PDF_MAC_WRAP_KDF)) + + der_seq(der_oid(OID_AES256_WRAP)) + der(0x04, aes_key_wrap(kek, mac_key))) + auth_data = der_seq( + der(0x02, b"\0"), # version 0 + der_set(pwri), # recipientInfos + hmac_alg, # macAlgorithm + der(0xA1, der_oid(OID_SHA256)), # digestAlgorithm [1] + encap, # encapContentInfo + der(0xA2, b"".join(attrs)), # authAttrs [2] + der(0x04, mac)) # mac + return der_seq(der_oid(OID_AUTH_DATA), der(0xA0, auth_data)) + + # --------------------------------------------------------------------------- # Minimal TrueType font program (OpenType spec; PDF clause 9.6.3 / 9.9) # --------------------------------------------------------------------------- @@ -690,6 +813,8 @@ def gen_png_predictor() -> bytes: PERMISSIONS = -4 # all permission bits set, reserved bits 1-2 clear (Table 22) OWNER_PASSWORD = b"owner" USER_PASSWORD = b"" +USER_PASSWORD_R6 = "p\u00e4sswort".encode("utf-8") # SASLprep leaves it unchanged (NFKC, nothing to map) +USER_PASSWORD_LEGACY = b"caf\xe9" # "cafe" with e-acute, PDFDocEncoding def encrypted_file(name: str, version: str, label: bytes, encrypt_dict, encrypt_stream) -> bytes: @@ -705,10 +830,10 @@ def encrypted_file(name: str, version: str, label: bytes, encrypt_dict, encrypt_ return f.finish_classic(b"<< /Size 7 /Root 1 0 R /Encrypt 6 0 R /ID [<%s> <%s>] >>" % ((id0.hex().encode(),) * 2)) -def gen_encrypted_legacy(name: str, r: int, label: bytes) -> bytes: +def gen_encrypted_legacy(name: str, r: int, label: bytes, n: int | None = None, rehash_first_n: bool = False) -> bytes: id0 = file_id(name) - n = 5 if r == 2 else 16 - o = legacy_o_entry(OWNER_PASSWORD, USER_PASSWORD, r, n) + n = n or (5 if r == 2 else 16) + o = legacy_o_entry(OWNER_PASSWORD, USER_PASSWORD, r, n, rehash_first_n) key = legacy_file_key(USER_PASSWORD, o, PERMISSIONS, id0, r, n) u = legacy_u_entry(key, id0, r) aes = r == 4 @@ -759,6 +884,185 @@ def encrypt(num: int, gen: int, data: bytes) -> bytes: # Algorithm 1.A return encrypted_file(name, "2.0", b"AES-256 (R6)", enc, encrypt) +def r6_entries(name: str, key: bytes, user_pw: bytes, owner_pw: bytes, p: int, + encrypt_metadata: bool = True) -> bytes: + """7.6.4.4.7-7.6.4.4.9 Algorithms 8-10: the /O /U /OE /UE /Perms entries of revisions 6 and 7.""" + uvs, uks = fixed_bytes(name + ":user-salts", 16)[:8], fixed_bytes(name + ":user-salts", 16)[8:] + ovs, oks = fixed_bytes(name + ":owner-salts", 16)[:8], fixed_bytes(name + ":owner-salts", 16)[8:] + u = hash_2b(user_pw + uvs, user_pw, b"") + uvs + uks + ue = aes_cbc_encrypt(hash_2b(user_pw + uks, user_pw, b""), bytes(16), key, pad=False) + o = hash_2b(owner_pw + ovs + u, owner_pw, u) + ovs + oks + oe = aes_cbc_encrypt(hash_2b(owner_pw + oks + u, owner_pw, u), bytes(16), key, pad=False) + perms_block = struct.pack(" /U <%s> /OE <%s> /UE <%s> /Perms <%s>" % ( + p, o.hex().encode(), u.hex().encode(), oe.hex().encode(), ue.hex().encode(), perms.hex().encode()) + + +def aes256_encryptor(name: str, key: bytes): + """7.6.3.3 Algorithm 1.A; ``label`` keeps every IV of the file distinct.""" + def encrypt(num: int, label: str, data: bytes) -> bytes: + iv = fixed_bytes("%s:iv:%d:%s" % (name, num, label), 16) + return iv + aes_cbc_encrypt(key, iv, data, pad=True) + return encrypt + + +def hex_string(data: bytes) -> bytes: + return b"<" + data.hex().encode() + b">" + + +def extensions(level: int, revision: bytes, url: bytes, encrypt, num: int = 1) -> bytes: + """7.12 developer extensions dictionary under the ISO_ prefix; its strings are encrypted (ISO/TS 32004 4 NOTE).""" + return (b" /Extensions << /ISO_ [<< /Type /DeveloperExtensions /BaseVersion /2.0 /ExtensionLevel %d" + b" /ExtensionRevision %s /URL %s >>] >>" % ( + level, hex_string(encrypt(num, "rev", revision)), hex_string(encrypt(num, "url", url)))) + + +def gen_encrypted_aes_gcm(name: str = "encrypted-aes-gcm") -> bytes: + """ISO/TS 32003: V 6, R 7, crypt filter /StdCF with /CFM /AESV4 (AES-256-GCM: 12-byte IV, ciphertext, + 16-byte tag, no AAD), the revision 6 password algorithms, the 32003 extension declared in the catalog, + and an encrypted Info string.""" + key = fixed_bytes(name + ":file-key", 32) + + def encrypt(num: int, label: str, data: bytes) -> bytes: + iv = fixed_bytes("%s:iv:%d:%s" % (name, num, label), 12) # never reused under the one key + ciphertext, tag = gcm_encrypt(key, iv, data) + return iv + ciphertext + tag + + enc = (b"<< /Filter /Standard /V 6 /R 7 /Length 256 " + r6_entries(name, key, USER_PASSWORD, OWNER_PASSWORD, PERMISSIONS) + + b" /CF << /StdCF << /CFM /AESV4 /AuthEvent /DocOpen /Length 32 >> >> /StmF /StdCF /StrF /StdCF >>") + id0 = file_id(name) + f = File("2.0", binary=True) + f.add(1, catalog(extensions(32003, b":2023", b"https://www.iso.org/standard/45876.html", encrypt))) + f.add(2, pages()) + f.add(3, page(contents=4, font=5)) + f.add(4, stream(b"", encrypt(4, "stream", text_content(b"AES-256-GCM (R7)")))) + f.add(5, HELVETICA) + f.add(6, enc) + f.add(7, b"<< /Title %s >>" % hex_string(encrypt(7, "title", b"AES-GCM"))) + return f.finish_classic(b"<< /Size 8 /Root 1 0 R /Info 7 0 R /Encrypt 6 0 R /ID [<%s> <%s>] >>" % ((id0.hex().encode(),) * 2)) + + +def gen_encrypted_user_password(name: str = "encrypted-user-password") -> bytes: + """R6 (V 5, AES-256) with a non-ASCII user password, prepared with SASLprep and UTF-8 (7.6.4.1), and + restricted user permissions: P -3372 grants printing (bit 3) and copying (bit 5) only (Table 22).""" + key = fixed_bytes(name + ":file-key", 32) + encrypt = aes256_encryptor(name, key) + enc = (b"<< /Filter /Standard /V 5 /R 6 /Length 256 " + r6_entries(name, key, USER_PASSWORD_R6, OWNER_PASSWORD, -3372) + + b" /CF << /StdCF << /CFM /AESV3 /AuthEvent /DocOpen /Length 32 >> >> /StmF /StdCF /StrF /StdCF >>") + id0 = file_id(name) + f = File("2.0", binary=True) + f.add(1, catalog()) + f.add(2, pages()) + f.add(3, page(contents=4, font=5)) + f.add(4, stream(b"", encrypt(4, "stream", text_content(b"User password (R6)")))) + f.add(5, HELVETICA) + f.add(6, enc) + f.add(7, b"<< /Title %s >>" % hex_string(encrypt(7, "title", b"Protected"))) + return f.finish_classic(b"<< /Size 8 /Root 1 0 R /Info 7 0 R /Encrypt 6 0 R /ID [<%s> <%s>] >>" % ((id0.hex().encode(),) * 2)) + + +def gen_encrypted_rc4_user_password(name: str = "encrypted-rc4-user-password") -> bytes: + """R3 (V 2, 128-bit RC4) with the user password ``caf\xe9`` in PDFDocEncoding (7.6.4.3.2 step a) and an + encrypted Info string: Algorithms 2, 5, 6 and 7 with a non-empty user password.""" + id0 = file_id(name) + n = 16 + o = legacy_o_entry(OWNER_PASSWORD, USER_PASSWORD_LEGACY, 3, n) + key = legacy_file_key(USER_PASSWORD_LEGACY, o, PERMISSIONS, id0, 3, n) + u = legacy_u_entry(key, id0, 3) + f = File("1.4", binary=True) + f.add(1, catalog()) + f.add(2, pages()) + f.add(3, page(contents=4, font=5)) + f.add(4, stream(b"", rc4(object_key(key, 4, 0, False), text_content(b"User password (R3)")))) + f.add(5, HELVETICA) + f.add(6, b"<< /Filter /Standard /V 2 /R 3 /Length 128 /P %d /O <%s> /U <%s> >>" % ( + PERMISSIONS, o.hex().encode(), u.hex().encode())) + f.add(7, b"<< /Title %s >>" % hex_string(rc4(object_key(key, 7, 0, False), b"Protected"))) + return f.finish_classic(b"<< /Size 8 /Root 1 0 R /Info 7 0 R /Encrypt 6 0 R /ID [<%s> <%s>] >>" % ((id0.hex().encode(),) * 2)) + + +def gen_encrypted_crypt_filters(name: str = "encrypted-crypt-filters") -> bytes: + """R4 (V 4) crypt filters (7.6.6, 7.4.10): StmF and StrF /StdCF (AESV2), /EncryptMetadata false (the + metadata stream is plaintext and Algorithm 2 step f appends FF FF FF FF), a content stream with + /Filter /Crypt /Name /Identity left unencrypted, one with /Name /StdCF (Algorithm 1 object key, as + qpdf and poppler read it), and an encrypted Info string.""" + id0 = file_id(name) + n = 16 + o = legacy_o_entry(OWNER_PASSWORD, USER_PASSWORD, 4, n) + key = legacy_file_key(USER_PASSWORD, o, PERMISSIONS, id0, 4, n, encrypt_metadata=False) + u = legacy_u_entry(key, id0, 4) + + def encrypt(num: int, label: str, data: bytes) -> bytes: + iv = fixed_bytes("%s:iv:%d:%s" % (name, num, label), 16) + return iv + aes_cbc_encrypt(object_key(key, num, 0, True), iv, data, pad=True) + + def text(y: int, label: bytes) -> bytes: + return b"BT /F1 24 Tf 72 %d Td (%s) Tj ET" % (y, label) + + f = File("1.6", binary=True) + f.add(1, catalog(b" /Metadata 8 0 R")) + f.add(2, pages()) + f.add(3, page(contents=None, font=5, extra=b" /Contents [4 0 R 7 0 R 10 0 R]")) + f.add(4, stream(b"", encrypt(4, "stream", text(700, b"StmF StdCF")))) + f.add(5, HELVETICA) + f.add(6, b"<< /Filter /Standard /V 4 /R 4 /Length 128 /P %d /O <%s> /U <%s> /EncryptMetadata false" + b" /CF << /StdCF << /CFM /AESV2 /AuthEvent /DocOpen /Length 16 >> >> /StmF /StdCF /StrF /StdCF >>" % ( + PERMISSIONS, o.hex().encode(), u.hex().encode())) + f.add(7, stream(b"/Filter /Crypt /DecodeParms << /Type /CryptFilterDecodeParms /Name /Identity >>", text(660, b"Identity crypt filter"))) + f.add(8, stream(b"/Type /Metadata /Subtype /XML", XMP)) + f.add(9, b"<< /Title %s >>" % hex_string(encrypt(9, "title", b"Crypt filters"))) + f.add(10, stream(b"/Filter /Crypt /DecodeParms << /Type /CryptFilterDecodeParms /Name /StdCF >>", encrypt(10, "stream", text(620, b"StdCF crypt filter")))) + return f.finish_classic(b"<< /Size 11 /Root 1 0 R /Info 9 0 R /Encrypt 6 0 R /ID [<%s> <%s>] >>" % ((id0.hex().encode(),) * 2)) + + +MAC_TAMPER_TARGET = b"% Integrity check target: original\n" + + +def gen_encrypted_mac(name: str = "encrypted-mac") -> bytes: + """ISO/TS 32004: R6 (V 5) with /KDFSalt, P -4100 (bit 13 clear: a MAC token is required) and a + standalone PDF MAC token in the trailer's /AuthCode, its /ByteRange covering the whole file except + the token, the 32004 extension declared in the catalog.""" + key = fixed_bytes(name + ":file-key", 32) + kdf_salt = fixed_bytes(name + ":kdf-salt", 32) + mac_key = fixed_bytes(name + ":mac-key", 32) + encrypt = aes256_encryptor(name, key) + p = -4100 + enc = (b"<< /Filter /Standard /V 5 /R 6 /Length 256 " + r6_entries(name, key, USER_PASSWORD, OWNER_PASSWORD, p) + + b" /KDFSalt <%s> /CF << /StdCF << /CFM /AESV3 /AuthEvent /DocOpen /Length 32 >> >>" + b" /StmF /StdCF /StrF /StdCF >>" % kdf_salt.hex().encode()) + id0 = file_id(name) + f = File("2.0", binary=True) + f.add(1, catalog(extensions(32004, b":2024", b"https://www.iso.org/standard/45877.html", encrypt))) + f.add(2, pages()) + f.add(3, page(contents=4, font=5)) + f.add(4, stream(b"", encrypt(4, "stream", text_content(b"Integrity MAC (R6)")))) + f.add(5, HELVETICA) + f.add(6, enc) + f.raw(MAC_TAMPER_TARGET) + token_length = len(pdf_mac_token(key, kdf_salt, mac_key, bytes(32))) + placeholder = b"<" + b"0" * (2 * token_length) + b">" + range_placeholder = b"[0 0000000000 0000000000 0000000000]" + data = bytearray(f.finish_classic( + b"<< /Size 7 /Root 1 0 R /Encrypt 6 0 R /ID [<%s> <%s>] /AuthCode << /MACLocation /Standalone" + b" /ByteRange %s /MAC %s >> >>" % (id0.hex().encode(), id0.hex().encode(), range_placeholder, placeholder))) + l1 = data.index(placeholder) + start = l1 + len(placeholder) + byte_range = b"[0 %010d %010d %010d]" % (l1, start, len(data) - start) + r = data.index(range_placeholder) + data[r:r + len(range_placeholder)] = byte_range + digest = hashlib.sha256(bytes(data[:l1]) + bytes(data[start:])).digest() + token = pdf_mac_token(key, kdf_salt, mac_key, digest) + data[l1:start] = b"<" + token.hex().upper().encode() + b">" + return bytes(data) + + +def gen_encrypted_mac_tampered() -> bytes: + """encrypted-mac.pdf with one byte of a comment changed after the MAC was computed.""" + data = gen_encrypted_mac() + return data.replace(MAC_TAMPER_TARGET, MAC_TAMPER_TARGET.replace(b"original", b"Original"), 1) + + def gen_broken_xref_offsets() -> bytes: f = File() f.add(1, catalog()) @@ -895,6 +1199,15 @@ def gen_metadata_xmp() -> bytes: "encrypted-rc4-128.pdf": lambda: gen_encrypted_legacy("encrypted-rc4-128", 3, b"RC4 128-bit (R3)"), "encrypted-aes-128.pdf": lambda: gen_encrypted_legacy("encrypted-aes-128", 4, b"AES-128 (R4)"), "encrypted-aes-256.pdf": gen_encrypted_aes_256, + "encrypted-rc4-40-r3.pdf": lambda: gen_encrypted_legacy("encrypted-rc4-40-r3", 3, b"RC4 40-bit (R3)", n=5), + "encrypted-crypt-filters.pdf": gen_encrypted_crypt_filters, + "encrypted-aes-gcm.pdf": gen_encrypted_aes_gcm, + "encrypted-mac.pdf": gen_encrypted_mac, + "encrypted-user-password.pdf": gen_encrypted_user_password, + "encrypted-rc4-user-password.pdf": gen_encrypted_rc4_user_password, + "encrypted-mac-tampered.pdf": gen_encrypted_mac_tampered, + "encrypted-owner-key-variant.pdf": lambda: gen_encrypted_legacy( + "encrypted-owner-key-variant", 3, b"RC4 40-bit (R3), qpdf owner key", n=5, rehash_first_n=True), "broken-xref-offsets.pdf": gen_broken_xref_offsets, "missing-endobj.pdf": gen_missing_endobj, "wrong-stream-length.pdf": gen_wrong_stream_length, @@ -924,6 +1237,17 @@ def self_test() -> None: assert aes_ecb_encrypt_block(k256, pt) == bytes.fromhex("8ea2b7ca516745bfeafc49904b496089") # RC4 known answer (key "Key", plaintext "Plaintext") assert rc4(b"Key", b"Plaintext") == bytes.fromhex("BBF316E8D940AF0AD3") + # GCM: the McGrew-Viega test cases 13 and 14 (AES-256, 96-bit zero IV, no AAD) + assert gcm_encrypt(bytes(32), bytes(12), b"") == (b"", bytes.fromhex("530f8afbc74536b9a963b4f1c4cb738b")) + assert gcm_encrypt(bytes(32), bytes(12), bytes(16)) == ( + bytes.fromhex("cea7403d4d606b6e074ec5d3baf39d18"), bytes.fromhex("d0d1c8a799996bf0265b98b5d48ab919")) + # RFC 3394 4.6: wrap 256 bits of key data with a 256-bit KEK + assert aes_key_wrap(bytes(range(32)), bytes.fromhex( + "00112233445566778899AABBCCDDEEFF000102030405060708090A0B0C0D0E0F")) == bytes.fromhex( + "28C9F404C4B810F4CBCCB35CFB87F8263F5786E2D80ED326CBC7F0E71A99F43BFB988B9B7A02DD21") + # RFC 5869 A.1 + assert hkdf_sha256(b"\x0b" * 22, bytes(range(13)), bytes(range(0xF0, 0xFA)), 42) == bytes.fromhex( + "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865") def main(argv: list[str]) -> int: diff --git a/tests/README.md b/tests/README.md index 19e0bbac..0ac0c0cd 100644 --- a/tests/README.md +++ b/tests/README.md @@ -44,7 +44,7 @@ string path = Corpus.Path("outline.pdf"); public void Opens(string fileName) { ... } ``` -`Corpus.WellFormedFiles`, `Corpus.MalformedFiles` and `Corpus.AllFiles` are `TheoryData` over the two tables in the corpus README; `WellFormedFileNames`, `MalformedFileNames` and `AllFileNames` are the same lists as `IReadOnlyList`. The lists are hard-coded and `CorpusSmokeTests.File_lists_match_the_corpus_directory` fails if they drift from the directory, so adding a corpus file means adding it to `Corpus.cs` and to the README table. +`Corpus.WellFormedFiles`, `Corpus.MalformedFiles` and `Corpus.AllFiles` are `TheoryData` over the well-formed and broken tables in the corpus README (`Corpus.PasswordProtectedFiles` is `TheoryData` of file name and user password over its password-protected table); `WellFormedFileNames`, `MalformedFileNames` and `AllFileNames` are the same lists as `IReadOnlyList`. The lists are hard-coded and `CorpusSmokeTests.File_lists_match_the_corpus_directory` fails if they drift from the directory, so adding a corpus file means adding it to `Corpus.cs` and to the README table. The real-world corpora in `corpus/` (gitignored, fetched by `tools/CorpusFetcher`) will get a similar helper when that tool lands. From 8f8e4acabc6fa2f4239bd06e152a07f9744daca7 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 15:29:57 -0500 Subject: [PATCH 015/152] feat(security): public-key security handler, adbe.pkcs7.s3/s4/s5 (#43) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Documents encrypted for certificate recipients (ISO 32000-2 §7.6.5) open with a certificate and its private key. - PublicKeySecurityHandler, registered by default (Filter Adobe.PubSec and any Filter with SubFilter adbe.pkcs7.s3/s4/s5): scans the recipient lists (CMS EnvelopedData via System.Security.Cryptography.Pkcs) for one of the reader's certificates by issuer/serial or subject key identifier; the first matching list wins; seed + permissions (most significant byte first); key = SHA-1 (<= 128 bits) or SHA-256 (256 bits) of the seed, every Recipients string and 0xFF x 4 when metadata is plaintext. - Recipients from the Encrypt dictionary (s3/s4) or the crypt filter StmF/StrF names (s5); crypt filters with their own recipients get their own keys through SecurityHandlerResult.CryptFilterKeys; one that does not name the reader gets an empty key and its streams stay encrypted. - Permissions: s3 with revision 2 meanings, s4/s5 revision 3; bit 2 gives owner access and every permission. - PdfCertificateCredentials, PdfCertificateException (+ PdfCertificateFailure Required / NoMatchingRecipient / PrivateKeyUnavailable, Recipients). - DocumentDecryptor reads EncryptMetadata from the StmF crypt filter when the Encrypt dictionary has none (Table 27); a handler without a revision and no V gets V 2 below 256-bit keys. - Diagnostics PublicKeyRecipientInvalid, PublicKeyEnvelopeInvalid, CryptFilterNotAuthorized. - Tests build every file in memory with EnvelopedCms; fuzz target public-key; conformance rows 7.6.5.1-7.6.5.3. Co-Authored-By: Claude Opus 5.5 --- docs/conformance/iso-32000-2.md | 6 +- src/Broadside/Parsing/DiagnosticCodes.cs | 3 + src/Broadside/PdfAccessLevel.cs | 6 +- src/Broadside/PdfEngine.cs | 9 +- src/Broadside/PublicAPI.Unshipped.txt | 21 + src/Broadside/Security/DocumentDecryptor.cs | 17 +- src/Broadside/Security/DocumentSecurity.cs | 14 +- src/Broadside/Security/ISecurityHandler.cs | 6 +- .../Security/PdfCertificateCredentials.cs | 48 ++ .../Security/PdfCertificateException.cs | 108 ++++ .../Security/PublicKeySecurityHandler.cs | 512 ++++++++++++++++++ .../Security/SecurityHandlerRegistry.cs | 8 +- tests/Broadside.Fuzz/FuzzTargets.cs | 13 + tests/Broadside.Fuzz/PublicKey.cs | 181 +++++++ tests/Broadside.Fuzz/README.md | 2 +- .../Security/PublicKeySecurityTests.cs | 350 ++++++++++++ .../Security/PublicKeyTestFile.cs | 210 +++++++ 17 files changed, 1499 insertions(+), 15 deletions(-) create mode 100644 src/Broadside/Security/PdfCertificateCredentials.cs create mode 100644 src/Broadside/Security/PdfCertificateException.cs create mode 100644 src/Broadside/Security/PublicKeySecurityHandler.cs create mode 100644 tests/Broadside.Fuzz/PublicKey.cs create mode 100644 tests/Broadside.Tests/Security/PublicKeySecurityTests.cs create mode 100644 tests/Broadside.Tests/Security/PublicKeyTestFile.cs diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index ca8d4f85..7358644e 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -38,10 +38,12 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.5.7 | Object streams | done | `ObjectStream`, `ObjectLoader`, `FileWriter` | `Broadside.Tests.Document.ObjectStreamTests.The_catalog_page_tree_and_page_resolve_from_an_object_stream`, `Broadside.Tests.Document.ObjectStreamTests.A_reference_to_a_member_with_a_generation_other_than_0_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.Members_need_no_white_space_between_them`, `Broadside.Tests.Document.ObjectStreamTests.A_member_at_another_index_than_its_entry_says_is_found_by_its_object_number`, `Broadside.Tests.Document.ObjectStreamTests.Offsets_out_of_order_bound_each_member_by_the_next_offset_in_sorted_order`, `Broadside.Tests.Document.ObjectStreamTests.A_member_the_object_stream_does_not_hold_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_whose_N_is_one_of_its_own_members_resolves_its_members_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_listed_as_compressed_itself_is_not_read`, `Broadside.Tests.Document.ObjectStreamTests.A_type_2_entry_naming_an_object_that_is_not_a_stream_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.A_flate_encoded_object_stream_is_decoded_through_the_filters`, `Broadside.Tests.Document.ObjectStreamTests.Members_of_one_object_stream_resolve_to_the_same_instances_from_concurrent_threads`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file`, `Broadside.Tests.Document.RepairTests.Objects_in_object_streams_survive_a_damaged_cross_reference_stream`, `Broadside.Tests.Writing.SaveTests.Objects_that_were_not_changed_keep_their_source_bytes_in_any_layout`, `Broadside.Tests.Writing.SaveTests.The_information_dictionary_of_a_hybrid_file_survives_from_its_object_stream` | Members located by type 2 entries (index checked against the header, searched by number when wrong, with ObjectStreamIndexMismatch); each member parsed over exactly the bytes up to the next offset (NOTE 7); out-of-order offsets sorted; container decoded once per document and shared, decrypted as a whole (members skip hooks 1 and 2); nested containers and self-referencing N/First/Filter end with ObjectStreamNested/ObjectStreamCycle; /Extends ignored (grouping only); object-stream.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `object-stream`; written by `PdfCrossReferenceLayout.StreamWithObjectStreams`: every object with generation 0 that is not a stream or a bare reference, at most 100 per Flate-encoded object stream; unchanged members keep their bytes (#44); a rebuilt cross-reference indexes the members of every object stream found by scanning (#41) | | 7.5.8 | Cross-reference streams | done | `XrefStreamReader`, `CrossReferenceReader`, `CrossReference`, `FileWriter`, `PdfCrossReferenceLayout` | `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file`, `Broadside.Tests.Document.CrossReferenceStreamTests.Strict_mode_opens_a_file_with_compressed_structures`, `Broadside.Tests.Document.CrossReferenceStreamTests.The_trailer_of_a_cross_reference_stream_is_its_dictionary_without_the_entries_that_describe_the_stream`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_type_field_makes_every_entry_type_1`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_generation_field_defaults_to_generation_0`, `Broadside.Tests.Document.CrossReferenceStreamTests.Index_with_two_subsections_numbers_the_entries_of_each_from_its_first_object_number`, `Broadside.Tests.Document.CrossReferenceStreamTests.Wide_fields_are_read_big_endian`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_entry_of_an_unknown_type_is_a_reference_to_the_null_object`, `Broadside.Tests.Document.CrossReferenceStreamTests.Data_shorter_than_the_entries_ends_the_section_where_the_data_ends`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_without_type_XRef_is_read_with_a_diagnostic`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_whose_W_cannot_be_read_is_not_a_cross_reference_section_so_the_file_is_rebuilt_by_scanning`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_update_written_as_a_cross_reference_stream_overrides_the_original_section`, `Broadside.Tests.Document.HybridFileTests.An_object_only_the_XRefStm_stream_lists_is_found`, `Broadside.Tests.Document.HybridFileTests.An_in_use_entry_in_the_table_of_a_section_takes_precedence_over_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.A_free_entry_in_the_table_of_a_section_gives_way_to_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.The_XRefStm_streams_dictionary_is_not_the_trailer_and_its_Prev_is_not_followed`, `Broadside.Tests.Document.HybridFileTests.An_XRefStm_offset_that_names_no_stream_is_reported_and_the_table_is_still_read`, `Broadside.Tests.Document.LinearizationTests.A_linearized_file_with_cross_reference_streams_has_its_first_page_and_main_streams_as_one_revision`, `Broadside.Tests.Writing.SaveTests.Startxref_gives_the_offset_of_the_cross_reference_information`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_passes_qpdf_check` | 7.5.8.1 to 7.5.8.4. W (0 to 8 bytes per field, W[0] = 0 means type 1), Index (default [0 Size]), Size, Prev; entries big-endian into long; type 0/1/2, other types are the null object; dictionary minus Type, Length, W, Index, Filter, DecodeParms, DL, F, FFilter, FDecodeParms is the trailer; data decoded through the filter pipeline under the engine's decoded-length limit, never decrypted; hybrid XRefStm read after its table and before Prev, its entries replacing the table's free entries (an in-use table entry wins), its own Prev not followed and its dictionary not a trailer; xref-stream.pdf, object-stream.pdf, png-predictor.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `xref-stream`; written by `PdfCrossReferenceLayout.Stream` and `StreamWithObjectStreams`: W [1 n 2] with n the fewest bytes for the largest offset, an entry for the stream itself, Flate with Predictor 12, trailer keys in its dictionary; hybrid files are not written (#44) | | 7.6.1 | General | done | `PdfDocument`, `PdfSecurity` | `Broadside.Tests.Security.EncryptedCorpusTests.An_encrypted_file_opens_with_the_empty_user_password_and_its_content_stream_decrypts`, `Broadside.Tests.Security.EncryptedCorpusTests.An_unencrypted_document_permits_everything` | An encrypted file opens transparently: `PdfDocument.IsEncrypted`, `PdfDocument.Security`, `PdfDocument.Permissions` | -| 7.6.2 | Application of encryption | done | `DocumentSecurity`, `DocumentDecryptor`, `SecurityHandlerRegistry`, `ISecurityHandler`, `SecurityHandlerContext`, `SecurityHandlerResult`, `PdfEncryptionNotSupportedException` | `Broadside.Tests.Security.EncryptedCorpusTests.Strings_are_decrypted_with_the_key_of_the_object_that_holds_them`, `Broadside.Tests.Security.EncryptedCorpusTests.The_encryption_dictionary_and_the_file_identifier_are_not_decrypted`, `Broadside.Tests.Security.EncryptedCorpusTests.Decrypting_marks_nothing_dirty`, `Broadside.Tests.Security.EncryptedCorpusTests.Concurrent_readers_see_the_same_decrypted_content`, `Broadside.Tests.Security.EncryptedCorpusTests.A_document_rebuilt_because_its_root_is_unusable_is_still_decrypted`, `Broadside.Tests.Security.EncryptedCorpusTests.A_document_whose_cross_reference_is_unreadable_is_rebuilt_and_decrypted`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.The_standard_handler_is_registered_by_default`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_handler_registered_for_standard_replaces_the_default`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.Two_engines_with_different_handlers_do_not_interfere`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_handler_that_supplies_the_key_another_way_decrypts_the_document`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_handler_is_chosen_by_subfilter_when_no_handler_has_the_filter_name`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_document_whose_handler_is_not_registered_is_not_supported` | Every string and stream is decrypted as its indirect object loads (hook 2), never the Encrypt dictionary, the trailer (ID, AuthCode), object-stream members (their container is decrypted), cross-reference streams or a signature dictionary's Contents; decryption never marks objects dirty; handler chosen by Filter, else by SubFilter (`PdfOptions.UseSecurityHandler`, standard handler by default); V 1-6 (V 3 read as V 2 with a diagnostic); newest trailer's Encrypt and ID; a missing ID is an empty identifier with EncryptionIdMissing; an Encrypt entry that does not resolve rebuilds the cross-reference (#41); fuzz `encrypted-document` | +| 7.6.2 | Application of encryption | done | `DocumentSecurity`, `DocumentDecryptor`, `SecurityHandlerRegistry`, `ISecurityHandler`, `SecurityHandlerContext`, `SecurityHandlerResult`, `PdfEncryptionNotSupportedException` | `Broadside.Tests.Security.EncryptedCorpusTests.Strings_are_decrypted_with_the_key_of_the_object_that_holds_them`, `Broadside.Tests.Security.EncryptedCorpusTests.The_encryption_dictionary_and_the_file_identifier_are_not_decrypted`, `Broadside.Tests.Security.EncryptedCorpusTests.Decrypting_marks_nothing_dirty`, `Broadside.Tests.Security.EncryptedCorpusTests.Concurrent_readers_see_the_same_decrypted_content`, `Broadside.Tests.Security.EncryptedCorpusTests.A_document_rebuilt_because_its_root_is_unusable_is_still_decrypted`, `Broadside.Tests.Security.EncryptedCorpusTests.A_document_whose_cross_reference_is_unreadable_is_rebuilt_and_decrypted`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.The_standard_handler_is_registered_by_default`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_handler_registered_for_standard_replaces_the_default`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.Two_engines_with_different_handlers_do_not_interfere`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_handler_that_supplies_the_key_another_way_decrypts_the_document`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_handler_is_chosen_by_subfilter_when_no_handler_has_the_filter_name`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_document_whose_handler_is_not_registered_is_not_supported` | Every string and stream is decrypted as its indirect object loads (hook 2), never the Encrypt dictionary, the trailer (ID, AuthCode), object-stream members (their container is decrypted), cross-reference streams or a signature dictionary's Contents; decryption never marks objects dirty; handler chosen by Filter, else by SubFilter (`PdfOptions.UseSecurityHandler`, standard and public-key handlers by default); V 1-6 (V 3 read as V 2 with a diagnostic); newest trailer's Encrypt and ID; a missing ID is an empty identifier with EncryptionIdMissing; an Encrypt entry that does not resolve rebuilds the cross-reference (#41); fuzz `encrypted-document` | | 7.6.3 | General encryption algorithm | done | `DocumentDecryptor`, `Rc4`, `AesCipher`, `ManagedAes`, `Md5`, `ManagedMd5`, `CryptographyBackend` | `Broadside.Tests.Security.EncryptedCorpusTests.The_managed_cryptography_decrypts_like_the_platform_cryptography`, `Broadside.Tests.Security.CryptFilterTests.Aes_data_with_a_damaged_pad_is_kept_whole_with_a_diagnostic`, `Broadside.Tests.Security.CryptographyTests.Managed_md5_matches_rfc_1321`, `Broadside.Tests.Security.CryptographyTests.Managed_md5_agrees_with_the_platform_at_every_padding_boundary`, `Broadside.Tests.Security.CryptographyTests.Managed_aes_matches_fips_197_appendix_c`, `Broadside.Tests.Security.CryptographyTests.Managed_aes_cbc_agrees_with_the_platform`, `Broadside.Tests.Security.CryptographyTests.Rc4_matches_the_published_vectors`, `Broadside.Tests.Security.DecryptionAllocationTests.Rc4_allocates_nothing`, `Broadside.Tests.Security.DecryptionAllocationTests.Aes_cbc_into_a_buffer_allocates_nothing_per_block` | 7.6.3.1 to 7.6.3.3. Algorithm 1 (RC4, AES-128-CBC with "sAlT") and 1.A (AES-256-CBC), IV prefix, PKCS#5 padding; damaged AES data repaired like pdf.js with EncryptedDataInvalid (too short: nothing; partial block dropped; bad pad kept); RC4 managed; MD5 and AES from the BCL, with managed MD5 and AES selected at run time where the platform has none (browser); `SecurityBenchmarks`; fuzz `decrypt` | | 7.6.4 | Standard security handler | done | `StandardSecurityHandler`, `PasswordEncoding`, `PdfPassword`, `PdfCredentials`, `PdfPasswordException`, `PdfPermissions`, `PdfAccessLevel`, `PdfSecurity` | `Broadside.Tests.Security.EncryptedCorpusTests.An_encrypted_file_opens_with_the_owner_password_and_gives_owner_access`, `Broadside.Tests.Security.EncryptedCorpusTests.An_encrypted_file_opens_in_strict_mode`, `Broadside.Tests.Security.EncryptedCorpusTests.The_security_describes_the_algorithm_revision_and_key_length`, `Broadside.Tests.Security.PasswordTests.A_document_with_a_user_password_needs_a_password`, `Broadside.Tests.Security.PasswordTests.A_wrong_password_is_reported_as_incorrect`, `Broadside.Tests.Security.PasswordTests.The_user_password_opens_the_document_with_user_access`, `Broadside.Tests.Security.PasswordTests.The_owner_password_opens_the_document_with_owner_access`, `Broadside.Tests.Security.PasswordTests.User_access_has_the_permissions_the_document_grants`, `Broadside.Tests.Security.PasswordTests.A_revision_6_password_maps_soft_hyphens_to_nothing`, `Broadside.Tests.Security.PasswordTests.A_legacy_password_can_be_given_as_bytes_in_a_code_page`, `Broadside.Tests.Security.PasswordTests.A_wrong_password_for_a_document_without_a_user_password_is_still_incorrect`, `Broadside.Tests.Security.PasswordTests.The_password_given_to_open_overrides_the_one_on_the_options`, `Broadside.Tests.Security.PasswordTests.An_owner_password_computed_by_rehashing_only_the_key_length_is_accepted_with_a_diagnostic`, `Broadside.Tests.Security.PasswordTests.The_owner_key_variant_throws_in_strict_mode`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.The_standard_handler_reads_permissions_by_revision`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.An_undefined_revision_is_an_unsupported_algorithm`, `Broadside.Tests.Security.CryptographyTests.Saslprep_maps_like_rfc_4013`, `Broadside.Tests.Security.CryptographyTests.Saslprep_rejects_prohibited_characters` | 7.6.4.1 to 7.6.4.4. Revisions 2, 3, 4, 6 (and the deprecated 5, read with EncryptionRevisionInvalid); Algorithms 2, 2.A, 2.B, 3-7, 11-13; default user password first, then user, then owner (`PdfPasswordFailure.Required` / `Incorrect`); PDFDocEncoding then Latin-1 for R2-4, SASLprep + UTF-8 (127 bytes) then plain UTF-8 for R6 (bidi check not applied; NFKC needs platform globalization data); O/U/OE/UE/Perms lengths repaired with EncryptionEntryLengthInvalid; Algorithm 3 rehash-first-n variant accepted with OwnerPasswordKeyVariant (encrypted-owner-key-variant.pdf); Perms checked (EncryptionPermissionsMismatch, Perms wins); permissions by revision (Table 22); corpus encrypted-rc4-40, -rc4-128, -rc4-40-r3, -aes-128, -aes-256, -user-password, -rc4-user-password; writing encrypted files is Phase 4 | -| 7.6.5 | Public-key security handlers | not started | | | #43, through `ISecurityHandler` (`PdfCredentials` for certificates, `SecurityHandlerResult.CryptFilterKeys` for crypt filters with their own recipients) | +| 7.6.5.1 | General | done | `PublicKeySecurityHandler`, `PdfCertificateCredentials`, `PdfCertificateException`, `PdfCertificateFailure`, `SecurityHandlerRegistry` | `Broadside.Tests.Security.PublicKeySecurityTests.A_document_encrypted_for_a_certificate_opens_with_that_certificate_and_its_private_key`, `Broadside.Tests.Security.PublicKeySecurityTests.Another_public_key_handler_name_opens_through_its_subfilter`, `Broadside.Tests.Security.PublicKeySecurityTests.A_recipient_named_by_subject_key_identifier_is_found_among_several_certificates`, `Broadside.Tests.Security.PublicKeySecurityTests.A_certificate_that_is_not_a_recipient_is_reported_with_the_recipients`, `Broadside.Tests.Security.PublicKeySecurityTests.A_document_encrypted_for_certificates_needs_a_certificate`, `Broadside.Tests.Security.PublicKeySecurityTests.A_recipient_certificate_without_its_private_key_cannot_open_the_document`, `Broadside.Tests.Security.PublicKeySecurityTests.A_well_formed_document_opens_in_strict_mode` | CMS (RFC 5652) through `System.Security.Cryptography.Pkcs` `EnvelopedCms`; the handler is registered by default (Filter `Adobe.PubSec`, and any Filter with SubFilter `adbe.pkcs7.s3`/`s4`/`s5`); certificates come from `PdfCertificateCredentials` (one certificate or a collection; the core never reads a store); recipients matched by issuer and serial number or subject key identifier; no certificate, no matching recipient, and a matching certificate without a usable private key are `PdfCertificateFailure.Required`/`NoMatchingRecipient`/`PrivateKeyUnavailable`, with the recipients listed; key-agreement recipients and legacy CMS ciphers the platform cannot decrypt, and every certificate on browser (WebAssembly), are `PdfEncryptionNotSupportedException` (Platform); fuzz `public-key` | +| 7.6.5.2 | Public-key encryption dictionary | done | `PublicKeySecurityHandler`, `PdfPermissions`, `PdfAccessLevel` | `Broadside.Tests.Security.PublicKeySecurityTests.Permissions_are_read_most_significant_byte_first_with_the_meanings_of_revision_3`, `Broadside.Tests.Security.PublicKeySecurityTests.Permission_bit_2_enables_every_permission`, `Broadside.Tests.Security.PublicKeySecurityTests.An_s3_document_has_the_permissions_of_revision_2_and_an_s4_document_those_of_revision_3`, `Broadside.Tests.Security.PublicKeySecurityTests.A_reader_in_two_lists_has_the_permissions_of_the_first`, `Broadside.Tests.Security.PublicKeySecurityTests.A_recipient_string_padded_with_zeros_is_read_with_a_diagnostic_and_digested_whole`, `Broadside.Tests.Security.PublicKeySecurityTests.A_recipient_string_that_is_not_cms_is_skipped_with_a_diagnostic`, `Broadside.Tests.Security.PublicKeySecurityTests.A_document_with_no_recipients_cannot_be_authenticated` | Table 23 Recipients (s3/s4 in the Encrypt dictionary, s5 in the crypt filter StmF, else StrF, names; found in the other place with EncryptDictionaryInvalid Warning); first matching list wins; Table 24 permissions: s3 with revision 2 meanings, s4/s5 revision 3, bit 2 gives `PdfAccessLevel.Owner` and `PdfPermissions.All`; a Recipients string that is not CMS is skipped and one with trailing bytes read up to its DER end, both PublicKeyRecipientInvalid; no Recipients anywhere is EncryptDictionaryInvalid (Error, `DiagnosticException`) | +| 7.6.5.3 | Public-key encryption algorithms | done | `PublicKeySecurityHandler`, `SecurityHandlerResult`, `DocumentDecryptor`, `DocumentSecurity` | `Broadside.Tests.Security.PublicKeySecurityTests.An_s4_document_encrypted_with_rc4_opens_with_a_128_bit_sha_1_key`, `Broadside.Tests.Security.PublicKeySecurityTests.An_s5_document_with_an_aes_128_crypt_filter_opens_with_a_128_bit_sha_1_key`, `Broadside.Tests.Security.PublicKeySecurityTests.The_key_digests_every_recipient_list_and_the_permissions_come_from_the_list_that_names_the_reader`, `Broadside.Tests.Security.PublicKeySecurityTests.Metadata_left_in_plaintext_by_the_crypt_filter_adds_the_marker_to_the_key`, `Broadside.Tests.Security.PublicKeySecurityTests.A_stream_whose_crypt_filter_has_its_own_recipients_decrypts_with_that_filter_s_key`, `Broadside.Tests.Security.PublicKeySecurityTests.A_stream_whose_crypt_filter_does_not_name_the_reader_stays_encrypted` | 20-byte seed + 4 permission bytes most significant first (shorter or longer enveloped data: PublicKeyEnvelopeInvalid); key = first n/8 bytes of SHA-1 (n up to 128) or SHA-256 (n = 256: V 5+ or CFM AESV3) over seed, every Recipients string in order (raw bytes, padding included), and 0xFF x 4 when EncryptMetadata (StmF crypt filter, else Encrypt dictionary) is false; n from CFM (AESV2 128, AESV3 256), else the crypt filter Length in bits (byte counts 5-16 read as bytes and out-of-range values clamped to 40-128, EncryptionKeyLengthInvalid), else the Encrypt Length (default 40); crypt filters with their own Recipients (a string for streams' Crypt decode parameters) get their own keys via `SecurityHandlerResult.CryptFilterKeys` (seed only, no 0xFF marker); one that does not name the reader gets an empty key, CryptFilterNotAuthorized (Information), and its streams stay encrypted; the ISO/TS 32004 MAC uses the file key, which is the StmF (DefaultCryptFilter) key for s5 (not tested end to end: no s5 file with a MAC is built yet) | | 7.6.6 | Crypt filters | done | `DocumentDecryptor`, `CryptFilter`, `CryptMethod` | `Broadside.Tests.Security.CryptFilterTests.An_embedded_file_is_decrypted_with_eff_which_defaults_to_stmf`, `Broadside.Tests.Security.CryptFilterTests.Each_content_stream_decrypts_with_the_crypt_filter_it_names_or_the_default_one`, `Broadside.Tests.Security.CryptFilterTests.Metadata_is_left_as_it_is_when_encrypt_metadata_is_false`, `Broadside.Tests.Security.CryptFilterTests.The_owner_password_opens_a_document_whose_metadata_is_not_encrypted`, `Broadside.Tests.Security.CryptFilterTests.A_stream_that_names_a_crypt_filter_the_document_does_not_define_is_left_encrypted_with_a_diagnostic`, `Broadside.Tests.Security.CryptFilterTests.Metadata_in_plaintext_although_encrypt_metadata_is_true_is_read_as_it_is_with_a_diagnostic`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.An_unknown_crypt_filter_method_is_an_unsupported_algorithm` | CF, StmF, StrF, EFF (default StmF), Identity, CFM V2/AESV2/AESV3 (and AESV4, ISO/TS 32003); CFM None leaves data as is with CryptFilterMethodInvalid; AESV2 under V 5 read as AESV3 with a diagnostic; unknown CFM for StmF/StrF/EFF throws `PdfEncryptionNotSupportedException`; EncryptMetadata false leaves /Type /Metadata streams alone (plaintext XMP under EncryptMetadata true read with MetadataNotEncrypted); crypt filter Length not used (keys come from the handler); encrypted-crypt-filters.pdf | | 7.6.7 | Unencrypted wrapper document | not started | | | Collections of encrypted payloads (PDF 2.0); a wrapper opens as an ordinary unencrypted document | | 7.7.1 | General | n/a | | | Introductory text | diff --git a/src/Broadside/Parsing/DiagnosticCodes.cs b/src/Broadside/Parsing/DiagnosticCodes.cs index fe1e1e0e..99d0f5de 100644 --- a/src/Broadside/Parsing/DiagnosticCodes.cs +++ b/src/Broadside/Parsing/DiagnosticCodes.cs @@ -101,6 +101,9 @@ internal static class DiagnosticCodes public const string IntegrityCodeMismatch = nameof(IntegrityCodeMismatch); public const string IntegrityCodeIncomplete = nameof(IntegrityCodeIncomplete); public const string IntegrityCodeNotVerified = nameof(IntegrityCodeNotVerified); + public const string PublicKeyRecipientInvalid = nameof(PublicKeyRecipientInvalid); + public const string PublicKeyEnvelopeInvalid = nameof(PublicKeyEnvelopeInvalid); + public const string CryptFilterNotAuthorized = nameof(CryptFilterNotAuthorized); // Document catalog (§7.7.2). public const string CatalogTypeInvalid = nameof(CatalogTypeInvalid); diff --git a/src/Broadside/PdfAccessLevel.cs b/src/Broadside/PdfAccessLevel.cs index e92874de..8b4d5295 100644 --- a/src/Broadside/PdfAccessLevel.cs +++ b/src/Broadside/PdfAccessLevel.cs @@ -1,7 +1,11 @@ namespace Broadside; /// Which credential opened an encrypted document. -/// ISO 32000-2 §7.6.4.1: the owner password gives full access; the user password (or the default, empty one) gives the access the permissions allow. +/// +/// ISO 32000-2 §7.6.4.1: the owner password gives full access; the user password (or the default, empty one) gives the access the +/// permissions allow. §7.6.5.2, Table 24: a certificate recipient whose permissions set bit 2 (change the encryption, every other +/// permission) has owner access; other recipients have user access. +/// public enum PdfAccessLevel { /// User access: the document's permissions apply. diff --git a/src/Broadside/PdfEngine.cs b/src/Broadside/PdfEngine.cs index ae6769bc..4bef3e53 100644 --- a/src/Broadside/PdfEngine.cs +++ b/src/Broadside/PdfEngine.cs @@ -119,7 +119,8 @@ public async Task OpenAsync(Stream stream, CancellationToken cancel /// /// The file cannot be read at all, or, in strict mode, deviates from ISO 32000-2. /// - /// The document is encrypted and the credentials do not open it. + /// The document is encrypted with a password and the credentials do not open it. + /// The document is encrypted for certificate recipients and the credentials do not open it. /// The document is encrypted in a way this engine cannot decrypt. /// ISO 32000-2 §7.5 and §7.6. For an unencrypted file the credentials are ignored. public PdfDocument Open(string path, PdfCredentials credentials) @@ -136,7 +137,8 @@ public PdfDocument Open(string path, PdfCredentials credentials) /// /// The file cannot be read at all, or, in strict mode, deviates from ISO 32000-2. /// - /// The document is encrypted and the credentials do not open it. + /// The document is encrypted with a password and the credentials do not open it. + /// The document is encrypted for certificate recipients and the credentials do not open it. /// The document is encrypted in a way this engine cannot decrypt. /// ISO 32000-2 §7.5 and §7.6. For an unencrypted file the credentials are ignored. public PdfDocument Open(Stream stream, PdfCredentials credentials) @@ -153,7 +155,8 @@ public PdfDocument Open(Stream stream, PdfCredentials credentials) /// /// The file cannot be read at all, or, in strict mode, deviates from ISO 32000-2. /// - /// The document is encrypted and the credentials do not open it. + /// The document is encrypted with a password and the credentials do not open it. + /// The document is encrypted for certificate recipients and the credentials do not open it. /// The document is encrypted in a way this engine cannot decrypt. /// ISO 32000-2 §7.5 and §7.6. For an unencrypted file the credentials are ignored. public PdfDocument Open(ReadOnlyMemory bytes, PdfCredentials credentials) diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index 6f88a918..a576dc7d 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -383,3 +383,24 @@ Broadside.PdfSaveOptions.CrossReferenceLayout.get -> Broadside.PdfCrossReference Broadside.PdfSaveOptions.CrossReferenceLayout.set -> void Broadside.PdfSaveOptions.PdfSaveOptions() -> void Broadside.PdfSaveOptions.WithCrossReferenceLayout(Broadside.PdfCrossReferenceLayout layout) -> Broadside.PdfSaveOptions! +Broadside.Security.PdfCertificateCredentials +Broadside.Security.PdfCertificateCredentials.Certificates.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Security.PdfCertificateCredentials.PdfCertificateCredentials(System.Collections.Generic.IEnumerable! certificates) -> void +Broadside.Security.PdfCertificateCredentials.PdfCertificateCredentials(System.Security.Cryptography.X509Certificates.X509Certificate2! certificate) -> void +Broadside.Security.PdfCertificateException +Broadside.Security.PdfCertificateException.Failure.get -> Broadside.Security.PdfCertificateFailure +Broadside.Security.PdfCertificateException.PdfCertificateException() -> void +Broadside.Security.PdfCertificateException.PdfCertificateException(Broadside.Security.PdfCertificateFailure failure, System.Collections.Generic.IEnumerable! recipients) -> void +Broadside.Security.PdfCertificateException.PdfCertificateException(string? message) -> void +Broadside.Security.PdfCertificateException.PdfCertificateException(string? message, System.Exception? innerException) -> void +Broadside.Security.PdfCertificateException.Recipients.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Security.PdfCertificateFailure +Broadside.Security.PdfCertificateFailure.NoMatchingRecipient = 1 -> Broadside.Security.PdfCertificateFailure +Broadside.Security.PdfCertificateFailure.PrivateKeyUnavailable = 2 -> Broadside.Security.PdfCertificateFailure +Broadside.Security.PdfCertificateFailure.Required = 0 -> Broadside.Security.PdfCertificateFailure +Broadside.Security.PublicKeySecurityHandler +Broadside.Security.PublicKeySecurityHandler.Authenticate(Broadside.Security.SecurityHandlerContext! context) -> Broadside.Security.SecurityHandlerResult! +Broadside.Security.PublicKeySecurityHandler.Filter.get -> Broadside.Objects.CosName! +Broadside.Security.PublicKeySecurityHandler.PublicKeySecurityHandler() -> void +Broadside.Security.PublicKeySecurityHandler.SubFilters.get -> System.Collections.Generic.IReadOnlyCollection! +override Broadside.Security.PdfCertificateCredentials.ToString() -> string! diff --git a/src/Broadside/Security/DocumentDecryptor.cs b/src/Broadside/Security/DocumentDecryptor.cs index c41d7592..b74b4917 100644 --- a/src/Broadside/Security/DocumentDecryptor.cs +++ b/src/Broadside/Security/DocumentDecryptor.cs @@ -163,6 +163,11 @@ public static DocumentDecryptor Create( } byte[] key = result.CryptFilterKeys is { } keys && keys.TryGetValue(name, out ReadOnlyMemory own) ? own.ToArray() : fileKey; + if (key.Length == 0) + { + continue; // Not authorized (§7.6.6): streams naming it stay encrypted, StmF/StrF naming it is CryptFilterMissing. + } + if (ReadFilter(name, resolve(entry) as CosDictionary, version, key, diagnostics, resolve, out string? problem) is { } filter) { named[name] = filter; @@ -202,7 +207,17 @@ CryptFilter Select(CosName key, CosName? fallback) CryptFilter streams = Select(StmF, null); CryptFilter strings = Select(StrF, null); CryptFilter embedded = encryption.ContainsKey(EFF) ? Select(EFF, null) : streams; - bool encryptMetadata = resolve(encryption.TryGetValue(EncryptMetadataName, out CosObject? flag) ? flag : null) is not CosBoolean { Value: false }; + // Table 21 puts EncryptMetadata in the encryption dictionary; Table 27 in the crypt filter StmF names (public-key handlers). + CosObject flag = resolve(encryption.TryGetValue(EncryptMetadataName, out CosObject? flagEntry) ? flagEntry : null); + if (flag is CosNull + && resolve(encryption.TryGetValue(StmF, out CosObject? stmF) ? stmF : null) is CosName streamFilter + && resolve(cf) is CosDictionary definitions + && resolve(definitions.TryGetValue(streamFilter, out CosObject? definition) ? definition : null) is CosDictionary streamFilterDictionary) + { + flag = resolve(streamFilterDictionary.TryGetValue(EncryptMetadataName, out CosObject? filterFlag) ? filterFlag : null); + } + + bool encryptMetadata = flag is not CosBoolean { Value: false }; return new DocumentDecryptor(strings, streams, embedded, named, encryptMetadata, diagnostics, resolve); } diff --git a/src/Broadside/Security/DocumentSecurity.cs b/src/Broadside/Security/DocumentSecurity.cs index bd2dcb41..d0171c7d 100644 --- a/src/Broadside/Security/DocumentSecurity.cs +++ b/src/Broadside/Security/DocumentSecurity.cs @@ -33,7 +33,8 @@ internal static class DocumentSecurity /// /// Set when the Encrypt entry does not resolve and is false. /// The document's security, or when it is not encrypted. - /// The credentials do not open the document. + /// The password does not open the document. + /// The certificates do not open the document. /// No handler or method for the document's encryption. public static PdfSecurity? Open( PdfSource source, @@ -90,7 +91,16 @@ internal static class DocumentSecurity SecurityHandlerResult result = handler.Authenticate(context); if (version == 0) { - version = result.Revision switch { 2 => 1, 3 => 2, 4 => 4, 7 => 6, _ => 5 }; + // No V: the standard handler's revision implies it; another handler's key length does (RC4 below 256 bits, AES-256 at 256). + version = result.Revision switch + { + 2 => 1, + 3 => 2, + 4 => 4, + 7 => 6, + null when result.FileEncryptionKey.Length < 32 => 2, + _ => 5, + }; } DocumentDecryptor decryptor = DocumentDecryptor.Create(encryption, version, result, diagnostics, loader.Resolve); diff --git a/src/Broadside/Security/ISecurityHandler.cs b/src/Broadside/Security/ISecurityHandler.cs index 1480cba3..d4ad599a 100644 --- a/src/Broadside/Security/ISecurityHandler.cs +++ b/src/Broadside/Security/ISecurityHandler.cs @@ -33,7 +33,8 @@ public interface ISecurityHandler /// Authenticates the credentials against the encryption dictionary. /// The encryption dictionary, the file identifier, the credentials and the diagnostics. /// The file encryption key, the access level and the permissions. - /// The credentials do not open the document. + /// The password does not open the document. + /// The certificates do not open the document. /// The handler does not implement what the dictionary asks for. /// The dictionary is too damaged to authenticate against. SecurityHandlerResult Authenticate(SecurityHandlerContext context); @@ -126,7 +127,8 @@ public SecurityHandlerResult(ReadOnlySpan fileEncryptionKey, PdfAccessLeve /// /// Gets keys for named crypt filters that do not use the file encryption key, such as a public-key handler's crypt filters with - /// their own recipients (§7.6.6, Table 27); when every crypt filter uses the file encryption key. + /// their own recipients (§7.6.6, Table 27); when every crypt filter uses the file encryption key. An empty + /// key marks a crypt filter the credentials are not authorized for: streams that name it stay encrypted (§7.6.6). /// public IReadOnlyDictionary>? CryptFilterKeys { get; init; } } diff --git a/src/Broadside/Security/PdfCertificateCredentials.cs b/src/Broadside/Security/PdfCertificateCredentials.cs new file mode 100644 index 00000000..1393eb0a --- /dev/null +++ b/src/Broadside/Security/PdfCertificateCredentials.cs @@ -0,0 +1,48 @@ +using System.Security.Cryptography.X509Certificates; + +namespace Broadside.Security; + +/// Certificates with their private keys, offered to open a document encrypted for certificate recipients. +/// +/// +/// ISO 32000-2 §7.6.5.1: the reader scans the document's recipient lists for one of its certificates and decrypts the enveloped data +/// with that certificate's private key. Each certificate is matched by issuer and serial number, or by subject key identifier, the +/// way the CMS recipient info (RFC 5652 §6.2) names it; the first one that matches opens the document. +/// +/// +/// A certificate's private key is read through the certificate (), so a certificate from +/// a store, a PKCS #12 file, or one paired with its key by CopyWithPrivateKey all work. The engine never reads a certificate +/// store by itself, and does not dispose the certificates. Certificates cannot be used in a browser (WebAssembly), where the +/// platform has no X.509 or CMS support. +/// +/// +public sealed class PdfCertificateCredentials : PdfCredentials +{ + private readonly X509Certificate2[] _certificates; + + /// Initializes a new instance of the class with one certificate. + /// A certificate with its private key. + public PdfCertificateCredentials(X509Certificate2 certificate) + { + ArgumentNullException.ThrowIfNull(certificate); + _certificates = [certificate]; + } + + /// Initializes a new instance of the class with candidate certificates, tried in order. + /// Certificates, such as an ; those without a private key match but cannot decrypt. + public PdfCertificateCredentials(IEnumerable certificates) + { + ArgumentNullException.ThrowIfNull(certificates); + _certificates = [.. certificates]; + if (Array.IndexOf(_certificates, null) >= 0) + { + throw new ArgumentException("The certificates cannot contain null.", nameof(certificates)); + } + } + + /// Gets the certificates, in the order they are tried. + public IReadOnlyList Certificates => _certificates; + + /// + public override string ToString() => "PdfCertificateCredentials"; +} diff --git a/src/Broadside/Security/PdfCertificateException.cs b/src/Broadside/Security/PdfCertificateException.cs new file mode 100644 index 00000000..05b8b4a3 --- /dev/null +++ b/src/Broadside/Security/PdfCertificateException.cs @@ -0,0 +1,108 @@ +using System.Globalization; +using System.Security.Cryptography.Pkcs; +using System.Security.Cryptography.Xml; +using System.Text; + +namespace Broadside.Security; + +/// Why a document encrypted for certificate recipients did not open with the certificates given. +/// ISO 32000-2 §7.6.5.1. +public enum PdfCertificateFailure +{ + /// No certificate was given: open the document with for one of its recipients. + Required, + + /// None of the certificates given is a recipient of the document. + NoMatchingRecipient, + + /// A certificate given is a recipient, but its private key is not available or does not decrypt the enveloped data. + PrivateKeyUnavailable, +} + +/// The exception thrown when a document encrypted for certificate recipients cannot be opened with the certificates given. +/// +/// ISO 32000-2 §7.6.5.1: only the listed recipients can open the document. names them (issuer and serial +/// number, or subject key identifier, RFC 5652 §6.2), so a caller can find the matching certificate, in a store for instance, and try +/// again. +/// +public sealed class PdfCertificateException : Exception +{ + /// Initializes a new instance of the class. + /// Why the certificates did not open the document. + /// The recipients the document is encrypted for. + public PdfCertificateException(PdfCertificateFailure failure, IEnumerable recipients) + : this(failure, (recipients ?? throw new ArgumentNullException(nameof(recipients))).ToArray(), innerException: null) + { + } + + /// Initializes a new instance of the class. + public PdfCertificateException() + : this(PdfCertificateFailure.Required, Array.Empty(), innerException: null) + { + } + + /// Initializes a new instance of the class. + /// The message. + public PdfCertificateException(string? message) + : this(message, null) + { + } + + /// Initializes a new instance of the class. + /// The message. + /// The cause. + public PdfCertificateException(string? message, Exception? innerException) + : base(message, innerException) + { + Failure = PdfCertificateFailure.NoMatchingRecipient; + Recipients = []; + } + + /// Initializes a new instance of the class with the cause. + internal PdfCertificateException(PdfCertificateFailure failure, SubjectIdentifier[] recipients, Exception? innerException) + : base(Describe(failure, recipients, innerException), innerException) + { + Failure = failure; + Recipients = recipients; + } + + /// Gets why the certificates did not open the document. + public PdfCertificateFailure Failure { get; } + + /// Gets the recipients of the document's recipient lists, in the order they appear. + public IReadOnlyList Recipients { get; } + + private static string Describe(PdfCertificateFailure failure, SubjectIdentifier[] recipients, Exception? innerException) + { + var message = new StringBuilder(failure switch + { + PdfCertificateFailure.Required => "The document is encrypted for certificate recipients; open it with the certificate and private key of one of them.", + PdfCertificateFailure.NoMatchingRecipient => "None of the certificates given is a recipient of the document.", + _ => "A certificate given is a recipient of the document, but its private key is not available or does not decrypt the enveloped data.", + }); + if (innerException is not null) + { + message.Append(' ').Append(innerException.Message); + } + + if (recipients.Length > 0) + { + message.Append(" Recipients: "); + for (int index = 0; index < recipients.Length; index++) + { + message.Append(index == 0 ? string.Empty : "; ").Append(Describe(recipients[index])); + } + + message.Append('.'); + } + + return message.ToString(); + } + + private static string Describe(SubjectIdentifier recipient) => recipient.Value switch + { + X509IssuerSerial serial => string.Create(CultureInfo.InvariantCulture, $"issuer '{serial.IssuerName}', serial number {serial.SerialNumber}"), + string keyIdentifier => $"subject key identifier {keyIdentifier}", + _ => recipient.Type.ToString(), + }; +} diff --git a/src/Broadside/Security/PublicKeySecurityHandler.cs b/src/Broadside/Security/PublicKeySecurityHandler.cs new file mode 100644 index 00000000..9393ff72 --- /dev/null +++ b/src/Broadside/Security/PublicKeySecurityHandler.cs @@ -0,0 +1,512 @@ +using System.Buffers.Binary; +using System.Formats.Asn1; +using System.Globalization; +using System.Security.Cryptography; +using System.Security.Cryptography.Pkcs; +using System.Security.Cryptography.X509Certificates; +using System.Security.Cryptography.Xml; +using Broadside.Diagnostics; +using Broadside.Filters; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Security; + +/// +/// The public-key security handler: documents encrypted for certificate recipients, SubFilters adbe.pkcs7.s3, +/// adbe.pkcs7.s4 and adbe.pkcs7.s5. Registered by default. +/// +/// +/// +/// ISO 32000-2 §7.6.5. Each Recipients string is a CMS enveloped-data object (RFC 5652) listing recipients with equal access; +/// the reader's certificates () are matched against them by issuer and serial number or subject +/// key identifier, and the first matching list's enveloped data, decrypted with the certificate's private key, holds a 20-byte seed and +/// 4 bytes of permissions, most significant byte first (§7.6.5.3). The file encryption key is the first n/8 bytes of the SHA-1 +/// (up to 128 bits) or SHA-256 (256 bits) digest of the seed, every string of the Recipients array in order, and four 0xFF +/// bytes when the document-level metadata is left in plaintext. +/// +/// +/// Where the recipients are: adbe.pkcs7.s3 and s4 list them in the encryption dictionary (Table 23); adbe.pkcs7.s5 +/// in the crypt filter StmF (else StrF) names (Table 27). Other crypt filters with their own Recipients (a single +/// string when streams name them in their Crypt decode parameters) get keys of their own, from a 20-byte seed without +/// permissions; one whose recipients do not include the reader is not authorized, and the streams that use it stay encrypted. The key +/// length comes from the crypt filter's method (AESV2 128 bits, AESV3 256) or its Length, in bits (Table 25), +/// else from the encryption dictionary's Length (default 40); V 5 and later always use 256 bits. +/// +/// +/// Permissions (Table 24): adbe.pkcs7.s3 has the meanings of the standard handler's revision 2, the others those of revision 3 +/// (); bit 2 permits changing the encryption and enables every permission, which +/// gives access. The integrity MAC of ISO/TS 32004 §6.4 uses the file encryption key, the key of +/// the crypt filter DefaultCryptFilter in an adbe.pkcs7.s5 document. +/// +/// +/// Certificates and CMS are not available in a browser (WebAssembly): there the handler throws +/// with , as it does for a +/// key-agreement recipient or a content-encryption algorithm (RC4, DES, RC2) the platform's CMS implementation cannot decrypt. +/// +/// +public sealed class PublicKeySecurityHandler : ISecurityHandler +{ + private static readonly CosName PubSec = new("Adobe.PubSec"); + private static readonly CosName S3 = new("adbe.pkcs7.s3"); + private static readonly CosName S4 = new("adbe.pkcs7.s4"); + private static readonly CosName S5 = new("adbe.pkcs7.s5"); + private static readonly CosName SubFilterName = new("SubFilter"); + private static readonly CosName RecipientsName = new("Recipients"); + private static readonly CosName CF = new("CF"); + private static readonly CosName StmF = new("StmF"); + private static readonly CosName StrF = new("StrF"); + private static readonly CosName CFM = new("CFM"); + private static readonly CosName AESV2 = new("AESV2"); + private static readonly CosName AESV3 = new("AESV3"); + private static readonly CosName LengthName = new("Length"); + private static readonly CosName EncryptMetadata = new("EncryptMetadata"); + + /// Permission bit 2 (Table 24): change the encryption, and every other permission. + private const int ChangeEncryption = 1 << 1; + + /// Gets Adobe.PubSec; documents naming another public-key handler open through . + /// ISO 32000-2 §7.6.5.2: Entrust.PPKEF, Adobe.PPKLite and Adobe.PubSec are examples of public-key handler names. + public CosName Filter => PubSec; + + /// Gets adbe.pkcs7.s3, adbe.pkcs7.s4 and adbe.pkcs7.s5. + /// ISO 32000-2 §7.6.5.2. + public IReadOnlyCollection SubFilters => [S3, S4, S5]; + + /// + /// No certificate given is a recipient with a usable private key. + public SecurityHandlerResult Authenticate(SecurityHandlerContext context) + { + ArgumentNullException.ThrowIfNull(context); + if (OperatingSystem.IsBrowser()) + { + throw new PdfEncryptionNotSupportedException( + PdfEncryptionNotSupportedReason.Platform, + "The document is encrypted for certificate recipients; certificates and CMS are not available in a browser."); + } + + CosDictionary encryption = context.EncryptionDictionary; + CosName? subFilter = context.Resolve(Get(encryption, SubFilterName)) as CosName; + int version = context.Resolve(Get(encryption, KnownNames.V)) is CosInteger { Value: >= 0 and <= int.MaxValue } v ? (int)v.Value : 0; + if (version == 0) + { + context.Report( + DiagnosticCodes.EncryptionVersionInvalid, + DiagnosticSeverity.Warning, + "The public-key encryption dictionary has no usable V entry; it is read by its key length (RC4 below 256 bits, AES-256 at 256)."); + } + + IReadOnlyList certificates = (context.Credentials as PdfCertificateCredentials)?.Certificates ?? []; + CosDictionary? filters = context.Resolve(Get(encryption, CF)) as CosDictionary; + + // The document-level recipients: the encryption dictionary's (s3, s4), else those of the crypt filter StmF or StrF names (s5). + CosName? documentFilter = null; + CosDictionary? documentFilterDictionary = null; + CosObject recipientsEntry = context.Resolve(Get(encryption, RecipientsName)); + if (recipientsEntry is CosNull) + { + foreach (CosName key in (ReadOnlySpan)[StmF, StrF]) + { + if (context.Resolve(Get(encryption, key)) is CosName name + && !name.Equals(FilterNames.Identity) + && context.Resolve(Get(filters, name)) is CosDictionary filter + && context.Resolve(Get(filter, RecipientsName)) is not CosNull) + { + documentFilter = name; + documentFilterDictionary = filter; + recipientsEntry = context.Resolve(Get(filter, RecipientsName)); + break; + } + } + + if (documentFilter is null) + { + throw Fail(context, "The public-key encryption dictionary has no Recipients, neither its own (Table 23) nor in the crypt filter StmF or StrF names (Table 27)."); + } + } + else if (version >= 4 && context.Resolve(Get(encryption, StmF)) is CosName stmF && context.Resolve(Get(filters, stmF)) is CosDictionary stmFilter) + { + documentFilterDictionary = stmFilter; + } + + if (subFilter is not null && subFilter.Equals(S5) != (documentFilter is not null)) + { + context.Report( + DiagnosticCodes.EncryptDictionaryInvalid, + DiagnosticSeverity.Warning, + $"With SubFilter /{subFilter.Value} the Recipients shall be in {(subFilter.Equals(S5) ? "the crypt filter dictionary (Table 27)" : "the encryption dictionary (Table 23)")}; they are read from where they are."); + } + + byte[][] recipients = ReadRecipients(context, recipientsEntry, "the document"); + bool encryptMetadata = context.Resolve(Get(documentFilterDictionary, EncryptMetadata)) is CosBoolean filterFlag + ? filterFlag.Value + : context.Resolve(Get(encryption, EncryptMetadata)) is not CosBoolean { Value: false }; + int keyLength = KeyLength(context, encryption, documentFilterDictionary, version, documentFilter is null ? "the encryption dictionary" : $"the crypt filter /{documentFilter.Value}"); + + Envelope envelope = Open(context, recipients, certificates, "the document") + ?? throw new PdfCertificateException( + certificates.Count == 0 ? PdfCertificateFailure.Required : PdfCertificateFailure.NoMatchingRecipient, + RecipientIdentifiers(recipients), + innerException: null); + + if (envelope.Content.Length < 20) + { + throw Fail(context, string.Create(CultureInfo.InvariantCulture, $"The enveloped data of the document's recipient list shall hold a 20-byte seed and 4 bytes of permissions (§7.6.5.3); it has {envelope.Content.Length} bytes.")); + } + + int rawPermissions = 0; + if (envelope.Content.Length >= 24) + { + rawPermissions = BinaryPrimitives.ReadInt32BigEndian(envelope.Content.AsSpan(20, 4)); + } + + if (envelope.Content.Length != 24) + { + context.Report( + DiagnosticCodes.PublicKeyEnvelopeInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The enveloped data of a document-level recipient list shall be a 20-byte seed and 4 bytes of permissions (§7.6.5.3); it has {envelope.Content.Length} bytes{(envelope.Content.Length < 24 ? ", so no permission is granted" : ", the rest is ignored")}.")); + } + + byte[] fileKey = DeriveKey(envelope.Content.AsSpan(0, 20), recipients, appendMetadataMarker: !encryptMetadata, keyLength); + Dictionary>? filterKeys = ReadFilterKeys(context, filters, documentFilter, fileKey, certificates, version); + + bool owner = (rawPermissions & ChangeEncryption) != 0; + PdfPermissions permissions = owner + ? PdfPermissions.All + : StandardSecurityHandler.UserPermissions(rawPermissions, S3.Equals(subFilter) ? 2 : 3); + return new SecurityHandlerResult(fileKey, owner ? PdfAccessLevel.Owner : PdfAccessLevel.User, permissions, rawPermissions) + { + CryptFilterKeys = filterKeys, + }; + } + + /// Keys for every other crypt filter with recipients of its own (Table 27); an empty key marks one the reader is not a recipient of. + private static Dictionary>? ReadFilterKeys( + SecurityHandlerContext context, + CosDictionary? filters, + CosName? documentFilter, + byte[] fileKey, + IReadOnlyList certificates, + int version) + { + if (filters is null) + { + return null; + } + + var keys = new Dictionary>(); + if (documentFilter is not null) + { + keys[documentFilter] = fileKey; + } + + for (int index = 0; index < filters.Count; index++) + { + (CosName name, CosObject value) = filters.GetAt(index); + if (name.Equals(documentFilter) + || context.Resolve(value) is not CosDictionary filter + || context.Resolve(Get(filter, RecipientsName)) is not { } entry + || entry is CosNull) + { + continue; + } + + string label = $"the crypt filter /{name.Value}"; + byte[][] recipients = ReadRecipients(context, entry, label); + Envelope? envelope = Open(context, recipients, certificates, label); + if (envelope is null) + { + context.Report( + DiagnosticCodes.CryptFilterNotAuthorized, + DiagnosticSeverity.Information, + $"None of the certificates given is a recipient of {label}; the streams that use it stay encrypted (§7.6.6)."); + keys[name] = ReadOnlyMemory.Empty; + continue; + } + + if (envelope.Content.Length < 20) + { + context.Report( + DiagnosticCodes.PublicKeyEnvelopeInvalid, + DiagnosticSeverity.Error, + string.Create(CultureInfo.InvariantCulture, $"The enveloped data of {label} shall hold a 20-byte seed (Table 27); it has {envelope.Content.Length} bytes, so the streams that use it stay encrypted.")); + keys[name] = ReadOnlyMemory.Empty; + continue; + } + + int keyLength = KeyLength(context, null, filter, version, label); + keys[name] = DeriveKey(envelope.Content.AsSpan(0, 20), recipients, appendMetadataMarker: false, keyLength); + } + + return keys.Count == 0 ? null : keys; + } + + /// §7.6.5.3 steps a-d. + private static byte[] DeriveKey(ReadOnlySpan seed, byte[][] recipients, bool appendMetadataMarker, int keyLength) + { + using var hash = IncrementalHash.CreateHash(keyLength > 20 ? HashAlgorithmName.SHA256 : HashAlgorithmName.SHA1); + hash.AppendData(seed); + foreach (byte[] recipient in recipients) + { + hash.AppendData(recipient); + } + + if (appendMetadataMarker) + { + hash.AppendData([0xFF, 0xFF, 0xFF, 0xFF]); + } + + return hash.GetHashAndReset()[..keyLength]; + } + + /// The key length in bytes: from the crypt filter's method or Length (bits), else the dictionary's Length (Table 25, Table 20). + private static int KeyLength(SecurityHandlerContext context, CosDictionary? encryption, CosDictionary? filter, int version, string label) + { + if (version >= 5) + { + return 32; + } + + CosName? method = context.Resolve(Get(filter, CFM)) as CosName; + if (AESV3.Equals(method)) + { + return 32; + } + + if (AESV2.Equals(method)) + { + return 16; + } + + CosObject length = context.Resolve(Get(filter, LengthName)); + if (length is CosNull) + { + length = context.Resolve(Get(encryption, LengthName)); + } + + if (length is not CosInteger { Value: var bits }) + { + return filter is null ? 5 : 16; // Table 20: Length defaults to 40 bits; a crypt filter's Length is required, 128 bits is what writers use. + } + + if (bits is >= 5 and <= 16) + { + context.Report( + DiagnosticCodes.EncryptionKeyLengthInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The Length of {label} is {bits}; public-key handlers give it in bits (Table 25), so it is read as a number of bytes.")); + bits *= 8; + } + + long clamped = Math.Clamp(bits / 8 * 8, 40, 128); + if (clamped != bits) + { + context.Report( + DiagnosticCodes.EncryptionKeyLengthInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The Length of {label} is {bits} bits; a SHA-1 derived key is a multiple of 8 from 40 to 128 bits (§7.6.5.3), so {clamped} bits are used.")); + } + + return (int)(clamped / 8); + } + + /// The bytes of each CMS object of a Recipients entry: an array of strings, or a single string (Table 27). + private static byte[][] ReadRecipients(SecurityHandlerContext context, CosObject entry, string label) + { + List recipients = []; + IEnumerable items = entry is CosArray array ? array : [entry]; + foreach (CosObject item in items) + { + if (context.Resolve(item) is CosString text) + { + recipients.Add(text.Bytes.ToArray()); + } + else + { + context.Report( + DiagnosticCodes.PublicKeyRecipientInvalid, + DiagnosticSeverity.Warning, + $"An entry of the Recipients of {label} is not a string; it is ignored."); + } + } + + if (recipients.Count == 0) + { + throw Fail(context, $"The Recipients of {label} hold no CMS object."); + } + + return [.. recipients]; + } + + /// Finds the first recipient list naming one of the certificates and decrypts its enveloped data; null when none names one. + private static Envelope? Open(SecurityHandlerContext context, byte[][] recipients, IReadOnlyList certificates, string label) + { + if (certificates.Count == 0) + { + return null; + } + + X509Certificate2? withoutKey = null; + foreach (byte[] recipient in recipients) + { + EnvelopedCms? cms = Decode(context, recipient, label); + if (cms is null) + { + continue; + } + + foreach (RecipientInfo info in cms.RecipientInfos) + { + foreach (X509Certificate2 certificate in certificates) + { + if (!Matches(info.RecipientIdentifier, certificate)) + { + continue; + } + + if (!certificate.HasPrivateKey) + { + withoutKey ??= certificate; + continue; + } + + return new Envelope(Decrypt(cms, info, certificate, recipients)); + } + } + } + + if (withoutKey is not null) + { + throw new PdfCertificateException( + PdfCertificateFailure.PrivateKeyUnavailable, + RecipientIdentifiers(recipients), + new CryptographicException($"The certificate '{withoutKey.Subject}' is a recipient of {label} but has no private key.")); + } + + return null; + } + + private static byte[] Decrypt(EnvelopedCms cms, RecipientInfo info, X509Certificate2 certificate, byte[][] recipients) + { + try + { + cms.Decrypt(info, new X509Certificate2Collection(certificate)); + return cms.ContentInfo.Content; + } + catch (PlatformNotSupportedException exception) + { + throw Unsupported(cms, info, exception); + } + catch (CryptographicException exception) + { + if (info.Type == RecipientInfoType.KeyAgreement || IsLegacyCipher(cms.ContentEncryptionAlgorithm.Oid.Value)) + { + throw Unsupported(cms, info, exception); + } + + throw new PdfCertificateException(PdfCertificateFailure.PrivateKeyUnavailable, RecipientIdentifiers(recipients), exception); + } + } + + private static PdfEncryptionNotSupportedException Unsupported(EnvelopedCms cms, RecipientInfo info, Exception exception) => + new( + PdfEncryptionNotSupportedReason.Platform, + $"The enveloped data ({(info.Type == RecipientInfoType.KeyAgreement ? "a key-agreement recipient, " : string.Empty)}content encrypted with {cms.ContentEncryptionAlgorithm.Oid.FriendlyName ?? cms.ContentEncryptionAlgorithm.Oid.Value}) cannot be decrypted on this platform: {exception.Message}"); + + /// RC4, DES and RC2 (§7.6.5.3, deprecated), which CMS implementations drop first. + private static bool IsLegacyCipher(string? oid) => oid is "1.2.840.113549.3.4" or "1.3.14.3.2.7" or "1.2.840.113549.3.2"; + + /// Decodes one CMS object; a string with bytes after the DER encoding (zero padding) is read up to its end. + private static EnvelopedCms? Decode(SecurityHandlerContext context, byte[] recipient, string label) + { + try + { + AsnDecoder.ReadEncodedValue(recipient, AsnEncodingRules.BER, out _, out _, out int consumed); + if (consumed != recipient.Length) + { + bool padding = recipient.AsSpan(consumed).IndexOfAnyExcept((byte)0) < 0; + context.Report( + DiagnosticCodes.PublicKeyRecipientInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"A CMS object in the Recipients of {label} is followed by {recipient.Length - consumed} {(padding ? "zero bytes" : "other bytes")}; they are ignored (but still digested into the key).")); + } + + var cms = new EnvelopedCms(); + cms.Decode(recipient.AsSpan(0, consumed)); + return cms; + } + catch (Exception exception) when (exception is CryptographicException or AsnContentException) + { + context.Report( + DiagnosticCodes.PublicKeyRecipientInvalid, + DiagnosticSeverity.Warning, + $"A string in the Recipients of {label} is not a CMS enveloped-data object (RFC 5652); it is skipped: {exception.Message}"); + return null; + } + } + + /// RFC 5652 §6.2: a recipient is named by issuer and serial number, or by subject key identifier. + private static bool Matches(SubjectIdentifier identifier, X509Certificate2 certificate) + { + switch (identifier.Value) + { + case X509IssuerSerial issuerSerial: + return string.Equals(issuerSerial.IssuerName, certificate.Issuer, StringComparison.OrdinalIgnoreCase) + && SameSerialNumber(issuerSerial.SerialNumber, certificate.SerialNumber); + case string keyIdentifier: + foreach (X509Extension extension in certificate.Extensions) + { + if (extension is X509SubjectKeyIdentifierExtension { SubjectKeyIdentifier: { } own }) + { + return string.Equals(own, keyIdentifier, StringComparison.OrdinalIgnoreCase); + } + } + + return false; + default: + return false; + } + } + + private static bool SameSerialNumber(string left, string right) => + string.Equals(left.TrimStart('0'), right.TrimStart('0'), StringComparison.OrdinalIgnoreCase); + + /// The recipients of every list that decodes, for the error message. + private static SubjectIdentifier[] RecipientIdentifiers(byte[][] recipients) + { + List identifiers = []; + foreach (byte[] recipient in recipients) + { + try + { + AsnDecoder.ReadEncodedValue(recipient, AsnEncodingRules.BER, out _, out _, out int consumed); + var cms = new EnvelopedCms(); + cms.Decode(recipient.AsSpan(0, consumed)); + foreach (RecipientInfo info in cms.RecipientInfos) + { + identifiers.Add(info.RecipientIdentifier); + } + } + catch (Exception exception) when (exception is CryptographicException or AsnContentException) + { + // Already reported while scanning. + } + } + + return [.. identifiers]; + } + + private static CosObject? Get(CosDictionary? dictionary, CosName key) => + dictionary is not null && dictionary.TryGetValue(key, out CosObject? value) ? value : null; + + private static DiagnosticException Fail(SecurityHandlerContext context, string message) + { + var diagnostic = new Diagnostic(DiagnosticCodes.EncryptDictionaryInvalid, DiagnosticSeverity.Error, message); + context.Report(diagnostic.Code, diagnostic.Severity, diagnostic.Message); + return new DiagnosticException(diagnostic); + } + + /// The decrypted enveloped data of the recipient list that names the reader. + private sealed record Envelope(byte[] Content); +} diff --git a/src/Broadside/Security/SecurityHandlerRegistry.cs b/src/Broadside/Security/SecurityHandlerRegistry.cs index 3914b0c8..e064180e 100644 --- a/src/Broadside/Security/SecurityHandlerRegistry.cs +++ b/src/Broadside/Security/SecurityHandlerRegistry.cs @@ -5,8 +5,9 @@ namespace Broadside.Security; /// The security handlers of one engine, by Filter name and by SubFilter format. Immutable once built. /// /// ISO 32000-2 §7.6.2, Table 20: the handler a document's Filter names opens it; when SubFilter is present, any handler -/// implementing that format may. is the default for Standard; a handler registered later -/// for the same name replaces an earlier one. +/// implementing that format may. is the default for Standard and +/// for Adobe.PubSec and the adbe.pkcs7 SubFilters (§7.6.5); a handler registered later for the same name replaces an +/// earlier one. /// internal sealed class SecurityHandlerRegistry { @@ -17,7 +18,7 @@ private SecurityHandlerRegistry() { } - /// Gets the registry of an engine with no handlers of its own: the standard handler only. + /// Gets the registry of an engine with no handlers of its own: the standard and public-key handlers. public static SecurityHandlerRegistry Default { get; } = Create([]); /// Builds a registry from the defaults and the handlers registered on the options, in order. @@ -27,6 +28,7 @@ public static SecurityHandlerRegistry Create(IEnumerable handl { var registry = new SecurityHandlerRegistry(); registry.Add(new StandardSecurityHandler()); + registry.Add(new PublicKeySecurityHandler()); foreach (ISecurityHandler handler in handlers) { registry.Add(handler); diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 2fc9f2d0..4a3ab467 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -36,6 +36,7 @@ internal static class FuzzTargets ["encrypted-document"] = EncryptedDocument, ["decrypt"] = Decrypt, ["mac-token"] = MacToken, + ["public-key"] = PublicKey.Target, }; private static readonly CosName ContentsKey = new("Contents"); @@ -143,6 +144,10 @@ private static string ReadEverything(Func open) { return exception.Reason.ToString(); } + catch (PdfCertificateException exception) + { + return exception.Failure.ToString(); + } using (document) { @@ -439,6 +444,10 @@ private static void ObjectStreamTarget(ReadOnlySpan data) { return null; } + catch (PdfCertificateException) + { + return null; + } } /// @@ -467,6 +476,10 @@ private static void EncryptedDocument(ReadOnlySpan data) { return; } + catch (PdfCertificateException) + { + return; + } using (document) { diff --git a/tests/Broadside.Fuzz/PublicKey.cs b/tests/Broadside.Fuzz/PublicKey.cs new file mode 100644 index 00000000..087e1a84 --- /dev/null +++ b/tests/Broadside.Fuzz/PublicKey.cs @@ -0,0 +1,181 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Security.Cryptography.Pkcs; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Security; + +namespace Broadside.Fuzz; + +/// +/// The public-key target: the input becomes recipient data of a document encrypted for certificate recipients, opened with a +/// fixed certificate that a valid recipient list names. +/// +/// ISO 32000-2 §7.6.5 (Tables 23, 24 and 27). +internal static class PublicKey +{ + private const string Content = "BT /F1 12 Tf 72 700 Td (fuzz) Tj ET"; + private static readonly CosName ContentsKey = new("Contents"); + private static readonly CosName ExtraKey = new("Extra"); + private static readonly byte[] Seed = [.. Enumerable.Range(1, 20).Select(i => (byte)i)]; + + // Immutable after the type initializer; shared by every call. + private static readonly X509Certificate2 Certificate = CreateCertificate(); + private static readonly byte[] ValidRecipients = Envelope([.. Seed, 0xFF, 0xFF, 0xFF, 0xFC]); + private static readonly byte[] FilterRecipients = Envelope(Seed); // A stream crypt filter's: the seed without permissions. + + /// + /// Byte 0 selects the layout: 0 an adbe.pkcs7.s5 dictionary whose DefaultCryptFilter lists the input then the valid + /// list, 1 an adbe.pkcs7.s4 dictionary with the same Recipients, 2 a stream's own crypt filter whose + /// Recipients string is the input (beside another that names the certificate). The document opens, the content stream + /// decrypts to its plaintext (so the input was digested into the key as given), and the extra stream decodes. The only other + /// outcomes are those of an input that forges a recipient list for the certificate: it fails to decrypt, or holds too short a seed. + /// + public static void Target(ReadOnlySpan data) + { + int layout = data.IsEmpty ? 0 : data[0] % 3; + byte[] input = data.IsEmpty ? [] : data[1..].ToArray(); + byte[] file = Build(layout, input); + PdfDocument document; + try + { + document = new PdfEngine().Open(file, new PdfCertificateCredentials(Certificate)); + } + catch (PdfCertificateException exception) when (exception.Failure == PdfCertificateFailure.PrivateKeyUnavailable) + { + return; + } + catch (PdfEncryptionNotSupportedException) + { + return; + } + catch (DiagnosticException exception) when (exception.Diagnostic.Code == "EncryptDictionaryInvalid") + { + return; + } + + using (document) + { + var contents = (CosStream)document.Resolve(document.Pages[0].Dictionary[ContentsKey]); + string text = Encoding.Latin1.GetString(document.DecodeStream(contents).Span); + if (text != Content) + { + throw new InvalidOperationException($"The content stream decrypted to '{text}', not its plaintext: the input changed the file key wrongly."); + } + + _ = document.DecodeStream((CosStream)document.Resolve(document.Catalog[ExtraKey])); + } + } + + private static byte[] Build(int layout, byte[] input) + { + string hexInput = "<" + Convert.ToHexString(input) + ">"; + string hexValid = "<" + Convert.ToHexString(ValidRecipients) + ">"; + string hexFilter = "<" + Convert.ToHexString(FilterRecipients) + ">"; + byte[][] recipients = layout == 2 ? [ValidRecipients] : [input, ValidRecipients]; + bool rc4 = layout == 1; + byte[] key = Key(recipients, rc4 ? 16 : 32); + string encryption = layout switch + { + 1 => $"<< /Filter /Adobe.PubSec /SubFilter /adbe.pkcs7.s4 /V 2 /Length 128 /Recipients [{hexInput} {hexValid}] >>", + 2 => $"<< /Filter /Adobe.PubSec /SubFilter /adbe.pkcs7.s5 /V 5 /CF << /DefaultCryptFilter << /CFM /AESV3 /Recipients [{hexValid}] >> /Own << /CFM /AESV3 /Recipients {hexInput} >> /Other << /CFM /AESV3 /Recipients {hexFilter} >> >> /StmF /DefaultCryptFilter /StrF /DefaultCryptFilter >>", + _ => $"<< /Filter /Adobe.PubSec /SubFilter /adbe.pkcs7.s5 /V 5 /CF << /DefaultCryptFilter << /CFM /AESV3 /Length 256 /Recipients [{hexInput} {hexValid}] >> >> /StmF /DefaultCryptFilter /StrF /DefaultCryptFilter >>", + }; + + byte[] content = Encrypt(rc4, key, 4, Encoding.Latin1.GetBytes(Content)); + byte[] extra = Encoding.Latin1.GetBytes(Content); // Decrypted with whatever key its filter gets; only decoding is checked. + string[] objects = + [ + "<< /Type /Catalog /Pages 2 0 R /Extra 6 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R >>", + Stream(string.Empty, content), + encryption, + Stream(layout == 2 ? "/Filter /Crypt /DecodeParms << /Name /Own >>" : string.Empty, extra), + ]; + + var text = new StringBuilder("%PDF-2.0\n"); + var offsets = new List(); + for (int index = 0; index < objects.Length; index++) + { + offsets.Add(text.Length); + text.Append(CultureInfo.InvariantCulture, $"{index + 1} 0 obj\n{objects[index]}\nendobj\n"); + } + + int xref = text.Length; + text.Append(CultureInfo.InvariantCulture, $"xref\n0 {objects.Length + 1}\n0000000000 65535 f \n"); + foreach (int offset in offsets) + { + text.Append(CultureInfo.InvariantCulture, $"{offset:D10} 00000 n \n"); + } + + string id = "<" + new string('0', 32) + ">"; + text.Append(CultureInfo.InvariantCulture, $"trailer\n<< /Size {objects.Length + 1} /Root 1 0 R /Encrypt 5 0 R /ID [{id} {id}] >>\nstartxref\n{xref}\n%%EOF\n"); + return Encoding.Latin1.GetBytes(text.ToString()); + } + + private static string Stream(string entries, byte[] data) => + string.Create(CultureInfo.InvariantCulture, $"<< {entries} /Length {data.Length} >>\nstream\n{Encoding.Latin1.GetString(data)}\nendstream"); + + /// §7.6.5.3: the digest of the seed and every recipient string. + private static byte[] Key(byte[][] recipients, int length) + { + using var hash = IncrementalHash.CreateHash(length == 32 ? HashAlgorithmName.SHA256 : HashAlgorithmName.SHA1); + hash.AppendData(Seed); + foreach (byte[] recipient in recipients) + { + hash.AppendData(recipient); + } + + return hash.GetHashAndReset()[..length]; + } + + /// AES-256-CBC with the file key (Algorithm 1.A), or RC4 with Algorithm 1's object key. + private static byte[] Encrypt(bool rc4, byte[] key, int objectNumber, byte[] plain) + { + if (!rc4) + { + byte[] iv = new byte[16]; + using var aes = Aes.Create(); + aes.Key = key; + return [.. iv, .. aes.EncryptCbc(plain, iv)]; + } + +#pragma warning disable CA5351 // Algorithm 1 prescribes MD5 (§7.6.3.2). + byte[] objectKey = MD5.HashData([.. key, (byte)objectNumber, 0, 0, 0, 0]); +#pragma warning restore CA5351 + byte[] s = [.. Enumerable.Range(0, 256).Select(i => (byte)i)]; + for (int i = 0, j = 0; i < 256; i++) + { + j = (j + s[i] + objectKey[i % objectKey.Length]) & 0xFF; + (s[i], s[j]) = (s[j], s[i]); + } + + byte[] output = new byte[plain.Length]; + for (int n = 0, i = 0, j = 0; n < plain.Length; n++) + { + i = (i + 1) & 0xFF; + j = (j + s[i]) & 0xFF; + (s[i], s[j]) = (s[j], s[i]); + output[n] = (byte)(plain[n] ^ s[(s[i] + s[j]) & 0xFF]); + } + + return output; + } + + private static byte[] Envelope(byte[] content) + { + var envelope = new EnvelopedCms(new ContentInfo(content)); + envelope.Encrypt(new CmsRecipient(Certificate)); + return envelope.Encode(); + } + + private static X509Certificate2 CreateCertificate() + { + using var rsa = RSA.Create(2048); + var request = new CertificateRequest("CN=Broadside fuzz recipient", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + return request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1)); + } +} diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index c203e85c..1a3db895 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. diff --git a/tests/Broadside.Tests/Security/PublicKeySecurityTests.cs b/tests/Broadside.Tests/Security/PublicKeySecurityTests.cs new file mode 100644 index 00000000..db8c5ff8 --- /dev/null +++ b/tests/Broadside.Tests/Security/PublicKeySecurityTests.cs @@ -0,0 +1,350 @@ +using System.Security.Cryptography.Pkcs; +using System.Security.Cryptography.X509Certificates; +using System.Security.Cryptography.Xml; +using System.Text; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Security; + +namespace Broadside.Tests.Security; + +/// +/// Documents encrypted for certificate recipients (ISO 32000-2 §7.6.5), built in memory with System.Security.Cryptography.Pkcs +/// and opened with a certificate and its private key. +/// +public sealed class PublicKeySecurityTests : IDisposable +{ + private const string S5Aes256 = "<< /Filter /Adobe.PubSec /SubFilter /adbe.pkcs7.s5 /V 5 /CF << /DefaultCryptFilter << /CFM /AESV3 /Length 256 /Recipients {0} >> >> /StmF /DefaultCryptFilter /StrF /DefaultCryptFilter >>"; + private const string RestrictedText = "Only for some recipients"; + + private readonly X509Certificate2 _reader = PublicKeyTestFile.Certificate("Broadside Reader"); + private readonly X509Certificate2 _other = PublicKeyTestFile.Certificate("Broadside Other"); + + public void Dispose() + { + _reader.Dispose(); + _other.Dispose(); + } + + [Fact] + public void A_document_encrypted_for_a_certificate_opens_with_that_certificate_and_its_private_key() + { + byte[] file = new PublicKeyTestFile + { + Encryption = S5Aes256, + Recipients = [PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0xFFFFF0E4, _reader)], + }.Build(); + + using PdfDocument document = new PdfEngine().Open(file, new PdfCertificateCredentials(_reader)); + + Assert.Equal(PublicKeyTestFile.Content, EncryptedCorpusTests.ContentText(document)); + Assert.Equal(PublicKeyTestFile.Title, EncryptedCorpusTests.InfoTitle(document)); + Assert.Equal(new CosName("Adobe.PubSec"), document.Security!.Handler); + Assert.Equal(new CosName("adbe.pkcs7.s5"), document.Security.SubFilter); + Assert.Equal(256, document.Security.KeyLength); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Another_public_key_handler_name_opens_through_its_subfilter() + { + byte[] file = new PublicKeyTestFile + { + Encryption = S5Aes256.Replace("/Adobe.PubSec", "/Adobe.PPKLite", StringComparison.Ordinal), + Recipients = [PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0xFFFFFFFC, _reader)], + }.Build(); + + using PdfDocument document = new PdfEngine().Open(file, new PdfCertificateCredentials(_reader)); + + Assert.Equal(PublicKeyTestFile.Content, EncryptedCorpusTests.ContentText(document)); + Assert.Equal(new CosName("Adobe.PubSec"), document.Security!.Handler); + } + + [Fact] + public void Permissions_are_read_most_significant_byte_first_with_the_meanings_of_revision_3() + { + byte[] file = S5File(PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0xFFFFF0E4, _reader)); + + using PdfDocument document = new PdfEngine().Open(file, new PdfCertificateCredentials(_reader)); + + // 0xE4: bits 3 and 6 (print, annotate), and annotating implies filling forms (Table 24, bit 9). Read least significant byte + // first, the word would set bit 2 and grant everything. + Assert.Equal(PdfAccessLevel.User, document.Security!.Access); + Assert.Equal(PdfPermissions.Print | PdfPermissions.Annotate | PdfPermissions.FillForms, document.Permissions); + Assert.Equal(unchecked((int)0xFFFFF0E4), document.Security.RawPermissions); + } + + [Fact] + public void Permission_bit_2_enables_every_permission() + { + byte[] file = S5File(PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0x00000002, _reader)); + + using PdfDocument document = new PdfEngine().Open(file, new PdfCertificateCredentials(_reader)); + + Assert.Equal(PdfAccessLevel.Owner, document.Security!.Access); + Assert.Equal(PdfPermissions.All, document.Permissions); + } + + [Theory] + [InlineData("adbe.pkcs7.s3", PdfPermissions.Print | PdfPermissions.Annotate | PdfPermissions.FillForms | PdfPermissions.PrintHighQuality)] + [InlineData("adbe.pkcs7.s4", PdfPermissions.Print | PdfPermissions.Annotate | PdfPermissions.FillForms | PdfPermissions.Assemble | PdfPermissions.PrintHighQuality)] + public void An_s3_document_has_the_permissions_of_revision_2_and_an_s4_document_those_of_revision_3(string subFilter, PdfPermissions expected) + { + // Bits 3, 6, 9, 11 and 12. Revision 2 knows bits 3 to 6 only: assembling follows modifying (clear), high-quality printing + // follows printing. + byte[] file = new PublicKeyTestFile + { + Encryption = $"<< /Filter /Adobe.PubSec /SubFilter /{subFilter} /V 2 /Length 128 /Recipients {{0}} >>", + Recipients = [PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0x00000D24, _reader)], + Cipher = TestCipher.Rc4, + KeyLength = 16, + }.Build(); + + using PdfDocument document = new PdfEngine().Open(file, new PdfCertificateCredentials(_reader)); + + Assert.Equal(expected, document.Permissions); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void An_s4_document_encrypted_with_rc4_opens_with_a_128_bit_sha_1_key() + { + byte[] file = new PublicKeyTestFile + { + Encryption = "<< /Filter /Adobe.PubSec /SubFilter /adbe.pkcs7.s4 /V 2 /Length 128 /Recipients {0} >>", + Recipients = [PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0xFFFFFFFC, _reader)], + Cipher = TestCipher.Rc4, + KeyLength = 16, + }.Build(); + + using PdfDocument document = new PdfEngine().Open(file, new PdfCertificateCredentials(_reader)); + + Assert.Equal(PublicKeyTestFile.Content, EncryptedCorpusTests.ContentText(document)); + Assert.Equal(PublicKeyTestFile.Title, EncryptedCorpusTests.InfoTitle(document)); + Assert.Equal(new CosName("adbe.pkcs7.s4"), document.Security!.SubFilter); + Assert.Equal(2, document.Security.Version); + Assert.Equal(128, document.Security.KeyLength); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void An_s5_document_with_an_aes_128_crypt_filter_opens_with_a_128_bit_sha_1_key() + { + byte[] file = new PublicKeyTestFile + { + Encryption = "<< /Filter /Adobe.PubSec /SubFilter /adbe.pkcs7.s5 /V 4 /CF << /DefaultCryptFilter << /CFM /AESV2 /Length 128 /Recipients {0} >> >> /StmF /DefaultCryptFilter /StrF /DefaultCryptFilter >>", + Recipients = [PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0xFFFFFFFC, _reader)], + Cipher = TestCipher.AesV2, + KeyLength = 16, + }.Build(); + + using PdfDocument document = new PdfEngine().Open(file, new PdfCertificateCredentials(_reader)); + + Assert.Equal(PublicKeyTestFile.Content, EncryptedCorpusTests.ContentText(document)); + Assert.Equal(PublicKeyTestFile.Title, EncryptedCorpusTests.InfoTitle(document)); + Assert.Equal(128, document.Security!.KeyLength); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void The_key_digests_every_recipient_list_and_the_permissions_come_from_the_list_that_names_the_reader() + { + byte[] seed = [.. Enumerable.Repeat((byte)0x5A, 20)]; + byte[] file = new PublicKeyTestFile + { + Encryption = S5Aes256, + Seed = seed, + Recipients = + [ + PublicKeyTestFile.Envelope(seed, 0xFFFFFFFE, _other), + PublicKeyTestFile.Envelope(seed, 0xFFFFF0C4, _reader), + ], + }.Build(); + + using PdfDocument document = new PdfEngine().Open(file, new PdfCertificateCredentials(_reader)); + + Assert.Equal(PublicKeyTestFile.Content, EncryptedCorpusTests.ContentText(document)); + Assert.Equal(PdfPermissions.Print, document.Permissions); + } + + [Fact] + public void A_reader_in_two_lists_has_the_permissions_of_the_first() + { + byte[] file = S5File( + PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0xFFFFF0D4, _other, _reader), + PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0xFFFFFFFE, _reader)); + + using PdfDocument document = new PdfEngine().Open(file, new PdfCertificateCredentials(_reader)); + + Assert.Equal(PublicKeyTestFile.Content, EncryptedCorpusTests.ContentText(document)); + Assert.Equal(PdfPermissions.Print | PdfPermissions.Extract, document.Permissions); + } + + [Fact] + public void A_recipient_named_by_subject_key_identifier_is_found_among_several_certificates() + { + byte[] file = S5File(PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0xFFFFFFFC, SubjectIdentifierType.SubjectKeyIdentifier, _reader)); + using X509Certificate2 publicOnly = X509CertificateLoader.LoadCertificate(_other.RawData); + + using PdfDocument document = new PdfEngine().Open(file, new PdfCertificateCredentials(new X509Certificate2Collection(new[] { publicOnly, _reader }))); + + Assert.Equal(PublicKeyTestFile.Content, EncryptedCorpusTests.ContentText(document)); + } + + [Fact] + public void A_certificate_that_is_not_a_recipient_is_reported_with_the_recipients() + { + byte[] file = S5File(PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0xFFFFFFFC, _reader)); + + var exception = Assert.Throws(() => new PdfEngine().Open(file, new PdfCertificateCredentials(_other))); + + Assert.Equal(PdfCertificateFailure.NoMatchingRecipient, exception.Failure); + SubjectIdentifier recipient = Assert.Single(exception.Recipients); + var issuerSerial = Assert.IsType(recipient.Value); + Assert.Equal(_reader.SerialNumber, issuerSerial.SerialNumber, ignoreCase: true); + Assert.Contains("CN=Broadside Reader", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public void A_document_encrypted_for_certificates_needs_a_certificate() + { + byte[] file = S5File(PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0xFFFFFFFC, _reader)); + + var withoutCredentials = Assert.Throws(() => PdfDocument.Open(file)); + var withPassword = Assert.Throws(() => new PdfEngine().Open(file, new PdfPassword("secret"))); + + Assert.Equal(PdfCertificateFailure.Required, withoutCredentials.Failure); + Assert.Equal(PdfCertificateFailure.Required, withPassword.Failure); + Assert.Single(withoutCredentials.Recipients); + } + + [Fact] + public void A_recipient_certificate_without_its_private_key_cannot_open_the_document() + { + byte[] file = S5File(PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0xFFFFFFFC, _reader)); + using X509Certificate2 publicOnly = X509CertificateLoader.LoadCertificate(_reader.RawData); + + var exception = Assert.Throws(() => new PdfEngine().Open(file, new PdfCertificateCredentials(publicOnly))); + + Assert.Equal(PdfCertificateFailure.PrivateKeyUnavailable, exception.Failure); + } + + [Fact] + public void Metadata_left_in_plaintext_by_the_crypt_filter_adds_the_marker_to_the_key() + { + const string xmp = ""; + byte[] file = new PublicKeyTestFile + { + Encryption = "<< /Filter /Adobe.PubSec /SubFilter /adbe.pkcs7.s5 /V 5 /CF << /DefaultCryptFilter << /CFM /AESV3 /Length 256 /EncryptMetadata false /Recipients {0} >> >> /StmF /DefaultCryptFilter /StrF /DefaultCryptFilter >>", + Recipients = [PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0xFFFFFFFC, _reader)], + MetadataInPlaintext = true, + CatalogEntries = "/Metadata 7 0 R", + ExtraObjects = [(_, _) => PublicKeyTestFile.Stream("/Type /Metadata /Subtype /XML", Encoding.UTF8.GetBytes(xmp))], + }.Build(); + + using PdfDocument document = new PdfEngine().Open(file, new PdfCertificateCredentials(_reader)); + var metadata = (CosStream)document.Resolve(document.Catalog[new CosName("Metadata")]); + + Assert.Equal(PublicKeyTestFile.Content, EncryptedCorpusTests.ContentText(document)); + Assert.False(document.Security!.EncryptsMetadata); + Assert.Equal(xmp, Encoding.UTF8.GetString(document.DecodeStream(metadata).Span)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_stream_whose_crypt_filter_has_its_own_recipients_decrypts_with_that_filter_s_key() + { + byte[] seed = [.. Enumerable.Repeat((byte)0xC3, 20)]; + byte[] restricted = PublicKeyTestFile.Envelope(seed, permissions: null, _other, _reader); + byte[] key = PublicKeyTestFile.DeriveKey(seed, [restricted], metadataInPlaintext: false, keyLength: 32); + + using PdfDocument document = new PdfEngine().Open(RestrictedFile(restricted, key), new PdfCertificateCredentials(_reader)); + + Assert.Equal(PublicKeyTestFile.Content, EncryptedCorpusTests.ContentText(document)); + Assert.Equal(RestrictedText, Encoding.Latin1.GetString(document.DecodeStream(RestrictedStream(document)).Span)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_stream_whose_crypt_filter_does_not_name_the_reader_stays_encrypted() + { + byte[] seed = [.. Enumerable.Repeat((byte)0xC3, 20)]; + byte[] restricted = PublicKeyTestFile.Envelope(seed, permissions: null, _other); + byte[] key = PublicKeyTestFile.DeriveKey(seed, [restricted], metadataInPlaintext: false, keyLength: 32); + + using PdfDocument document = new PdfEngine().Open(RestrictedFile(restricted, key), new PdfCertificateCredentials(_reader)); + CosStream stream = RestrictedStream(document); + + Assert.Equal(PublicKeyTestFile.Content, EncryptedCorpusTests.ContentText(document)); + Assert.True(document.DecodeStream(stream).Span.SequenceEqual(stream.EncodedData.Span)); + Assert.Contains(document.Diagnostics, d => d.Code == "CryptFilterNotAuthorized"); + Assert.Contains(document.Diagnostics, d => d.Code == "CryptFilterUnsupported"); + } + + [Fact] + public void A_recipient_string_padded_with_zeros_is_read_with_a_diagnostic_and_digested_whole() + { + byte[] padded = [.. PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0xFFFFFFFC, _reader), 0, 0, 0, 0]; + + using PdfDocument document = new PdfEngine().Open(S5File(padded), new PdfCertificateCredentials(_reader)); + + Assert.Equal(PublicKeyTestFile.Content, EncryptedCorpusTests.ContentText(document)); + Assert.Equal("PublicKeyRecipientInvalid", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_recipient_string_that_is_not_cms_is_skipped_with_a_diagnostic() + { + byte[] file = S5File([0x30, 0x03, 0x02, 0x01, 0x00], PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0xFFFFFFFC, _reader)); + + using PdfDocument document = new PdfEngine().Open(file, new PdfCertificateCredentials(_reader)); + + Assert.Equal(PublicKeyTestFile.Content, EncryptedCorpusTests.ContentText(document)); + Assert.Equal("PublicKeyRecipientInvalid", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_well_formed_document_opens_in_strict_mode() + { + byte[] file = S5File(PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0xFFFFFFFC, _reader)); + + using PdfDocument document = new PdfEngine(new PdfOptions().UseStrict()).Open(file, new PdfCertificateCredentials(_reader)); + + Assert.Equal(PublicKeyTestFile.Content, EncryptedCorpusTests.ContentText(document)); + } + + [Fact] + public void A_document_with_no_recipients_cannot_be_authenticated() + { + byte[] file = new PublicKeyTestFile + { + Encryption = "<< /Filter /Adobe.PubSec /SubFilter /adbe.pkcs7.s5 /V 5 /CF << /DefaultCryptFilter << /CFM /AESV3 /Length 256 >> >> /StmF /DefaultCryptFilter /StrF /DefaultCryptFilter /Unused {0} >>", + Recipients = [PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0xFFFFFFFC, _reader)], + }.Build(); + + var exception = Assert.Throws(() => new PdfEngine().Open(file, new PdfCertificateCredentials(_reader))); + + Assert.Equal("EncryptDictionaryInvalid", exception.Diagnostic.Code); + } + + private static CosStream RestrictedStream(PdfDocument document) => + Assert.IsType(document.Resolve(document.Catalog[new CosName("Restricted")])); + + private static byte[] S5File(params byte[][] recipients) => + new PublicKeyTestFile { Encryption = S5Aes256, Recipients = recipients }.Build(); + + /// Object 7 names the crypt filter /Restricted, whose recipients (one CMS string, Table 27) have a seed of their own. + private byte[] RestrictedFile(byte[] restricted, byte[] restrictedKey) => + new PublicKeyTestFile + { + Encryption = "<< /Filter /Adobe.PubSec /SubFilter /adbe.pkcs7.s5 /V 5 /CF << /DefaultCryptFilter << /CFM /AESV3 /Length 256 /Recipients {0} >> /Restricted << /CFM /AESV3 /Length 256 /Recipients " + PublicKeyTestFile.Hex(restricted) + " >> >> /StmF /DefaultCryptFilter /StrF /DefaultCryptFilter >>", + Recipients = [PublicKeyTestFile.Envelope(PublicKeyTestFile.DefaultSeed, 0xFFFFFFFC, _reader)], + CatalogEntries = "/Restricted 7 0 R", + ExtraObjects = + [ + (_, number) => PublicKeyTestFile.Stream( + "/Filter /Crypt /DecodeParms << /Type /CryptFilterDecodeParms /Name /Restricted >>", + PublicKeyTestFile.Encrypt(TestCipher.AesV3, restrictedKey, number, Encoding.Latin1.GetBytes(RestrictedText))), + ], + }.Build(); +} diff --git a/tests/Broadside.Tests/Security/PublicKeyTestFile.cs b/tests/Broadside.Tests/Security/PublicKeyTestFile.cs new file mode 100644 index 00000000..17144d22 --- /dev/null +++ b/tests/Broadside.Tests/Security/PublicKeyTestFile.cs @@ -0,0 +1,210 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Security.Cryptography.Pkcs; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using Broadside.Tests.Document; + +namespace Broadside.Tests.Security; + +/// How a test file's strings and streams are encrypted with the file encryption key (ISO 32000-2 §7.6.3). +internal enum TestCipher +{ + /// Algorithm 1 with RC4. + Rc4, + + /// Algorithm 1 with AES-128-CBC ("sAlT"). + AesV2, + + /// Algorithm 1.A, AES-256-CBC with the file key. + AesV3, +} + +/// +/// Builds a document encrypted for certificate recipients (ISO 32000-2 §7.6.5) in memory, independently of the engine: the +/// enveloped data are made with , the file key is the digest §7.6.5.3 describes, and the content stream +/// and the Info title are encrypted with the BCL's AES and a local RC4 the way §7.6.3 describes. +/// +/// +/// Objects: 1 catalog, 2 page tree, 3 page, 4 content stream, 5 Info, 6 encryption dictionary, then +/// from 7 on, each built with the file key and its object number. +/// +internal sealed class PublicKeyTestFile +{ + /// The page's content, in plaintext. + public const string Content = "BT /F1 24 Tf 72 700 Td (Public key) Tj ET"; + + /// The Info dictionary's title, in plaintext. + public const string Title = "Certificate encrypted"; + + /// Gets the encryption dictionary; {0} is replaced by the Recipients array's strings. + public required string Encryption { get; init; } + + /// Gets the Recipients strings, each a DER-encoded CMS enveloped-data object. + public required byte[][] Recipients { get; init; } + + /// Gets how the content stream and the title are encrypted. + public TestCipher Cipher { get; init; } = TestCipher.AesV3; + + /// Gets the length of the file encryption key, in bytes. + public int KeyLength { get; init; } = 32; + + /// Gets the seed the recipients' enveloped data carry. + public byte[] Seed { get; init; } = DefaultSeed; + + /// Gets a value indicating whether the key digest ends with four 0xFF bytes (metadata left in plaintext). + public bool MetadataInPlaintext { get; init; } + + /// Gets extra catalog entries. + public string CatalogEntries { get; init; } = string.Empty; + + /// Gets objects 7 onward, given the file key and their object number. + public IReadOnlyList> ExtraObjects { get; init; } = []; + + /// Gets the seed most tests use: bytes 1 to 20. + public static byte[] DefaultSeed { get; } = [.. Enumerable.Range(1, 20).Select(i => (byte)i)]; + + /// Gets the file encryption key §7.6.5.3 derives: SHA-1 or SHA-256 of the seed, every recipient string, and 0xFF x 4. + public byte[] FileKey => DeriveKey(Seed, Recipients, MetadataInPlaintext, KeyLength); + + /// Creates a self-signed RSA certificate with its private key and a subject key identifier. + public static X509Certificate2 Certificate(string name) + { + using var rsa = RSA.Create(2048); + var request = new CertificateRequest($"CN={name}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, critical: false)); + DateTimeOffset now = DateTimeOffset.UtcNow; + return request.CreateSelfSigned(now.AddDays(-1), now.AddDays(1)); + } + + /// The enveloped data of §7.6.5.3: the seed, then the permissions most significant byte first (unless null). + public static byte[] Envelope(byte[] seed, uint? permissions, params X509Certificate2[] recipients) => + Envelope(seed, permissions, SubjectIdentifierType.IssuerAndSerialNumber, recipients); + + /// The enveloped data of §7.6.5.3 addressed to the recipients by the given kind of identifier. + public static byte[] Envelope(byte[] seed, uint? permissions, SubjectIdentifierType identifier, params X509Certificate2[] recipients) + { + byte[] content = seed; + if (permissions is { } value) + { + content = [.. seed, (byte)(value >> 24), (byte)(value >> 16), (byte)(value >> 8), (byte)value]; + } + + var envelope = new EnvelopedCms(new ContentInfo(content)); + var collection = new CmsRecipientCollection(); + foreach (X509Certificate2 recipient in recipients) + { + collection.Add(new CmsRecipient(identifier, recipient)); + } + + envelope.Encrypt(collection); + return envelope.Encode(); + } + + /// §7.6.5.3 steps a-d. + public static byte[] DeriveKey(byte[] seed, IEnumerable recipients, bool metadataInPlaintext, int keyLength) + { + using var hash = IncrementalHash.CreateHash(keyLength == 32 ? HashAlgorithmName.SHA256 : HashAlgorithmName.SHA1); + hash.AppendData(seed); + foreach (byte[] recipient in recipients) + { + hash.AppendData(recipient); + } + + if (metadataInPlaintext) + { + hash.AppendData([0xFF, 0xFF, 0xFF, 0xFF]); + } + + return hash.GetHashAndReset()[..keyLength]; + } + + /// A PDF array of hexadecimal strings. + public static string HexArray(IEnumerable strings) => "[" + string.Join(' ', strings.Select(Hex)) + "]"; + + /// A PDF hexadecimal string. + public static string Hex(byte[] bytes) => "<" + Convert.ToHexString(bytes) + ">"; + + /// A stream object whose data are , written byte for byte. + public static string Stream(string dictionaryEntries, byte[] data) => + string.Create(CultureInfo.InvariantCulture, $"<< {dictionaryEntries} /Length {data.Length} >>\nstream\n{Encoding.Latin1.GetString(data)}\nendstream"); + + /// Encrypts data for an object (§7.6.3, Algorithms 1 and 1.A) with a fixed IV. + public static byte[] Encrypt(TestCipher cipher, byte[] fileKey, int objectNumber, byte[] plain) + { + byte[] iv = [.. Enumerable.Range(0, 16).Select(i => (byte)(0xA0 + i))]; + switch (cipher) + { + case TestCipher.Rc4: + return Rc4(ObjectKey(fileKey, objectNumber, aes: false), plain); + case TestCipher.AesV2: + { + using var aes = Aes.Create(); + aes.Key = ObjectKey(fileKey, objectNumber, aes: true); + return [.. iv, .. aes.EncryptCbc(plain, iv)]; + } + + default: + { + using var aes = Aes.Create(); + aes.Key = fileKey; + return [.. iv, .. aes.EncryptCbc(plain, iv)]; + } + } + } + + /// Writes the file. + public byte[] Build() + { + byte[] key = FileKey; + byte[] content = Encrypt(Cipher, key, 4, Encoding.Latin1.GetBytes(Content)); + byte[] title = Encrypt(Cipher, key, 5, Encoding.Latin1.GetBytes(Title)); + string encryption = Encryption.Replace("{0}", HexArray(Recipients), StringComparison.Ordinal); + List objects = + [ + $"<< /Type /Catalog /Pages 2 0 R {CatalogEntries} >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> /Contents 4 0 R >>", + Stream(string.Empty, content), + $"<< /Title {Hex(title)} >>", + encryption, + ]; + for (int index = 0; index < ExtraObjects.Count; index++) + { + objects.Add(ExtraObjects[index](key, objects.Count + 1)); + } + + string id = "<" + new string('0', 32) + ">"; + return new TestPdf { Header = "%PDF-2.0", TrailerEntries = $"/Info 5 0 R /Encrypt 6 0 R /ID [{id} {id}]" }.Build([.. objects]); + } + + /// Algorithm 1 steps a-d. + private static byte[] ObjectKey(byte[] fileKey, int objectNumber, bool aes) + { + byte[] input = [.. fileKey, (byte)objectNumber, (byte)(objectNumber >> 8), (byte)(objectNumber >> 16), 0, 0, .. aes ? "sAlT"u8.ToArray() : []]; +#pragma warning disable CA5351 // Algorithm 1 prescribes MD5 (§7.6.3.2). + return MD5.HashData(input)[..Math.Min(fileKey.Length + 5, 16)]; +#pragma warning restore CA5351 + } + + private static byte[] Rc4(byte[] key, byte[] data) + { + byte[] s = [.. Enumerable.Range(0, 256).Select(i => (byte)i)]; + for (int i = 0, j = 0; i < 256; i++) + { + j = (j + s[i] + key[i % key.Length]) & 0xFF; + (s[i], s[j]) = (s[j], s[i]); + } + + byte[] output = new byte[data.Length]; + for (int n = 0, i = 0, j = 0; n < data.Length; n++) + { + i = (i + 1) & 0xFF; + j = (j + s[i]) & 0xFF; + (s[i], s[j]) = (s[j], s[i]); + output[n] = (byte)(data[n] ^ s[(s[i] + s[j]) & 0xFF]); + } + + return output; + } +} From 16b34640e02ec43182113dd19e3e3e54417fd8af Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 15:44:33 -0500 Subject: [PATCH 016/152] test(cos): real-world corpus gate and veraPDF agreement (#47) Every PDF of the pdf.js, PDFBox, qpdf and PDFium corpora (and the PDF 2.0 examples), 2,612 files, opens in lenient mode and walks completely (pages, every object, every stream decoded) with no crash and no hang (30 s limit per file). Password, certificate and unsupported-encryption outcomes are counted per corpus; 17 files every reader fails on are listed with their reasons. The per-corpus counts and diagnostic histograms are a Verify snapshot. Strict mode is compared with veraPDF's verdicts on the 171 syntactic PDF/A file-structure tests; all 118 disagreements are triaged per rule (104 PDF/A-only, 14 known gaps) and listed in a snapshot. Corpus tests skip when the corpora are not fetched. Fixes the gate found: - Standard security: the empty string is tried as the owner password (pdf.js pr6531_2.pdf) and a V 2/3 dictionary without Length is retried at 128 bits with EncryptionKeyLengthInvalid (qpdf bad-encryption-length.pdf); new corpus files encrypted-empty-owner-password.pdf and encrypted-rc4-length-missing.pdf. - Strict mode too strict: ASCIIHexDecode data without > is not a deviation (7.4.2); external stream file data (F) is Information, not Error. - Strict mode too lenient: HeaderInvalid (7.5.2 single EOL after the version), XrefSubsectionHeaderInvalid (7.5.4), EndOfFileMarkerNotLast and TrailerIdMissing for PDF 2.0 (7.5.5 Table 15); pdf20-header.pdf now has an ID. Adds DocumentWalker and RealWorldCorpus to Broadside.TestSupport (the walk is meant to be shared with the #48 fuzz target and benchmark) and a corpus locator that reuses the main checkout's corpus/ from a worktree or BROADSIDE_CORPUS_DIR. Conformance rows 7.2.2-7.6.4 updated. Co-Authored-By: Claude Opus 5.5 --- docs/conformance/iso-32000-2.md | 20 +- src/Broadside/Filters/AsciiHexDecodeFilter.cs | 11 +- src/Broadside/Filters/StreamDecoder.cs | 2 +- src/Broadside/Parsing/CrossReferenceReader.cs | 41 +++- src/Broadside/Parsing/DiagnosticCodes.cs | 4 + src/Broadside/Parsing/FileHeader.cs | 14 +- src/Broadside/Parsing/XrefTableReader.cs | 39 ++- src/Broadside/PdfDocument.cs | 16 +- .../Security/StandardSecurityHandler.cs | 43 +++- .../Broadside.TestSupport.csproj | 1 + tests/Broadside.TestSupport/Corpus.cs | 2 + tests/Broadside.TestSupport/CorpusLocator.cs | 31 +++ tests/Broadside.TestSupport/DocumentWalker.cs | 152 ++++++++++++ .../Broadside.TestSupport/RealWorldCorpus.cs | 197 +++++++++++++++ .../Document/ConcurrencyTests.cs | 15 +- .../Document/FileLayoutTests.cs | 172 +++++++++++++ .../Document/RealWorldCorpusTests.cs | 153 ++++++++++++ ...histograms_match_the_snapshot.verified.txt | 225 ++++++++++++++++++ ..._triaged_rule_still_disagrees.verified.txt | 119 +++++++++ .../Document/VeraPdfAgreementTests.cs | 222 +++++++++++++++++ .../Broadside.Tests/Document/VersionTests.cs | 7 +- .../Filters/AsciiFilterTests.cs | 6 +- .../Filters/FilterPipelineTests.cs | 15 ++ .../Security/IntegrityTests.cs | 4 +- .../Broadside.Tests/Security/PasswordTests.cs | 44 ++++ ...pus_file_names_match_snapshot.verified.txt | 2 + tests/Corpus/README.md | 4 +- .../Corpus/encrypted-empty-owner-password.pdf | Bin 0 -> 1317 bytes tests/Corpus/encrypted-rc4-length-missing.pdf | Bin 0 -> 942 bytes tests/Corpus/generate.py | 34 ++- tests/Corpus/pdf20-header.pdf | Bin 360 -> 436 bytes tests/README.md | 13 +- 32 files changed, 1567 insertions(+), 41 deletions(-) create mode 100644 tests/Broadside.TestSupport/DocumentWalker.cs create mode 100644 tests/Broadside.TestSupport/RealWorldCorpus.cs create mode 100644 tests/Broadside.Tests/Document/FileLayoutTests.cs create mode 100644 tests/Broadside.Tests/Document/RealWorldCorpusTests.cs create mode 100644 tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt create mode 100644 tests/Broadside.Tests/Document/Snapshots/VeraPdfAgreementTests.Every_disagreement_matches_the_snapshot_and_every_triaged_rule_still_disagrees.verified.txt create mode 100644 tests/Broadside.Tests/Document/VeraPdfAgreementTests.cs create mode 100644 tests/Corpus/encrypted-empty-owner-password.pdf create mode 100644 tests/Corpus/encrypted-rc4-length-missing.pdf diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index 7358644e..22181c28 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -6,21 +6,21 @@ Clause numbers at the second level; split rows to the third level as clauses are |---|---|---|---|---|---| | 7.1 | Syntax: General | not started | | | | | 7.2.1 | General | n/a | | | Introductory text | -| 7.2.2 | Representation | done | `CosLexer`, `CosObject` | `Broadside.Tests.Objects.StringAndNameParsingTests.Literal_strings_may_hold_any_byte`, `Broadside.Tests.Objects.ContainerParsingTests.Stream_data_is_binary_and_may_contain_the_endstream_keyword_when_length_says_so`, `Broadside.Tests.Objects.LexerAllocationTests` | Lexer is internal and allocation-free (`bench/Broadside.Benchmarks/LexerBenchmarks.cs`); fuzz targets `lexer`, `object-parser` | +| 7.2.2 | Representation | done | `CosLexer`, `CosObject` | `Broadside.Tests.Objects.StringAndNameParsingTests.Literal_strings_may_hold_any_byte`, `Broadside.Tests.Objects.ContainerParsingTests.Stream_data_is_binary_and_may_contain_the_endstream_keyword_when_length_says_so`, `Broadside.Tests.Objects.LexerAllocationTests`, `Broadside.Tests.Document.RealWorldCorpusTests.A_real_world_file_opens_and_walks_leniently_without_an_exception` | Lexer is internal and allocation-free (`bench/Broadside.Benchmarks/LexerBenchmarks.cs`); fuzz targets `lexer`, `object-parser`. Real-world gate (#47): every pdf.js, PDFBox, qpdf and PDFium corpus file lexes without an exception. | | 7.2.3 | Character set | done | `CosLexer` | `Broadside.Tests.Objects.ScalarParsingTests.Whitespace_and_comments_around_an_object_are_ignored`, `Broadside.Tests.Objects.ContainerParsingTests.Arrays_nest_hold_references_and_keep_null_elements`, `Broadside.Tests.Objects.SerializationTests.Writes_canonical_syntax` | | | 7.2.4 | Comments | done | `CosLexer` | `Broadside.Tests.Objects.ScalarParsingTests.Whitespace_and_comments_around_an_object_are_ignored`, `Broadside.Tests.Objects.ScalarParsingTests.Parses_indirect_references` | Comments are skipped, not preserved (allowed by the clause) | -| 7.3.1 | General | done | `CosObject` | `Broadside.Tests.Objects.CorpusObjectTests`, `Broadside.Tests.Objects.SerializationTests.A_written_object_parses_back_to_an_equal_object` | Closed `CosObject` hierarchy; equality rules on `CosObject.DeepEquals`; dirty tracking on `CosObject.IsDirty` (`Broadside.Tests.Objects.DirtyTrackingTests`) | +| 7.3.1 | General | done | `CosObject` | `Broadside.Tests.Objects.CorpusObjectTests`, `Broadside.Tests.Objects.SerializationTests.A_written_object_parses_back_to_an_equal_object`, `Broadside.Tests.Document.RealWorldCorpusTests.A_real_world_file_opens_and_walks_leniently_without_an_exception`, `Broadside.Tests.Document.VeraPdfAgreementTests.Strict_mode_agrees_with_veraPDF_or_the_disagreement_is_triaged` | Closed `CosObject` hierarchy; equality rules on `CosObject.DeepEquals`; dirty tracking on `CosObject.IsDirty` (`Broadside.Tests.Objects.DirtyTrackingTests`). Real-world gate (#47): the walk resolves every object of every corpus file; strict mode vs veraPDF triaged per rule (`VeraPdfAgreementTests` snapshot). | | 7.3.2 | Boolean objects | done | `CosBoolean` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_booleans` | | | 7.3.3 | Numeric objects | done | `CosNumber`, `CosInteger`, `CosReal` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_integers_from_the_spec_examples`, `Broadside.Tests.Objects.ScalarParsingTests.Parses_reals_from_the_spec_examples`, `Broadside.Tests.Objects.ScalarParsingTests.Integer_too_large_for_64_bits_is_read_as_a_real`, `Broadside.Tests.Objects.SerializationTests.Reals_round_trip_exactly_without_exponent_notation` | Integers are 64-bit; a larger integer literal reads as a real (Annex C); reals are written without exponent | -| 7.3.4 | String objects | done | `CosString` | `Broadside.Tests.Objects.StringAndNameParsingTests.Literal_strings_from_example_1_keep_balanced_parentheses`, `Broadside.Tests.Objects.StringAndNameParsingTests.Literal_strings_decode_every_escape_in_table_3`, `Broadside.Tests.Objects.StringAndNameParsingTests.Octal_escapes_take_one_to_three_digits_and_ignore_overflow`, `Broadside.Tests.Objects.StringAndNameParsingTests.Hexadecimal_strings_ignore_white_space_and_pad_an_odd_digit_with_zero`, `Broadside.Tests.Objects.SerializationTests.Every_byte_value_survives_a_round_trip_in_strings_and_names` | 7.3.4.1 to 7.3.4.3 | +| 7.3.4 | String objects | done | `CosString` | `Broadside.Tests.Objects.StringAndNameParsingTests.Literal_strings_from_example_1_keep_balanced_parentheses`, `Broadside.Tests.Objects.StringAndNameParsingTests.Literal_strings_decode_every_escape_in_table_3`, `Broadside.Tests.Objects.StringAndNameParsingTests.Octal_escapes_take_one_to_three_digits_and_ignore_overflow`, `Broadside.Tests.Objects.StringAndNameParsingTests.Hexadecimal_strings_ignore_white_space_and_pad_an_odd_digit_with_zero`, `Broadside.Tests.Objects.SerializationTests.Every_byte_value_survives_a_round_trip_in_strings_and_names`, `Broadside.Tests.Document.VeraPdfAgreementTests.Strict_mode_agrees_with_veraPDF_or_the_disagreement_is_triaged` | 7.3.4.1 to 7.3.4.3. Odd-length hex strings are legal (padded with 0), not a deviation (veraPDF PDF/A rule 6.1.6 disagrees by scope); a non-hex digit inside a content stream is found from Phase 2 (content interpreter). | | 7.3.5 | Name objects | done | `CosName` | `Broadside.Tests.Objects.StringAndNameParsingTests.Names_from_table_4_expand_number_sign_escapes`, `Broadside.Tests.Objects.StringAndNameParsingTests.Names_are_equal_when_their_expanded_bytes_are_equal`, `Broadside.Tests.Objects.SerializationTests.Names_escape_delimiters_white_space_number_signs_and_non_ascii_bytes` | | | 7.3.6 | Array objects | done | `CosArray` | `Broadside.Tests.Objects.ContainerParsingTests.Parses_the_array_example`, `Broadside.Tests.Objects.ContainerParsingTests.Arrays_nest_hold_references_and_keep_null_elements` | | | 7.3.7 | Dictionary objects | done | `CosDictionary` | `Broadside.Tests.Objects.ContainerParsingTests.Parses_the_dictionary_example`, `Broadside.Tests.Objects.ContainerParsingTests.A_null_valued_entry_is_the_same_as_an_absent_one` | Null-valued entries are never stored | -| 7.3.8 | Stream objects | partial | `CosStream`, `DefaultStreamExtentResolver`, `FileWriter` | `Broadside.Tests.Objects.ContainerParsingTests.A_stream_takes_its_data_from_its_length_or_from_endstream`, `Broadside.Tests.Objects.ContainerParsingTests.Streams_with_a_wrong_length_or_no_endstream_are_rejected`, `Broadside.Tests.Objects.CorpusObjectTests.The_metadata_stream_of_metadata_xmp_pdf_holds_its_declared_length`, `Broadside.Tests.Document.BrokenCorpusTests.A_wrong_stream_length_is_recovered_from_endstream_without_changing_the_length_entry`, `Broadside.Tests.Document.RepairTests.Stream_lengths_that_refer_to_each_other_are_recovered_from_endstream`, `Broadside.Tests.Document.RepairTests.A_stream_without_endstream_ends_at_endobj`, `Broadside.Tests.Writing.SaveTests.A_repaired_file_is_saved_with_a_new_cross_reference_section_and_reopens_without_warnings_or_errors` | Extent from a direct or indirect Length (`Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length`), else from endstream; filters decode through `PdfDocument.DecodeStream` (7.4) with DL as a capacity hint; external stream files (F, FFilter, FDecodeParms) are not read: `StreamExternalFileUnsupported` and the embedded bytes decode instead (`Broadside.Tests.Filters.FilterPipelineTests.Data_in_an_external_file_is_not_read_and_the_stream_bytes_decode_instead_with_a_diagnostic`); a wrong, missing or unresolvable Length is recovered from endstream without the end-of-line before it (StreamLengthInvalid; the Length entry is not changed), lengths that refer to each other are unknown rather than looping, and a stream without endstream ends at endobj (EndstreamMissing); written as `stream` LF, the data, LF `endstream` with a direct Length equal to the data; a stream read with a wrong Length is re-serialized with the right one, never copied (#44) | +| 7.3.8 | Stream objects | partial | `CosStream`, `DefaultStreamExtentResolver`, `FileWriter` | `Broadside.Tests.Objects.ContainerParsingTests.A_stream_takes_its_data_from_its_length_or_from_endstream`, `Broadside.Tests.Objects.ContainerParsingTests.Streams_with_a_wrong_length_or_no_endstream_are_rejected`, `Broadside.Tests.Objects.CorpusObjectTests.The_metadata_stream_of_metadata_xmp_pdf_holds_its_declared_length`, `Broadside.Tests.Document.BrokenCorpusTests.A_wrong_stream_length_is_recovered_from_endstream_without_changing_the_length_entry`, `Broadside.Tests.Document.RepairTests.Stream_lengths_that_refer_to_each_other_are_recovered_from_endstream`, `Broadside.Tests.Document.RepairTests.A_stream_without_endstream_ends_at_endobj`, `Broadside.Tests.Writing.SaveTests.A_repaired_file_is_saved_with_a_new_cross_reference_section_and_reopens_without_warnings_or_errors`, `Broadside.Tests.Filters.FilterPipelineTests.Data_in_an_external_file_is_a_legal_unsupported_feature_that_strict_mode_does_not_reject` | Extent from a direct or indirect Length (`Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length`), else from endstream; filters decode through `PdfDocument.DecodeStream` (7.4) with DL as a capacity hint; external stream files (F, FFilter, FDecodeParms) are not read: `StreamExternalFileUnsupported` and the embedded bytes decode instead (`Broadside.Tests.Filters.FilterPipelineTests.Data_in_an_external_file_is_not_read_and_the_stream_bytes_decode_instead_with_a_diagnostic`); a wrong, missing or unresolvable Length is recovered from endstream without the end-of-line before it (StreamLengthInvalid; the Length entry is not changed), lengths that refer to each other are unknown rather than looping, and a stream without endstream ends at endobj (EndstreamMissing); written as `stream` LF, the data, LF `endstream` with a direct Length equal to the data; a stream read with a wrong Length is re-serialized with the right one, never copied (#44). External file data is legal (Table 5): `StreamExternalFileUnsupported` is Information since #47, so strict mode no longer rejects it. | | 7.3.9 | Null object | done | `CosNull` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_null_as_the_single_null_object`, `Broadside.Tests.Objects.ContainerParsingTests.A_null_valued_entry_is_the_same_as_an_absent_one` | | | 7.3.10 | Indirect objects | done | `CosReference`, `PdfDocument`, `ObjectLoader`, `FileScan`, `FileWriter`, `SavePlan` | `Broadside.Tests.Objects.ScalarParsingTests.Parses_indirect_references`, `Broadside.Tests.Document.FileStructureTests.References_to_missing_free_or_other_generation_objects_resolve_to_null_without_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.An_object_without_endobj_is_read_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_is_read_from_where_its_header_is_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.An_entry_for_an_object_the_file_does_not_hold_reads_as_null_with_an_error`, `Broadside.Tests.Document.BrokenCorpusTests.A_broken_file_opens_leniently_with_exactly_the_documented_diagnostics_and_the_intact_pages`, `Broadside.Tests.Writing.SaveTests.Objects_that_were_not_changed_keep_their_source_bytes_in_any_layout`, `Broadside.Tests.Writing.SaveTests.Bytes_a_canonical_writer_would_change_are_kept_in_every_layout`, `Broadside.Tests.Writing.SaveTests.A_changed_object_is_written_with_its_new_value_and_the_others_keep_their_bytes` | `PdfDocument.Resolve`; references to missing, free or other-generation objects are null with no diagnostic; loading goes through the internal `ObjectLoader` (hooks for #42, #45); an entry whose offset does not hold the object's header is searched near the offset, then in a scan of the whole file (newest copy), with XrefEntryOffsetInvalid (Warning when found, Error and null when not); a missing endobj ends the object at the next keyword (MissingEndobj); broken-xref-offsets.pdf, missing-endobj.pdf; a save writes `N G obj` LF value LF `endobj` under the source number and generation; an unchanged object read without repair keeps its exact bytes (from the first token after obj to the end of its last token), others are serialized (#44) | | 7.4.1 | General | done | `IStreamFilter`, `FilterContext`, `StreamDecoder`, `FilterRegistry`, `PdfDocument`, `PdfOptions` | `Broadside.Tests.Filters.CorpusFilterTests.A_filtered_content_stream_decodes_to_the_bytes_that_were_encoded`, `Broadside.Tests.Filters.CorpusFilterTests.Every_page_content_stream_of_a_well_formed_file_decodes_with_no_diagnostics`, `Broadside.Tests.Filters.FilterPipelineTests.Filters_apply_in_array_order_and_the_same_filter_may_appear_twice`, `Broadside.Tests.Filters.FilterPipelineTests.Decode_parameters_align_with_the_filter_array_and_null_means_defaults`, `Broadside.Tests.Filters.FilterPipelineTests.Deviations_from_table_5_are_repaired_with_one_diagnostic`, `Broadside.Tests.Filters.FilterPipelineTests.An_unknown_filter_leaves_the_stream_readable_as_raw_bytes_with_a_diagnostic`, `Broadside.Tests.Filters.FilterPipelineTests.Output_beyond_the_decoded_length_limit_is_truncated_with_a_diagnostic`, `Broadside.Tests.Filters.FilterExtensionPointTests.A_decorator_registered_through_the_options_replaces_the_default_flate_filter`, `Broadside.Tests.Filters.FilterExtensionPointTests.Two_engines_in_one_process_keep_their_own_filters` | `PdfDocument.DecodeStream`; filter extension point `PdfOptions.UseFilter` (per engine, no static registry); unknown or not-yet-implemented filters stop the chain with `FilterUnsupported`; decoded-length limit `PdfOptions.WithMaxDecodedStreamLength`; fuzz targets `filter-*`, `document` decodes page contents; Table 92 abbreviations outside inline images read with a diagnostic | -| 7.4.2 | ASCIIHexDecode filter | done | `AsciiHexDecodeFilter` | `Broadside.Tests.Filters.AsciiFilterTests.Ascii_hex_decodes_digit_pairs_ignores_white_space_and_pads_an_odd_final_digit`, `Broadside.Tests.Filters.AsciiFilterTests.Ascii_hex_skips_invalid_characters_with_one_diagnostic`, `Broadside.Tests.Filters.AsciiFilterTests.Ascii_hex_without_the_end_marker_decodes_to_its_end_with_a_diagnostic`, `Broadside.Tests.Filters.AsciiFilterTests.Both_filters_round_trip_the_encoders_of_the_corpus_generator` | Decode; `asciihex-stream.pdf`; `AsciiHexBenchmarks`; fuzz `filter-asciihex`; encoding is Phase 4 | +| 7.4.2 | ASCIIHexDecode filter | done | `AsciiHexDecodeFilter` | `Broadside.Tests.Filters.AsciiFilterTests.Ascii_hex_decodes_digit_pairs_ignores_white_space_and_pads_an_odd_final_digit`, `Broadside.Tests.Filters.AsciiFilterTests.Ascii_hex_skips_invalid_characters_with_one_diagnostic`, `Broadside.Tests.Filters.AsciiFilterTests.Ascii_hex_without_the_end_marker_decodes_to_its_end_without_a_diagnostic`, `Broadside.Tests.Filters.AsciiFilterTests.Both_filters_round_trip_the_encoders_of_the_corpus_generator` | Decode; `asciihex-stream.pdf`; `AsciiHexBenchmarks`; fuzz `filter-asciihex`; encoding is Phase 4. Data without the `>` marker decodes with no diagnostic: the clause defines the marker but does not require it (#47, from veraPDF's PDF/A-1b 6-1-2-t01-pass-a.pdf). | | 7.4.3 | ASCII85Decode filter | done | `Ascii85DecodeFilter` | `Broadside.Tests.Filters.AsciiFilterTests.Ascii85_decodes_groups_z_partial_groups_and_ignores_white_space`, `Broadside.Tests.Filters.AsciiFilterTests.Ascii85_repairs_impossible_sequences_with_a_diagnostic`, `Broadside.Tests.Filters.AsciiFilterTests.Ascii85_without_the_end_marker_decodes_the_partial_group_with_a_diagnostic`, `Broadside.Tests.Filters.AsciiFilterTests.Strict_mode_throws_for_an_invalid_character` | Decode; `ascii85-stream.pdf`, `filter-chain.pdf`; `Ascii85Benchmarks`; fuzz `filter-ascii85`; encoding is Phase 4 | | 7.4.4 | LZWDecode and FlateDecode filters | done | `LzwDecodeFilter`, `FlateDecodeFilter`, `Predictor` | `Broadside.Tests.Filters.LzwDecodeFilterTests.Decodes_the_packed_example_after_table_7`, `Broadside.Tests.Filters.LzwDecodeFilterTests.Round_trips_data_that_grows_the_code_length_to_12_bits_and_clears_the_table`, `Broadside.Tests.Filters.LzwDecodeFilterTests.Data_without_the_end_of_data_code_decodes_to_its_end_with_a_diagnostic`, `Broadside.Tests.Filters.FlateDecodeFilterTests.Inflates_zlib_data`, `Broadside.Tests.Filters.FlateDecodeFilterTests.Truncated_data_keeps_everything_inflated_with_a_diagnostic`, `Broadside.Tests.Filters.PredictorTests.Png_predicted_rows_decode_to_the_samples_whatever_predictor_10_to_15_is_declared`, `Broadside.Tests.Filters.PredictorTests.Tiff_predictor_2_adds_each_component_to_the_same_component_to_its_left`, `Broadside.Tests.Filters.PredictorTests.Malformed_predictor_data_or_parameters_are_repaired_with_a_diagnostic`, `Broadside.Tests.Filters.FilterAllocationTests.Decoding_through_the_contract_allocates_nothing` | 7.4.4.1 to 7.4.4.4. Flate through the BCL `DeflateStream` (zlib header checked, Adler-32 not read); LZW honors EarlyChange; predictors 2 and 10 to 15 applied by the pipeline after any LZWDecode/FlateDecode filter; `lzw-stream.pdf`, `flate-stream.pdf`; `LzwBenchmarks`, `FlateBenchmarks`, `PredictorBenchmarks`; fuzz `filter-lzw`, `filter-flate`, `filter-predictor`; encoding (Flate, PNG predictors) is Phase 4A | | 7.4.5 | RunLengthDecode filter | done | `RunLengthDecodeFilter` | `Broadside.Tests.Filters.RunLengthDecodeFilterTests.Decodes_literal_and_repeated_runs_up_to_the_end_of_data_byte`, `Broadside.Tests.Filters.RunLengthDecodeFilterTests.Data_that_ends_early_keeps_what_is_available_with_a_diagnostic`, `Broadside.Tests.Filters.RunLengthDecodeFilterTests.Round_trips_the_encoder_of_the_corpus_generator` | Decode; `runlength-stream.pdf`; `RunLengthBenchmarks`; fuzz `filter-runlength`; encoding is Phase 4 | @@ -29,18 +29,18 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.4.8 | DCTDecode filter | not started | | | Phase 2B (#61, #62) | | 7.4.9 | JPXDecode filter | not started | | | Phase 2B (#67, #68) | | 7.4.10 | Crypt filter | done | `StreamDecoder`, `ICryptFilterHandler`, `DocumentDecryptor` | `Broadside.Tests.Filters.FilterPipelineTests.The_identity_crypt_filter_passes_the_data_through`, `Broadside.Tests.Filters.FilterPipelineTests.A_crypt_filter_the_security_handler_does_not_know_leaves_the_data_encrypted_with_a_diagnostic`, `Broadside.Tests.Filters.FilterPipelineTests.A_crypt_filter_that_is_not_first_is_applied_where_it_is_with_a_diagnostic`, `Broadside.Tests.Security.CryptFilterTests.Each_content_stream_decrypts_with_the_crypt_filter_it_names_or_the_default_one`, `Broadside.Tests.Security.CryptFilterTests.A_stream_that_names_a_crypt_filter_the_document_does_not_define_is_left_encrypted_with_a_diagnostic` | The security handler decrypts a stream whose Filter starts with Crypt when its object loads, with the named crypt filter (DecodeParms Name, default Identity) and that filter's key used as is; for AES-128 data that does not decrypt that way, Algorithm 1's object key (what qpdf reads) is tried; the pipeline's Crypt stage then passes known names through and reports CryptFilterUnsupported for unknown ones | -| 7.5.1 | General | done | `PdfDocument`, `CrossReferenceReader`, `PdfSource`, `MappedFileSource`, `StreamSource` | `Broadside.Tests.Document.OpenDocumentTests.A_file_opens_identically_from_a_path_a_stream_and_bytes_with_no_diagnostics`, `Broadside.Tests.Document.WellFormedCorpusTests.A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics`, `Broadside.Tests.Document.SourceTests.A_seekable_stream_is_read_in_place_only_where_objects_are_needed`, `Broadside.Tests.Document.SourceTests.A_non_seekable_stream_is_read_whole_when_opened`, `Broadside.Tests.Document.SourceTests.A_non_seekable_stream_longer_than_the_buffer_limit_is_read_through_a_temporary_file`, `Broadside.Tests.Document.SourceTests.OpenAsync_reads_a_non_seekable_stream_asynchronously`, `Broadside.Tests.Document.LargeFileTests.A_file_over_2_GiB_opens_and_reads_its_last_page_in_bounded_memory` | Read from the end through startxref, the cross-reference table and the trailer, never serially; linearized files read through the same path (Annex F). Sources (#45): bytes (zero-copy), paths and FileStreams memory-mapped, other seekable streams read in place under a lock in growing windows, non-seekable streams copied at open (memory up to `StreamBufferLimit`, then a temporary file; `OpenAsync` copies asynchronously); fuzz `windowed-document` | -| 7.5.2 | File header | done | `FileHeader`, `PdfVersion`, `PdfDocument`, `FileWriter` | `Broadside.Tests.Document.FileStructureTests.Offsets_count_from_the_header_so_bytes_before_it_do_not_matter`, `Broadside.Tests.Document.FileStructureTests.A_file_without_a_header_opens_from_byte_0_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_header_without_a_valid_version_takes_the_catalog_version_with_a_diagnostic`, `Broadside.Tests.Document.RepairTests.Offsets_counted_from_byte_0_instead_of_the_header_are_repaired`, `Broadside.Tests.Writing.SaveTests.The_header_keeps_the_version_unless_the_layout_needs_a_later_one`, `Broadside.Tests.Writing.CreateTests.A_created_document_has_one_empty_letter_page_and_is_PDF_2_0` | Header searched in the first 1024 bytes; every stated offset is relative to it; missing header: offsets from byte 0, version 1.4 unless the catalog says otherwise; offsets a writer counted from byte 0 despite junk before the header are repaired by the nearest-section and object searches; written: `%PDF-n.m` LF, then a comment of four bytes above 127; the document version is kept and raised to 1.5 for cross-reference streams (ADR 0003); `Create` writes 2.0 (#44) | +| 7.5.1 | General | done | `PdfDocument`, `CrossReferenceReader`, `PdfSource`, `MappedFileSource`, `StreamSource` | `Broadside.Tests.Document.OpenDocumentTests.A_file_opens_identically_from_a_path_a_stream_and_bytes_with_no_diagnostics`, `Broadside.Tests.Document.WellFormedCorpusTests.A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics`, `Broadside.Tests.Document.SourceTests.A_seekable_stream_is_read_in_place_only_where_objects_are_needed`, `Broadside.Tests.Document.SourceTests.A_non_seekable_stream_is_read_whole_when_opened`, `Broadside.Tests.Document.SourceTests.A_non_seekable_stream_longer_than_the_buffer_limit_is_read_through_a_temporary_file`, `Broadside.Tests.Document.SourceTests.OpenAsync_reads_a_non_seekable_stream_asynchronously`, `Broadside.Tests.Document.LargeFileTests.A_file_over_2_GiB_opens_and_reads_its_last_page_in_bounded_memory`, `Broadside.Tests.Document.RealWorldCorpusTests.A_real_world_file_opens_and_walks_leniently_without_an_exception`, `Broadside.Tests.Document.RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot` | Read from the end through startxref, the cross-reference table and the trailer, never serially; linearized files read through the same path (Annex F). Sources (#45): bytes (zero-copy), paths and FileStreams memory-mapped, other seekable streams read in place under a lock in growing windows, non-seekable streams copied at open (memory up to `StreamBufferLimit`, then a temporary file; `OpenAsync` copies asynchronously); fuzz `windowed-document`. Real-world gate (#47): 2,612 corpus files open and walk leniently with no crash or hang (30 s per file); per-corpus counts and diagnostic histograms in the `RealWorldCorpusTests` snapshot. | +| 7.5.2 | File header | done | `FileHeader`, `PdfVersion`, `PdfDocument`, `FileWriter` | `Broadside.Tests.Document.FileStructureTests.Offsets_count_from_the_header_so_bytes_before_it_do_not_matter`, `Broadside.Tests.Document.FileStructureTests.A_file_without_a_header_opens_from_byte_0_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_header_without_a_valid_version_takes_the_catalog_version_with_a_diagnostic`, `Broadside.Tests.Document.RepairTests.Offsets_counted_from_byte_0_instead_of_the_header_are_repaired`, `Broadside.Tests.Writing.SaveTests.The_header_keeps_the_version_unless_the_layout_needs_a_later_one`, `Broadside.Tests.Writing.CreateTests.A_created_document_has_one_empty_letter_page_and_is_PDF_2_0`, `Broadside.Tests.Document.FileLayoutTests.A_layout_deviation_is_read_with_one_diagnostic`, `Broadside.Tests.Document.FileLayoutTests.Strict_mode_throws_on_a_layout_deviation`, `Broadside.Tests.Document.FileLayoutTests.A_header_ended_by_any_end_of_line_marker_has_no_diagnostic`, `Broadside.Tests.Document.VeraPdfAgreementTests.Strict_mode_agrees_with_veraPDF_or_the_disagreement_is_triaged` | Header searched in the first 1024 bytes; every stated offset is relative to it; missing header: offsets from byte 0, version 1.4 unless the catalog says otherwise; offsets a writer counted from byte 0 despite junk before the header are repaired by the nearest-section and object searches; written: `%PDF-n.m` LF, then a comment of four bytes above 127; the document version is kept and raised to 1.5 for cross-reference streams (ADR 0003); `Create` writes 2.0 (#44). A header whose version is not followed by an end-of-line marker: `HeaderInvalid` (#47). Not checked yet: the binary comment line a file with binary data shall have (needs a whole-file scan; follow-up from the #47 veraPDF triage). | | 7.5.3 | File body | done | `ObjectLoader`, `FileWriter`, `ObjectCache`, `OnceCache` | `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_reopens_with_the_same_objects_and_no_diagnostics`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_passes_qpdf_check`, `Broadside.Tests.Document.LazyLoadingTests.Opening_a_file_parses_the_catalog_and_nothing_else`, `Broadside.Tests.Document.LazyLoadingTests.Every_object_is_parsed_once_however_many_threads_read_it`, `Broadside.Tests.Document.LazyLoadingTests.An_object_stream_is_decoded_once_however_many_threads_read_its_members`, `Broadside.Tests.Document.LazyLoadingTests.Two_threads_each_loading_a_stream_whose_Length_is_the_other_one_do_not_deadlock`, `Broadside.Tests.Document.ConcurrencyTests.Every_page_and_object_reads_the_same_from_many_threads_as_from_one` | Objects load lazily by cross-reference entry, from the file body or an object stream (7.5.7); a full save writes every in-use object of the newest revision, dropping only old cross-reference streams, object streams and linearization data that nothing refers to (#44), parsed once per (number, generation) and object streams decoded once, under the concurrency contract on `PdfDocument` (#45); stream data stays in the source and is read on access; parses traced at Trace level (`ObjectParsed`, `ObjectStreamDecoded`); `bench/Broadside.Benchmarks/LazyLoadingBenchmarks.cs` (cached resolve allocates nothing) | -| 7.5.4 | Cross-reference table | done | `XrefTableReader`, `CrossReference`, `FileScan`, `CrossReferenceReconstructor`, `FileWriter` | `Broadside.Tests.Document.FileStructureTests.Entries_are_read_as_tokens_not_fixed_width_records`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_is_read_from_where_its_header_is_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation`, `Broadside.Tests.Document.RepairTests.Entries_that_are_not_20_bytes_long_are_read_with_one_diagnostic_per_section`, `Broadside.Tests.Document.RepairTests.A_subsection_numbered_from_1_whose_first_entry_is_the_free_list_head_is_renumbered_from_0`, `Broadside.Tests.Document.RepairTests.A_file_whose_line_endings_were_converted_to_crlf_opens_with_the_intact_pages`, `Broadside.Tests.Document.RepairTests.Rebuilding_an_updated_file_keeps_the_newest_copy_of_each_object_and_the_newest_trailer`, `Broadside.Tests.Document.RepairTests.A_repair_met_twice_is_recorded_once`, `Broadside.Tests.Document.BrokenCorpusTests.A_broken_file_opens_leniently_with_exactly_the_documented_diagnostics_and_the_intact_pages`, `Broadside.Tests.Document.BrokenCorpusTests.Strict_mode_throws_on_a_broken_file_with_the_code_of_its_first_diagnostic`, `Broadside.Tests.Writing.SaveTests.Startxref_gives_the_offset_of_the_cross_reference_information`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_passes_qpdf_check` | Subsections and n/f entries read as tokens; entries not 20 bytes long reported once per section (XrefEntryFormatInvalid); a subsection numbered from 1 whose first entry is the free-list head renumbered from 0 (XrefSubsectionNumberingInvalid); offset-0 in-use entries read as free; misplaced objects searched (7.3.10); an unreadable table is rebuilt by one windowed scan for N G obj headers (newest copy wins), object stream members and trailers (repair is informative, ADR 0005); comments inside a table are read silently; broken-xref-offsets.pdf, no-xref.pdf; fuzz `repair`; written as one subsection from 0 with 20-byte entries (CR LF), free entries linked from object 0 (generation 65535); offsets above ten digits refuse the table layout (#44) | -| 7.5.5 | File trailer | partial | `CrossReferenceReader`, `CrossReference`, `PdfDocument`, `CrossReferenceReconstructor`, `FileWriter` | `Broadside.Tests.Document.FileStructureTests.A_startxref_offset_on_the_white_space_before_xref_is_repaired_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_file_with_no_startxref_is_rebuilt_by_scanning_and_keeps_its_trailer`, `Broadside.Tests.Document.FileStructureTests.A_trailer_without_root_is_repaired_by_finding_the_catalog_by_scanning`, `Broadside.Tests.Document.FileStructureTests.A_prev_chain_that_loops_ends_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic`, `Broadside.Tests.Document.RepairTests.A_wrong_prev_offset_reads_the_nearest_older_section`, `Broadside.Tests.Document.RepairTests.Rebuilding_an_encrypted_file_keeps_its_encryption_dictionary_and_identifier`, `Broadside.Tests.Document.RepairTests.A_compressed_catalog_is_found_when_no_trailer_survives`, `Broadside.Tests.Document.RepairTests.A_file_with_nothing_but_junk_cannot_be_read`, `Broadside.Tests.Document.BrokenCorpusTests.A_broken_file_opens_leniently_with_exactly_the_documented_diagnostics_and_the_intact_pages`, `Broadside.Tests.Writing.SaveTests.Saving_an_updated_file_collapses_its_revisions_into_one_with_the_newest_objects`, `Broadside.Tests.Writing.SaveTests.Startxref_gives_the_offset_of_the_cross_reference_information` | Last startxref, Prev chain with loop guard, Root; trailer merged newest-first; a startxref or Prev offset at neither xref nor N G obj reads the nearest section (table wins ties, never one already read); missing or unusable startxref, or a Root that does not lead to the catalog, rebuilds the cross-reference from a scan: newest trailer or xref-stream dictionary whose Root leads to a catalog, Encrypt/ID/Info from any trailer, else the newest /Catalog (TrailerMissing or RootMissing); no catalog at all throws CatalogNotFound; startxref-wrong.pdf, no-xref.pdf; ignoring entries beyond Size is not done; Encrypt and ID are read from the newest trailer (#42); written trailer: Size, the source trailer without Size, Prev, XRefStm and ID, then ID; startxref and %%EOF (#44) | +| 7.5.4 | Cross-reference table | done | `XrefTableReader`, `CrossReference`, `FileScan`, `CrossReferenceReconstructor`, `FileWriter` | `Broadside.Tests.Document.FileStructureTests.Entries_are_read_as_tokens_not_fixed_width_records`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_is_read_from_where_its_header_is_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation`, `Broadside.Tests.Document.RepairTests.Entries_that_are_not_20_bytes_long_are_read_with_one_diagnostic_per_section`, `Broadside.Tests.Document.RepairTests.A_subsection_numbered_from_1_whose_first_entry_is_the_free_list_head_is_renumbered_from_0`, `Broadside.Tests.Document.RepairTests.A_file_whose_line_endings_were_converted_to_crlf_opens_with_the_intact_pages`, `Broadside.Tests.Document.RepairTests.Rebuilding_an_updated_file_keeps_the_newest_copy_of_each_object_and_the_newest_trailer`, `Broadside.Tests.Document.RepairTests.A_repair_met_twice_is_recorded_once`, `Broadside.Tests.Document.BrokenCorpusTests.A_broken_file_opens_leniently_with_exactly_the_documented_diagnostics_and_the_intact_pages`, `Broadside.Tests.Document.BrokenCorpusTests.Strict_mode_throws_on_a_broken_file_with_the_code_of_its_first_diagnostic`, `Broadside.Tests.Writing.SaveTests.Startxref_gives_the_offset_of_the_cross_reference_information`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_passes_qpdf_check`, `Broadside.Tests.Document.FileLayoutTests.A_layout_deviation_is_read_with_one_diagnostic`, `Broadside.Tests.Document.FileLayoutTests.A_subsection_header_on_its_own_line_has_no_diagnostic_whatever_ends_the_xref_line`, `Broadside.Tests.Document.VeraPdfAgreementTests.Strict_mode_agrees_with_veraPDF_or_the_disagreement_is_triaged` | Subsections and n/f entries read as tokens; entries not 20 bytes long reported once per section (XrefEntryFormatInvalid); a subsection numbered from 1 whose first entry is the free-list head renumbered from 0 (XrefSubsectionNumberingInvalid); offset-0 in-use entries read as free; misplaced objects searched (7.3.10); an unreadable table is rebuilt by one windowed scan for N G obj headers (newest copy wins), object stream members and trailers (repair is informative, ADR 0005); comments inside a table are read silently; broken-xref-offsets.pdf, no-xref.pdf; fuzz `repair`; written as one subsection from 0 with 20-byte entries (CR LF), free entries linked from object 0 (generation 65535); offsets above ten digits refuse the table layout (#44). A subsection header that is not its own line of two integers separated by one space: `XrefSubsectionHeaderInvalid`, once per section (trailing spaces tolerated, as Acrobat writes them) (#47). | +| 7.5.5 | File trailer | partial | `CrossReferenceReader`, `CrossReference`, `PdfDocument`, `CrossReferenceReconstructor`, `FileWriter` | `Broadside.Tests.Document.FileStructureTests.A_startxref_offset_on_the_white_space_before_xref_is_repaired_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_file_with_no_startxref_is_rebuilt_by_scanning_and_keeps_its_trailer`, `Broadside.Tests.Document.FileStructureTests.A_trailer_without_root_is_repaired_by_finding_the_catalog_by_scanning`, `Broadside.Tests.Document.FileStructureTests.A_prev_chain_that_loops_ends_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic`, `Broadside.Tests.Document.RepairTests.A_wrong_prev_offset_reads_the_nearest_older_section`, `Broadside.Tests.Document.RepairTests.Rebuilding_an_encrypted_file_keeps_its_encryption_dictionary_and_identifier`, `Broadside.Tests.Document.RepairTests.A_compressed_catalog_is_found_when_no_trailer_survives`, `Broadside.Tests.Document.RepairTests.A_file_with_nothing_but_junk_cannot_be_read`, `Broadside.Tests.Document.BrokenCorpusTests.A_broken_file_opens_leniently_with_exactly_the_documented_diagnostics_and_the_intact_pages`, `Broadside.Tests.Writing.SaveTests.Saving_an_updated_file_collapses_its_revisions_into_one_with_the_newest_objects`, `Broadside.Tests.Writing.SaveTests.Startxref_gives_the_offset_of_the_cross_reference_information`, `Broadside.Tests.Document.FileLayoutTests.A_layout_deviation_is_read_with_one_diagnostic`, `Broadside.Tests.Document.FileLayoutTests.White_space_after_the_last_end_of_file_marker_has_no_diagnostic`, `Broadside.Tests.Document.FileLayoutTests.A_trailer_id_is_required_only_from_pdf_2_0`, `Broadside.Tests.Document.VeraPdfAgreementTests.Strict_mode_agrees_with_veraPDF_or_the_disagreement_is_triaged` | Last startxref, Prev chain with loop guard, Root; trailer merged newest-first; a startxref or Prev offset at neither xref nor N G obj reads the nearest section (table wins ties, never one already read); missing or unusable startxref, or a Root that does not lead to the catalog, rebuilds the cross-reference from a scan: newest trailer or xref-stream dictionary whose Root leads to a catalog, Encrypt/ID/Info from any trailer, else the newest /Catalog (TrailerMissing or RootMissing); no catalog at all throws CatalogNotFound; startxref-wrong.pdf, no-xref.pdf; ignoring entries beyond Size is not done; Encrypt and ID are read from the newest trailer (#42); written trailer: Size, the source trailer without Size, Prev, XRefStm and ID, then ID; startxref and %%EOF (#44). Data (not white-space) after the %%EOF that follows the last startxref: `EndOfFileMarkerNotLast`; a PDF 2.0 document (header or catalog Version) whose trailer has no ID: `TrailerIdMissing` (Table 15) (#47). | | 7.5.6 | Incremental updates | done | `CrossReference`, `RevisionReader`, `PdfRevision`, `PdfDocument` | `Broadside.Tests.Document.IncrementalUpdateTests.An_updated_file_has_one_revision_per_update_and_the_first_is_the_original_file`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_is_the_file_as_it_was_after_that_save`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_has_its_own_trailer`, `Broadside.Tests.Document.IncrementalUpdateTests.A_hybrid_file_has_its_main_section_and_its_update_section_as_two_revisions`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_earlier_revision_without_its_end_of_file_marker_ends_after_its_startxref_offset_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`, `Broadside.Tests.Writing.SaveTests.Saving_an_updated_file_collapses_its_revisions_into_one_with_the_newest_objects` | Revisions oldest first, each the byte prefix up to its %%EOF and end-of-line; newest section decides per object number, free hides older copies, a reference must match the live generation; Root, Info, Encrypt and ID missing from the newest trailer are taken from an older one with TrailerEntryFromOlderRevision; a linearized pair is one revision; a hybrid XRefStm stream joins its table's revision; a full save collapses the revisions into one (#44); writing an incremental update is Phase 4 | | 7.5.7 | Object streams | done | `ObjectStream`, `ObjectLoader`, `FileWriter` | `Broadside.Tests.Document.ObjectStreamTests.The_catalog_page_tree_and_page_resolve_from_an_object_stream`, `Broadside.Tests.Document.ObjectStreamTests.A_reference_to_a_member_with_a_generation_other_than_0_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.Members_need_no_white_space_between_them`, `Broadside.Tests.Document.ObjectStreamTests.A_member_at_another_index_than_its_entry_says_is_found_by_its_object_number`, `Broadside.Tests.Document.ObjectStreamTests.Offsets_out_of_order_bound_each_member_by_the_next_offset_in_sorted_order`, `Broadside.Tests.Document.ObjectStreamTests.A_member_the_object_stream_does_not_hold_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_whose_N_is_one_of_its_own_members_resolves_its_members_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_listed_as_compressed_itself_is_not_read`, `Broadside.Tests.Document.ObjectStreamTests.A_type_2_entry_naming_an_object_that_is_not_a_stream_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.A_flate_encoded_object_stream_is_decoded_through_the_filters`, `Broadside.Tests.Document.ObjectStreamTests.Members_of_one_object_stream_resolve_to_the_same_instances_from_concurrent_threads`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file`, `Broadside.Tests.Document.RepairTests.Objects_in_object_streams_survive_a_damaged_cross_reference_stream`, `Broadside.Tests.Writing.SaveTests.Objects_that_were_not_changed_keep_their_source_bytes_in_any_layout`, `Broadside.Tests.Writing.SaveTests.The_information_dictionary_of_a_hybrid_file_survives_from_its_object_stream` | Members located by type 2 entries (index checked against the header, searched by number when wrong, with ObjectStreamIndexMismatch); each member parsed over exactly the bytes up to the next offset (NOTE 7); out-of-order offsets sorted; container decoded once per document and shared, decrypted as a whole (members skip hooks 1 and 2); nested containers and self-referencing N/First/Filter end with ObjectStreamNested/ObjectStreamCycle; /Extends ignored (grouping only); object-stream.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `object-stream`; written by `PdfCrossReferenceLayout.StreamWithObjectStreams`: every object with generation 0 that is not a stream or a bare reference, at most 100 per Flate-encoded object stream; unchanged members keep their bytes (#44); a rebuilt cross-reference indexes the members of every object stream found by scanning (#41) | | 7.5.8 | Cross-reference streams | done | `XrefStreamReader`, `CrossReferenceReader`, `CrossReference`, `FileWriter`, `PdfCrossReferenceLayout` | `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file`, `Broadside.Tests.Document.CrossReferenceStreamTests.Strict_mode_opens_a_file_with_compressed_structures`, `Broadside.Tests.Document.CrossReferenceStreamTests.The_trailer_of_a_cross_reference_stream_is_its_dictionary_without_the_entries_that_describe_the_stream`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_type_field_makes_every_entry_type_1`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_generation_field_defaults_to_generation_0`, `Broadside.Tests.Document.CrossReferenceStreamTests.Index_with_two_subsections_numbers_the_entries_of_each_from_its_first_object_number`, `Broadside.Tests.Document.CrossReferenceStreamTests.Wide_fields_are_read_big_endian`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_entry_of_an_unknown_type_is_a_reference_to_the_null_object`, `Broadside.Tests.Document.CrossReferenceStreamTests.Data_shorter_than_the_entries_ends_the_section_where_the_data_ends`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_without_type_XRef_is_read_with_a_diagnostic`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_whose_W_cannot_be_read_is_not_a_cross_reference_section_so_the_file_is_rebuilt_by_scanning`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_update_written_as_a_cross_reference_stream_overrides_the_original_section`, `Broadside.Tests.Document.HybridFileTests.An_object_only_the_XRefStm_stream_lists_is_found`, `Broadside.Tests.Document.HybridFileTests.An_in_use_entry_in_the_table_of_a_section_takes_precedence_over_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.A_free_entry_in_the_table_of_a_section_gives_way_to_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.The_XRefStm_streams_dictionary_is_not_the_trailer_and_its_Prev_is_not_followed`, `Broadside.Tests.Document.HybridFileTests.An_XRefStm_offset_that_names_no_stream_is_reported_and_the_table_is_still_read`, `Broadside.Tests.Document.LinearizationTests.A_linearized_file_with_cross_reference_streams_has_its_first_page_and_main_streams_as_one_revision`, `Broadside.Tests.Writing.SaveTests.Startxref_gives_the_offset_of_the_cross_reference_information`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_passes_qpdf_check` | 7.5.8.1 to 7.5.8.4. W (0 to 8 bytes per field, W[0] = 0 means type 1), Index (default [0 Size]), Size, Prev; entries big-endian into long; type 0/1/2, other types are the null object; dictionary minus Type, Length, W, Index, Filter, DecodeParms, DL, F, FFilter, FDecodeParms is the trailer; data decoded through the filter pipeline under the engine's decoded-length limit, never decrypted; hybrid XRefStm read after its table and before Prev, its entries replacing the table's free entries (an in-use table entry wins), its own Prev not followed and its dictionary not a trailer; xref-stream.pdf, object-stream.pdf, png-predictor.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `xref-stream`; written by `PdfCrossReferenceLayout.Stream` and `StreamWithObjectStreams`: W [1 n 2] with n the fewest bytes for the largest offset, an entry for the stream itself, Flate with Predictor 12, trailer keys in its dictionary; hybrid files are not written (#44) | | 7.6.1 | General | done | `PdfDocument`, `PdfSecurity` | `Broadside.Tests.Security.EncryptedCorpusTests.An_encrypted_file_opens_with_the_empty_user_password_and_its_content_stream_decrypts`, `Broadside.Tests.Security.EncryptedCorpusTests.An_unencrypted_document_permits_everything` | An encrypted file opens transparently: `PdfDocument.IsEncrypted`, `PdfDocument.Security`, `PdfDocument.Permissions` | | 7.6.2 | Application of encryption | done | `DocumentSecurity`, `DocumentDecryptor`, `SecurityHandlerRegistry`, `ISecurityHandler`, `SecurityHandlerContext`, `SecurityHandlerResult`, `PdfEncryptionNotSupportedException` | `Broadside.Tests.Security.EncryptedCorpusTests.Strings_are_decrypted_with_the_key_of_the_object_that_holds_them`, `Broadside.Tests.Security.EncryptedCorpusTests.The_encryption_dictionary_and_the_file_identifier_are_not_decrypted`, `Broadside.Tests.Security.EncryptedCorpusTests.Decrypting_marks_nothing_dirty`, `Broadside.Tests.Security.EncryptedCorpusTests.Concurrent_readers_see_the_same_decrypted_content`, `Broadside.Tests.Security.EncryptedCorpusTests.A_document_rebuilt_because_its_root_is_unusable_is_still_decrypted`, `Broadside.Tests.Security.EncryptedCorpusTests.A_document_whose_cross_reference_is_unreadable_is_rebuilt_and_decrypted`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.The_standard_handler_is_registered_by_default`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_handler_registered_for_standard_replaces_the_default`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.Two_engines_with_different_handlers_do_not_interfere`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_handler_that_supplies_the_key_another_way_decrypts_the_document`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_handler_is_chosen_by_subfilter_when_no_handler_has_the_filter_name`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_document_whose_handler_is_not_registered_is_not_supported` | Every string and stream is decrypted as its indirect object loads (hook 2), never the Encrypt dictionary, the trailer (ID, AuthCode), object-stream members (their container is decrypted), cross-reference streams or a signature dictionary's Contents; decryption never marks objects dirty; handler chosen by Filter, else by SubFilter (`PdfOptions.UseSecurityHandler`, standard and public-key handlers by default); V 1-6 (V 3 read as V 2 with a diagnostic); newest trailer's Encrypt and ID; a missing ID is an empty identifier with EncryptionIdMissing; an Encrypt entry that does not resolve rebuilds the cross-reference (#41); fuzz `encrypted-document` | | 7.6.3 | General encryption algorithm | done | `DocumentDecryptor`, `Rc4`, `AesCipher`, `ManagedAes`, `Md5`, `ManagedMd5`, `CryptographyBackend` | `Broadside.Tests.Security.EncryptedCorpusTests.The_managed_cryptography_decrypts_like_the_platform_cryptography`, `Broadside.Tests.Security.CryptFilterTests.Aes_data_with_a_damaged_pad_is_kept_whole_with_a_diagnostic`, `Broadside.Tests.Security.CryptographyTests.Managed_md5_matches_rfc_1321`, `Broadside.Tests.Security.CryptographyTests.Managed_md5_agrees_with_the_platform_at_every_padding_boundary`, `Broadside.Tests.Security.CryptographyTests.Managed_aes_matches_fips_197_appendix_c`, `Broadside.Tests.Security.CryptographyTests.Managed_aes_cbc_agrees_with_the_platform`, `Broadside.Tests.Security.CryptographyTests.Rc4_matches_the_published_vectors`, `Broadside.Tests.Security.DecryptionAllocationTests.Rc4_allocates_nothing`, `Broadside.Tests.Security.DecryptionAllocationTests.Aes_cbc_into_a_buffer_allocates_nothing_per_block` | 7.6.3.1 to 7.6.3.3. Algorithm 1 (RC4, AES-128-CBC with "sAlT") and 1.A (AES-256-CBC), IV prefix, PKCS#5 padding; damaged AES data repaired like pdf.js with EncryptedDataInvalid (too short: nothing; partial block dropped; bad pad kept); RC4 managed; MD5 and AES from the BCL, with managed MD5 and AES selected at run time where the platform has none (browser); `SecurityBenchmarks`; fuzz `decrypt` | -| 7.6.4 | Standard security handler | done | `StandardSecurityHandler`, `PasswordEncoding`, `PdfPassword`, `PdfCredentials`, `PdfPasswordException`, `PdfPermissions`, `PdfAccessLevel`, `PdfSecurity` | `Broadside.Tests.Security.EncryptedCorpusTests.An_encrypted_file_opens_with_the_owner_password_and_gives_owner_access`, `Broadside.Tests.Security.EncryptedCorpusTests.An_encrypted_file_opens_in_strict_mode`, `Broadside.Tests.Security.EncryptedCorpusTests.The_security_describes_the_algorithm_revision_and_key_length`, `Broadside.Tests.Security.PasswordTests.A_document_with_a_user_password_needs_a_password`, `Broadside.Tests.Security.PasswordTests.A_wrong_password_is_reported_as_incorrect`, `Broadside.Tests.Security.PasswordTests.The_user_password_opens_the_document_with_user_access`, `Broadside.Tests.Security.PasswordTests.The_owner_password_opens_the_document_with_owner_access`, `Broadside.Tests.Security.PasswordTests.User_access_has_the_permissions_the_document_grants`, `Broadside.Tests.Security.PasswordTests.A_revision_6_password_maps_soft_hyphens_to_nothing`, `Broadside.Tests.Security.PasswordTests.A_legacy_password_can_be_given_as_bytes_in_a_code_page`, `Broadside.Tests.Security.PasswordTests.A_wrong_password_for_a_document_without_a_user_password_is_still_incorrect`, `Broadside.Tests.Security.PasswordTests.The_password_given_to_open_overrides_the_one_on_the_options`, `Broadside.Tests.Security.PasswordTests.An_owner_password_computed_by_rehashing_only_the_key_length_is_accepted_with_a_diagnostic`, `Broadside.Tests.Security.PasswordTests.The_owner_key_variant_throws_in_strict_mode`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.The_standard_handler_reads_permissions_by_revision`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.An_undefined_revision_is_an_unsupported_algorithm`, `Broadside.Tests.Security.CryptographyTests.Saslprep_maps_like_rfc_4013`, `Broadside.Tests.Security.CryptographyTests.Saslprep_rejects_prohibited_characters` | 7.6.4.1 to 7.6.4.4. Revisions 2, 3, 4, 6 (and the deprecated 5, read with EncryptionRevisionInvalid); Algorithms 2, 2.A, 2.B, 3-7, 11-13; default user password first, then user, then owner (`PdfPasswordFailure.Required` / `Incorrect`); PDFDocEncoding then Latin-1 for R2-4, SASLprep + UTF-8 (127 bytes) then plain UTF-8 for R6 (bidi check not applied; NFKC needs platform globalization data); O/U/OE/UE/Perms lengths repaired with EncryptionEntryLengthInvalid; Algorithm 3 rehash-first-n variant accepted with OwnerPasswordKeyVariant (encrypted-owner-key-variant.pdf); Perms checked (EncryptionPermissionsMismatch, Perms wins); permissions by revision (Table 22); corpus encrypted-rc4-40, -rc4-128, -rc4-40-r3, -aes-128, -aes-256, -user-password, -rc4-user-password; writing encrypted files is Phase 4 | +| 7.6.4 | Standard security handler | done | `StandardSecurityHandler`, `PasswordEncoding`, `PdfPassword`, `PdfCredentials`, `PdfPasswordException`, `PdfPermissions`, `PdfAccessLevel`, `PdfSecurity` | `Broadside.Tests.Security.EncryptedCorpusTests.An_encrypted_file_opens_with_the_owner_password_and_gives_owner_access`, `Broadside.Tests.Security.EncryptedCorpusTests.An_encrypted_file_opens_in_strict_mode`, `Broadside.Tests.Security.EncryptedCorpusTests.The_security_describes_the_algorithm_revision_and_key_length`, `Broadside.Tests.Security.PasswordTests.A_document_with_a_user_password_needs_a_password`, `Broadside.Tests.Security.PasswordTests.A_wrong_password_is_reported_as_incorrect`, `Broadside.Tests.Security.PasswordTests.The_user_password_opens_the_document_with_user_access`, `Broadside.Tests.Security.PasswordTests.The_owner_password_opens_the_document_with_owner_access`, `Broadside.Tests.Security.PasswordTests.User_access_has_the_permissions_the_document_grants`, `Broadside.Tests.Security.PasswordTests.A_revision_6_password_maps_soft_hyphens_to_nothing`, `Broadside.Tests.Security.PasswordTests.A_legacy_password_can_be_given_as_bytes_in_a_code_page`, `Broadside.Tests.Security.PasswordTests.A_wrong_password_for_a_document_without_a_user_password_is_still_incorrect`, `Broadside.Tests.Security.PasswordTests.The_password_given_to_open_overrides_the_one_on_the_options`, `Broadside.Tests.Security.PasswordTests.An_owner_password_computed_by_rehashing_only_the_key_length_is_accepted_with_a_diagnostic`, `Broadside.Tests.Security.PasswordTests.The_owner_key_variant_throws_in_strict_mode`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.The_standard_handler_reads_permissions_by_revision`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.An_undefined_revision_is_an_unsupported_algorithm`, `Broadside.Tests.Security.CryptographyTests.Saslprep_maps_like_rfc_4013`, `Broadside.Tests.Security.CryptographyTests.Saslprep_rejects_prohibited_characters`, `Broadside.Tests.Security.PasswordTests.An_empty_owner_password_opens_the_document_with_owner_access`, `Broadside.Tests.Security.PasswordTests.A_128_bit_key_without_a_length_entry_is_found_by_trying_128_bits_with_a_diagnostic` | 7.6.4.1 to 7.6.4.4. Revisions 2, 3, 4, 6 (and the deprecated 5, read with EncryptionRevisionInvalid); Algorithms 2, 2.A, 2.B, 3-7, 11-13; default user password first, then user, then owner (`PdfPasswordFailure.Required` / `Incorrect`); PDFDocEncoding then Latin-1 for R2-4, SASLprep + UTF-8 (127 bytes) then plain UTF-8 for R6 (bidi check not applied; NFKC needs platform globalization data); O/U/OE/UE/Perms lengths repaired with EncryptionEntryLengthInvalid; Algorithm 3 rehash-first-n variant accepted with OwnerPasswordKeyVariant (encrypted-owner-key-variant.pdf); Perms checked (EncryptionPermissionsMismatch, Perms wins); permissions by revision (Table 22); corpus encrypted-rc4-40, -rc4-128, -rc4-40-r3, -aes-128, -aes-256, -user-password, -rc4-user-password; writing encrypted files is Phase 4. The empty string is tried as the owner password too (pdf.js pr6531_2.pdf); a V 2/3 dictionary without Length whose 40-bit default authenticates nothing is retried with 128 bits (`EncryptionKeyLengthInvalid`; qpdf bad-encryption-length.pdf) (#47). | | 7.6.5.1 | General | done | `PublicKeySecurityHandler`, `PdfCertificateCredentials`, `PdfCertificateException`, `PdfCertificateFailure`, `SecurityHandlerRegistry` | `Broadside.Tests.Security.PublicKeySecurityTests.A_document_encrypted_for_a_certificate_opens_with_that_certificate_and_its_private_key`, `Broadside.Tests.Security.PublicKeySecurityTests.Another_public_key_handler_name_opens_through_its_subfilter`, `Broadside.Tests.Security.PublicKeySecurityTests.A_recipient_named_by_subject_key_identifier_is_found_among_several_certificates`, `Broadside.Tests.Security.PublicKeySecurityTests.A_certificate_that_is_not_a_recipient_is_reported_with_the_recipients`, `Broadside.Tests.Security.PublicKeySecurityTests.A_document_encrypted_for_certificates_needs_a_certificate`, `Broadside.Tests.Security.PublicKeySecurityTests.A_recipient_certificate_without_its_private_key_cannot_open_the_document`, `Broadside.Tests.Security.PublicKeySecurityTests.A_well_formed_document_opens_in_strict_mode` | CMS (RFC 5652) through `System.Security.Cryptography.Pkcs` `EnvelopedCms`; the handler is registered by default (Filter `Adobe.PubSec`, and any Filter with SubFilter `adbe.pkcs7.s3`/`s4`/`s5`); certificates come from `PdfCertificateCredentials` (one certificate or a collection; the core never reads a store); recipients matched by issuer and serial number or subject key identifier; no certificate, no matching recipient, and a matching certificate without a usable private key are `PdfCertificateFailure.Required`/`NoMatchingRecipient`/`PrivateKeyUnavailable`, with the recipients listed; key-agreement recipients and legacy CMS ciphers the platform cannot decrypt, and every certificate on browser (WebAssembly), are `PdfEncryptionNotSupportedException` (Platform); fuzz `public-key` | | 7.6.5.2 | Public-key encryption dictionary | done | `PublicKeySecurityHandler`, `PdfPermissions`, `PdfAccessLevel` | `Broadside.Tests.Security.PublicKeySecurityTests.Permissions_are_read_most_significant_byte_first_with_the_meanings_of_revision_3`, `Broadside.Tests.Security.PublicKeySecurityTests.Permission_bit_2_enables_every_permission`, `Broadside.Tests.Security.PublicKeySecurityTests.An_s3_document_has_the_permissions_of_revision_2_and_an_s4_document_those_of_revision_3`, `Broadside.Tests.Security.PublicKeySecurityTests.A_reader_in_two_lists_has_the_permissions_of_the_first`, `Broadside.Tests.Security.PublicKeySecurityTests.A_recipient_string_padded_with_zeros_is_read_with_a_diagnostic_and_digested_whole`, `Broadside.Tests.Security.PublicKeySecurityTests.A_recipient_string_that_is_not_cms_is_skipped_with_a_diagnostic`, `Broadside.Tests.Security.PublicKeySecurityTests.A_document_with_no_recipients_cannot_be_authenticated` | Table 23 Recipients (s3/s4 in the Encrypt dictionary, s5 in the crypt filter StmF, else StrF, names; found in the other place with EncryptDictionaryInvalid Warning); first matching list wins; Table 24 permissions: s3 with revision 2 meanings, s4/s5 revision 3, bit 2 gives `PdfAccessLevel.Owner` and `PdfPermissions.All`; a Recipients string that is not CMS is skipped and one with trailing bytes read up to its DER end, both PublicKeyRecipientInvalid; no Recipients anywhere is EncryptDictionaryInvalid (Error, `DiagnosticException`) | | 7.6.5.3 | Public-key encryption algorithms | done | `PublicKeySecurityHandler`, `SecurityHandlerResult`, `DocumentDecryptor`, `DocumentSecurity` | `Broadside.Tests.Security.PublicKeySecurityTests.An_s4_document_encrypted_with_rc4_opens_with_a_128_bit_sha_1_key`, `Broadside.Tests.Security.PublicKeySecurityTests.An_s5_document_with_an_aes_128_crypt_filter_opens_with_a_128_bit_sha_1_key`, `Broadside.Tests.Security.PublicKeySecurityTests.The_key_digests_every_recipient_list_and_the_permissions_come_from_the_list_that_names_the_reader`, `Broadside.Tests.Security.PublicKeySecurityTests.Metadata_left_in_plaintext_by_the_crypt_filter_adds_the_marker_to_the_key`, `Broadside.Tests.Security.PublicKeySecurityTests.A_stream_whose_crypt_filter_has_its_own_recipients_decrypts_with_that_filter_s_key`, `Broadside.Tests.Security.PublicKeySecurityTests.A_stream_whose_crypt_filter_does_not_name_the_reader_stays_encrypted` | 20-byte seed + 4 permission bytes most significant first (shorter or longer enveloped data: PublicKeyEnvelopeInvalid); key = first n/8 bytes of SHA-1 (n up to 128) or SHA-256 (n = 256: V 5+ or CFM AESV3) over seed, every Recipients string in order (raw bytes, padding included), and 0xFF x 4 when EncryptMetadata (StmF crypt filter, else Encrypt dictionary) is false; n from CFM (AESV2 128, AESV3 256), else the crypt filter Length in bits (byte counts 5-16 read as bytes and out-of-range values clamped to 40-128, EncryptionKeyLengthInvalid), else the Encrypt Length (default 40); crypt filters with their own Recipients (a string for streams' Crypt decode parameters) get their own keys via `SecurityHandlerResult.CryptFilterKeys` (seed only, no 0xFF marker); one that does not name the reader gets an empty key, CryptFilterNotAuthorized (Information), and its streams stay encrypted; the ISO/TS 32004 MAC uses the file key, which is the StmF (DefaultCryptFilter) key for s5 (not tested end to end: no s5 file with a MAC is built yet) | diff --git a/src/Broadside/Filters/AsciiHexDecodeFilter.cs b/src/Broadside/Filters/AsciiHexDecodeFilter.cs index 6000df8f..c2d2f7aa 100644 --- a/src/Broadside/Filters/AsciiHexDecodeFilter.cs +++ b/src/Broadside/Filters/AsciiHexDecodeFilter.cs @@ -12,8 +12,8 @@ namespace Broadside.Filters; /// digit decodes as if a 0 followed it. Takes no parameters. /// /// -/// Lenient repairs: any other character is skipped (FilterDataInvalid); data without the > marker decodes to -/// its end (FilterDataTruncated). +/// Lenient repairs: any other character is skipped (FilterDataInvalid). Data without the > marker decodes to its end +/// with no diagnostic: the clause defines the marker but does not require it. /// /// public sealed class AsciiHexDecodeFilter : IStreamFilter @@ -35,12 +35,10 @@ public void Decode(ReadOnlyMemory encoded, IBufferWriter output, Fil var writer = new FilterOutput(output); int high = -1; bool invalidReported = false; - bool ended = false; foreach (byte character in input) { if (character == (byte)'>') { - ended = true; break; } @@ -70,11 +68,8 @@ public void Decode(ReadOnlyMemory encoded, IBufferWriter output, Fil writer.Write((byte)(high << 4)); } + // Data without the > marker simply ends: §7.4.2 defines the marker but, unlike §7.4.3, does not require it. writer.Flush(); - if (!ended) - { - context.Report(DiagnosticCodes.FilterDataTruncated, DiagnosticSeverity.Warning, "ASCIIHexDecode data ends without the > end-of-data marker; it is decoded to its end."); - } } /// The value of each byte as a hexadecimal digit; -1 for white-space (§7.2.3), otherwise. diff --git a/src/Broadside/Filters/StreamDecoder.cs b/src/Broadside/Filters/StreamDecoder.cs index abd17611..57aceddc 100644 --- a/src/Broadside/Filters/StreamDecoder.cs +++ b/src/Broadside/Filters/StreamDecoder.cs @@ -256,7 +256,7 @@ private void CheckExternalFile(CosStream stream) { Report( DiagnosticCodes.StreamExternalFileUnsupported, - DiagnosticSeverity.Error, + DiagnosticSeverity.Information, "The stream's data is in an external file (F), which is not read; the bytes in the stream itself are decoded instead."); } } diff --git a/src/Broadside/Parsing/CrossReferenceReader.cs b/src/Broadside/Parsing/CrossReferenceReader.cs index 7ed45179..05d773fe 100644 --- a/src/Broadside/Parsing/CrossReferenceReader.cs +++ b/src/Broadside/Parsing/CrossReferenceReader.cs @@ -1,3 +1,4 @@ +using System.Buffers; using System.Globalization; using Broadside.Diagnostics; using Broadside.Filters; @@ -35,6 +36,9 @@ internal static class CrossReferenceReader private static readonly CosName XRefStm = new("XRefStm"); + /// The white-space characters of §7.2.3 Table 1. + private static readonly SearchValues WhiteSpace = SearchValues.Create("\0\t\n\f\r "u8); + /// Reads the cross-reference sections of . /// The file. /// The header, whose offset every stated offset is relative to. @@ -146,7 +150,8 @@ private static bool TryReadStartxref(PdfSource source, FileHeader header, Diagno return false; } - if (tail[lexer.Position..].IndexOf("%%EOF"u8) < 0) + int marker = tail[lexer.Position..].IndexOf("%%EOF"u8); + if (marker < 0) { diagnostics.Report( DiagnosticCodes.EndOfFileMarkerMissing, @@ -154,6 +159,16 @@ private static bool TryReadStartxref(PdfSource source, FileHeader header, Diagno "The startxref offset is not followed by the %%EOF marker.", keyword + lexer.Position); } + else if (DataAfter(source, keyword + lexer.Position + marker + "%%EOF"u8.Length) is { } data) + { + // §7.5.5: "The last line of the file shall contain only the end-of-file marker, %%EOF." White-space after it (an + // end-of-line marker, padding) is not data. + diagnostics.Report( + DiagnosticCodes.EndOfFileMarkerNotLast, + DiagnosticSeverity.Warning, + "Data follows the %%EOF marker after the last startxref; the last line of the file shall contain only the marker. The data is ignored.", + data); + } offset = header.Offset + stated; return true; @@ -381,6 +396,30 @@ void Consider(long candidate) return null; } + /// The position of the first byte from on that is not white-space (§7.2.3), if any. + private static long? DataAfter(PdfSource source, long offset) + { + Span buffer = stackalloc byte[TailWindow]; + while (offset < source.Length) + { + Span window = buffer[..source.Read(offset, buffer[..(int)Math.Min(TailWindow, source.Length - offset)])]; + if (window.IsEmpty) + { + return null; + } + + int found = window.IndexOfAnyExcept(WhiteSpace); + if (found >= 0) + { + return offset + found; + } + + offset += window.Length; + } + + return null; + } + /// Finds the last occurrence of in the file, searching backwards one window at a time. private static long FindLast(PdfSource source, ReadOnlySpan value) { diff --git a/src/Broadside/Parsing/DiagnosticCodes.cs b/src/Broadside/Parsing/DiagnosticCodes.cs index 99d0f5de..38370fe5 100644 --- a/src/Broadside/Parsing/DiagnosticCodes.cs +++ b/src/Broadside/Parsing/DiagnosticCodes.cs @@ -13,11 +13,14 @@ internal static class DiagnosticCodes // File header (ISO 32000-2 §7.5.2). public const string HeaderMissing = nameof(HeaderMissing); public const string HeaderVersionInvalid = nameof(HeaderVersionInvalid); + public const string HeaderInvalid = nameof(HeaderInvalid); // File trailer and startxref (§7.5.5). public const string StartxrefMissing = nameof(StartxrefMissing); public const string StartxrefInvalid = nameof(StartxrefInvalid); public const string EndOfFileMarkerMissing = nameof(EndOfFileMarkerMissing); + public const string EndOfFileMarkerNotLast = nameof(EndOfFileMarkerNotLast); + public const string TrailerIdMissing = nameof(TrailerIdMissing); public const string TrailerMissing = nameof(TrailerMissing); public const string TrailerPrevInvalid = nameof(TrailerPrevInvalid); public const string RootMissing = nameof(RootMissing); @@ -31,6 +34,7 @@ internal static class DiagnosticCodes public const string XrefEntryInvalid = nameof(XrefEntryInvalid); public const string XrefEntryFormatInvalid = nameof(XrefEntryFormatInvalid); public const string XrefSubsectionNumberingInvalid = nameof(XrefSubsectionNumberingInvalid); + public const string XrefSubsectionHeaderInvalid = nameof(XrefSubsectionHeaderInvalid); public const string XrefPrevLoop = nameof(XrefPrevLoop); // Cross-reference streams and hybrid files (§7.5.8). diff --git a/src/Broadside/Parsing/FileHeader.cs b/src/Broadside/Parsing/FileHeader.cs index 85d7b5aa..bfdd4b7e 100644 --- a/src/Broadside/Parsing/FileHeader.cs +++ b/src/Broadside/Parsing/FileHeader.cs @@ -9,7 +9,9 @@ namespace Broadside.Parsing; /// ISO 32000-2 §7.5.2. Byte offsets in the file (startxref, cross-reference entries, Prev) are counted from the /// percent sign of the header, and arbitrary bytes may precede it (NOTE 1), so every offset the file states is relative to /// . A file whose writer counted from byte 0 anyway is repaired by the loader's object search and the -/// nearest-section search for startxref (issue #41). +/// nearest-section search for startxref (issue #41). A version followed by anything but an end-of-line marker is read with +/// (issue #47). The binary comment line a file with binary data shall have is not +/// checked: deciding whether the file holds binary data needs a scan of the whole file. /// /// The absolute position of the % of %PDF-; 0 when no header was found. /// The version the header states, or when it is missing or malformed. @@ -47,6 +49,16 @@ public static FileHeader Locate(PdfSource source, DiagnosticSink diagnostics) ReadOnlySpan versionText = end < 0 ? afterMarker : afterMarker[..end]; if (PdfVersion.TryParse(versionText, out PdfVersion version) && version.Major is 1 or 2) { + // "The file header shall consist of %PDF-1.n or %PDF-2.n followed by a single EOL marker" (added in 2020). + if (end >= 0 && afterMarker[end] is not ((byte)'\r' or (byte)'\n')) + { + diagnostics.Report( + DiagnosticCodes.HeaderInvalid, + DiagnosticSeverity.Warning, + "The header's version shall be followed by an end-of-line marker; the version is read and the rest of the line is ignored.", + offset: marker); + } + return new FileHeader(marker, version); } diff --git a/src/Broadside/Parsing/XrefTableReader.cs b/src/Broadside/Parsing/XrefTableReader.cs index 9e48b989..eb993ef1 100644 --- a/src/Broadside/Parsing/XrefTableReader.cs +++ b/src/Broadside/Parsing/XrefTableReader.cs @@ -69,6 +69,7 @@ internal static class XrefTableReader private static bool ReadSubsections(ref CosLexer lexer, Dictionary entries, long sectionOffset, DiagnosticSink diagnostics) { bool formatReported = false; + bool headerReported = false; while (true) { CosToken next = lexer.Peek(); @@ -79,7 +80,10 @@ private static bool ReadSubsections(ref CosLexer lexer, Dictionary + /// Whether the subsection header from to is a line of its own holding two + /// integers separated by exactly one space (§7.5.4). Spaces between the count and the end of the line are tolerated: many writers + /// (Acrobat among them) end the line with SP EOL, as an entry may, and no reader misreads it. + /// + private static bool IsSubsectionHeaderLine(ReadOnlySpan source, int start, int firstEnd, int countStart, int countEnd) + { + if (start == 0 || source[start - 1] is not ((byte)'\r' or (byte)'\n') || countStart != firstEnd + 1 || source[firstEnd] != (byte)' ') + { + return false; + } + + int end = countEnd; + while (end < source.Length && source[end] == (byte)' ') + { + end++; + } + + return end < source.Length && source[end] is (byte)'\r' or (byte)'\n'; + } + /// Whether starts with the exact 20-byte form of §7.5.4: nnnnnnnnnn ggggg n plus a two-byte end of line. private static bool IsTwentyByteEntry(ReadOnlySpan entry) { diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 61b5949a..5c0e9ec2 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -48,6 +48,8 @@ namespace Broadside; /// public sealed class PdfDocument : IDisposable { + private static readonly PdfVersion Pdf20 = new(2, 0); + private readonly PdfSource _source; private readonly DiagnosticSink _diagnostics; private readonly ObjectLoader _loader; @@ -476,7 +478,19 @@ internal static PdfDocument Read(PdfSource source, EngineConfiguration configura } PdfLinearization? linearization = LinearizationReader.Read(source, loader, diagnostics); - return new PdfDocument(source, diagnostics, loader, streams, catalog, revisions, linearization, security); + var document = new PdfDocument(source, diagnostics, loader, streams, catalog, revisions, linearization, security); + + // Table 15: ID is "required in PDF 2.0 or if an Encrypt entry is present" (the latter is the security handler's + // EncryptionIdMissing). + if (security is null && document.Version >= Pdf20 && !loader.CrossReference.Trailer.ContainsKey(KnownNames.ID)) + { + diagnostics.Report( + DiagnosticCodes.TrailerIdMissing, + DiagnosticSeverity.Warning, + "The document is PDF 2.0, whose trailer shall have an ID entry; it has none."); + } + + return document; } catch { diff --git a/src/Broadside/Security/StandardSecurityHandler.cs b/src/Broadside/Security/StandardSecurityHandler.cs index 9495918d..cb5f4cae 100644 --- a/src/Broadside/Security/StandardSecurityHandler.cs +++ b/src/Broadside/Security/StandardSecurityHandler.cs @@ -201,8 +201,41 @@ private static SecurityHandlerResult AuthenticateLegacy( bool encryptMetadata = version < 4 || revision < 4 || (ReadBoolean(context, dictionary, EncryptMetadata) ?? true); byte[] owner = ReadEntry(context, dictionary, O, 32, required: true)!; byte[] user = ReadEntry(context, dictionary, U, 32, required: true)!; - var legacy = new LegacyKeys(revision, keyLength, owner, user, rawPermissions, context.DocumentId.Span.ToArray(), encryptMetadata); + byte[] documentId = context.DocumentId.Span.ToArray(); + var legacy = new LegacyKeys(revision, keyLength, owner, user, rawPermissions, documentId, encryptMetadata); + if (TryLegacyPasswords(context, legacy, password, revision, rawPermissions) is { } result) + { + return result; + } + + // Table 20: Length is optional and defaults to 40 bits. A writer that left it out for a 128-bit key (qpdf's test file + // bad-encryption-length.pdf; qpdf assumes 128 bits whenever Length is missing) is read by trying 128 bits once 40 bits + // authenticate nothing. + if (revision >= 3 && version is 2 or 3 && !dictionary.ContainsKey(LengthName)) + { + var longer = new LegacyKeys(revision, 16, owner, user, rawPermissions, documentId, encryptMetadata); + if (TryLegacyPasswords(context, longer, password, revision, rawPermissions) is { } repaired) + { + context.Report( + DiagnosticCodes.EncryptionKeyLengthInvalid, + DiagnosticSeverity.Warning, + "The encryption dictionary has no Length entry, so the key is 40 bits long (Table 20), but only a 128-bit key authenticates; it is read as 128 bits."); + return repaired; + } + } + throw new PdfPasswordException(password is null || password.IsEmpty ? PdfPasswordFailure.Required : PdfPasswordFailure.Incorrect); + } + + /// Algorithms 6 and 7 for every encoding of : the user password first, then the owner password. + /// The result, or when no encoding authenticates. + private static SecurityHandlerResult? TryLegacyPasswords( + SecurityHandlerContext context, + LegacyKeys legacy, + PdfPassword? password, + int revision, + int rawPermissions) + { PdfPermissions userPermissions = UserPermissions(rawPermissions, revision); foreach (byte[] candidate in PasswordEncoding.Legacy(password)) { @@ -211,13 +244,14 @@ private static SecurityHandlerResult AuthenticateLegacy( return new SecurityHandlerResult(userKey, PdfAccessLevel.User, userPermissions, rawPermissions) { Revision = revision }; } - if (candidate.Length > 0 && legacy.TryOwner(candidate, context) is { } ownerKey) + // The empty string is a password like any other: Algorithm 7 does not exclude it. + if (legacy.TryOwner(candidate, context) is { } ownerKey) { return new SecurityHandlerResult(ownerKey, PdfAccessLevel.Owner, PdfPermissions.All, rawPermissions) { Revision = revision }; } } - throw new PdfPasswordException(password is null || password.IsEmpty ? PdfPasswordFailure.Required : PdfPasswordFailure.Incorrect); + return null; } private static SecurityHandlerResult AuthenticateModern( @@ -243,8 +277,9 @@ private static SecurityHandlerResult AuthenticateModern( { access = PdfAccessLevel.User; } - else if (candidate.Length > 0 && (key = TryModernOwner(revision, candidate, owner, user, ownerEncryption)) is not null) + else if ((key = TryModernOwner(revision, candidate, owner, user, ownerEncryption)) is not null) { + // An empty owner password is a password like any other (Algorithms 9 and 12; pdf.js test file pr6531_2.pdf). access = PdfAccessLevel.Owner; } diff --git a/tests/Broadside.TestSupport/Broadside.TestSupport.csproj b/tests/Broadside.TestSupport/Broadside.TestSupport.csproj index 74232a99..ac5050be 100644 --- a/tests/Broadside.TestSupport/Broadside.TestSupport.csproj +++ b/tests/Broadside.TestSupport/Broadside.TestSupport.csproj @@ -11,6 +11,7 @@ + diff --git a/tests/Broadside.TestSupport/Corpus.cs b/tests/Broadside.TestSupport/Corpus.cs index 14474402..e98e5c47 100644 --- a/tests/Broadside.TestSupport/Corpus.cs +++ b/tests/Broadside.TestSupport/Corpus.cs @@ -33,6 +33,7 @@ public static class Corpus "encrypted-crypt-filters.pdf", "encrypted-aes-gcm.pdf", "encrypted-mac.pdf", + "encrypted-empty-owner-password.pdf", "inline-image.pdf", "page-tree-inherited.pdf", "annotations-link.pdf", @@ -50,6 +51,7 @@ public static class Corpus "startxref-wrong.pdf", "encrypted-mac-tampered.pdf", "encrypted-owner-key-variant.pdf", + "encrypted-rc4-length-missing.pdf", ]; private static readonly (string FileName, string UserPassword)[] PasswordProtected = diff --git a/tests/Broadside.TestSupport/CorpusLocator.cs b/tests/Broadside.TestSupport/CorpusLocator.cs index fbad3f7b..a39b0b6a 100644 --- a/tests/Broadside.TestSupport/CorpusLocator.cs +++ b/tests/Broadside.TestSupport/CorpusLocator.cs @@ -14,6 +14,17 @@ internal static class CorpusLocator /// The absolute path of tests/Corpus/. public static string CorpusDirectory { get; } = FindCorpusDirectory(); + /// The environment variable that names the real-world corpus directory, overriding the search. + public const string RealWorldCorpusVariable = "BROADSIDE_CORPUS_DIR"; + + /// + /// The directory tools/CorpusFetcher fetched the real-world corpora into (one sub-directory per corpus id), or + /// when none is fetched. wins; otherwise the gitignored + /// corpus/ of this checkout, or of the nearest enclosing checkout (a git worktree under .claude/worktrees/ reuses + /// the main checkout's corpora). + /// + public static string? RealWorldCorpusDirectory { get; } = FindRealWorldCorpusDirectory(); + /// Every .pdf in the corpus directory, sorted by ordinal file name. public static string[] CorpusFiles() { @@ -39,6 +50,26 @@ private static string FindRepositoryRoot() $"Could not find Broadside.slnx in any parent of '{AppContext.BaseDirectory}'. Corpus-driven code must run from a checkout of the repository."); } + private static string? FindRealWorldCorpusDirectory() + { + string? configured = Environment.GetEnvironmentVariable(RealWorldCorpusVariable); + if (!string.IsNullOrWhiteSpace(configured)) + { + return Directory.Exists(configured) ? Path.GetFullPath(configured) : null; + } + + for (DirectoryInfo? directory = new(RepositoryRoot); directory is not null; directory = directory.Parent) + { + string corpus = Path.Combine(directory.FullName, "corpus"); + if (File.Exists(Path.Combine(directory.FullName, "Broadside.slnx")) && Directory.Exists(corpus)) + { + return corpus; + } + } + + return null; + } + private static string FindCorpusDirectory() { string corpus = Path.Combine(RepositoryRoot, "tests", "Corpus"); diff --git a/tests/Broadside.TestSupport/DocumentWalker.cs b/tests/Broadside.TestSupport/DocumentWalker.cs new file mode 100644 index 00000000..572aabdc --- /dev/null +++ b/tests/Broadside.TestSupport/DocumentWalker.cs @@ -0,0 +1,152 @@ +using System.Buffers; +using Broadside.Objects; + +namespace Broadside.TestSupport; + +/// What one pass read. +/// The page count. +/// How many distinct indirect objects resolved to something other than null. +/// How many distinct streams were decoded through the filter pipeline. +/// The total length of the decoded stream data. +public sealed record DocumentWalkResult(int Pages, int Objects, int Streams, long DecodedBytes); + +/// +/// Reads everything the document model exposes, so that "the file opens" means more than "the trailer parsed" (objects load +/// lazily, issue #45): version, trailer, revisions, linearization and hint tables, security, every page's boxes, rotation, user unit +/// and resources, every indirect object reachable from the trailer and every object number below the trailer's Size, and +/// every stream decoded through the filter pipeline (image filters that are not implemented yet end in a diagnostic, not an +/// exception). Used by the real-world corpus gate (issue #47) and meant to be shared with the open-and-walk fuzz target and +/// benchmark (issue #48): link this file as source there, as is. Public API only. +/// +/// ISO 32000-2 §7 (file structure, objects, filters, encryption), §7.7.3 (page tree). +public static class DocumentWalker +{ + /// The highest object number resolved by number alone; a damaged trailer may claim any Size. + public const int MaxObjectNumber = 8_388_607; + + private static readonly CosName SizeKey = new("Size"); + + /// Walks . Every exception the library throws propagates to the caller. + /// An open document. + /// What was read. + public static DocumentWalkResult Walk(PdfDocument document) + { + ArgumentNullException.ThrowIfNull(document); + + _ = document.Version; + _ = document.Catalog.Count; + _ = document.IsEncrypted; + _ = (document.Security?.Revision, document.Permissions); + foreach (PdfRevision revision in document.Revisions) + { + _ = (revision.Index, revision.Length, revision.Trailer.Count); + } + + _ = document.IsLinearized; + if (document.Linearization is { } linearization) + { + _ = (linearization.FileLength, linearization.PageCount, linearization.FirstPageObjects.Count); + _ = (linearization.Hints?.Pages.Count, linearization.Hints?.SharedObjects.Count); + } + + int pages = 0; + foreach (PdfPage page in document.Pages) + { + pages++; + _ = (page.MediaBox, page.CropBox, page.BleedBox, page.TrimBox, page.ArtBox, page.Rotation, page.UserUnit, page.Resources?.Count); + } + + var walk = new GraphWalk(document); + walk.Visit(document.Trailer); + long size = document.Trailer.TryGetValue(SizeKey, out CosObject? entry) && entry is CosInteger integer ? integer.Value : 0; + for (int number = 1; number < Math.Min(size, MaxObjectNumber + 1L); number++) + { + walk.Visit(new CosReference(number, 0)); + } + + return new DocumentWalkResult(pages, walk.Objects, walk.Streams, walk.DecodedBytes); + } + + /// An iterative depth-first walk (no recursion: real files nest deeply) over references, containers and streams. + private sealed class GraphWalk(PdfDocument document) + { + private readonly HashSet _references = []; + private readonly HashSet _containers = new(ReferenceEqualityComparer.Instance); + private readonly Stack _pending = new(); + private readonly DiscardingWriter _sink = new(); + + public int Objects { get; private set; } + + public int Streams { get; private set; } + + public long DecodedBytes => _sink.Written; + + public void Visit(CosObject root) + { + _pending.Push(root); + while (_pending.TryPop(out CosObject? value)) + { + switch (value) + { + case CosReference reference: + if (_references.Add(reference)) + { + CosObject resolved = document.Resolve(reference); + if (resolved is not CosNull) + { + Objects++; + _pending.Push(resolved); + } + } + + break; + case CosDictionary dictionary when _containers.Add(dictionary): + foreach (KeyValuePair item in dictionary) + { + _pending.Push(item.Value); + } + + break; + case CosArray array when _containers.Add(array): + foreach (CosObject item in array) + { + _pending.Push(item); + } + + break; + case CosStream stream when _containers.Add(stream): + Streams++; + document.DecodeStream(stream, _sink); + _pending.Push(stream.Dictionary); + break; + default: + break; + } + } + } + } + + /// Counts what the filter pipeline writes and keeps none of it, so decoding a large file holds no decoded data. + private sealed class DiscardingWriter : IBufferWriter + { + private byte[] _buffer = new byte[64 * 1024]; + + public long Written { get; private set; } + + public void Advance(int count) => Written += count; + + public Memory GetMemory(int sizeHint = 0) => Buffer(sizeHint); + + public Span GetSpan(int sizeHint = 0) => Buffer(sizeHint); + + private byte[] Buffer(int sizeHint) + { + if (sizeHint > _buffer.Length) + { + _buffer = new byte[sizeHint]; + } + + return _buffer; + } + } +} diff --git a/tests/Broadside.TestSupport/RealWorldCorpus.cs b/tests/Broadside.TestSupport/RealWorldCorpus.cs new file mode 100644 index 00000000..c398d27f --- /dev/null +++ b/tests/Broadside.TestSupport/RealWorldCorpus.cs @@ -0,0 +1,197 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using Broadside.Diagnostics; +using Broadside.Security; + +namespace Broadside.TestSupport; + +/// How opening and walking one real-world file ended. +public enum CorpusOutcomeKind +{ + /// Opened and walked with no Warning or Error diagnostic. + Clean, + + /// Opened and walked; repairs or deviations were recorded as diagnostics. + Diagnostics, + + /// Encrypted with a user password that is not empty (): a documented outcome. + PasswordRequired, + + /// Encrypted for certificate recipients (): a documented outcome. + CertificateRequired, + + /// Encrypted by a handler or algorithm this engine does not implement (). + EncryptionUnsupported, + + /// + /// The library gave up with a : in lenient mode, a file whose structure cannot be read at all; + /// in strict mode, the first deviation. + /// + Rejected, + + /// Any other exception: a bug. + Crash, + + /// The file did not finish within the time limit: a bug. + Timeout, +} + +/// The outcome of one file. +/// How it ended. +/// The distinct codes of the Warning and Error diagnostics, ordinal order; for , the code thrown. +/// The exception, for anything that threw. +/// Managed bytes allocated by the open and walk (on the thread that ran them). +/// How long it took. +public sealed record CorpusOutcome(CorpusOutcomeKind Kind, IReadOnlyList Codes, string? Detail, long AllocatedBytes, TimeSpan Elapsed) +{ + /// Gets whether the outcome is a bug in the reader: an unexpected exception or a hang. + public bool IsFailure => Kind is CorpusOutcomeKind.Crash or CorpusOutcomeKind.Timeout; +} + +/// +/// The real-world corpora fetched by tools/CorpusFetcher (gitignored corpus/<id>/): file enumeration and the +/// open-and-walk run the corpus gate (issue #47) applies to each file, with a time limit so one file cannot stall a run. +/// +public static class RealWorldCorpus +{ + /// The environment variable that names the corpus root, overriding the search for corpus/. + public const string EnvironmentVariable = CorpusLocator.RealWorldCorpusVariable; + + /// How long one file may take before it counts as a hang. + public static readonly TimeSpan TimeLimit = TimeSpan.FromSeconds(30); + + private static readonly ConcurrentDictionary<(string Path, bool Strict), Lazy>> Outcomes = new(); + + /// At most one walk per processor at a time, however many files are awaited together. + private static readonly SemaphoreSlim Gate = new(Environment.ProcessorCount); + + /// The directory of the corpus , or when it is not fetched. + /// A corpus id from tools/CorpusFetcher/corpora.json. + /// The directory. + public static string? Directory(string id) => + CorpusLocator.RealWorldCorpusDirectory is { } root && System.IO.Directory.Exists(Path.Combine(root, id)) ? Path.Combine(root, id) : null; + + /// + /// Every PDF of corpus (any case of the .pdf extension) as a path relative to the corpus root, + /// with forward slashes, ordinal order; empty when the corpus is not fetched. + /// + /// A corpus id. + /// The relative paths, starting with . + public static IReadOnlyList Files(string id) + { + if (Directory(id) is not { } directory) + { + return []; + } + + string root = CorpusLocator.RealWorldCorpusDirectory!; + return + [ + .. System.IO.Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories) + .Where(static path => path.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)) + .Select(path => Path.GetRelativePath(root, path).Replace('\\', '/')) + .Order(StringComparer.Ordinal), + ]; + } + + /// The absolute path of a file named relative to the corpus root. + /// A path from . + /// The path. + public static string PathOf(string relativePath) => + Path.Combine(CorpusLocator.RealWorldCorpusDirectory ?? throw new InvalidOperationException("No real-world corpus is fetched."), relativePath); + + /// + /// Opens the file from bytes with the empty password and walks it with , once per file and mode + /// for the whole test run (the theory and the summary share the result). The walk runs on its own task with + /// ; a hung walk is abandoned (the library has no cancellation), reported as a timeout, and keeps its + /// thread. + /// + /// A path from . + /// Strict mode instead of lenient mode. + /// The outcome. + public static Task OutcomeAsync(string relativePath, bool strict = false) => + Outcomes.GetOrAdd((relativePath, strict), key => new Lazy>(() => RunAsync(key.Path, key.Strict))).Value; + + private static async Task RunAsync(string relativePath, bool strict) + { + await Gate.WaitAsync().ConfigureAwait(false); + try + { + return await RunGatedAsync(relativePath, strict).ConfigureAwait(false); + } + finally + { + // A walk that timed out keeps running on its own thread; its slot is released anyway so the run goes on. + Gate.Release(); + } + } + + private static async Task RunGatedAsync(string relativePath, bool strict) + { + byte[] bytes = await File.ReadAllBytesAsync(PathOf(relativePath)).ConfigureAwait(false); + var stopwatch = Stopwatch.StartNew(); + Task walk = Task.Factory.StartNew( + () => Walk(bytes, strict, stopwatch), + CancellationToken.None, + TaskCreationOptions.LongRunning, + TaskScheduler.Default); + try + { + return await walk.WaitAsync(TimeLimit).ConfigureAwait(false); + } + catch (TimeoutException) + { + return new CorpusOutcome(CorpusOutcomeKind.Timeout, [], $"Did not finish within {TimeLimit.TotalSeconds} s.", 0, stopwatch.Elapsed); + } + } + + private static CorpusOutcome Walk(byte[] bytes, bool strict, Stopwatch stopwatch) + { + long before = GC.GetAllocatedBytesForCurrentThread(); + CorpusOutcome Outcome(CorpusOutcomeKind kind, IReadOnlyList codes, string? detail = null) => + new(kind, codes, detail, GC.GetAllocatedBytesForCurrentThread() - before, stopwatch.Elapsed); + + try + { + var options = new PdfOptions(); + if (strict) + { + options.UseStrict(); + } + + using PdfDocument document = PdfDocument.Open(bytes, options); + _ = DocumentWalker.Walk(document); + string[] codes = + [ + .. document.Diagnostics + .Where(static diagnostic => diagnostic.Severity > DiagnosticSeverity.Information) + .Select(static diagnostic => diagnostic.Code) + .Distinct() + .Order(StringComparer.Ordinal), + ]; + return Outcome(codes.Length == 0 ? CorpusOutcomeKind.Clean : CorpusOutcomeKind.Diagnostics, codes); + } + catch (DiagnosticException exception) + { + return Outcome(CorpusOutcomeKind.Rejected, [exception.Diagnostic.Code], exception.Message); + } + catch (PdfPasswordException exception) + { + return Outcome(CorpusOutcomeKind.PasswordRequired, [], exception.Message); + } + catch (PdfCertificateException exception) + { + return Outcome(CorpusOutcomeKind.CertificateRequired, [], exception.Message); + } + catch (PdfEncryptionNotSupportedException exception) + { + return Outcome(CorpusOutcomeKind.EncryptionUnsupported, [], exception.Message); + } +#pragma warning disable CA1031 // Any other exception is the finding this run exists to report. + catch (Exception exception) +#pragma warning restore CA1031 + { + return Outcome(CorpusOutcomeKind.Crash, [], exception.ToString()); + } + } +} diff --git a/tests/Broadside.Tests/Document/ConcurrencyTests.cs b/tests/Broadside.Tests/Document/ConcurrencyTests.cs index 37adb5ec..ead8cd75 100644 --- a/tests/Broadside.Tests/Document/ConcurrencyTests.cs +++ b/tests/Broadside.Tests/Document/ConcurrencyTests.cs @@ -30,6 +30,9 @@ public class ConcurrencyTests /// The owner password of the encrypted corpus files, so the password-protected ones open too (ignored elsewhere). private static readonly PdfOptions Options = new PdfOptions().WithPassword("owner"); + /// No password for the one file whose owner password is empty: owner is neither of its passwords. + private static PdfOptions OptionsFor(string fileName) => fileName == "encrypted-empty-owner-password.pdf" ? new PdfOptions() : Options; + public static TheoryData FilesBySource { get @@ -54,7 +57,7 @@ public void Every_page_and_object_reads_the_same_from_many_threads_as_from_one(s Reading expected; try { - using PdfDocument alone = PdfDocument.Open(Corpus.Bytes(fileName), Options); + using PdfDocument alone = PdfDocument.Open(Corpus.Bytes(fileName), OptionsFor(fileName)); expected = Reading.Of(alone, References(alone)); } catch (DiagnosticException unreadable) @@ -126,18 +129,18 @@ private static CosReference[] References(PdfDocument document) private static PdfDocument Open(string fileName, ConcurrentSource source) => source switch { - ConcurrentSource.Bytes => PdfDocument.Open(Corpus.Bytes(fileName), Options), - ConcurrentSource.Path => PdfDocument.Open(Corpus.Path(fileName), Options), + ConcurrentSource.Bytes => PdfDocument.Open(Corpus.Bytes(fileName), OptionsFor(fileName)), + ConcurrentSource.Path => PdfDocument.Open(Corpus.Path(fileName), OptionsFor(fileName)), ConcurrentSource.FileStream => OpenFileStream(fileName), - ConcurrentSource.SeekableStream => PdfDocument.Open(new ProbeStream(Corpus.Bytes(fileName)), Options), - _ => PdfDocument.Open(new ProbeStream(Corpus.Bytes(fileName), seekable: false), Options), + ConcurrentSource.SeekableStream => PdfDocument.Open(new ProbeStream(Corpus.Bytes(fileName)), OptionsFor(fileName)), + _ => PdfDocument.Open(new ProbeStream(Corpus.Bytes(fileName), seekable: false), OptionsFor(fileName)), }; /// Opens through a the test then closes: the mapping outlives the caller's handle. private static PdfDocument OpenFileStream(string fileName) { using FileStream stream = Corpus.Open(fileName); - return PdfDocument.Open(stream, Options); + return PdfDocument.Open(stream, OptionsFor(fileName)); } /// What one complete read of a document saw, as values. diff --git a/tests/Broadside.Tests/Document/FileLayoutTests.cs b/tests/Broadside.Tests/Document/FileLayoutTests.cs new file mode 100644 index 00000000..02154eab --- /dev/null +++ b/tests/Broadside.Tests/Document/FileLayoutTests.cs @@ -0,0 +1,172 @@ +using System.Text; +using Broadside.Diagnostics; + +namespace Broadside.Tests.Document; + +/// +/// The line layout ISO 32000-2 requires of the header, the cross-reference subsection headers and the end of the file, and the +/// trailer's ID in a PDF 2.0 file. Each case is a deviation the veraPDF agreement check of the real-world corpus gate (issue #47) +/// found strict mode accepting; each is read leniently with one diagnostic, and strict mode throws it. ISO 32000-2 §7.5.2, §7.5.4, +/// §7.5.5 Table 15. +/// +public class FileLayoutTests +{ + public static TheoryData Deviations => new() + { + { "header followed by spaces", "HeaderInvalid" }, + { "two spaces in a subsection header", "XrefSubsectionHeaderInvalid" }, + { "space before a subsection header", "XrefSubsectionHeaderInvalid" }, + { "data after the last %%EOF", "EndOfFileMarkerNotLast" }, + { "PDF 2.0 trailer without ID", "TrailerIdMissing" }, + }; + + public static TheoryData TrailerIdCases => new() + { + { "%PDF-1.7", "", "" }, + { "%PDF-2.0", "", "/ID [<0123> <0123>]" }, + { "%PDF-1.7", "/Version /2.0", "/ID [<0123> <0123>]" }, + }; + + [Theory] + [MemberData(nameof(Deviations))] + public void A_layout_deviation_is_read_with_one_diagnostic(string deviation, string code) + { + using PdfDocument document = PdfDocument.Open(File(deviation)); + + _ = Assert.Single(document.Pages); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal(code, diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); + } + + [Theory] + [MemberData(nameof(Deviations))] + public void Strict_mode_throws_on_a_layout_deviation(string deviation, string code) + { + DiagnosticException error = Assert.Throws(() => PdfDocument.Open(File(deviation), new PdfOptions().UseStrict())); + + Assert.Equal(code, error.Diagnostic.Code); + } + + [Theory] + [InlineData("%PDF-1.7\r\n")] + [InlineData("%PDF-1.7\r")] + public void A_header_ended_by_any_end_of_line_marker_has_no_diagnostic(string header) + { + byte[] file = Replace(TestPdf.OnePage("/MediaBox [0 0 612 792]"), "%PDF-1.7\n", header); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Empty(document.Diagnostics); + } + + [Theory] + [InlineData("xref\r\n0 4\r\n")] + [InlineData("xref \n0 4\n")] + [InlineData("xref\n\n0 4\n")] + [InlineData("xref\n0 4 \n")] + public void A_subsection_header_on_its_own_line_has_no_diagnostic_whatever_ends_the_xref_line(string layout) + { + // §7.5.4 asks for "a line containing only two integers separated by a SPACE"; of the xref line it asks only that it contain + // the keyword. White-space after the keyword, and a blank line, are PDF/A-1 rules (ISO 19005-1 6.1.4), not ISO 32000-2 ones. + // A space before the end of the subsection header line is tolerated: Acrobat writes it (pdf.js TAMReview.pdf, qpdf enc-base.pdf). + byte[] file = Replace(TestPdf.OnePage("/MediaBox [0 0 612 792]"), "xref\n0 4\n", layout); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Empty(document.Diagnostics); + } + + [Theory] + [InlineData("\n")] + [InlineData("\r\n")] + [InlineData("\r\n\0\0 \n")] + [InlineData("")] + public void White_space_after_the_last_end_of_file_marker_has_no_diagnostic(string tail) + { + byte[] file = [.. Trimmed(TestPdf.OnePage("/MediaBox [0 0 612 792]")), .. Encoding.Latin1.GetBytes(tail)]; + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Data_far_after_the_last_end_of_file_marker_is_found() + { + byte[] file = [.. TestPdf.OnePage("/MediaBox [0 0 612 792]"), .. new byte[5000], .. "x"u8]; + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal("EndOfFileMarkerNotLast", Assert.Single(document.Diagnostics).Code); + } + + [Theory] + [MemberData(nameof(TrailerIdCases))] + public void A_trailer_id_is_required_only_from_pdf_2_0(string header, string catalogEntries, string trailerEntries) + { + byte[] file = new TestPdf { Header = header, TrailerEntries = trailerEntries }.Build( + $"<< /Type /Catalog /Pages 2 0 R {catalogEntries} >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>"); + + using PdfDocument document = PdfDocument.Open(file); + + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_catalog_version_of_2_0_requires_the_trailer_id_too() + { + using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", "/Version /2.0")); + + Assert.Equal("TrailerIdMissing", Assert.Single(document.Diagnostics).Code); + } + + private static byte[] File(string deviation) + { + byte[] file = TestPdf.OnePage("/MediaBox [0 0 612 792]"); + return deviation switch + { + "header followed by spaces" => Replace(file, "%PDF-1.7\n", "%PDF-1.7 \n"), + "two spaces in a subsection header" => Replace(file, "xref\n0 4\n", "xref\n0 4\n"), + "space before a subsection header" => Replace(file, "xref\n0 4\n", "xref\n 0 4\n"), + "data after the last %%EOF" => [.. file, .. "SomeData"u8], + "PDF 2.0 trailer without ID" => TestPdf.OnePage("/MediaBox [0 0 612 792]", header: "%PDF-2.0"), + _ => throw new ArgumentOutOfRangeException(nameof(deviation)), + }; + } + + /// Replaces , which must occur once, keeping every offset before it. + private static byte[] Replace(byte[] file, string before, string after) + { + string text = Encoding.Latin1.GetString(file); + int at = text.IndexOf(before, StringComparison.Ordinal); + Assert.True(at >= 0 && text.IndexOf(before, at + 1, StringComparison.Ordinal) < 0, $"'{before}' must occur once."); + string replaced = text[..at] + after + text[(at + before.Length)..]; + + // Cross-reference offsets count from the header; a header of another length moves every object. + int shift = after.Length - before.Length; + if (at == 0 && shift != 0) + { + replaced = Shift(replaced, shift); + } + + return Encoding.Latin1.GetBytes(replaced); + } + + /// Rewrites every 10-digit in-use offset and the startxref offset of a file by . + private static string Shift(string text, int shift) + { + string shifted = System.Text.RegularExpressions.Regex.Replace( + text, + "(?m)^(\\d{10}) 00000 n", + match => $"{long.Parse(match.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture) + shift:D10} 00000 n"); + return System.Text.RegularExpressions.Regex.Replace( + shifted, + "startxref\\n(\\d+)", + match => $"startxref\n{long.Parse(match.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture) + shift}"); + } + + private static byte[] Trimmed(byte[] file) => Encoding.Latin1.GetBytes(Encoding.Latin1.GetString(file).TrimEnd('\n')); +} diff --git a/tests/Broadside.Tests/Document/RealWorldCorpusTests.cs b/tests/Broadside.Tests/Document/RealWorldCorpusTests.cs new file mode 100644 index 00000000..54cb1965 --- /dev/null +++ b/tests/Broadside.Tests/Document/RealWorldCorpusTests.cs @@ -0,0 +1,153 @@ +using System.Globalization; +using System.Text; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// +/// The real-world corpus gate (issue #47): every PDF of the pdf.js, PDFBox, qpdf and PDFium corpora (and the PDF Association's PDF +/// 2.0 examples) opens in lenient mode and walks completely (: pages, every object, every stream +/// decoded) without an exception and within . The documented outcomes that are not crashes +/// are counted per corpus: a password or a certificate is required, the encryption is not supported, or the file is listed in +/// . The corpora are fetched by tools/CorpusFetcher and are not in CI; every test skips when they +/// are absent. ISO 32000-2 §7. +/// +[Trait("Category", "Corpus")] +public class RealWorldCorpusTests(ITestOutputHelper output) +{ + /// The corpora of the gate, by fetcher id. + public static readonly string[] CorpusIds = ["pdfjs", "pdfbox", "qpdf", "pdfium-tests", "pdf20examples"]; + + /// + /// Files no reader can open in lenient mode: each threw CatalogNotFound, and each was checked by hand against qpdf 12.4.2 + /// (qpdf --show-npages fails on every one) and poppler (pdfinfo). A file another reader opens does not belong here. + /// + public static readonly IReadOnlyDictionary Unreadable = new Dictionary(StringComparer.Ordinal) + { + ["pdfbox/org/apache/pdfbox/pdfparser/PDFBOX-6041-example.pdf"] = "No %PDF- header and no trailer (pdfinfo: Couldn't find trailer dictionary).", + ["pdfium-tests/fx/FRC_3.5_part1/FRC_3.5_Encrypt_is_damage.pdf"] = "Encrypt dictionary and cross-reference deliberately damaged (qpdf: xref not found; pdfinfo: Unknown compression method).", + ["pdfjs/Brotli-Prototype-FileA.pdf"] = "Cross-reference stream and the object stream holding the page tree use /BrotliDecode, which ISO 32000-2:2020 does not define (qpdf: unfilterable stream; poppler 25+ reads Brotli).", + ["pdfjs/REDHAT-1531897-0.pdf"] = "Fuzzed: cross-reference stream with an out-of-range number and no recoverable catalog (qpdf and pdfinfo fail too).", + ["qpdf/bad1.pdf"] = "Not a PDF: no header, no objects (qpdf: can't find PDF header).", + ["qpdf/issue-100.pdf"] = "Fuzzed (qpdf issue 100): no readable cross-reference and no catalog.", + ["qpdf/issue-101.pdf"] = "Fuzzed (qpdf issue 101): no readable cross-reference and no catalog.", + ["qpdf/issue-141a.pdf"] = "Fuzzed (qpdf issue 141): cross-reference stream without Length, no catalog.", + ["qpdf/issue-141b.pdf"] = "Fuzzed (qpdf issue 141): no header, no catalog.", + ["qpdf/issue-146.pdf"] = "Fuzzed (qpdf issue 146): no startxref, no catalog.", + ["qpdf/issue-147.pdf"] = "Fuzzed (qpdf issue 147): no header, no catalog.", + ["qpdf/issue-148.pdf"] = "Fuzzed (qpdf issue 148): cross-reference stream without Length, no catalog.", + ["qpdf/issue-150.pdf"] = "Fuzzed (qpdf issue 150): integer overflow in the cross-reference stream, no catalog.", + ["qpdf/issue-263.pdf"] = "Fuzzed (qpdf issue 263): no header, no catalog.", + ["qpdf/issue-335a.pdf"] = "Fuzzed (qpdf issue 335): no header, no catalog.", + ["qpdf/issue-335b.pdf"] = "Fuzzed (qpdf issue 335): no header, no trailer, no catalog.", + ["qpdf/issue-99b.pdf"] = "Fuzzed (qpdf issue 99): object 0 referenced, no catalog.", + }; + + public static TheoryData Files + { + get + { + var data = new TheoryData(); + foreach (string id in CorpusIds) + { + IReadOnlyList files = RealWorldCorpus.Files(id); + if (files.Count == 0) + { + data.Add($"{id}/(not fetched)"); + } + + foreach (string file in files) + { + data.Add(file); + } + } + + return data; + } + } + + [Theory] + [MemberData(nameof(Files))] + public async Task A_real_world_file_opens_and_walks_leniently_without_an_exception(string file) + { + SkipWhenNotFetched(file); + + CorpusOutcome outcome = await RealWorldCorpus.OutcomeAsync(file); + + Assert.False(outcome.IsFailure, $"{outcome.Kind}: {outcome.Detail}"); + if (outcome.Kind == CorpusOutcomeKind.Rejected) + { + Assert.True(Unreadable.ContainsKey(file), $"Lenient mode gave up on a file that is not listed as unreadable: {outcome.Detail}"); + } + } + + [Fact] + public async Task The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot() + { + string[] fetched = [.. CorpusIds.Where(id => RealWorldCorpus.Directory(id) is not null)]; + if (fetched.Length != CorpusIds.Length) + { + Assert.Skip($"Corpora not fetched ({string.Join(", ", CorpusIds.Except(fetched))}); run tools/CorpusFetcher."); + } + + var outcomes = new Dictionary(StringComparer.Ordinal); + foreach (string id in CorpusIds) + { + string[] files = [.. RealWorldCorpus.Files(id)]; + CorpusOutcome[] results = await Task.WhenAll(files.Select(file => RealWorldCorpus.OutcomeAsync(file))); + for (int index = 0; index < files.Length; index++) + { + outcomes[files[index]] = results[index]; + } + } + + string summary = Summarize(outcomes); + output.WriteLine(summary); + foreach ((string file, CorpusOutcome outcome) in outcomes.OrderByDescending(entry => entry.Value.AllocatedBytes).Take(5)) + { + output.WriteLine(string.Create(CultureInfo.InvariantCulture, $"allocated {outcome.AllocatedBytes / (1024 * 1024)} MB, {outcome.Elapsed.TotalMilliseconds:F0} ms: {file}")); + } + + string[] failures = [.. outcomes.Where(entry => entry.Value.IsFailure).Select(entry => $"{entry.Key}: {entry.Value.Kind} {entry.Value.Detail}")]; + Assert.Empty(failures); + string[] stale = [.. Unreadable.Keys.Where(file => !outcomes.TryGetValue(file, out CorpusOutcome? outcome) || outcome.Kind != CorpusOutcomeKind.Rejected)]; + Assert.Empty(stale); + await Verify(summary); + } + + internal static void SkipWhenNotFetched(string file) + { + if (file.EndsWith("/(not fetched)", StringComparison.Ordinal)) + { + Assert.Skip($"Corpus '{file[..file.IndexOf('/', StringComparison.Ordinal)]}' not fetched; run tools/CorpusFetcher (or set {RealWorldCorpus.EnvironmentVariable})."); + } + } + + /// Per corpus: the count of each outcome, then how many files carry each diagnostic code. + private static string Summarize(Dictionary outcomes) + { + var text = new StringBuilder(); + foreach (string id in CorpusIds) + { + CorpusOutcome[] corpus = [.. outcomes.Where(entry => entry.Key.StartsWith(id + "/", StringComparison.Ordinal)).Select(entry => entry.Value)]; + text.Append(CultureInfo.InvariantCulture, $"{id}: {corpus.Length} files\n"); + foreach (CorpusOutcomeKind kind in Enum.GetValues()) + { + text.Append(CultureInfo.InvariantCulture, $" {kind}: {corpus.Count(outcome => outcome.Kind == kind)}\n"); + } + + text.Append(" files with each diagnostic code:\n"); + foreach (IGrouping code in corpus + .Where(outcome => outcome.Kind == CorpusOutcomeKind.Diagnostics) + .SelectMany(outcome => outcome.Codes) + .GroupBy(code => code, StringComparer.Ordinal) + .OrderByDescending(group => group.Count()) + .ThenBy(group => group.Key, StringComparer.Ordinal)) + { + text.Append(CultureInfo.InvariantCulture, $" {code.Key}: {code.Count()}\n"); + } + } + + return text.ToString(); + } +} diff --git a/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt b/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt new file mode 100644 index 00000000..e91fe552 --- /dev/null +++ b/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt @@ -0,0 +1,225 @@ +pdfjs: 989 files + Clean: 689 + Diagnostics: 286 + PasswordRequired: 12 + CertificateRequired: 0 + EncryptionUnsupported: 0 + Rejected: 2 + Crash: 0 + Timeout: 0 + files with each diagnostic code: + FilterUnsupported: 186 + XrefEntryInvalid: 112 + RootMissing: 110 + XrefEntryOffsetInvalid: 26 + StreamLengthInvalid: 24 + StartxrefInvalid: 21 + MissingEndobj: 12 + PageResourcesMissing: 11 + TrailerPrevInvalid: 8 + UnexpectedToken: 8 + XrefEntryFormatInvalid: 8 + StartxrefMissing: 7 + FilterDataInvalid: 6 + FilterDataTruncated: 6 + DictionaryKeyNotName: 5 + HeaderInvalid: 5 + PageTreeCountMismatch: 5 + CatalogTypeInvalid: 4 + DictionaryDuplicateKey: 4 + PageMediaBoxMissing: 4 + DictionaryUnterminated: 3 + PageTreeNodeTypeInvalid: 3 + PagesMissing: 3 + ArrayUnterminated: 2 + DecodeParmsInvalid: 2 + EncryptionEntryLengthInvalid: 2 + EndOfFileMarkerMissing: 2 + FilterAbbreviationNotAllowed: 2 + LinearizationHintsInvalid: 2 + PageTreeKidsInvalid: 2 + PageTreeParentMismatch: 2 + StreamKeywordEndOfLine: 2 + TrailerIdMissing: 2 + TrailerMissing: 2 + DictionaryValueMissing: 1 + EncryptDictionaryInvalid: 1 + EncryptedDataInvalid: 1 + EndOfFileMarkerNotLast: 1 + EndstreamMissing: 1 + HeaderMissing: 1 + HeaderVersionInvalid: 1 + HexStringInvalidDigit: 1 + NumberMalformed: 1 + ObjectStreamIndexMismatch: 1 + ObjectStreamInvalid: 1 + PageResourcesInvalid: 1 + PageTreeCycle: 1 + PageTreeKidInvalid: 1 + PageTreeKidNotIndirect: 1 + RootNotIndirect: 1 + StringUnterminated: 1 + TrailerEntryFromOlderRevision: 1 + TrailerXRefStmInvalid: 1 + XrefStreamDataTruncated: 1 + XrefStreamSizeInvalid: 1 + XrefSubsectionNumberingInvalid: 1 +pdfbox: 137 files + Clean: 105 + Diagnostics: 24 + PasswordRequired: 3 + CertificateRequired: 4 + EncryptionUnsupported: 0 + Rejected: 1 + Crash: 0 + Timeout: 0 + files with each diagnostic code: + FilterUnsupported: 6 + PageResourcesMissing: 6 + EndOfFileMarkerMissing: 4 + XrefEntryInvalid: 3 + XrefEntryOffsetInvalid: 3 + RootMissing: 2 + CatalogTypeInvalid: 1 + DictionaryDuplicateKey: 1 + EndOfFileMarkerNotLast: 1 + FilterAbbreviationNotAllowed: 1 + HeaderMissing: 1 + PageMediaBoxMissing: 1 + PageTreeKidInvalid: 1 + StartxrefInvalid: 1 + StreamLengthInvalid: 1 +qpdf: 639 files + Clean: 450 + Diagnostics: 152 + PasswordRequired: 23 + CertificateRequired: 0 + EncryptionUnsupported: 1 + Rejected: 13 + Crash: 0 + Timeout: 0 + files with each diagnostic code: + FilterUnsupported: 33 + MissingEndobj: 18 + FilterDataInvalid: 17 + XrefEntryOffsetInvalid: 15 + StartxrefInvalid: 14 + PageResourcesMissing: 11 + UnexpectedToken: 11 + DictionaryKeyNotName: 10 + RootMissing: 10 + StreamLengthInvalid: 10 + CatalogTypeInvalid: 7 + ObjectStreamIndexMismatch: 7 + XrefEntryInvalid: 7 + PageTreeCountMismatch: 6 + PagesMissing: 6 + XrefEntryFormatInvalid: 6 + DecodeParmsInvalid: 5 + DictionaryUnterminated: 5 + DictionaryValueMissing: 5 + HeaderMissing: 5 + PageTreeCycle: 5 + PageTreeNodeTypeInvalid: 5 + PageTreeParentMismatch: 5 + PageMediaBoxMissing: 4 + PredictorInvalid: 4 + EndOfFileMarkerNotLast: 3 + EndstreamMissing: 3 + FilterDataTruncated: 3 + NameInvalidEscape: 3 + ObjectStreamNested: 3 + StartxrefMissing: 3 + TrailerPrevInvalid: 3 + ArrayUnterminated: 2 + DictionaryDuplicateKey: 2 + EndOfFileMarkerMissing: 2 + FilterAbbreviationNotAllowed: 2 + FilterInvalid: 2 + HexStringInvalidDigit: 2 + NameContainsNull: 2 + RootNotIndirect: 2 + StreamKeywordEndOfLine: 2 + TrailerMissing: 2 + XrefPrevLoop: 2 + XrefSectionInvalid: 2 + EncryptionEntryLengthInvalid: 1 + EncryptionIdMissing: 1 + EncryptionKeyLengthInvalid: 1 + HeaderInvalid: 1 + NestingTooDeep: 1 + ObjectStreamHeaderInvalid: 1 + ObjectStreamInvalid: 1 + ObjectStreamTypeInvalid: 1 + PageBoxInvalid: 1 + PageTreeKidInvalid: 1 + PageTreeKidNotIndirect: 1 + ReferenceInvalid: 1 + StringUnterminated: 1 + TrailerEntryFromOlderRevision: 1 + TrailerIdMissing: 1 + XrefStreamSizeInvalid: 1 + XrefStreamTypeInvalid: 1 + XrefStreamWidthsInvalid: 1 + XrefSubsectionHeaderInvalid: 1 +pdfium-tests: 840 files + Clean: 384 + Diagnostics: 449 + PasswordRequired: 2 + CertificateRequired: 4 + EncryptionUnsupported: 0 + Rejected: 1 + Crash: 0 + Timeout: 0 + files with each diagnostic code: + FilterUnsupported: 247 + XrefEntryInvalid: 158 + RootMissing: 151 + StartxrefInvalid: 99 + StreamLengthInvalid: 92 + XrefSectionInvalid: 84 + PredictorInvalid: 72 + HeaderInvalid: 29 + FilterDataInvalid: 28 + DecodeParmsInvalid: 24 + XrefEntryOffsetInvalid: 21 + MissingEndobj: 12 + UnexpectedToken: 10 + CatalogTypeInvalid: 5 + DictionaryDuplicateKey: 5 + PageMediaBoxMissing: 5 + PageResourcesMissing: 5 + PageTreeNodeTypeInvalid: 5 + PageTreeParentMismatch: 5 + DictionaryUnterminated: 4 + StartxrefMissing: 4 + XrefEntryFormatInvalid: 4 + DictionaryKeyNotName: 3 + MetadataNotEncrypted: 3 + StringUnterminated: 3 + ArrayUnterminated: 2 + EncryptionRevisionInvalid: 2 + EndOfFileMarkerNotLast: 2 + TrailerMissing: 2 + XrefSubsectionHeaderInvalid: 2 + DictionaryValueMissing: 1 + EncryptDictionaryInvalid: 1 + EndOfFileMarkerMissing: 1 + EndstreamMissing: 1 + HeaderMissing: 1 + HexStringInvalidDigit: 1 + LinearizationHintsInvalid: 1 + PageTreeCountMismatch: 1 + PageTreeKidInvalid: 1 + PageTreeKidNotIndirect: 1 +pdf20examples: 7 files + Clean: 6 + Diagnostics: 1 + PasswordRequired: 0 + CertificateRequired: 0 + EncryptionUnsupported: 0 + Rejected: 0 + Crash: 0 + Timeout: 0 + files with each diagnostic code: + FilterUnsupported: 1 diff --git a/tests/Broadside.Tests/Document/Snapshots/VeraPdfAgreementTests.Every_disagreement_matches_the_snapshot_and_every_triaged_rule_still_disagrees.verified.txt b/tests/Broadside.Tests/Document/Snapshots/VeraPdfAgreementTests.Every_disagreement_matches_the_snapshot_and_every_triaged_rule_still_disagrees.verified.txt new file mode 100644 index 00000000..01ed8759 --- /dev/null +++ b/tests/Broadside.Tests/Document/Snapshots/VeraPdfAgreementTests.Every_disagreement_matches_the_snapshot_and_every_triaged_rule_still_disagrees.verified.txt @@ -0,0 +1,119 @@ +171 files, 53 agree, 118 disagree +PdfAOnly | Isartor 6-1-12-t01 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.12 Implementation Limits/isartor-6-1-12-t01-fail-a.pdf +PdfAOnly | Isartor 6-1-12-t01 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.12 Implementation Limits/isartor-6-1-12-t01-fail-b.pdf +PdfAOnly | Isartor 6-1-12-t01 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.12 Implementation Limits/isartor-6-1-12-t01-fail-c.pdf +PdfAOnly | Isartor 6-1-12-t01 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.12 Implementation Limits/isartor-6-1-12-t01-fail-d.pdf +PdfAOnly | Isartor 6-1-2-t01 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.2 File header/isartor-6-1-2-t01-fail-a.pdf +StrictTooLenient | Isartor 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.2 File header/isartor-6-1-2-t02-fail-a.pdf +PdfAOnly | Isartor 6-1-3-t01 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.3 File trailer/isartor-6-1-3-t01-fail-a.pdf +PdfAOnly | Isartor 6-1-3-t02 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.3 File trailer/isartor-6-1-3-t02-fail-a.pdf +PdfAOnly | Isartor 6-1-3-t04 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.3 File trailer/isartor-6-1-3-t04-fail-a.pdf +PdfAOnly | Isartor 6-1-6-t01 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.6 String objects/isartor-6-1-6-t01-fail-a.pdf +PdfAOnly | Isartor 6-1-7-t02 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.7 Stream objects/isartor-6-1-7-t02-fail-a.pdf +PdfAOnly | Isartor 6-1-7-t03 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.7 Stream objects/isartor-6-1-7-t03-fail-a.pdf +PdfAOnly | Isartor 6-1-7-t04 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.7 Stream objects/isartor-6-1-7-t04-fail-a.pdf +PdfAOnly | Isartor 6-1-7-t04 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.7 Stream objects/isartor-6-1-7-t04-fail-b.pdf +PdfAOnly | Isartor 6-1-7-t04 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.7 Stream objects/isartor-6-1-7-t04-fail-c.pdf +PdfAOnly | Isartor 6-1-8-t01 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.8 Indirect objects/isartor-6-1-8-t01-fail-a.pdf +PdfAOnly | Isartor 6-1-8-t02 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.8 Indirect objects/isartor-6-1-8-t02-fail-a.pdf +PdfAOnly | Isartor 6-1-8-t03 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.8 Indirect objects/isartor-6-1-8-t03-fail-a.pdf +PdfAOnly | Isartor 6-1-8-t04 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.8 Indirect objects/isartor-6-1-8-t04-fail-a.pdf +PdfAOnly | Isartor 6-1-8-t05 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.8 Indirect objects/isartor-6-1-8-t05-fail-a.pdf +PdfAOnly | Isartor 6-1-8-t06 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.8 Indirect objects/isartor-6-1-8-t06-fail-a.pdf +PdfAOnly | PDF_A-1b 6-1-12-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t01-fail-a.pdf +PdfAOnly | PDF_A-1b 6-1-12-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t02-fail-c.pdf +PdfAOnly | PDF_A-1b 6-1-12-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t02-fail-d.pdf +PdfAOnly | PDF_A-1b 6-1-12-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t02-fail-e.pdf +PdfAOnly | PDF_A-1b 6-1-12-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t02-fail-f.pdf +PdfAOnly | PDF_A-1b 6-1-12-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t02-fail-l.pdf +PdfAOnly | PDF_A-1b 6-1-12-t03 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t03-fail-a.pdf +PdfAOnly | PDF_A-1b 6-1-12-t03 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t03-fail-b.pdf +PdfAOnly | PDF_A-1b 6-1-12-t03 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t03-fail-c.pdf +PdfAOnly | PDF_A-1b 6-1-12-t03 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t03-fail-d.pdf +PdfAOnly | PDF_A-1b 6-1-12-t04 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t04-fail-a.pdf +PdfAOnly | PDF_A-1b 6-1-12-t06 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t06-fail-a.pdf +PdfAOnly | PDF_A-1b 6-1-12-t08 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t08-fail-a.pdf +PdfAOnly | PDF_A-1b 6-1-12-t09 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t09-fail-a.pdf +PdfAOnly | PDF_A-1b 6-1-12-t10 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t10-fail-a.pdf +PdfAOnly | PDF_A-1b 6-1-12-t10 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t10-fail-b.pdf +StrictTooLenient | PDF_A-1b 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t02-fail-a.pdf +StrictTooLenient | PDF_A-1b 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t02-fail-b.pdf +StrictTooLenient | PDF_A-1b 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t02-fail-c.pdf +PdfAOnly | PDF_A-1b 6-1-3-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.3 File trailer/veraPDF test suite 6-1-3-t02-fail-a.pdf +PdfAOnly | PDF_A-1b 6-1-4-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.4 Cross reference table/veraPDF test suite 6-1-4-t02-fail-a.pdf +PdfAOnly | PDF_A-1b 6-1-4-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.4 Cross reference table/veraPDF test suite 6-1-4-t02-fail-b.pdf +PdfAOnly | PDF_A-1b 6-1-4-t03 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.4 Cross reference table/veraPDF test suite 6-1-4-t03-fail-a.pdf +PdfAOnly | PDF_A-1b 6-1-6-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.6 String objects/veraPDF test suite 6-1-6-t01-fail-a.pdf +PdfAOnly | PDF_A-1b 6-1-6-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.6 String objects/veraPDF test suite 6-1-6-t01-fail-b.pdf +PdfAOnly | PDF_A-1b 6-1-8-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.8 Indirect objects/veraPDF test suite 6-1-8-t01-fail-a.pdf +PdfAOnly | PDF_A-2b 6-1-13-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t01-fail-a.pdf +PdfAOnly | PDF_A-2b 6-1-13-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t01-fail-b.pdf +PdfAOnly | PDF_A-2b 6-1-13-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t01-fail-c.pdf +PdfAOnly | PDF_A-2b 6-1-13-t03 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t03-fail-a.pdf +PdfAOnly | PDF_A-2b 6-1-13-t03 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t03-fail-d.pdf +PdfAOnly | PDF_A-2b 6-1-13-t04 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t04-fail-a.pdf +PdfAOnly | PDF_A-2b 6-1-13-t04 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t04-fail-b.pdf +PdfAOnly | PDF_A-2b 6-1-13-t08 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t08-fail-b.pdf +PdfAOnly | PDF_A-2b 6-1-13-t09 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t09-fail-a.pdf +PdfAOnly | PDF_A-2b 6-1-13-t09 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t09-fail-b.pdf +PdfAOnly | PDF_A-2b 6-1-13-t09 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t09-fail-c.pdf +PdfAOnly | PDF_A-2b 6-1-13-t09 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t09-fail-d.pdf +PdfAOnly | PDF_A-2b 6-1-13-t09 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t09-fail-e.pdf +PdfAOnly | PDF_A-2b 6-1-13-t09 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t09-fail-f.pdf +PdfAOnly | PDF_A-2b 6-1-13-t10 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t10-fail-a.pdf +PdfAOnly | PDF_A-2b 6-1-2-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t01-fail-a.pdf +PdfAOnly | PDF_A-2b 6-1-2-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t01-fail-b.pdf +PdfAOnly | PDF_A-2b 6-1-2-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t01-fail-d.pdf +StrictTooLenient | PDF_A-2b 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t02-fail-a.pdf +StrictTooLenient | PDF_A-2b 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t02-fail-b.pdf +StrictTooLenient | PDF_A-2b 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t02-fail-c.pdf +StrictTooLenient | PDF_A-2b 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t02-fail-d.pdf +PdfAOnly | PDF_A-2b 6-1-3-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.3 File trailer/veraPDF test suite 6-1-3-t01-fail-a.pdf +PdfAOnly | PDF_A-2b 6-1-3-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.3 File trailer/veraPDF test suite 6-1-3-t01-fail-b.pdf +PdfAOnly | PDF_A-2b 6-1-3-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.3 File trailer/veraPDF test suite 6-1-3-t01-fail-c.pdf +PdfAOnly | PDF_A-2b 6-1-3-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.3 File trailer/veraPDF test suite 6-1-3-t02-fail-a.pdf +PdfAOnly | PDF_A-2b 6-1-4-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.4 Cross reference table/veraPDF test suite 6-1-4-t01-fail-a.pdf +PdfAOnly | PDF_A-2b 6-1-4-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.4 Cross reference table/veraPDF test suite 6-1-4-t01-fail-b.pdf +PdfAOnly | PDF_A-2b 6-1-6-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.6 String objects/veraPDF test suite 6-1-6-t01-fail-a.pdf +StrictTooLenient | PDF_A-2b 6-1-6-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.6 String objects/veraPDF test suite 6-1-6-t02-fail-a.pdf +PdfAOnly | PDF_A-2b 6-1-7-1-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.7.1 General/veraPDF test suite 6-1-7-1-t02-fail-a.pdf +PdfAOnly | PDF_A-2b 6-1-7-1-t04 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.7.1 General/veraPDF test suite 6-1-7-1-t04-fail-a.pdf +PdfAOnly | PDF_A-2b 6-1-7-1-t04 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.7.1 General/veraPDF test suite 6-1-7-1-t04-fail-b.pdf +PdfAOnly | PDF_A-2b 6-1-7-1-t04 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.7.1 General/veraPDF test suite 6-1-7-1-t04-fail-c.pdf +PdfAOnly | PDF_A-2b 6-1-8-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.8 Name objects/veraPDF test suite 6-1-8-t01-fail-a.pdf +PdfAOnly | PDF_A-2b 6-1-8-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.8 Name objects/veraPDF test suite 6-1-8-t01-fail-b.pdf +PdfAOnly | PDF_A-2b 6-1-9-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.9 Indirect objects/veraPDF test suite 6-1-9-t01-fail-a.pdf +PdfAOnly | PDF_A-2b 6-1-9-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.9 Indirect objects/veraPDF test suite 6-1-9-t02-fail-a.pdf +PdfAOnly | PDF_A-2b 6-1-9-t03 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.9 Indirect objects/veraPDF test suite 6-1-9-t03-fail-a.pdf +PdfAOnly | PDF_A-2b 6-1-9-t03 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.9 Indirect objects/veraPDF test suite 6-1-9-t03-fail-b.pdf +PdfAOnly | PDF_A-2b 6-1-9-t03 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.9 Indirect objects/veraPDF test suite 6-1-9-t03-fail-c.pdf +PdfAOnly | PDF_A-2b 6-1-9-t04 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.9 Indirect objects/veraPDF test suite 6-1-9-t04-fail-a.pdf +PdfAOnly | PDF_A-2b 6-1-9-t04 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.9 Indirect objects/veraPDF test suite 6-1-9-t04-fail-b.pdf +PdfAOnly | PDF_A-4 6-1-2-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t01-fail-a.pdf +PdfAOnly | PDF_A-4 6-1-2-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t01-fail-b.pdf +StrictTooLenient | PDF_A-4 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t02-fail-a.pdf +StrictTooLenient | PDF_A-4 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t02-fail-b.pdf +StrictTooLenient | PDF_A-4 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t02-fail-c.pdf +StrictTooLenient | PDF_A-4 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t02-fail-d.pdf +PdfAOnly | PDF_A-4 6-1-3-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.3 File trailer/veraPDF test suite 6-1-3-t01-fail-b.pdf +PdfAOnly | PDF_A-4 6-1-3-t04 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.3 File trailer/veraPDF test suite 6-1-3-t04-fail-a.pdf +PdfAOnly | PDF_A-4 6-1-3-t05 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.3 File trailer/veraPDF test suite 6-1-3-t05-fail-a.pdf +PdfAOnly | PDF_A-4 6-1-4-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.4 Cross reference table/veraPDF test suite 6-1-4-t01-fail-a.pdf +PdfAOnly | PDF_A-4 6-1-4-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.4 Cross reference table/veraPDF test suite 6-1-4-t01-fail-b.pdf +PdfAOnly | PDF_A-4 6-1-5-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.5 String objects/veraPDF test suite 6-1-5-t01-fail-a.pdf +StrictTooLenient | PDF_A-4 6-1-5-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.5 String objects/veraPDF test suite 6-1-5-t02-fail-a.pdf +PdfAOnly | PDF_A-4 6-1-6-1-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.6 Stream objects/6.1.6.1 General/veraPDF test suite 6-1-6-1-t02-fail-a.pdf +PdfAOnly | PDF_A-4 6-1-6-1-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.6 Stream objects/6.1.6.1 General/veraPDF test suite 6-1-6-1-t02-fail-b.pdf +PdfAOnly | PDF_A-4 6-1-6-1-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.6 Stream objects/6.1.6.1 General/veraPDF test suite 6-1-6-1-t02-fail-c.pdf +PdfAOnly | PDF_A-4 6-1-7-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.7 Name objects/veraPDF test suite 6-1-7-t01-fail-a.pdf +PdfAOnly | PDF_A-4 6-1-7-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.7 Name objects/veraPDF test suite 6-1-7-t01-fail-b.pdf +PdfAOnly | PDF_A-4 6-1-7-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.7 Name objects/veraPDF test suite 6-1-7-t01-fail-c.pdf +PdfAOnly | PDF_A-4 6-1-7-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.7 Name objects/veraPDF test suite 6-1-7-t01-fail-d.pdf +PdfAOnly | PDF_A-4 6-1-7-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.7 Name objects/veraPDF test suite 6-1-7-t01-fail-e.pdf +PdfAOnly | PDF_A-4 6-1-8-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.8 Indirect objects/veraPDF test suite 6-1-8-t01-fail-a.pdf +PdfAOnly | PDF_A-4 6-1-8-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.8 Indirect objects/veraPDF test suite 6-1-8-t01-fail-b.pdf +PdfAOnly | PDF_A-4 6-1-8-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.8 Indirect objects/veraPDF test suite 6-1-8-t01-fail-c.pdf +PdfAOnly | PDF_A-4 6-1-8-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.8 Indirect objects/veraPDF test suite 6-1-8-t01-fail-d.pdf +PdfAOnly | PDF_A-4 6-1-8-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.8 Indirect objects/veraPDF test suite 6-1-8-t01-fail-e.pdf +PdfAOnly | PDF_A-4 6-1-8-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.8 Indirect objects/veraPDF test suite 6-1-8-t01-fail-f.pdf +PdfAOnly | PDF_A-4 6-1-8-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.8 Indirect objects/veraPDF test suite 6-1-8-t01-fail-g.pdf diff --git a/tests/Broadside.Tests/Document/VeraPdfAgreementTests.cs b/tests/Broadside.Tests/Document/VeraPdfAgreementTests.cs new file mode 100644 index 00000000..74a71b19 --- /dev/null +++ b/tests/Broadside.Tests/Document/VeraPdfAgreementTests.cs @@ -0,0 +1,222 @@ +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// How a disagreement between strict mode and veraPDF is explained. +public enum VeraPdfTriage +{ + /// (a) The rule is PDF/A's (ISO 19005), stricter than ISO 32000-2, which strict mode implements. + PdfAOnly, + + /// (b) ISO 32000-2 is violated and strict mode does not see it yet: a known gap, with the issue that closes it. + StrictTooLenient, + + /// (c) Strict mode rejects what ISO 32000-2 allows. + StrictTooStrict, + + /// (d) veraPDF's verdict is wrong. + VeraPdfIssue, +} + +/// +/// Strict mode against veraPDF's well-formedness verdicts on the purely syntactic subset of the veraPDF corpus (issue #47): the +/// PDF/A-1b (veraPDF and Isartor), PDF/A-2b and PDF/A-4 "6.1 File structure" tests for the header, trailer, cross-reference +/// table, strings, streams, names, indirect objects and implementation limits. veraPDF's verdict is the pass/fail in +/// each file name; strict mode's is whether opening and walking the file () throws. Every +/// disagreement is triaged, by rule, in ; the snapshot lists each one. ISO 32000-2 §7.2-§7.5. +/// +[Trait("Category", "Corpus")] +public partial class VeraPdfAgreementTests(ITestOutputHelper output) +{ + /// The syntactic folders, below 6.1 File structure/ of each profile. + private static readonly string[] SyntacticFolders = + [ + "File header", "File trailer", "Cross reference", "String objects", "Stream objects", "6.1.7.1 General", "Name objects", + "Indirect objects", "Implementation limits", "Implementation Limits", + ]; + + /// Every disagreement's explanation, keyed by profile and veraPDF rule (clause and test number). + public static readonly IReadOnlyDictionary Triage = new Dictionary(StringComparer.Ordinal) + { + // Header (§7.5.2). + ["Isartor 6-1-2-t01"] = (VeraPdfTriage.PdfAOnly, "Bytes before %PDF-: §7.5.2 NOTE 1 allows them; offsets count from the header."), + ["PDF_A-2b 6-1-2-t01"] = (VeraPdfTriage.PdfAOnly, "%PDF-2.0 or %PDF-1.9 in PDF/A-2, or bytes before the header: ISO 32000-2 accepts 1.0-2.0 and leading bytes."), + ["PDF_A-4 6-1-2-t01"] = (VeraPdfTriage.PdfAOnly, "%PDF-1.7 in PDF/A-4 (which requires 2.n), or bytes before the header: both legal in ISO 32000-2."), + ["Isartor 6-1-2-t02"] = (VeraPdfTriage.StrictTooLenient, "Binary comment line missing or short. §7.5.2: a file with binary data shall have it. Not checked: it needs a whole-file scan for binary bytes; follow-up."), + ["PDF_A-1b 6-1-2-t02"] = (VeraPdfTriage.StrictTooLenient, "Binary comment line missing or short (§7.5.2); not checked yet, follow-up."), + ["PDF_A-2b 6-1-2-t02"] = (VeraPdfTriage.StrictTooLenient, "Binary comment line missing, short or not immediately after the header (§7.5.2); not checked yet, follow-up."), + ["PDF_A-4 6-1-2-t02"] = (VeraPdfTriage.StrictTooLenient, "Binary comment line missing, short or not immediately after the header (§7.5.2); not checked yet, follow-up."), + + // Trailer (§7.5.5, §14.4). + ["Isartor 6-1-3-t01"] = (VeraPdfTriage.PdfAOnly, "No ID in a PDF 1.4 trailer: Table 15 requires ID only in PDF 2.0 or with Encrypt."), + ["PDF_A-2b 6-1-3-t01"] = (VeraPdfTriage.PdfAOnly, "PDF 1.7 trailer without ID, with empty ID strings, or a linearized first-page trailer without ID: ID is optional before 2.0 and §14.4 sets no length."), + ["PDF_A-4 6-1-3-t01"] = (VeraPdfTriage.PdfAOnly, "ID present with an empty string: Table 15 and §14.4 require two byte strings but no length. (The PDF 2.0 trailer without ID now fails: TrailerIdMissing.)"), + ["Isartor 6-1-3-t02"] = (VeraPdfTriage.PdfAOnly, "Encrypt in the trailer: PDF/A forbids encryption; ISO 32000-2 §7.6 defines it."), + ["PDF_A-1b 6-1-3-t02"] = (VeraPdfTriage.PdfAOnly, "Encrypt in the trailer: PDF/A forbids encryption."), + ["PDF_A-2b 6-1-3-t02"] = (VeraPdfTriage.PdfAOnly, "Encrypt in the trailer: PDF/A forbids encryption."), + ["Isartor 6-1-3-t04"] = (VeraPdfTriage.PdfAOnly, "Linearized file whose first-page and last trailer IDs differ: ISO 32000-2 does not require them to match."), + ["PDF_A-4 6-1-3-t04"] = (VeraPdfTriage.PdfAOnly, "Info in the trailer without PieceInfo: a PDF/A-4 rule (Info is deprecated, not forbidden, in PDF 2.0)."), + ["PDF_A-4 6-1-3-t05"] = (VeraPdfTriage.PdfAOnly, "Info dictionary with entries other than ModDate: a PDF/A-4 rule."), + + // Cross-reference table (§7.5.4). + ["PDF_A-1b 6-1-4-t02"] = (VeraPdfTriage.PdfAOnly, "Space after xref, or a blank line before the subsection header: §7.5.4 asks only for a line containing the keyword xref."), + ["PDF_A-2b 6-1-4-t01"] = (VeraPdfTriage.PdfAOnly, "Space after xref, or a blank line before the subsection header (PDF/A-2 6.1.4)."), + ["PDF_A-4 6-1-4-t01"] = (VeraPdfTriage.PdfAOnly, "Space after xref, or a blank line before the subsection header (PDF/A-4 6.1.4)."), + ["PDF_A-1b 6-1-4-t03"] = (VeraPdfTriage.PdfAOnly, "Cross-reference stream: PDF/A-1 forbids them; §7.5.8 defines them."), + + // Strings (§7.3.4). + ["Isartor 6-1-6-t01"] = (VeraPdfTriage.PdfAOnly, "Hexadecimal string with an odd number of digits: §7.3.4.3 pads the last digit with 0."), + ["PDF_A-1b 6-1-6-t01"] = (VeraPdfTriage.PdfAOnly, "Hexadecimal string with an odd number of digits: legal (§7.3.4.3)."), + ["PDF_A-2b 6-1-6-t01"] = (VeraPdfTriage.PdfAOnly, "Hexadecimal string with an odd number of digits: legal (§7.3.4.3)."), + ["PDF_A-4 6-1-5-t01"] = (VeraPdfTriage.PdfAOnly, "Hexadecimal string with an odd number of digits: legal (§7.3.4.3)."), + ["PDF_A-2b 6-1-6-t02"] = (VeraPdfTriage.StrictTooLenient, "A non-hexadecimal character in a hexadecimal string inside a content stream (<484!> Tj). Content streams are parsed by the content interpreter (Phase 2), not by the Phase 1 walk."), + ["PDF_A-4 6-1-5-t02"] = (VeraPdfTriage.StrictTooLenient, "A non-hexadecimal character in a hexadecimal string inside a content stream; parsed from Phase 2 (content interpreter)."), + + // Streams (§7.3.8). + ["Isartor 6-1-7-t02"] = (VeraPdfTriage.PdfAOnly, "endstream not preceded by an end-of-line marker: §7.3.8.1 says there should be one."), + ["PDF_A-2b 6-1-7-1-t02"] = (VeraPdfTriage.PdfAOnly, "endstream preceded by an end-of-line marker and a space: §7.3.8.1 says should."), + ["Isartor 6-1-7-t03"] = (VeraPdfTriage.PdfAOnly, "Length counts the end-of-line marker before endstream. Read by Length the stream ends right before endstream, which §7.3.8.1 allows (the marker is a should); only a PDF/A reader that requires the marker can tell."), + ["Isartor 6-1-7-t04"] = (VeraPdfTriage.PdfAOnly, "F, FFilter or FDecodeParms in a stream dictionary: legal in Table 5 (external file data is not read: an Information diagnostic)."), + ["PDF_A-2b 6-1-7-1-t04"] = (VeraPdfTriage.PdfAOnly, "F, FFilter or FDecodeParms in a stream dictionary: legal in Table 5."), + ["PDF_A-4 6-1-6-1-t02"] = (VeraPdfTriage.PdfAOnly, "F, FFilter or FDecodeParms in a stream dictionary: legal in Table 5."), + + // Names (§7.3.5). + ["PDF_A-2b 6-1-8-t01"] = (VeraPdfTriage.PdfAOnly, "Font, colourant or structure type name that is not valid UTF-8: §7.3.5 says names should be UTF-8."), + ["PDF_A-4 6-1-7-t01"] = (VeraPdfTriage.PdfAOnly, "Name that is not valid UTF-8: §7.3.5 says should."), + + // Indirect objects (§7.3.10). + ["Isartor 6-1-8-t01"] = (VeraPdfTriage.PdfAOnly, "More than one white-space character between object and generation number: §7.3.10 asks only for white space."), + ["Isartor 6-1-8-t02"] = (VeraPdfTriage.PdfAOnly, "More than one white-space character between generation number and obj: legal (§7.3.10)."), + ["Isartor 6-1-8-t03"] = (VeraPdfTriage.PdfAOnly, "Object number not preceded by an end-of-line marker: legal (§7.3.10, §7.2.3)."), + ["Isartor 6-1-8-t04"] = (VeraPdfTriage.PdfAOnly, "endobj not preceded by an end-of-line marker: legal."), + ["Isartor 6-1-8-t05"] = (VeraPdfTriage.PdfAOnly, "obj not followed by an end-of-line marker: legal."), + ["Isartor 6-1-8-t06"] = (VeraPdfTriage.PdfAOnly, "endobj not followed by an end-of-line marker: legal."), + ["PDF_A-1b 6-1-8-t01"] = (VeraPdfTriage.PdfAOnly, "obj/endobj spacing and end-of-line rules of PDF/A-1 6.1.8: ISO 32000-2 requires only white space."), + ["PDF_A-2b 6-1-9-t01"] = (VeraPdfTriage.PdfAOnly, "obj/endobj spacing rules of PDF/A-2 6.1.9: legal in ISO 32000-2."), + ["PDF_A-2b 6-1-9-t02"] = (VeraPdfTriage.PdfAOnly, "obj/endobj spacing rules of PDF/A-2 6.1.9: legal in ISO 32000-2."), + ["PDF_A-2b 6-1-9-t03"] = (VeraPdfTriage.PdfAOnly, "obj/endobj end-of-line rules of PDF/A-2 6.1.9: legal in ISO 32000-2."), + ["PDF_A-2b 6-1-9-t04"] = (VeraPdfTriage.PdfAOnly, "obj/endobj end-of-line rules of PDF/A-2 6.1.9: legal in ISO 32000-2."), + ["PDF_A-4 6-1-8-t01"] = (VeraPdfTriage.PdfAOnly, "obj/endobj spacing and end-of-line rules of PDF/A-4 6.1.8: legal in ISO 32000-2."), + + // Implementation limits: ISO 32000-2 Annex C is informative advice, not requirements on a file. + ["Isartor 6-1-12-t01"] = (VeraPdfTriage.PdfAOnly, "Array over 8191 elements, name over 127 bytes, integer over 2^31-1: PDF/A-1 limits (ISO 32000-2 Annex C is informative)."), + ["PDF_A-1b 6-1-12-t01"] = (VeraPdfTriage.PdfAOnly, "Integer outside 32 bits: a PDF/A-1 limit."), + ["PDF_A-1b 6-1-12-t02"] = (VeraPdfTriage.PdfAOnly, "Real over 32767: a PDF/A-1 limit."), + ["PDF_A-1b 6-1-12-t03"] = (VeraPdfTriage.PdfAOnly, "String over 65535 bytes: a PDF/A-1 limit."), + ["PDF_A-1b 6-1-12-t04"] = (VeraPdfTriage.PdfAOnly, "Name over 127 bytes: a PDF/A-1 limit."), + ["PDF_A-1b 6-1-12-t06"] = (VeraPdfTriage.PdfAOnly, "Dictionary over 4095 entries: a PDF/A-1 limit."), + ["PDF_A-1b 6-1-12-t08"] = (VeraPdfTriage.PdfAOnly, "q/Q nesting over 28: a PDF/A-1 limit (and a content stream rule)."), + ["PDF_A-1b 6-1-12-t09"] = (VeraPdfTriage.PdfAOnly, "DeviceN over 8 components: a PDF/A-1 limit."), + ["PDF_A-1b 6-1-12-t10"] = (VeraPdfTriage.PdfAOnly, "CID over 65535: a PDF/A-1 limit."), + ["PDF_A-2b 6-1-13-t01"] = (VeraPdfTriage.PdfAOnly, "Integer outside 32 bits: a PDF/A-2 limit."), + ["PDF_A-2b 6-1-13-t03"] = (VeraPdfTriage.PdfAOnly, "String over 32767 bytes: a PDF/A-2 limit."), + ["PDF_A-2b 6-1-13-t04"] = (VeraPdfTriage.PdfAOnly, "Name over 127 bytes: a PDF/A-2 limit."), + ["PDF_A-2b 6-1-13-t08"] = (VeraPdfTriage.PdfAOnly, "q/Q nesting over 28: a PDF/A-2 limit."), + ["PDF_A-2b 6-1-13-t09"] = (VeraPdfTriage.PdfAOnly, "DeviceN over 32 colourants: a PDF/A-2 limit."), + ["PDF_A-2b 6-1-13-t10"] = (VeraPdfTriage.PdfAOnly, "CID over 65535: a PDF/A-2 limit."), + }; + + public static TheoryData Files + { + get + { + var data = new TheoryData(); + IReadOnlyList files = SubsetFiles(); + if (files.Count == 0) + { + data.Add("verapdf-corpus/(not fetched)"); + } + + foreach (string file in files) + { + data.Add(file); + } + + return data; + } + } + + [Theory] + [MemberData(nameof(Files))] + public async Task Strict_mode_agrees_with_veraPDF_or_the_disagreement_is_triaged(string file) + { + RealWorldCorpusTests.SkipWhenNotFetched(file); + + CorpusOutcome outcome = await RealWorldCorpus.OutcomeAsync(file, strict: true); + + Assert.False(outcome.IsFailure, $"{outcome.Kind}: {outcome.Detail}"); + Assert.Contains(outcome.Kind, (CorpusOutcomeKind[])[CorpusOutcomeKind.Clean, CorpusOutcomeKind.Rejected]); + if (Ours(outcome) != VeraPdf(file)) + { + Assert.True(Triage.ContainsKey(Rule(file)), $"Strict mode says {Ours(outcome)}, veraPDF {VeraPdf(file)}, and rule '{Rule(file)}' is not triaged ({outcome.Detail})."); + } + } + + [Fact] + public async Task Every_disagreement_matches_the_snapshot_and_every_triaged_rule_still_disagrees() + { + IReadOnlyList files = SubsetFiles(); + if (files.Count == 0) + { + Assert.Skip($"Corpus 'verapdf-corpus' not fetched; run tools/CorpusFetcher (or set {RealWorldCorpus.EnvironmentVariable})."); + } + + CorpusOutcome[] outcomes = await Task.WhenAll(files.Select(file => RealWorldCorpus.OutcomeAsync(file, strict: true))); + var table = new StringBuilder(); + var disagreeingRules = new HashSet(StringComparer.Ordinal); + int agreements = 0; + for (int index = 0; index < files.Count; index++) + { + string file = files[index]; + string ours = Ours(outcomes[index]); + if (ours == VeraPdf(file)) + { + agreements++; + continue; + } + + string rule = Rule(file); + disagreeingRules.Add(rule); + string triage = Triage.TryGetValue(rule, out (VeraPdfTriage Triage, string Reason) entry) ? entry.Triage.ToString() : "UNTRIAGED"; + table.Append(CultureInfo.InvariantCulture, $"{triage} | {rule} | veraPDF {VeraPdf(file)}, strict {ours} | {file}\n"); + } + + string summary = string.Create(CultureInfo.InvariantCulture, $"{files.Count} files, {agreements} agree, {files.Count - agreements} disagree\n") + table; + output.WriteLine(summary); + Assert.Empty(Triage.Keys.Except(disagreeingRules)); + await Verify(summary); + } + + private static IReadOnlyList SubsetFiles() => + [ + .. RealWorldCorpus.Files("verapdf-corpus").Where(static file => + { + int structure = file.IndexOf("/6.1 File structure/", StringComparison.Ordinal); + if (structure < 0 || !(file.Contains("/PDF_A-", StringComparison.Ordinal) || file.Contains("/Isartor test files/", StringComparison.Ordinal))) + { + return false; + } + + string folder = file[(structure + "/6.1 File structure/".Length)..]; + return !folder.Contains("Filters", StringComparison.Ordinal) && SyntacticFolders.Any(name => folder.Contains(name, StringComparison.Ordinal)); + }), + ]; + + private static string Ours(CorpusOutcome outcome) => outcome.Kind == CorpusOutcomeKind.Rejected ? "fail" : "pass"; + + private static string VeraPdf(string file) => file.Contains("-pass-", StringComparison.Ordinal) ? "pass" : "fail"; + + /// The profile (first folder) and the rule id from the file name, such as PDF_A-2b 6-1-2-t02. + private static string Rule(string file) + { + string[] parts = file.Split('/'); + string profile = parts[1] == "Isartor test files" ? "Isartor" : parts[1]; + return $"{profile} {RuleId().Match(parts[^1]).Value}"; + } + + [GeneratedRegex("[0-9]+(-[0-9]+)+-t[0-9]+")] + private static partial Regex RuleId(); +} diff --git a/tests/Broadside.Tests/Document/VersionTests.cs b/tests/Broadside.Tests/Document/VersionTests.cs index 2f7a9b8b..e4213b9b 100644 --- a/tests/Broadside.Tests/Document/VersionTests.cs +++ b/tests/Broadside.Tests/Document/VersionTests.cs @@ -14,7 +14,12 @@ public class VersionTests [InlineData("%PDF-1.0", "", "1.0")] public void The_catalog_version_overrides_the_header_only_when_later(string header, string catalogEntries, string expected) { - using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", catalogEntries, header)); + // Table 15: a PDF 2.0 file's trailer shall have an ID, so every variant carries one. + byte[] file = new TestPdf { Header = header, TrailerEntries = "/ID [<0123> <0123>]" }.Build( + $"<< /Type /Catalog /Pages 2 0 R {catalogEntries} >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>"); + using PdfDocument document = PdfDocument.Open(file); Assert.Equal(expected, document.Version.ToString()); Assert.Empty(document.Diagnostics); diff --git a/tests/Broadside.Tests/Filters/AsciiFilterTests.cs b/tests/Broadside.Tests/Filters/AsciiFilterTests.cs index bb5c40f1..5eb38bf1 100644 --- a/tests/Broadside.Tests/Filters/AsciiFilterTests.cs +++ b/tests/Broadside.Tests/Filters/AsciiFilterTests.cs @@ -33,12 +33,14 @@ public void Ascii_hex_skips_invalid_characters_with_one_diagnostic() } [Fact] - public void Ascii_hex_without_the_end_marker_decodes_to_its_end_with_a_diagnostic() + public void Ascii_hex_without_the_end_marker_decodes_to_its_end_without_a_diagnostic() { + // §7.4.2 says > "indicates EOD"; unlike §7.4.3 for ASCII85 it never requires the marker, so data that simply ends is not + // a deviation. veraPDF passes such a stream (veraPDF corpus PDF_A-1b 6-1-2-t01-pass-a.pdf; issue #47). (byte[] decoded, string[] codes) = FilterTesting.Run(new AsciiHexDecodeFilter(), "414"u8); Assert.Equal([0x41, 0x40], decoded); - Assert.Equal(["FilterDataTruncated"], codes); + Assert.Empty(codes); } [Theory] diff --git a/tests/Broadside.Tests/Filters/FilterPipelineTests.cs b/tests/Broadside.Tests/Filters/FilterPipelineTests.cs index f65be2d4..6288b8a0 100644 --- a/tests/Broadside.Tests/Filters/FilterPipelineTests.cs +++ b/tests/Broadside.Tests/Filters/FilterPipelineTests.cs @@ -196,6 +196,21 @@ public void Data_in_an_external_file_is_not_read_and_the_stream_bytes_decode_ins Assert.Equal(["StreamExternalFileUnsupported"], codes); } + [Fact] + public void Data_in_an_external_file_is_a_legal_unsupported_feature_that_strict_mode_does_not_reject() + { + // Table 5 allows F (PDF 1.2); not reading the file is a limit of this reader, not a deviation of the file, so the diagnostic + // is Information (issue #41's severity rule). The veraPDF agreement check of issue #47 found it thrown in strict mode. + byte[] file = FilterTesting.FileWithStream("/F (data.bin) /Filter /ASCIIHexDecode", "41>"u8); + + (byte[] decoded, PdfDocument document) = FilterTesting.Decode(file, new PdfOptions().UseStrict()); + using (document) + { + Assert.Equal("A", Encoding.Latin1.GetString(decoded)); + Assert.Equal(Broadside.Diagnostics.DiagnosticSeverity.Information, Assert.Single(document.Diagnostics).Severity); + } + } + [Fact] public void The_maximum_decoded_length_must_be_positive() { diff --git a/tests/Broadside.Tests/Security/IntegrityTests.cs b/tests/Broadside.Tests/Security/IntegrityTests.cs index 187df09e..92cc7192 100644 --- a/tests/Broadside.Tests/Security/IntegrityTests.cs +++ b/tests/Broadside.Tests/Security/IntegrityTests.cs @@ -55,7 +55,9 @@ public void Bytes_appended_after_the_covered_range_make_the_mac_incomplete() using PdfDocument document = PdfDocument.Open(file); Assert.Equal(PdfIntegrityStatus.Failed, document.Security!.Integrity); - Assert.Equal("IntegrityCodeIncomplete", Assert.Single(document.Diagnostics).Code); + + // The appended line also follows the last %%EOF, which §7.5.5 forbids (issue #47). + Assert.Equal(["EndOfFileMarkerNotLast", "IntegrityCodeIncomplete"], document.Diagnostics.Select(diagnostic => diagnostic.Code)); } [Fact] diff --git a/tests/Broadside.Tests/Security/PasswordTests.cs b/tests/Broadside.Tests/Security/PasswordTests.cs index d6e8aba4..8184bee2 100644 --- a/tests/Broadside.Tests/Security/PasswordTests.cs +++ b/tests/Broadside.Tests/Security/PasswordTests.cs @@ -142,4 +142,48 @@ public void The_owner_key_variant_opens_with_the_empty_user_password_without_a_d Assert.Equal(PdfAccessLevel.User, document.Security!.Access); Assert.Empty(document.Diagnostics); } + + [Fact] + public void An_empty_owner_password_opens_the_document_with_owner_access() + { + // §7.6.4.3.3 Algorithm 2.A checks the password as the owner password first; the empty string is a password like any other + // (pdf.js test file pr6531_2.pdf, found by the real-world corpus gate, issue #47). + using PdfDocument document = PdfDocument.Open(Corpus.Path("encrypted-empty-owner-password.pdf")); + + Assert.Equal(PdfAccessLevel.Owner, document.Security!.Access); + Assert.Equal("BT /F1 24 Tf 72 700 Td (Empty owner password (R6)) Tj ET", EncryptedCorpusTests.ContentText(document)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void The_user_password_of_a_document_with_an_empty_owner_password_gives_user_access() + { + using PdfDocument document = new PdfEngine().Open(Corpus.Path("encrypted-empty-owner-password.pdf"), new PdfPassword("user")); + + Assert.Equal(PdfAccessLevel.User, document.Security!.Access); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_128_bit_key_without_a_length_entry_is_found_by_trying_128_bits_with_a_diagnostic() + { + // Table 20: Length defaults to 40 bits. qpdf guesses 128 when it is missing (qpdf test file bad-encryption-length.pdf, + // found by the real-world corpus gate, issue #47); the reader tries 128 bits when 40 bits authenticate nothing. + using PdfDocument document = PdfDocument.Open(Corpus.Path("encrypted-rc4-length-missing.pdf")); + + Assert.Equal(PdfAccessLevel.User, document.Security!.Access); + Assert.Equal(128, document.Security.KeyLength); + Assert.Equal("BT /F1 24 Tf 72 700 Td (RC4 128-bit (R3), no Length) Tj ET", EncryptedCorpusTests.ContentText(document)); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("EncryptionKeyLengthInvalid", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); + } + + [Fact] + public void A_missing_length_entry_that_hides_a_128_bit_key_throws_in_strict_mode() + { + var exception = Assert.Throws(() => PdfDocument.Open(Corpus.Path("encrypted-rc4-length-missing.pdf"), new PdfOptions().UseStrict())); + + Assert.Equal("EncryptionKeyLengthInvalid", exception.Diagnostic.Code); + } } diff --git a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt index 745e6669..f9e9b5e1 100644 --- a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt +++ b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt @@ -8,12 +8,14 @@ encrypted-aes-256.pdf, encrypted-aes-gcm.pdf, encrypted-crypt-filters.pdf, + encrypted-empty-owner-password.pdf, encrypted-mac-tampered.pdf, encrypted-mac.pdf, encrypted-owner-key-variant.pdf, encrypted-rc4-128.pdf, encrypted-rc4-40-r3.pdf, encrypted-rc4-40.pdf, + encrypted-rc4-length-missing.pdf, encrypted-rc4-user-password.pdf, encrypted-user-password.pdf, filter-chain.pdf, diff --git a/tests/Corpus/README.md b/tests/Corpus/README.md index caa4f3ec..f693ab10 100644 --- a/tests/Corpus/README.md +++ b/tests/Corpus/README.md @@ -33,7 +33,7 @@ Verification was run with qpdf 12.4.2 (`qpdf --check`), poppler (`pdfinfo`, `pdf | File | Feature | Clauses | How to verify | Result | |---|---|---|---|---| | `empty-page.pdf` | One blank Letter page, classic cross-reference table, `%PDF-1.7` header. The baseline every other file is a variation of. | 7.5.2, 7.5.4, 7.5.5, 7.7.2, 7.7.3 | `qpdf --check`, `pdfinfo` | clean | -| `pdf20-header.pdf` | `%PDF-2.0` header and catalog `/Version /2.0`. | 7.5.2, 7.7.2 Table 29 | `pdfinfo` shows `PDF version: 2.0` | clean | +| `pdf20-header.pdf` | `%PDF-2.0` header and catalog `/Version /2.0`; the trailer carries the `/ID` a PDF 2.0 file requires (Table 15). | 7.5.2, 7.5.5 Table 15, 7.7.2 Table 29 | `pdfinfo` shows `PDF version: 2.0`; `qpdf --check` | clean | | `text-standard14.pdf` | One line of text in non-embedded Helvetica with `/WinAnsiEncoding`. | 9.6.2, 9.6.5, 9.4.3 | `pdftotext` prints `Hello, Broadside` | clean | | `text-truetype-embedded.pdf` | One line of text in an embedded TrueType font (`/FontFile2`, `/Length1`). The font program is synthesized by the script: `.notdef`, `H` and `I` drawn as rectangles, tables `head hhea maxp OS/2 hmtx cmap(3,1 format 4) loca glyf name post`. It is not a real typeface and carries no license. | 9.6.3, 9.8.2, 9.9 Table 125 | `pdftotext` prints `HI`; `pdffonts` shows `TrueType WinAnsi emb=yes`; `fc-scan` on the extracted stream reports `Broadside Minimal Regular TrueType charset=48-49`; `pdftoppm` renders two block glyphs | clean | | `xref-stream.pdf` | Cross-reference stream (`/Type /XRef`, `/W [1 2 1]`, uncompressed), no classic table, no `trailer` keyword. | 7.5.8.2, 7.5.8.3 | `qpdf --check`; `qpdf --qdf --object-streams=disable` | clean | @@ -57,6 +57,7 @@ Verification was run with qpdf 12.4.2 (`qpdf --check`), poppler (`pdfinfo`, `pdf | `encrypted-crypt-filters.pdf` | R4 (`/V 4`) crypt filters: `/StmF /StdCF` and `/StrF /StdCF` (`AESV2`), `/EncryptMetadata false` (Algorithm 2 step f appends `FF FF FF FF`; the catalog's `/Metadata` stream is plaintext), page `/Contents [4 0 R 7 0 R 10 0 R]`: object 4 by `StmF`, object 7 `/Filter /Crypt` with `/Name /Identity` (plaintext), object 10 `/Filter /Crypt` with `/Name /StdCF`, encrypted with the Algorithm 1 object key (what qpdf reads; 7.4.10 says "the key as is"), and an encrypted `/Info /Title`. | 7.4.10 Table 14, 7.6.2, 7.6.4.3.2 step f, 7.6.6 Tables 25-26 | `qpdf --check`, `qpdf --show-object=7 --filtered-stream-data`, `--show-object=10 ...`, `pdfinfo` | clean; qpdf decodes objects 7 and 10 (`Identity crypt filter`, `StdCF crypt filter`) and reports `AESv2` for streams, strings and files; pdfinfo `Title: Crypt filters`; pdftotext prints `StmF StdCF` and `Identity crypt filter` but not object 10 (poppler reads neither key form for a named crypt filter) | | `encrypted-aes-gcm.pdf` | ISO/TS 32003: `/V 6 /R 7`, `/CFM /AESV4` (AES-256-GCM: 12-byte IV, ciphertext, 16-byte tag, no AAD), revision 6 password algorithms, catalog `/Extensions << /ISO_ [<< ... /ExtensionLevel 32003 >>] >>` with encrypted strings, encrypted `/Info /Title`. `%PDF-2.0`. | ISO/TS 32003 4, 5.1, 5.2 | `generate.py` self-tests GCM against the McGrew-Viega test cases 13 and 14 | neither qpdf 12.4.2 (`Unsupported /R or /V ... R = 7 (max 6), V = 6 (max 5)`) nor poppler (`Invalid encryption key length. version: 6 - revision: 7`) supports revision 7; verified by Broadside's reader only (no reference implementation exists) | | `encrypted-mac.pdf` | ISO/TS 32004: R6 with `/KDFSalt`, `/P -4100` (bit 13 clear: a MAC token is required), trailer `/AuthCode << /MACLocation /Standalone /ByteRange [0 L1 S L2] /MAC <...> >>` covering the whole file except the token; the token is a CMS AuthenticatedData (one PasswordRecipientInfo, pdfMacWrapKdf, AES-256 key wrap, HMAC-SHA-256, SHA-256 digests, CMSAlgorithmProtection), catalog `/Extensions` with level 32004. `%PDF-2.0`. | ISO/TS 32004 4, 5.1, 5.2, 6.2-6.6 | `qpdf --check`, `qpdf --show-encryption`; `pdftotext` prints `Integrity MAC (R6)`; `generate.py` self-tests RFC 3394 4.6, RFC 5869 A.1 | clean (qpdf and poppler ignore `/AuthCode`); the MAC is verified by Broadside's reader only | +| `encrypted-empty-owner-password.pdf` | R6 (`/V 5`, AES-256) with an empty owner password and the user password `user`: opening without a password authenticates as the owner (Algorithm 2.A tries the owner password first, and the empty string is a password like any other). The case of pdf.js's `pr6531_2.pdf`, which the real-world corpus gate (issue #47) found reported as "password required". `%PDF-2.0`. | 7.6.4.3.3 Algorithm 2.A, 7.6.4.4.7-7.6.4.4.9 Algorithms 8-10, 7.6.4.4.11 Algorithm 12 | `qpdf --check`, `qpdf --show-encryption`; `pdftotext` prints `Empty owner password (R6)`; `pdfinfo` | clean; qpdf reports `Supplied password is owner password`; pdfinfo `Encrypted: yes (... algorithm:AES-256)` | | `inline-image.pdf` | Content stream with a 2x2 8-bit DeviceGray inline image (`BI /W 2 /H 2 /CS /G /BPC 8 ID ... EI`) scaled to 100x100 at (72, 600). | 8.9.7 | `pdftoppm` renders a checkerboard (black top-left and bottom-right) | clean | | `page-tree-inherited.pdf` | Root `/Pages` (2) with one intermediate `/Pages` node (3) that carries `/MediaBox` and `/Resources`; the two leaf pages (4, 5) have neither. | 7.7.3.2, 7.7.3.4 | `pdfinfo` shows 2 Letter pages; `pdftotext` prints `Page 1` and `Page 2` (the font comes from the inherited resources) | clean | | `annotations-link.pdf` | One `/Link` annotation with a `/URI` action in the page's `/Annots`. | 12.5.2, 12.5.6.5, 12.6.4.8 | `qpdf --check`; `qpdf --json --json-key=qpdf` shows the `/Link` dictionary | clean | @@ -79,6 +80,7 @@ Each file is `empty-page.pdf` (or `text-standard14.pdf`) with exactly one defect | `startxref-wrong.pdf` | `startxref` points 100 bytes past the real `xref` keyword (into the table body). | 7.5.5 | qpdf (exit 3): `(offset 303): xref not found`, `Attempting to reconstruct cross-reference table`. pdfinfo: clean. | Read the cross-reference section nearest to the stated offset (the `xref` keyword at 203), record `StartxrefInvalid` at offset 303; the document opens with one Letter page. | | `encrypted-mac-tampered.pdf` | `encrypted-mac.pdf` with one byte of a comment inside the MAC's byte range changed (`original` -> `Original`) after the MAC was computed. | ISO/TS 32004 6.6.2, B.2.2.3 | qpdf and poppler: clean (they do not check the MAC). | Open (the document is intact), record `IntegrityCodeMismatch` (Error, no offset or object): the file's digest does not match the token's `dataDigest`; `PdfSecurity.Integrity` is `Failed`. Strict mode throws it at open. | | `encrypted-owner-key-variant.pdf` | R3 40-bit RC4 whose `O` entry was computed rehashing only the first n bytes in Algorithm 3 step c (what qpdf and PDFBox write), not the whole digest the clause describes. | 7.6.4.4.2 Algorithm 3 step c | qpdf: clean, and `qpdf --password=owner` accepts the owner password. | Opens with the empty user password with no diagnostic. Opened with the owner password `owner`, record `OwnerPasswordKeyVariant` (Warning) and grant owner access. | +| `encrypted-rc4-length-missing.pdf` | R3 (`/V 2`) RC4 with a 128-bit key but no `/Length` entry, so the key is 40 bits by Table 20's default. The case of qpdf's `bad-encryption-length.pdf`, which the real-world corpus gate (issue #47) found reported as "password required". | 7.6.2 Table 20 | qpdf (exit 3): `object 6 0 ... dictionary key /Length: operation for integer attempted on object of type null: returning 0`, then opens it (qpdf assumes 128 bits when Length is missing). pdfinfo and pdftotext: `Command Line Error: Incorrect password`. | No key of the default 40 bits authenticates, so 128 bits are tried: the empty user password authenticates, record `EncryptionKeyLengthInvalid` (Warning, no offset or object); `PdfSecurity.KeyLength` is 128 and the content decrypts to `RC4 128-bit (R3), no Length`. Strict mode throws it at open. | ## Password-protected files diff --git a/tests/Corpus/encrypted-empty-owner-password.pdf b/tests/Corpus/encrypted-empty-owner-password.pdf new file mode 100644 index 0000000000000000000000000000000000000000..34dcb5a633f35af8c93e28e24a984c4882551c15 GIT binary patch literal 1317 zcmah}&5ImG6h8z!^vxK-n{^okA$EO#kYQkVX9j~VyV;2waEYNlH!Zu}OHWU}$VpG0 zJm|%%2e0v(lY*cp@gRyGL{P+#KR}Y3uX>i*P4SJ7^CBUJ{Cwp}oJl1K1q#On}OrIByoM zhX8Zr(*`{B0zsk&j7C6xianbhv!n9eSnqc?k;WM?@7ib&i?4ru_4}vnmD``5w~rp( zzjk}~qx)+=ekT_<{@nlPg9eE$0S_}}3lkI!v>@$iSQE?v1Welqyh zJ>2{T|5v@#eYyL_;}1Uh?8f_V=6oHyKF(YY?AZkLVVARo>-x;+{1a5J+j(5>yd4j2 z#jf%em6O^xp{k)Q*Q$E0o>wcyNonLMf@yWo#TJ#b&ep-U0hPOunQ{lo)$yqSc^h5i zsN6zB<((AL5fP{)LU`h((m`=dgo#vX>Wy|hBxy`ih6xvhW)WLr6N^@Jr(6P28;5nk z(l|r4p^gbdEX5p;Q28DjhMqGE_%a~lG*hw2*!q_q?aNxkm zxHrrQYeWc4Kw!pLVv=LgOUg7Om=Yp0%hm)9ad1>{;sUcODPbK+AakybRgolNL%=u+ zrI=TVa|Kbt5wX);N+pud!Gaqh9E1}I6F`zg1Uxq0LoCvRaq`|8Wvoa<^B5hs6n+to z?So;SN^r9s+e7G4Gji*8W)0{DVTAoT-EH%ROdYnX9DlctM$WuH0so;&9rH`;5hCGQq>8Ye%FzB?Yc zkjKxQW)sl%{y+g*6_x1cJwR>IQzc+S*n%i>R3j^t zrqG^TEVMF(GSsmSy02s^R`L;aUBhP{1|H(NUsf4f3DgPz+EQgcED|%IoxGKs4)u!% zeocrXBR!*T%O>i8?y0O-Jq16ogt97>*mHK?gdct#9{wCG;Ok$1Ut8UI^5yZTkJ|_D zmOp2Ur*Dr(-M5)Fn8>;_YRcRsst!GIt)66X3QJUS(%JdAFE`iMmw95bLK?2Q`q+T2bRN;h4frVh&j{rS@ zW{eXqlp83Y2C?FyW`tovbc|!p11a509@FKa+41xWqe5xN1@24>f%!i1LBkp587J)n z*%V`Dm2;SfO^oL-O!) bytes: def gen_pdf20_header() -> bytes: - return simple_file([(1, catalog(b" /Version /2.0")), (2, pages()), (3, page())], version="2.0") + """7.5.2 header and 7.7.2 Table 29 Version; 7.5.5 Table 15: a PDF 2.0 trailer shall carry ID.""" + id0 = file_id("pdf20-header").hex().encode() + return simple_file([(1, catalog(b" /Version /2.0")), (2, pages()), (3, page())], version="2.0", + trailer_extra=b" /ID [<%s> <%s>]" % (id0, id0)) def gen_text_standard14() -> bytes: @@ -830,7 +833,10 @@ def encrypted_file(name: str, version: str, label: bytes, encrypt_dict, encrypt_ return f.finish_classic(b"<< /Size 7 /Root 1 0 R /Encrypt 6 0 R /ID [<%s> <%s>] >>" % ((id0.hex().encode(),) * 2)) -def gen_encrypted_legacy(name: str, r: int, label: bytes, n: int | None = None, rehash_first_n: bool = False) -> bytes: +def gen_encrypted_legacy(name: str, r: int, label: bytes, n: int | None = None, rehash_first_n: bool = False, + omit_length: bool = False) -> bytes: + """Standard security handler R2-R4. ``omit_length`` drops /Length although the key is longer than the 40-bit default + (7.6.2 Table 20: "Default value: 40"), the defect of ``encrypted-rc4-length-missing.pdf``.""" id0 = file_id(name) n = n or (5 if r == 2 else 16) o = legacy_o_entry(OWNER_PASSWORD, USER_PASSWORD, r, n, rehash_first_n) @@ -839,6 +845,8 @@ def gen_encrypted_legacy(name: str, r: int, label: bytes, n: int | None = None, aes = r == 4 common = b"<< /Filter /Standard /R %d /Length %d /P %d /O <%s> /U <%s>" % ( r, n * 8, PERMISSIONS, o.hex().encode(), u.hex().encode()) + if omit_length: + common = common.replace(b" /Length %d" % (n * 8), b"") if r == 2: enc = common + b" /V 1 >>" version = "1.1" @@ -962,6 +970,25 @@ def gen_encrypted_user_password(name: str = "encrypted-user-password") -> bytes: return f.finish_classic(b"<< /Size 8 /Root 1 0 R /Info 7 0 R /Encrypt 6 0 R /ID [<%s> <%s>] >>" % ((id0.hex().encode(),) * 2)) +def gen_encrypted_empty_owner_password(name: str = "encrypted-empty-owner-password") -> bytes: + """R6 (V 5, AES-256) whose owner password is empty and whose user password is ``user`` (7.6.4.4.7-7.6.4.4.9 + Algorithms 8-10 with an empty owner password string): opening without a password authenticates as the owner + (7.6.4.3.3 Algorithm 2.A tries the owner password first). The case of pdf.js's pr6531_2.pdf.""" + key = fixed_bytes(name + ":file-key", 32) + encrypt = aes256_encryptor(name, key) + enc = (b"<< /Filter /Standard /V 5 /R 6 /Length 256 " + r6_entries(name, key, b"user", b"", PERMISSIONS) + + b" /CF << /StdCF << /CFM /AESV3 /AuthEvent /DocOpen /Length 32 >> >> /StmF /StdCF /StrF /StdCF >>") + id0 = file_id(name) + f = File("2.0", binary=True) + f.add(1, catalog()) + f.add(2, pages()) + f.add(3, page(contents=4, font=5)) + f.add(4, stream(b"", encrypt(4, "stream", text_content(b"Empty owner password (R6)")))) + f.add(5, HELVETICA) + f.add(6, enc) + return f.finish_classic(b"<< /Size 7 /Root 1 0 R /Encrypt 6 0 R /ID [<%s> <%s>] >>" % ((id0.hex().encode(),) * 2)) + + def gen_encrypted_rc4_user_password(name: str = "encrypted-rc4-user-password") -> bytes: """R3 (V 2, 128-bit RC4) with the user password ``caf\xe9`` in PDFDocEncoding (7.6.4.3.2 step a) and an encrypted Info string: Algorithms 2, 5, 6 and 7 with a non-empty user password.""" @@ -1203,11 +1230,14 @@ def gen_metadata_xmp() -> bytes: "encrypted-crypt-filters.pdf": gen_encrypted_crypt_filters, "encrypted-aes-gcm.pdf": gen_encrypted_aes_gcm, "encrypted-mac.pdf": gen_encrypted_mac, + "encrypted-empty-owner-password.pdf": gen_encrypted_empty_owner_password, "encrypted-user-password.pdf": gen_encrypted_user_password, "encrypted-rc4-user-password.pdf": gen_encrypted_rc4_user_password, "encrypted-mac-tampered.pdf": gen_encrypted_mac_tampered, "encrypted-owner-key-variant.pdf": lambda: gen_encrypted_legacy( "encrypted-owner-key-variant", 3, b"RC4 40-bit (R3), qpdf owner key", n=5, rehash_first_n=True), + "encrypted-rc4-length-missing.pdf": lambda: gen_encrypted_legacy( + "encrypted-rc4-length-missing", 3, b"RC4 128-bit (R3), no Length", omit_length=True), "broken-xref-offsets.pdf": gen_broken_xref_offsets, "missing-endobj.pdf": gen_missing_endobj, "wrong-stream-length.pdf": gen_wrong_stream_length, diff --git a/tests/Corpus/pdf20-header.pdf b/tests/Corpus/pdf20-header.pdf index aa941975f1eb8f5aad5779a1d8d76de00300cc65..4ca56eb95558f766175a2cfca06b08891155e260 100644 GIT binary patch delta 87 zcmaFCw1s&?Afvawr;9?gO|n5!Qc7}4nsK73p^>F|nz4ncsi~1+YHFgTsd<{Av7G{8 KC9#tO7$pE delta 11 ScmdnO{DNsiAmik@jN$+r6a(x4 diff --git a/tests/README.md b/tests/README.md index 0ac0c0cd..1e5b7776 100644 --- a/tests/README.md +++ b/tests/README.md @@ -46,7 +46,18 @@ public void Opens(string fileName) { ... } `Corpus.WellFormedFiles`, `Corpus.MalformedFiles` and `Corpus.AllFiles` are `TheoryData` over the well-formed and broken tables in the corpus README (`Corpus.PasswordProtectedFiles` is `TheoryData` of file name and user password over its password-protected table); `WellFormedFileNames`, `MalformedFileNames` and `AllFileNames` are the same lists as `IReadOnlyList`. The lists are hard-coded and `CorpusSmokeTests.File_lists_match_the_corpus_directory` fails if they drift from the directory, so adding a corpus file means adding it to `Corpus.cs` and to the README table. -The real-world corpora in `corpus/` (gitignored, fetched by `tools/CorpusFetcher`) will get a similar helper when that tool lands. +## The real-world corpus gate + +The real-world corpora in `corpus/` (gitignored, fetched by `tools/CorpusFetcher`) are reached through `RealWorldCorpus` in `Broadside.TestSupport`. It finds `corpus/` in this checkout or the nearest enclosing one (so a worktree under `.claude/worktrees/` reuses the main checkout's corpora), or the directory named by `BROADSIDE_CORPUS_DIR`. CI does not fetch the corpora; every corpus test then skips. + +```sh +dotnet run --project tools/CorpusFetcher -- --only pdfjs,pdfbox,qpdf,pdfium-tests,verapdf-corpus,pdf20examples +dotnet test tests/Broadside.Tests -- --filter-trait "Category=Corpus" +``` + +- `RealWorldCorpusTests` (issue #47): one theory row per PDF of pdf.js, PDFBox, qpdf, PDFium and the PDF 2.0 examples, opened leniently and walked completely (`DocumentWalker`: pages, every object, every stream decoded) within 30 s. Password, certificate and unsupported-encryption outcomes are counted, not failures; a file lenient mode gives up on must be listed, with the reason qpdf and poppler fail too, in `RealWorldCorpusTests.Unreadable`. The per-corpus counts and diagnostic histograms are a Verify snapshot, so a change in what the reader reports shows as a diff. +- `VeraPdfAgreementTests`: strict mode against the pass/fail verdict in each veraPDF corpus file name, on the syntactic "6.1 File structure" tests of PDF/A-1b, PDF/A-2b and PDF/A-4. Every disagreement is triaged per rule in `VeraPdfAgreementTests.Triage` and listed in the snapshot. +- `DocumentWalker` is meant to be shared with the open-and-walk fuzz target and benchmark: link it as source, as `CorpusLocator` is. ## Snapshots (Verify) From f82211962500ae0ab837ca9ee1cfff9c1016ed8b Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 15:56:37 -0500 Subject: [PATCH 017/152] feat(document): PDF and XMP date values (#69) PdfDate parses ISO 32000-2 7.9.4 dates without throwing, accepting the legacy trailing apostrophe and repairing common deviations; XmpDate parses the ISO 16684-1 8.2.1.2 subset. Co-Authored-By: Claude Opus 5.5 --- src/Broadside/PdfDate.cs | 261 ++++++++++++++++++++ src/Broadside/PdfDatePrecision.cs | 30 +++ src/Broadside/PublicAPI.Unshipped.txt | 34 +++ src/Broadside/XmpDate.cs | 243 ++++++++++++++++++ tests/Broadside.Tests/Document/DateTests.cs | 134 ++++++++++ 5 files changed, 702 insertions(+) create mode 100644 src/Broadside/PdfDate.cs create mode 100644 src/Broadside/PdfDatePrecision.cs create mode 100644 src/Broadside/XmpDate.cs create mode 100644 tests/Broadside.Tests/Document/DateTests.cs diff --git a/src/Broadside/PdfDate.cs b/src/Broadside/PdfDate.cs new file mode 100644 index 00000000..300aa626 --- /dev/null +++ b/src/Broadside/PdfDate.cs @@ -0,0 +1,261 @@ +namespace Broadside; + +/// A date as a PDF file writes it, D:YYYYMMDDHHmmSSOHH'mm: the instant it denotes and the text it was read from. +/// +/// +/// ISO 32000-2 §7.9.4. A date is a text string (decode it with first). The prefix D: +/// and the year are required; every other field is optional, but only when all the fields before it are present, and defaults to 01 +/// (month and day) or zero. O is the relation of local time to Universal Time: +, - or Z, followed by +/// the offset hours (00-23), an apostrophe and the offset minutes. Without it the time is GMT. The apostrophe that PDF 1.7 and +/// earlier put after the offset minutes is accepted (NOTE 2), as are hours and minutes after Z (NOTE 3). +/// +/// +/// never throws. It also reads the forms real files use that deviate from the clause, with each deviating field +/// clamped into range: no D: prefix, an offset without the apostrophe (+0100), a month, day, hour, minute or second out +/// of range (day 31 of a 30-day month reads as day 30), trailing white-space. Anything else does not parse, and a document keeps the +/// text so nothing is lost: free text such as Monday, March 3, 1997, the year-2000 bug D:19100... (a field with too +/// many digits), separators, a one-digit offset. +/// +/// +/// carries the offset the string gives. holds offsets up to ±14 hours and PDF allows +/// up to ±23:59; for a larger offset is the same instant in Universal Time and keeps +/// the offset as written. +/// +/// +public readonly struct PdfDate : IEquatable +{ + private static readonly long MaxOffsetTicks = TimeSpan.FromHours(14).Ticks; + + private PdfDate(DateTimeOffset value, int? utcOffsetMinutes, PdfDatePrecision precision, string text) + { + Value = value; + UtcOffsetMinutes = utcOffsetMinutes; + Precision = precision; + Text = text; + } + + /// Gets the instant the date denotes, with the offset the string gives when can hold it. + public DateTimeOffset Value { get; } + + /// + /// Gets the offset of local time from Universal Time in minutes as the string writes it (negative west of Greenwich), or + /// when the string has no O field and the time is read as GMT. + /// + public int? UtcOffsetMinutes { get; } + + /// Gets the last field the string gives. + public PdfDatePrecision Precision { get; } + + /// Gets the text the date was read from. + public string Text => field ?? string.Empty; + + /// Returns whether two dates are equal: the same instant, offset, precision and text. + /// The first date. + /// The second date. + /// when they are equal. + public static bool operator ==(PdfDate left, PdfDate right) => left.Equals(right); + + /// Returns whether two dates differ. + /// The first date. + /// The second date. + /// when they differ. + public static bool operator !=(PdfDate left, PdfDate right) => !left.Equals(right); + + /// Parses a PDF date; never throws. + /// The date as decoded text, such as D:199812231952-08'00. + /// The date, or when is not one. + /// when is a date, including the deviating forms the remarks list. + /// ISO 32000-2 §7.9.4. + public static bool TryParse(string? text, out PdfDate date) => Parse(text, out date) != DateParseOutcome.Unreadable; + + /// + public bool Equals(PdfDate other) => + Value.Equals(other.Value) && Value.Offset == other.Value.Offset && UtcOffsetMinutes == other.UtcOffsetMinutes + && Precision == other.Precision && string.Equals(Text, other.Text, StringComparison.Ordinal); + + /// + public override bool Equals(object? obj) => obj is PdfDate other && Equals(other); + + /// + public override int GetHashCode() => HashCode.Combine(Value, UtcOffsetMinutes, Precision, StringComparer.Ordinal.GetHashCode(Text)); + + /// Returns the text the date was read from. + /// . + public override string ToString() => Text; + + /// Parses a PDF date and says whether it conforms to §7.9.4, deviates but was read, or could not be read. + internal static DateParseOutcome Parse(string? text, out PdfDate date) + { + date = default; + if (text is null) + { + return DateParseOutcome.Unreadable; + } + + bool repaired = false; + ReadOnlySpan rest = text.AsSpan(); + int trimmed = rest.TrimEnd().Length; + if (trimmed != rest.Length) + { + repaired = true; + rest = rest[..trimmed]; + } + + if (rest.StartsWith("D:", StringComparison.Ordinal)) + { + rest = rest[2..]; + } + else + { + repaired = true; + } + + // The fields before O are a run of 4 to 14 digits, two per field after the year. + int digits = 0; + while (digits < rest.Length && char.IsAsciiDigit(rest[digits])) + { + digits++; + } + + if (digits is < 4 or > 14 || digits % 2 != 0) + { + return DateParseOutcome.Unreadable; + } + + ReadOnlySpan fields = rest[..digits]; + rest = rest[digits..]; + var precision = (PdfDatePrecision)((digits - 4) / 2); + int year = Number(fields[..4]); + int month = digits >= 6 ? Number(fields.Slice(4, 2)) : 1; + int day = digits >= 8 ? Number(fields.Slice(6, 2)) : 1; + int hour = digits >= 10 ? Number(fields.Slice(8, 2)) : 0; + int minute = digits >= 12 ? Number(fields.Slice(10, 2)) : 0; + int second = digits >= 14 ? Number(fields.Slice(12, 2)) : 0; + repaired |= Clamp(ref year, 1, 9999) | Clamp(ref month, 1, 12) | Clamp(ref day, 1, DateTime.DaysInMonth(year, month)) + | Clamp(ref hour, 0, 23) | Clamp(ref minute, 0, 59) | Clamp(ref second, 0, 59); + + int? offsetMinutes = null; + if (!rest.IsEmpty) + { + if (!TryParseOffset(rest, ref repaired, out int minutes)) + { + return DateParseOutcome.Unreadable; + } + + offsetMinutes = minutes; + } + + var local = new DateTime(year, month, day, hour, minute, second, DateTimeKind.Unspecified); + long offsetTicks = TimeSpan.FromMinutes(offsetMinutes ?? 0).Ticks; + long utcTicks = local.Ticks - offsetTicks; + if (utcTicks < DateTime.MinValue.Ticks || utcTicks > DateTime.MaxValue.Ticks) + { + // The offset would move the instant outside the representable range (year 1 or 9999): read it as GMT. + offsetTicks = 0; + utcTicks = local.Ticks; + repaired = true; + } + + DateTimeOffset value = Math.Abs(offsetTicks) <= MaxOffsetTicks + ? new DateTimeOffset(local, TimeSpan.FromTicks(offsetTicks)) + : new DateTimeOffset(utcTicks, TimeSpan.Zero); + date = new PdfDate(value, offsetMinutes, precision, text); + return repaired ? DateParseOutcome.Repaired : DateParseOutcome.Valid; + } + + /// Reads O, HH, the apostrophe, mm and the legacy apostrophe. + private static bool TryParseOffset(ReadOnlySpan text, ref bool repaired, out int minutes) + { + minutes = 0; + int sign = text[0] switch + { + '+' => 1, + '-' => -1, + 'Z' => 0, + _ => 2, + }; + if (sign == 2) + { + return false; + } + + text = text[1..]; + if (text.IsEmpty) + { + return sign == 0; + } + + if (text.Length < 2 || !char.IsAsciiDigit(text[0]) || !char.IsAsciiDigit(text[1])) + { + return false; + } + + int hours = Number(text[..2]); + text = text[2..]; + int offsetMinutes = 0; + if (!text.IsEmpty && text[0] == '\'') + { + text = text[1..]; + } + else if (!text.IsEmpty) + { + repaired = true; // +0100: the apostrophe after the hours is missing. + } + + if (!text.IsEmpty) + { + if (text.Length < 2 || !char.IsAsciiDigit(text[0]) || !char.IsAsciiDigit(text[1])) + { + return false; + } + + offsetMinutes = Number(text[..2]); + text = text[2..]; + if (!text.IsEmpty && text[0] == '\'') + { + text = text[1..]; // §7.9.4 NOTE 2: the terminating apostrophe of PDF 1.7 and earlier. + } + } + + if (!text.IsEmpty) + { + return false; + } + + repaired |= Clamp(ref hours, 0, 23) | Clamp(ref offsetMinutes, 0, 59); + minutes = sign * ((hours * 60) + offsetMinutes); + return true; + } + + private static int Number(ReadOnlySpan digits) + { + int value = 0; + foreach (char digit in digits) + { + value = (value * 10) + (digit - '0'); + } + + return value; + } + + private static bool Clamp(ref int value, int minimum, int maximum) + { + int clamped = Math.Clamp(value, minimum, maximum); + bool changed = clamped != value; + value = clamped; + return changed; + } +} + +/// What parsing a date found. +internal enum DateParseOutcome : byte +{ + /// The text conforms to the date format. + Valid, + + /// The text deviates from the format but was read. + Repaired, + + /// The text is not a date. + Unreadable, +} diff --git a/src/Broadside/PdfDatePrecision.cs b/src/Broadside/PdfDatePrecision.cs new file mode 100644 index 00000000..83649390 --- /dev/null +++ b/src/Broadside/PdfDatePrecision.cs @@ -0,0 +1,30 @@ +namespace Broadside; + +/// The last field a date string gives; every later field takes its default. +/// +/// ISO 32000-2 §7.9.4: each field of a PDF date may be present only if all the fields before it are, so the fields present are +/// always a prefix and this one value describes them. ISO 16684-1 §8.2.1.2 restricts an XMP date the same way. +/// +public enum PdfDatePrecision +{ + /// The year only (YYYY). + Year, + + /// The year and month. + Month, + + /// The year, month and day. + Day, + + /// Down to the hour (PDF dates only; an XMP date gives hours and minutes together). + Hour, + + /// Down to the minute. + Minute, + + /// Down to the second. + Second, + + /// Down to a fraction of a second (XMP dates only). + FractionOfSecond, +} diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index a576dc7d..0014eb43 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -404,3 +404,37 @@ Broadside.Security.PublicKeySecurityHandler.Filter.get -> Broadside.Objects.CosN Broadside.Security.PublicKeySecurityHandler.PublicKeySecurityHandler() -> void Broadside.Security.PublicKeySecurityHandler.SubFilters.get -> System.Collections.Generic.IReadOnlyCollection! override Broadside.Security.PdfCertificateCredentials.ToString() -> string! +Broadside.PdfDate +Broadside.PdfDate.Equals(Broadside.PdfDate other) -> bool +Broadside.PdfDate.PdfDate() -> void +Broadside.PdfDate.Precision.get -> Broadside.PdfDatePrecision +Broadside.PdfDate.Text.get -> string! +Broadside.PdfDate.UtcOffsetMinutes.get -> int? +Broadside.PdfDate.Value.get -> System.DateTimeOffset +Broadside.PdfDatePrecision +Broadside.PdfDatePrecision.Day = 2 -> Broadside.PdfDatePrecision +Broadside.PdfDatePrecision.FractionOfSecond = 6 -> Broadside.PdfDatePrecision +Broadside.PdfDatePrecision.Hour = 3 -> Broadside.PdfDatePrecision +Broadside.PdfDatePrecision.Minute = 4 -> Broadside.PdfDatePrecision +Broadside.PdfDatePrecision.Month = 1 -> Broadside.PdfDatePrecision +Broadside.PdfDatePrecision.Second = 5 -> Broadside.PdfDatePrecision +Broadside.PdfDatePrecision.Year = 0 -> Broadside.PdfDatePrecision +Broadside.XmpDate +Broadside.XmpDate.Equals(Broadside.XmpDate other) -> bool +Broadside.XmpDate.HasTimeZone.get -> bool +Broadside.XmpDate.Precision.get -> Broadside.PdfDatePrecision +Broadside.XmpDate.Text.get -> string! +Broadside.XmpDate.Value.get -> System.DateTimeOffset +Broadside.XmpDate.XmpDate() -> void +override Broadside.PdfDate.Equals(object? obj) -> bool +override Broadside.PdfDate.GetHashCode() -> int +override Broadside.PdfDate.ToString() -> string! +override Broadside.XmpDate.Equals(object? obj) -> bool +override Broadside.XmpDate.GetHashCode() -> int +override Broadside.XmpDate.ToString() -> string! +static Broadside.PdfDate.operator !=(Broadside.PdfDate left, Broadside.PdfDate right) -> bool +static Broadside.PdfDate.operator ==(Broadside.PdfDate left, Broadside.PdfDate right) -> bool +static Broadside.PdfDate.TryParse(string? text, out Broadside.PdfDate date) -> bool +static Broadside.XmpDate.operator !=(Broadside.XmpDate left, Broadside.XmpDate right) -> bool +static Broadside.XmpDate.operator ==(Broadside.XmpDate left, Broadside.XmpDate right) -> bool +static Broadside.XmpDate.TryParse(string? text, out Broadside.XmpDate date) -> bool diff --git a/src/Broadside/XmpDate.cs b/src/Broadside/XmpDate.cs new file mode 100644 index 00000000..6f52aa59 --- /dev/null +++ b/src/Broadside/XmpDate.cs @@ -0,0 +1,243 @@ +using System.Globalization; + +namespace Broadside; + +/// A date as XMP writes it, a subset of ISO 8601 such as 2014-09-24T21:23:03+02:00: the instant and the text. +/// +/// +/// ISO 16684-1 §8.2.1.2: YYYY, YYYY-MM, YYYY-MM-DD, YYYY-MM-DDThh:mmTZD, YYYY-MM-DDThh:mm:ssTZD or +/// YYYY-MM-DDThh:mm:ss.sTZD, where the time zone designator TZD is Z or +hh:mm / -hh:mm. Fields +/// not given default to 01 (month and day) or zero. +/// +/// +/// The time zone is optional and its absence means the zone is unknown, not Universal Time. then carries the +/// local time with a zero offset and is : compare such a value as a local time, not +/// as an instant. +/// +/// +public readonly struct XmpDate : IEquatable +{ + private XmpDate(DateTimeOffset value, bool hasTimeZone, PdfDatePrecision precision, string text) + { + Value = value; + HasTimeZone = hasTimeZone; + Precision = precision; + Text = text; + } + + /// Gets the date; with a zero offset and the local time when is . + public DateTimeOffset Value { get; } + + /// Gets a value indicating whether the text gives a time zone designator. + public bool HasTimeZone { get; } + + /// Gets the last field the text gives. + public PdfDatePrecision Precision { get; } + + /// Gets the text the date was read from. + public string Text => field ?? string.Empty; + + /// Returns whether two dates are equal: the same value, offset, precision and text. + /// The first date. + /// The second date. + /// when they are equal. + public static bool operator ==(XmpDate left, XmpDate right) => left.Equals(right); + + /// Returns whether two dates differ. + /// The first date. + /// The second date. + /// when they differ. + public static bool operator !=(XmpDate left, XmpDate right) => !left.Equals(right); + + /// Parses an XMP date; never throws. + /// The text, such as 2014-09-24T21:23:03Z. Leading and trailing white-space is ignored. + /// The date, or when is not one. + /// when is a date in one of the forms the remarks list. + /// ISO 16684-1 §8.2.1.2. + public static bool TryParse(string? text, out XmpDate date) + { + date = default; + if (text is null) + { + return false; + } + + ReadOnlySpan rest = text.AsSpan().Trim(); + if (!TryNumber(ref rest, 4, out int year)) + { + return false; + } + + int month = 1, day = 1, hour = 0, minute = 0, second = 0; + long fractionTicks = 0; + PdfDatePrecision precision = PdfDatePrecision.Year; + bool hasTimeZone = false; + int offsetMinutes = 0; + if (Take(ref rest, '-')) + { + if (!TryNumber(ref rest, 2, out month)) + { + return false; + } + + precision = PdfDatePrecision.Month; + if (Take(ref rest, '-')) + { + if (!TryNumber(ref rest, 2, out day)) + { + return false; + } + + precision = PdfDatePrecision.Day; + if (Take(ref rest, 'T')) + { + if (!TryNumber(ref rest, 2, out hour) || !Take(ref rest, ':') || !TryNumber(ref rest, 2, out minute)) + { + return false; + } + + precision = PdfDatePrecision.Minute; + if (Take(ref rest, ':')) + { + if (!TryNumber(ref rest, 2, out second)) + { + return false; + } + + precision = PdfDatePrecision.Second; + if (Take(ref rest, '.')) + { + if (!TryFraction(ref rest, out fractionTicks)) + { + return false; + } + + precision = PdfDatePrecision.FractionOfSecond; + } + } + + if (!TryTimeZone(ref rest, out hasTimeZone, out offsetMinutes)) + { + return false; + } + } + } + } + + if (!rest.IsEmpty || year < 1 || month is < 1 or > 12 || day < 1 || day > DateTime.DaysInMonth(year, month) + || hour > 23 || minute > 59 || second > 59) + { + return false; + } + + var local = new DateTime(year, month, day, hour, minute, second, DateTimeKind.Unspecified).AddTicks(fractionTicks); + long utcTicks = local.Ticks - TimeSpan.FromMinutes(offsetMinutes).Ticks; + if (utcTicks < DateTime.MinValue.Ticks || utcTicks > DateTime.MaxValue.Ticks) + { + return false; + } + + date = new XmpDate(new DateTimeOffset(local, TimeSpan.FromMinutes(offsetMinutes)), hasTimeZone, precision, text); + return true; + } + + /// + public bool Equals(XmpDate other) => + Value.Equals(other.Value) && Value.Offset == other.Value.Offset && HasTimeZone == other.HasTimeZone + && Precision == other.Precision && string.Equals(Text, other.Text, StringComparison.Ordinal); + + /// + public override bool Equals(object? obj) => obj is XmpDate other && Equals(other); + + /// + public override int GetHashCode() => HashCode.Combine(Value, HasTimeZone, Precision, StringComparer.Ordinal.GetHashCode(Text)); + + /// Returns the text the date was read from. + /// . + public override string ToString() => Text; + + private static bool Take(ref ReadOnlySpan text, char expected) + { + if (!text.IsEmpty && text[0] == expected) + { + text = text[1..]; + return true; + } + + return false; + } + + private static bool TryNumber(ref ReadOnlySpan text, int length, out int value) + { + value = 0; + if (text.Length < length) + { + return false; + } + + for (int index = 0; index < length; index++) + { + if (!char.IsAsciiDigit(text[index])) + { + return false; + } + + value = (value * 10) + (text[index] - '0'); + } + + text = text[length..]; + return true; + } + + private static bool TryFraction(ref ReadOnlySpan text, out long ticks) + { + int length = 0; + while (length < text.Length && char.IsAsciiDigit(text[length])) + { + length++; + } + + ticks = 0; + if (length == 0) + { + return false; + } + + // Seven digits are a tick; further digits are below the resolution of DateTime. + ReadOnlySpan digits = text[..Math.Min(length, 7)]; + ticks = long.Parse(digits, NumberStyles.None, CultureInfo.InvariantCulture); + for (int index = digits.Length; index < 7; index++) + { + ticks *= 10; + } + + text = text[length..]; + return true; + } + + private static bool TryTimeZone(ref ReadOnlySpan text, out bool hasTimeZone, out int offsetMinutes) + { + hasTimeZone = false; + offsetMinutes = 0; + if (text.IsEmpty) + { + return true; + } + + hasTimeZone = true; + if (Take(ref text, 'Z')) + { + return true; + } + + int sign = Take(ref text, '+') ? 1 : Take(ref text, '-') ? -1 : 0; + if (sign == 0 || !TryNumber(ref text, 2, out int hours) || !Take(ref text, ':') || !TryNumber(ref text, 2, out int minutes) + || hours > 14 || minutes > 59) + { + return false; + } + + offsetMinutes = sign * ((hours * 60) + minutes); + return Math.Abs(offsetMinutes) <= 14 * 60; + } +} diff --git a/tests/Broadside.Tests/Document/DateTests.cs b/tests/Broadside.Tests/Document/DateTests.cs new file mode 100644 index 00000000..4edd70c0 --- /dev/null +++ b/tests/Broadside.Tests/Document/DateTests.cs @@ -0,0 +1,134 @@ +namespace Broadside.Tests.Document; + +/// PDF dates (ISO 32000-2 §7.9.4) and XMP dates (ISO 16684-1 §8.2.1.2), parsed without ever throwing. +public class DateTests +{ + public static TheoryData WellFormedDates => new() + { + // The example of §7.9.4, and its legacy form with the terminating apostrophe (NOTE 2). + { "D:199812231952-08'00", "1998-12-23T19:52:00-08:00", PdfDatePrecision.Minute, -480 }, + { "D:19981223195200-08'00'", "1998-12-23T19:52:00-08:00", PdfDatePrecision.Second, -480 }, + { "D:20140314124211+01'00", "2014-03-14T12:42:11+01:00", PdfDatePrecision.Second, 60 }, + { "D:20140924212303Z", "2014-09-24T21:23:03+00:00", PdfDatePrecision.Second, 0 }, + { "D:20140924212303Z00'00'", "2014-09-24T21:23:03+00:00", PdfDatePrecision.Second, 0 }, + { "D:20140924212303+05", "2014-09-24T21:23:03+05:00", PdfDatePrecision.Second, 300 }, + { "D:20140924212303+05'", "2014-09-24T21:23:03+05:00", PdfDatePrecision.Second, 300 }, + { "D:2014", "2014-01-01T00:00:00+00:00", PdfDatePrecision.Year, null }, + { "D:201409", "2014-09-01T00:00:00+00:00", PdfDatePrecision.Month, null }, + { "D:20140924", "2014-09-24T00:00:00+00:00", PdfDatePrecision.Day, null }, + { "D:2014092421", "2014-09-24T21:00:00+00:00", PdfDatePrecision.Hour, null }, + }; + + [Theory] + [MemberData(nameof(WellFormedDates))] + public void A_date_reads_every_field_its_string_has_and_defaults_the_rest(string text, string expected, PdfDatePrecision precision, int? offset) + { + Assert.True(PdfDate.TryParse(text, out PdfDate date)); + + Assert.Equal(DateTimeOffset.Parse(expected, System.Globalization.CultureInfo.InvariantCulture), date.Value); + Assert.Equal(expected, date.Value.ToString("yyyy-MM-ddTHH:mm:sszzz", System.Globalization.CultureInfo.InvariantCulture)); + Assert.Equal(precision, date.Precision); + Assert.Equal(offset, date.UtcOffsetMinutes); + Assert.Equal(text, date.Text); + Assert.Equal(text, date.ToString()); + } + + [Fact] + public void An_offset_beyond_what_DateTimeOffset_holds_keeps_the_instant_in_universal_time() + { + // §7.9.4 allows offset hours up to 23; DateTimeOffset holds at most 14. + Assert.True(PdfDate.TryParse("D:20000101120000+23'30", out PdfDate date)); + + Assert.Equal(new DateTimeOffset(2000, 1, 1, 12, 0, 0, TimeSpan.Zero).AddMinutes(-(23 * 60) - 30), date.Value); + Assert.Equal(TimeSpan.Zero, date.Value.Offset); + Assert.Equal((23 * 60) + 30, date.UtcOffsetMinutes); + } + + [Theory] + [InlineData("20140924212303Z", "2014-09-24T21:23:03+00:00")] + [InlineData("D:20140924212303+0100", "2014-09-24T21:23:03+01:00")] + [InlineData("D:20140931", "2014-09-30T00:00:00+00:00")] + [InlineData("D:20141324", "2014-12-24T00:00:00+00:00")] + [InlineData("D:20140924256199", "2014-09-24T23:59:59+00:00")] + [InlineData("D:20140924212303 ", "2014-09-24T21:23:03+00:00")] + public void A_date_that_deviates_but_can_be_read_is_read_with_its_fields_clamped(string text, string expected) + { + Assert.True(PdfDate.TryParse(text, out PdfDate date)); + + Assert.Equal(expected, date.Value.ToString("yyyy-MM-ddTHH:mm:sszzz", System.Globalization.CultureInfo.InvariantCulture)); + } + + [Theory] + [InlineData("")] + [InlineData("D:")] + [InlineData("D:201")] + [InlineData("D:191001223195200-08'00'")] + [InlineData("Monday, March 3, 1997")] + [InlineData("D:2014-09-24")] + [InlineData("D:20140924212303X")] + [InlineData("D:20140924212303+1")] + [InlineData(null)] + public void A_string_that_is_not_a_date_does_not_parse(string? text) + { + Assert.False(PdfDate.TryParse(text, out PdfDate date)); + Assert.Equal(default, date); + } + + [Fact] + public void Dates_compare_by_value_and_text() + { + Assert.True(PdfDate.TryParse("D:2014", out PdfDate first)); + Assert.True(PdfDate.TryParse("D:2014", out PdfDate second)); + Assert.True(PdfDate.TryParse("D:201401", out PdfDate third)); + + Assert.Equal(first, second); + Assert.True(first == second); + Assert.NotEqual(first, third); + Assert.True(first != third); + Assert.Equal(first.GetHashCode(), second.GetHashCode()); + } + + public static TheoryData XmpDates => new() + { + { "2014", "2014-01-01T00:00:00+00:00", PdfDatePrecision.Year, false }, + { "2014-09", "2014-09-01T00:00:00+00:00", PdfDatePrecision.Month, false }, + { "2014-09-24", "2014-09-24T00:00:00+00:00", PdfDatePrecision.Day, false }, + { "2014-09-24T21:23+02:00", "2014-09-24T21:23:00+02:00", PdfDatePrecision.Minute, true }, + { "2014-09-24T21:23:03Z", "2014-09-24T21:23:03+00:00", PdfDatePrecision.Second, true }, + { "2014-09-24T21:23:03.25-05:30", "2014-09-24T21:23:03+00:00", PdfDatePrecision.FractionOfSecond, true }, + { "2014-09-24T21:23:03", "2014-09-24T21:23:03+00:00", PdfDatePrecision.Second, false }, + }; + + [Theory] + [MemberData(nameof(XmpDates))] + public void An_xmp_date_reads_the_iso_8601_subset_and_knows_whether_it_has_a_time_zone(string text, string expectedLocal, PdfDatePrecision precision, bool hasTimeZone) + { + Assert.True(XmpDate.TryParse(text, out XmpDate date)); + + Assert.Equal(precision, date.Precision); + Assert.Equal(hasTimeZone, date.HasTimeZone); + Assert.Equal(text, date.Text); + if (precision != PdfDatePrecision.FractionOfSecond) + { + Assert.Equal(expectedLocal, date.Value.ToString("yyyy-MM-ddTHH:mm:sszzz", System.Globalization.CultureInfo.InvariantCulture)); + } + else + { + Assert.Equal(new DateTimeOffset(2014, 9, 24, 21, 23, 3, 250, TimeSpan.FromMinutes(-330)), date.Value); + } + } + + [Theory] + [InlineData("")] + [InlineData("14")] + [InlineData("2014-13")] + [InlineData("2014-02-30")] + [InlineData("2014-09-24T21")] + [InlineData("2014-09-24T25:00Z")] + [InlineData("2014-09-24 21:23Z")] + [InlineData("D:20140924")] + public void A_string_that_is_not_an_xmp_date_does_not_parse(string text) + { + Assert.False(XmpDate.TryParse(text, out _)); + } +} From fe6935e70b444599d78fcf824caf15ffbe136778 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:00:04 -0500 Subject: [PATCH 018/152] feat(model): file specifications and embedded file streams (#76) PdfFileSpecification (string and dictionary form, UF > F > Unix > Mac > DOS, path components with escaped solidus, sanitised SafeFileName, FS URL, ID, V, Desc, AFRelationship, EF/RF/CI/Thumb/EP), PdfEmbeddedFile (Subtype, Params, Decode, VerifyCheckSum with managed MD5), PdfEmbeddedFileParameters, PdfRelatedFile, PdfCollectionItem(+Value) and PdfDocument.GetFileSpecification. Diagnostic codes for issue #76 (optional content, files, metadata). Co-Authored-By: Claude Opus 5.5 --- src/Broadside/FileAndLayerNames.cs | 124 +++++++ src/Broadside/Parsing/DiagnosticCodes.cs | 26 ++ src/Broadside/PdfCheckSumStatus.cs | 15 + src/Broadside/PdfCollectionItem.cs | 52 +++ src/Broadside/PdfCollectionItemValue.cs | 28 ++ src/Broadside/PdfDocument.cs | 9 + src/Broadside/PdfEmbeddedFile.cs | 67 ++++ src/Broadside/PdfEmbeddedFileParameters.cs | 40 +++ src/Broadside/PdfFileRelationship.cs | 33 ++ src/Broadside/PdfFileSpecification.cs | 313 ++++++++++++++++++ src/Broadside/PdfRelatedFile.cs | 26 ++ src/Broadside/PublicAPI.Unshipped.txt | 65 ++++ src/Broadside/ViewReading.cs | 51 +++ .../Files/FileSpecificationTests.cs | 234 +++++++++++++ 14 files changed, 1083 insertions(+) create mode 100644 src/Broadside/FileAndLayerNames.cs create mode 100644 src/Broadside/PdfCheckSumStatus.cs create mode 100644 src/Broadside/PdfCollectionItem.cs create mode 100644 src/Broadside/PdfCollectionItemValue.cs create mode 100644 src/Broadside/PdfEmbeddedFile.cs create mode 100644 src/Broadside/PdfEmbeddedFileParameters.cs create mode 100644 src/Broadside/PdfFileRelationship.cs create mode 100644 src/Broadside/PdfFileSpecification.cs create mode 100644 src/Broadside/PdfRelatedFile.cs create mode 100644 src/Broadside/ViewReading.cs create mode 100644 tests/Broadside.Tests/Files/FileSpecificationTests.cs diff --git a/src/Broadside/FileAndLayerNames.cs b/src/Broadside/FileAndLayerNames.cs new file mode 100644 index 00000000..2d15a740 --- /dev/null +++ b/src/Broadside/FileAndLayerNames.cs @@ -0,0 +1,124 @@ +using Broadside.Objects; + +namespace Broadside; + +/// +/// Names the optional content, file specification, associated file and object metadata views look up (issue #76), created once. +/// Kept apart from so parallel tickets adding names do not collide. +/// +internal static class FileAndLayerNames +{ + // File specifications (ISO 32000-2 §7.11, Tables 43-47). + public static readonly CosName Filespec = new("Filespec"); + public static readonly CosName FS = new("FS"); + public static readonly CosName F = new("F"); + public static readonly CosName UF = new("UF"); + public static readonly CosName DOS = new("DOS"); + public static readonly CosName Mac = new("Mac"); + public static readonly CosName Unix = new("Unix"); + public static readonly CosName ID = new("ID"); + public static readonly CosName V = new("V"); + public static readonly CosName EF = new("EF"); + public static readonly CosName RF = new("RF"); + public static readonly CosName Desc = new("Desc"); + public static readonly CosName CI = new("CI"); + public static readonly CosName Thumb = new("Thumb"); + public static readonly CosName EP = new("EP"); + public static readonly CosName AFRelationship = new("AFRelationship"); + public static readonly CosName URL = new("URL"); + public static readonly CosName Subtype = new("Subtype"); + public static readonly CosName Params = new("Params"); + public static readonly CosName Size = new("Size"); + public static readonly CosName CreationDate = new("CreationDate"); + public static readonly CosName ModDate = new("ModDate"); + public static readonly CosName CheckSum = new("CheckSum"); + public static readonly CosName Unspecified = new("Unspecified"); + public static readonly CosName EmbeddedFile = new("EmbeddedFile"); + + // Associated files and metadata (§14.13, §14.3.2). + public static readonly CosName AF = new("AF"); + public static readonly CosName MCAF = new("MCAF"); + public static readonly CosName Metadata = new("Metadata"); + public static readonly CosName XML = new("XML"); + + // Optional content (§8.11). + public static readonly CosName OCProperties = new("OCProperties"); + public static readonly CosName OCGs = new("OCGs"); + public static readonly CosName D = new("D"); + public static readonly CosName Configs = new("Configs"); + public static readonly CosName OCG = new("OCG"); + public static readonly CosName OCMD = new("OCMD"); + public static readonly CosName OC = new("OC"); + public static readonly CosName Name = new("Name"); + public static readonly CosName Intent = new("Intent"); + public static readonly CosName Usage = new("Usage"); + public static readonly CosName P = new("P"); + public static readonly CosName VE = new("VE"); + public static readonly CosName View = new("View"); + public static readonly CosName Design = new("Design"); + public static readonly CosName All = new("All"); + public static readonly CosName AllOn = new("AllOn"); + public static readonly CosName AnyOn = new("AnyOn"); + public static readonly CosName AnyOff = new("AnyOff"); + public static readonly CosName AllOff = new("AllOff"); + public static readonly CosName And = new("And"); + public static readonly CosName Or = new("Or"); + public static readonly CosName Not = new("Not"); + public static readonly CosName Creator = new("Creator"); + public static readonly CosName BaseState = new("BaseState"); + public static readonly CosName ON = new("ON"); + public static readonly CosName OFF = new("OFF"); + public static readonly CosName Unchanged = new("Unchanged"); + public static readonly CosName AS = new("AS"); + public static readonly CosName Order = new("Order"); + public static readonly CosName ListMode = new("ListMode"); + public static readonly CosName AllPages = new("AllPages"); + public static readonly CosName VisiblePages = new("VisiblePages"); + public static readonly CosName RBGroups = new("RBGroups"); + public static readonly CosName Locked = new("Locked"); + public static readonly CosName Event = new("Event"); + public static readonly CosName Category = new("Category"); + public static readonly CosName Print = new("Print"); + public static readonly CosName Export = new("Export"); + public static readonly CosName CreatorInfo = new("CreatorInfo"); + public static readonly CosName Language = new("Language"); + public static readonly CosName Lang = new("Lang"); + public static readonly CosName Preferred = new("Preferred"); + public static readonly CosName ExportState = new("ExportState"); + public static readonly CosName Zoom = new("Zoom"); + public static readonly CosName Min = new("min"); + public static readonly CosName Max = new("max"); + public static readonly CosName PrintState = new("PrintState"); + public static readonly CosName ViewState = new("ViewState"); + public static readonly CosName User = new("User"); + public static readonly CosName PageElement = new("PageElement"); + public static readonly CosName Properties = new("Properties"); + public static readonly CosName XObject = new("XObject"); + public static readonly CosName Annots = new("Annots"); + + // Collections (§12.3.5). + public static readonly CosName Collection = new("Collection"); + public static readonly CosName Schema = new("Schema"); + public static readonly CosName Navigator = new("Navigator"); + public static readonly CosName Colors = new("Colors"); + public static readonly CosName Sort = new("Sort"); + public static readonly CosName Folders = new("Folders"); + public static readonly CosName Split = new("Split"); + public static readonly CosName N = new("N"); + public static readonly CosName O = new("O"); + public static readonly CosName E = new("E"); + public static readonly CosName S = new("S"); + public static readonly CosName A = new("A"); + public static readonly CosName Background = new("Background"); + public static readonly CosName CardBackground = new("CardBackground"); + public static readonly CosName CardBorder = new("CardBorder"); + public static readonly CosName PrimaryText = new("PrimaryText"); + public static readonly CosName SecondaryText = new("SecondaryText"); + public static readonly CosName Direction = new("Direction"); + public static readonly CosName Position = new("Position"); + public static readonly CosName Child = new("Child"); + public static readonly CosName Next = new("Next"); + public static readonly CosName Free = new("Free"); + public static readonly CosName CollectionSubitem = new("CollectionSubitem"); + public static readonly CosName Type = KnownNames.Type; +} diff --git a/src/Broadside/Parsing/DiagnosticCodes.cs b/src/Broadside/Parsing/DiagnosticCodes.cs index 38370fe5..53e47499 100644 --- a/src/Broadside/Parsing/DiagnosticCodes.cs +++ b/src/Broadside/Parsing/DiagnosticCodes.cs @@ -132,4 +132,30 @@ internal static class DiagnosticCodes public const string PageResourcesMissing = nameof(PageResourcesMissing); public const string PageResourcesInvalid = nameof(PageResourcesInvalid); public const string PageUserUnitInvalid = nameof(PageUserUnitInvalid); + + // Optional content (§8.11; issue #76). + public const string OptionalContentConfigMissing = nameof(OptionalContentConfigMissing); + public const string OptionalContentGroupsMissing = nameof(OptionalContentGroupsMissing); + public const string OptionalContentGroupNotListed = nameof(OptionalContentGroupNotListed); + public const string OptionalContentGroupInvalid = nameof(OptionalContentGroupInvalid); + public const string OptionalContentBaseStateInvalid = nameof(OptionalContentBaseStateInvalid); + public const string OptionalContentIntentInvalid = nameof(OptionalContentIntentInvalid); + public const string OptionalContentGroupOnAndOff = nameof(OptionalContentGroupOnAndOff); + public const string VisibilityExpressionInvalid = nameof(VisibilityExpressionInvalid); + public const string VisibilityPolicyInvalid = nameof(VisibilityPolicyInvalid); + public const string OptionalContentInlineProperties = nameof(OptionalContentInlineProperties); + + // File specifications, embedded files, collections and associated files (§7.11, §12.3.5, §14.13; issue #76). + public const string FileSpecificationInvalid = nameof(FileSpecificationInvalid); + public const string EmbeddedFileMissing = nameof(EmbeddedFileMissing); + public const string EmbeddedFileSubtypeMissing = nameof(EmbeddedFileSubtypeMissing); + public const string EmbeddedFileParamsInvalid = nameof(EmbeddedFileParamsInvalid); + public const string RelatedFilesInvalid = nameof(RelatedFilesInvalid); + public const string AssociatedFilesInvalid = nameof(AssociatedFilesInvalid); + public const string CollectionInvalid = nameof(CollectionInvalid); + public const string CollectionFolderCycle = nameof(CollectionFolderCycle); + public const string CollectionFolderIdDuplicate = nameof(CollectionFolderIdDuplicate); + + // Object-level metadata (§14.3.2; issue #76). + public const string MetadataStreamInvalid = nameof(MetadataStreamInvalid); } diff --git a/src/Broadside/PdfCheckSumStatus.cs b/src/Broadside/PdfCheckSumStatus.cs new file mode 100644 index 00000000..49d13705 --- /dev/null +++ b/src/Broadside/PdfCheckSumStatus.cs @@ -0,0 +1,15 @@ +namespace Broadside; + +/// The outcome of comparing an embedded file's data with the CheckSum its parameters record. +/// ISO 32000-2 §7.11.4.1, Table 45: CheckSum is the 16-byte MD5 digest (RFC 1321) of the decoded file data. +public enum PdfCheckSumStatus +{ + /// The file records no checksum, or it is not a 16-byte string. + Absent, + + /// The MD5 digest of the decoded data equals the recorded checksum. + Matches, + + /// The MD5 digest of the decoded data differs from the recorded checksum. + DoesNotMatch, +} diff --git a/src/Broadside/PdfCollectionItem.cs b/src/Broadside/PdfCollectionItem.cs new file mode 100644 index 00000000..0891e0b1 --- /dev/null +++ b/src/Broadside/PdfCollectionItem.cs @@ -0,0 +1,52 @@ +using Broadside.Objects; + +namespace Broadside; + +/// +/// A collection item: the values a file in a portable collection shows for each field of the collection's schema. A live view over +/// the collection item dictionary. +/// +/// +/// ISO 32000-2 §7.11.6 (PDF 1.7), Tables 46 and 47. Each entry other than Type is keyed by a schema field key and holds a +/// text string, a date, a number, or a collection subitem dictionary (data D plus a prefix P that sorting ignores). +/// +public sealed class PdfCollectionItem +{ + private readonly PdfDocument _document; + + internal PdfCollectionItem(PdfDocument document, CosDictionary dictionary) + { + _document = document; + Dictionary = dictionary; + } + + /// Gets the collection item dictionary. + /// ISO 32000-2 §7.11.6, Table 46. + public CosDictionary Dictionary { get; } + + /// Gets the field keys the item has values for, in the order they are stored. + /// ISO 32000-2 §7.11.6, Table 46: every key except Type. + public IReadOnlyList Keys => [.. Dictionary.Keys.Where(key => !key.Equals(KnownNames.Type)).Select(key => key.Value)]; + + /// Returns the item's value for the schema field , or when it has none. + /// The field's key in the collection schema. + /// The value; a subitem dictionary is unwrapped into its data and prefix. + /// ISO 32000-2 §7.11.6, Tables 46 and 47. + public PdfCollectionItemValue? GetValue(string fieldKey) + { + ArgumentNullException.ThrowIfNull(fieldKey); + if (ViewReading.Get(_document, Dictionary, new CosName(fieldKey)) is not { } value) + { + return null; + } + + if (value is CosDictionary subitem) + { + return ViewReading.Get(_document, subitem, FileAndLayerNames.D) is { } data + ? new PdfCollectionItemValue(data, ViewReading.Text(_document, subitem, FileAndLayerNames.P)) + : null; + } + + return new PdfCollectionItemValue(value, prefix: null); + } +} diff --git a/src/Broadside/PdfCollectionItemValue.cs b/src/Broadside/PdfCollectionItemValue.cs new file mode 100644 index 00000000..852ebad5 --- /dev/null +++ b/src/Broadside/PdfCollectionItemValue.cs @@ -0,0 +1,28 @@ +using Broadside.Objects; + +namespace Broadside; + +/// One value of a collection item: a text string, a date string or a number, with the prefix of a subitem. +/// ISO 32000-2 §7.11.6, Tables 46 and 47. The data type matches the schema field's subtype (§12.3.5, Table 155). +public sealed class PdfCollectionItemValue +{ + internal PdfCollectionItemValue(CosObject data, string? prefix) + { + Data = data; + Prefix = prefix; + } + + /// Gets the value as stored, resolved: a (text or date) or a . + /// ISO 32000-2 §7.11.6, Table 47 (D). + public CosObject Data { get; } + + /// Gets the subitem's prefix (P), shown before the value and ignored when sorting, or . + /// ISO 32000-2 §7.11.6, Table 47. + public string? Prefix { get; } + + /// Gets the value decoded as text when it is a string, else . + public string? Text => Data is CosString value ? value.DecodeText() : null; + + /// Gets the value when it is a number, else . + public double? Number => Data is CosNumber value ? value.ToDouble() : null; +} diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 5c0e9ec2..cc956b8f 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -161,6 +161,9 @@ public PdfVersion Version /// public IReadOnlyList Diagnostics => _diagnostics.Snapshot(); + /// Gets the sink the document model's views report the deviations they find to (lazy diagnostics). + internal DiagnosticSink DiagnosticSink => _diagnostics; + /// Opens the PDF file at with default options. /// The file path. The file is memory-mapped and shared for reading: do not change it until the document is disposed. /// The document. Dispose it when done. @@ -344,6 +347,12 @@ public async Task SaveAsync(Stream stream, PdfSaveOptions? options = null, Cance /// ISO 32000-2 §7.3.10. public CosObject Resolve(CosObject? value) => _loader.Resolve(value); + /// Returns a view over a file specification held by , resolving it first. + /// A file specification string or dictionary, or a reference to one, of this document. + /// The view, or when the value is neither a string nor a dictionary. + /// ISO 32000-2 §7.11. For file specifications the document model does not reach itself (an action's F, say). + public PdfFileSpecification? GetFileSpecification(CosObject? value) => PdfFileSpecification.Create(this, value); + /// Returns the data of decoded through the filters its Filter entry names. /// A stream of this document. /// The decoded data; for a stream without filters, its itself. diff --git a/src/Broadside/PdfEmbeddedFile.cs b/src/Broadside/PdfEmbeddedFile.cs new file mode 100644 index 00000000..21d728e2 --- /dev/null +++ b/src/Broadside/PdfEmbeddedFile.cs @@ -0,0 +1,67 @@ +using System.Buffers; +using Broadside.Objects; +using Broadside.Security.Cryptography; + +namespace Broadside; + +/// An embedded file stream: the contents of a file stored inside the document. A live view over the stream. +/// +/// ISO 32000-2 §7.11.4 (PDF 1.3), Table 44. In a file encrypted with an EFF crypt filter the stream is decrypted with that +/// filter (§7.6.2, Table 20). Subtype and Params are required when the file is an associated file (§14.13.2). +/// +public sealed class PdfEmbeddedFile +{ + private readonly PdfDocument _document; + + internal PdfEmbeddedFile(PdfDocument document, CosStream stream, CosReference? reference) + { + _document = document; + Stream = stream; + Reference = reference; + } + + /// Gets the embedded file stream. + /// ISO 32000-2 §7.11.4.1. + public CosStream Stream { get; } + + /// Gets the indirect reference to the stream, when it was reached through one. + public CosReference? Reference { get; } + + /// Gets the media type (Subtype, an RFC 2046 MIME type such as text/plain), or . + /// ISO 32000-2 §7.11.4.1, Table 44. The name's #2F escapes are already decoded. + public string? Subtype => ViewReading.Name(_document, Stream.Dictionary, FileAndLayerNames.Subtype)?.Value; + + /// Gets , or application/octet-stream when the file has none. + /// ISO 32000-2 §14.13.2: an unknown type is treated as application/octet-stream. + public string MediaType => Subtype ?? "application/octet-stream"; + + /// Gets the embedded file parameters (Params), or . + /// ISO 32000-2 §7.11.4.1, Tables 44 and 45. + public PdfEmbeddedFileParameters? Parameters => + ViewReading.Get(_document, Stream.Dictionary, FileAndLayerNames.Params) is CosDictionary parameters ? new PdfEmbeddedFileParameters(_document, parameters) : null; + + /// Returns the file's contents: the stream data decoded through its filters. + /// The decoded bytes. + /// ISO 32000-2 §7.11.4.1 and §7.4. As ; nothing is cached. + public ReadOnlyMemory Decode() => _document.DecodeStream(Stream); + + /// Writes the file's contents, decoded through its filters, into . + /// Where to write. + /// ISO 32000-2 §7.11.4.1 and §7.4. + public void Decode(IBufferWriter output) => _document.DecodeStream(Stream, output); + + /// Compares the MD5 digest of the decoded contents with . + /// Whether the checksum is absent, matches or differs. A difference is a result, not a diagnostic. + /// ISO 32000-2 §7.11.4.1, Table 45. Uses a managed MD5 where the platform has none. + public PdfCheckSumStatus VerifyCheckSum() + { + if (Parameters?.CheckSum is not { Length: Md5.HashSize } expected) + { + return PdfCheckSumStatus.Absent; + } + + Span actual = stackalloc byte[Md5.HashSize]; + Md5.HashData(Decode().Span, actual); + return actual.SequenceEqual(expected.Span) ? PdfCheckSumStatus.Matches : PdfCheckSumStatus.DoesNotMatch; + } +} diff --git a/src/Broadside/PdfEmbeddedFileParameters.cs b/src/Broadside/PdfEmbeddedFileParameters.cs new file mode 100644 index 00000000..83513024 --- /dev/null +++ b/src/Broadside/PdfEmbeddedFileParameters.cs @@ -0,0 +1,40 @@ +using Broadside.Objects; + +namespace Broadside; + +/// The parameters of an embedded file: size, dates and checksum. A live view over the parameter dictionary. +/// ISO 32000-2 §7.11.4.1, Table 45. +public sealed class PdfEmbeddedFileParameters +{ + private readonly PdfDocument _document; + + internal PdfEmbeddedFileParameters(PdfDocument document, CosDictionary dictionary) + { + _document = document; + Dictionary = dictionary; + } + + /// Gets the embedded file parameter dictionary. + /// ISO 32000-2 §7.11.4.1, Table 45. + public CosDictionary Dictionary { get; } + + /// Gets the size of the uncompressed file in bytes (Size), or . + /// ISO 32000-2 §7.11.4.1, Table 45. + public long? Size => ViewReading.Integer(_document, Dictionary, FileAndLayerNames.Size); + + /// Gets the creation date as written (CreationDate, a §7.9.4 date string), or . + /// ISO 32000-2 §7.11.4.1, Table 45. + public CosString? CreationDate => ViewReading.Get(_document, Dictionary, FileAndLayerNames.CreationDate) as CosString; + + /// Gets the date the file was last modified as written (ModDate, a §7.9.4 date string), or . + /// ISO 32000-2 §7.11.4.1, Table 45. Required when the file is an associated file (§14.13.2). + public CosString? ModificationDate => ViewReading.Get(_document, Dictionary, FileAndLayerNames.ModDate) as CosString; + + /// Gets the recorded MD5 checksum of the uncompressed file (CheckSum, 16 bytes), or . + /// ISO 32000-2 §7.11.4.1, Table 45. Compare with . + public ReadOnlyMemory? CheckSum => ViewReading.Get(_document, Dictionary, FileAndLayerNames.CheckSum) is CosString value ? value.Bytes.ToArray() : null; + + /// Gets the Mac OS file information (Mac), or . + /// ISO 32000-2 §7.11.4.1, Table 45; deprecated in PDF 2.0. + public CosDictionary? Mac => ViewReading.Get(_document, Dictionary, FileAndLayerNames.Mac) as CosDictionary; +} diff --git a/src/Broadside/PdfFileRelationship.cs b/src/Broadside/PdfFileRelationship.cs new file mode 100644 index 00000000..380360e4 --- /dev/null +++ b/src/Broadside/PdfFileRelationship.cs @@ -0,0 +1,33 @@ +namespace Broadside; + +/// The relationship of an associated file to the part of the document that refers to it (AFRelationship). +/// ISO 32000-2 §7.11.3, Table 43 (PDF 2.0), and §14.13. Informational only: it gives no processing instructions. +public enum PdfFileRelationship +{ + /// The relationship is not known or cannot be described by another value. The default. + Unspecified, + + /// The original source material for the associated content. + Source, + + /// Information used to derive a visual presentation, such as the data behind a table or graph. + Data, + + /// An alternative representation of the content, such as audio. + Alternative, + + /// A supplemental representation that may be easier to consume, such as MathML for an equation. + Supplement, + + /// An encrypted payload document (§7.6.7). + EncryptedPayload, + + /// The data of the document's interactive form (§12.7.3). + FormData, + + /// A schema definition for the associated object, such as an XML schema for a metadata stream. + Schema, + + /// A second-class name (Annex E) or another name; see . + Other, +} diff --git a/src/Broadside/PdfFileSpecification.cs b/src/Broadside/PdfFileSpecification.cs new file mode 100644 index 00000000..5de39010 --- /dev/null +++ b/src/Broadside/PdfFileSpecification.cs @@ -0,0 +1,313 @@ +using System.Buffers; +using System.Text; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// +/// A file specification: a reference from the document to another file, external or embedded, in string or dictionary form. A live +/// view over its COS object. +/// +/// +/// +/// ISO 32000-2 §7.11 (PDF 1.1). §7.11.2: a file specification string divides into components separated by /; a component's +/// literal solidus is written \/ (the PDF string (in\\/out)); a leading / makes it absolute, otherwise it is +/// relative to the containing file, and .. moves up a level. §7.11.3, Table 43: the dictionary form adds the file system +/// (FS), per-platform names, the file identifier, the volatile flag, embedded files (EF), related files (RF), a +/// description, a collection item, a thumbnail, an encrypted payload and the associated-file relationship. +/// +/// +/// Name preference (Table 43 says a reader shall use UF instead of F): UF, then F, then the deprecated +/// Unix, Mac and DOS. The embedded file stream is chosen from EF in the same key order. +/// +/// +/// File names are untrusted: they may hold .., absolute paths, backslashes, NUL or reserved device names. The library never +/// combines them with a file-system path; gives a sanitised last component for callers that do. +/// +/// +public sealed class PdfFileSpecification +{ + /// The EF/name preference order of Table 43. + private static readonly CosName[] NameKeys = + [FileAndLayerNames.UF, FileAndLayerNames.F, FileAndLayerNames.Unix, FileAndLayerNames.Mac, FileAndLayerNames.DOS]; + + /// The characters no platform allows in a file name. + private static readonly SearchValues Invalid = SearchValues.Create( + "\0\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f\u007f:*?\"<>|"); + + private readonly PdfDocument _document; + + internal PdfFileSpecification(PdfDocument document, CosObject value, CosReference? reference) + { + _document = document; + Value = value; + Reference = reference; + } + + /// Gets the file specification as stored: a or a . + /// ISO 32000-2 §7.11.1. + public CosObject Value { get; } + + /// Gets the file specification dictionary, or for the string form. + /// ISO 32000-2 §7.11.3, Table 43. + public CosDictionary? Dictionary => Value as CosDictionary; + + /// Gets the indirect reference the specification was reached through, or when it is direct. + public CosReference? Reference { get; } + + /// Gets the file system the specification is interpreted by (FS), or . + /// ISO 32000-2 §7.11.3, Table 43. URL is the only standard file system (§7.11.5). + public CosName? FileSystem => Dictionary is { } dictionary ? ViewReading.Name(_document, dictionary, FileAndLayerNames.FS) : null; + + /// Gets a value indicating whether the file system is URL: the file name is a uniform resource locator (RFC 3986). + /// ISO 32000-2 §7.11.5. + public bool IsUrl => FileSystem is { } fileSystem && fileSystem.Equals(FileAndLayerNames.URL); + + /// Gets the raw string the file name comes from: the string form itself, else UF, F, Unix, Mac or DOS. + /// ISO 32000-2 §7.11.3, Table 43 (UF PDF 1.7; Unix, Mac, DOS deprecated in PDF 2.0). + public CosString? FileNameString + { + get + { + if (Value is CosString value) + { + return value; + } + + foreach (CosName key in NameKeys) + { + if (ViewReading.Get(_document, (CosDictionary)Value, key) is CosString name) + { + return name; + } + } + + return null; + } + } + + /// Gets the file specification string, decoded as text, or when the dictionary names no file. + /// ISO 32000-2 §7.11.2 and §7.11.3. UF is a text string (§7.9.2.2); the other keys are decoded the same way. + public string? FileName => FileNameString?.DecodeText(); + + /// Gets a value indicating whether is an absolute specification (it begins with /). + /// ISO 32000-2 §7.11.2.2. + public bool IsAbsolute => FileName is { Length: > 0 } name && name[0] == '/'; + + /// + /// Gets the components of : split at each /, with an escaped solidus (\/) kept inside its + /// component and the escape removed. A leading / gives no empty first component; .. components are kept as written. + /// + /// ISO 32000-2 §7.11.2.1. For a URL () the components are the URL's path segments as written. + public IReadOnlyList PathComponents => FileName is { } name ? SplitComponents(name) : []; + + /// + /// Gets the last component of , made safe to use as a file name on any platform, or + /// when nothing usable is left. Backslashes and drive prefixes count as separators; characters no platform allows + /// (NUL, control characters, / \ : * ? " < > |) become _; trailing dots and spaces are removed; a + /// reserved device name (CON, NUL, COM1, ...) is prefixed with _; . and .. give + /// . + /// + /// Not a spec concept: file names are untrusted input (CWE-22). The library itself never writes a file under any name. + public string? SafeFileName => FileName is { } name ? Sanitize(name) : null; + + /// Gets the description of the file (Desc), or . + /// ISO 32000-2 §7.11.3, Table 43 (PDF 1.6). + public string? Description => Dictionary is { } dictionary ? ViewReading.Text(_document, dictionary, FileAndLayerNames.Desc) : null; + + /// Gets a value indicating whether the file is volatile and shall not be cached (V). Default . + /// ISO 32000-2 §7.11.3, Table 43 (PDF 1.2). + public bool IsVolatile => Dictionary is { } dictionary && ViewReading.Boolean(_document, dictionary, FileAndLayerNames.V, fallback: false); + + /// Gets the file identifier of the referenced file (ID, two byte strings), or . + /// ISO 32000-2 §7.11.3, Table 43, and §14.4. + public CosArray? FileIdentifier => Dictionary is { } dictionary ? ViewReading.Get(_document, dictionary, FileAndLayerNames.ID) as CosArray : null; + + /// Gets the relationship of the associated file to the object that refers to it (AFRelationship). + /// ISO 32000-2 §7.11.3, Table 43 (PDF 2.0), and §14.13. Default ; a second-class name reads as . + public PdfFileRelationship Relationship => RelationshipName.Value switch + { + "Source" => PdfFileRelationship.Source, + "Data" => PdfFileRelationship.Data, + "Alternative" => PdfFileRelationship.Alternative, + "Supplement" => PdfFileRelationship.Supplement, + "EncryptedPayload" => PdfFileRelationship.EncryptedPayload, + "FormData" => PdfFileRelationship.FormData, + "Schema" => PdfFileRelationship.Schema, + "Unspecified" => PdfFileRelationship.Unspecified, + _ => PdfFileRelationship.Other, + }; + + /// Gets the AFRelationship name as written, or Unspecified when absent. + /// ISO 32000-2 §7.11.3, Table 43 (PDF 2.0). + public CosName RelationshipName => + (Dictionary is { } dictionary ? ViewReading.Name(_document, dictionary, FileAndLayerNames.AFRelationship) : null) ?? FileAndLayerNames.Unspecified; + + /// Gets the embedded file stream (EF, by key preference UF, F, Unix, Mac, DOS), or . + /// In strict mode, when EF holds no stream (EmbeddedFileMissing). + /// + /// ISO 32000-2 §7.11.3, Table 43 (PDF 1.3), and §7.11.4. When EF is present but none of its entries is a stream, the + /// specification is still readable; the embedded file reads as absent with an EmbeddedFileMissing diagnostic. + /// + public PdfEmbeddedFile? EmbeddedFile + { + get + { + if (Dictionary is not { } dictionary || ViewReading.Get(_document, dictionary, FileAndLayerNames.EF) is not { } entry) + { + return null; + } + + if (entry is CosDictionary files) + { + foreach (CosName key in NameKeys) + { + if (ViewReading.Get(_document, files, key) is CosStream stream) + { + return new PdfEmbeddedFile(_document, stream, ViewReading.ReferenceOf(files, key)); + } + } + } + + ViewReading.Warn(_document, DiagnosticCodes.EmbeddedFileMissing, "The file specification's EF entry holds no embedded file stream; the file reads as not embedded.", Reference); + return null; + } + } + + /// Gets the related files of the embedded file (RF, the array under the same key comes from). + /// + /// ISO 32000-2 §7.11.3, Table 43 (PDF 1.3), and §7.11.4.2: an array of name strings, each followed by an embedded file stream. + /// A pair whose name is not a string or whose file is not a stream is skipped with a RelatedFilesInvalid diagnostic. + /// + public IReadOnlyList RelatedFiles + { + get + { + if (Dictionary is not { } dictionary || ViewReading.Get(_document, dictionary, FileAndLayerNames.RF) is not CosDictionary related) + { + return []; + } + + CosObject? entry = null; + foreach (CosName key in NameKeys) + { + entry = ViewReading.Get(_document, related, key); + if (entry is not null) + { + break; + } + } + + if (entry is not CosArray array) + { + if (entry is not null) + { + Report(); + } + + return []; + } + + var files = new List(array.Count / 2); + bool invalid = array.Count % 2 != 0; + for (int index = 0; index + 1 < array.Count; index += 2) + { + if (_document.Resolve(array[index]) is CosString name && _document.Resolve(array[index + 1]) is CosStream stream) + { + files.Add(new PdfRelatedFile(name, new PdfEmbeddedFile(_document, stream, array[index + 1] as CosReference))); + } + else + { + invalid = true; + } + } + + if (invalid) + { + Report(); + } + + return files; + + void Report() => ViewReading.Warn(_document, DiagnosticCodes.RelatedFilesInvalid, "The related files array is not pairs of a name string and an embedded file stream; malformed pairs are skipped.", Reference); + } + } + + /// Gets the collection item (CI) that supplies this file's values in a portable collection, or . + /// ISO 32000-2 §7.11.3, Table 43 (PDF 1.7), and §7.11.6. + public PdfCollectionItem? CollectionItem => + Dictionary is { } dictionary && ViewReading.Get(_document, dictionary, FileAndLayerNames.CI) is CosDictionary item ? new PdfCollectionItem(_document, item) : null; + + /// Gets the thumbnail image of the file (Thumb), or . + /// ISO 32000-2 §7.11.3, Table 43 (PDF 2.0), and §12.3.4. + public CosStream? Thumbnail => Dictionary is { } dictionary ? ViewReading.Get(_document, dictionary, FileAndLayerNames.Thumb) as CosStream : null; + + /// Gets the encrypted payload dictionary (EP), or . Exposed as is; the payload is not unwrapped. + /// ISO 32000-2 §7.11.3, Table 43 (PDF 2.0), and §7.6.7. + public CosDictionary? EncryptedPayload => Dictionary is { } dictionary ? ViewReading.Get(_document, dictionary, FileAndLayerNames.EP) as CosDictionary : null; + + /// Creates the view over , resolving it; when it is neither a string nor a dictionary. + internal static PdfFileSpecification? Create(PdfDocument document, CosObject? value) + { + CosObject resolved = document.Resolve(value); + return resolved is CosString or CosDictionary ? new PdfFileSpecification(document, resolved, value as CosReference) : null; + } + + /// Splits a file specification string at unescaped solidus characters (§7.11.2.1). + private static List SplitComponents(string name) + { + var components = new List(); + var current = new StringBuilder(); + int start = name.Length > 0 && name[0] == '/' ? 1 : 0; + for (int index = start; index < name.Length; index++) + { + char c = name[index]; + if (c == '\\' && index + 1 < name.Length && name[index + 1] == '/') + { + current.Append('/'); + index++; + } + else if (c == '/') + { + components.Add(current.ToString()); + current.Clear(); + } + else + { + current.Append(c); + } + } + + components.Add(current.ToString()); + return components; + } + + private static string? Sanitize(string name) + { + // Treat every separator any platform uses as a separator: solidus, reverse solidus, and a drive colon. + int last = name.AsSpan().LastIndexOfAny('/', '\\'); + string component = name[(last + 1)..]; + var builder = new StringBuilder(component.Length); + foreach (char c in component) + { + builder.Append(Invalid.Contains(c) ? '_' : c); + } + + string result = builder.ToString().TrimEnd('.', ' '); + if (result.Length == 0 || result is "." or "..") + { + return null; + } + + if (result.Length > 255) + { + result = result[..255]; + } + + string stem = result.Split('.')[0]; + bool reserved = stem.ToUpperInvariant() is "CON" or "PRN" or "AUX" or "NUL" + || (stem.Length == 4 && (stem.StartsWith("COM", StringComparison.OrdinalIgnoreCase) || stem.StartsWith("LPT", StringComparison.OrdinalIgnoreCase)) && stem[3] is >= '1' and <= '9'); + return reserved ? "_" + result : result; + } +} diff --git a/src/Broadside/PdfRelatedFile.cs b/src/Broadside/PdfRelatedFile.cs new file mode 100644 index 00000000..8369804c --- /dev/null +++ b/src/Broadside/PdfRelatedFile.cs @@ -0,0 +1,26 @@ +using Broadside.Objects; + +namespace Broadside; + +/// One entry of a related files array: a file that belongs with an embedded file, such as a resource of a Mac OS file. +/// ISO 32000-2 §7.11.4.2. +public sealed class PdfRelatedFile +{ + internal PdfRelatedFile(CosString name, PdfEmbeddedFile file) + { + NameString = name; + File = file; + } + + /// Gets the name of the related file, as stored. + /// ISO 32000-2 §7.11.4.2. + public CosString NameString { get; } + + /// Gets the name of the related file, decoded as text. + /// ISO 32000-2 §7.11.4.2. + public string Name => NameString.DecodeText(); + + /// Gets the embedded file stream that holds the related file. + /// ISO 32000-2 §7.11.4.2. + public PdfEmbeddedFile File { get; } +} diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index a576dc7d..3960d15b 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -65,6 +65,71 @@ Broadside.Objects.CosString.CosString(System.ReadOnlySpan bytes, bool hexa Broadside.Objects.CosString.DecodeText() -> string! Broadside.Objects.CosString.Equals(Broadside.Objects.CosString? other) -> bool Broadside.Objects.CosString.IsHexadecimal.get -> bool +Broadside.PdfCheckSumStatus +Broadside.PdfCheckSumStatus.Absent = 0 -> Broadside.PdfCheckSumStatus +Broadside.PdfCheckSumStatus.DoesNotMatch = 2 -> Broadside.PdfCheckSumStatus +Broadside.PdfCheckSumStatus.Matches = 1 -> Broadside.PdfCheckSumStatus +Broadside.PdfCollectionItem +Broadside.PdfCollectionItem.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfCollectionItem.GetValue(string! fieldKey) -> Broadside.PdfCollectionItemValue? +Broadside.PdfCollectionItem.Keys.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfCollectionItemValue +Broadside.PdfCollectionItemValue.Data.get -> Broadside.Objects.CosObject! +Broadside.PdfCollectionItemValue.Number.get -> double? +Broadside.PdfCollectionItemValue.Prefix.get -> string? +Broadside.PdfCollectionItemValue.Text.get -> string? +Broadside.PdfDocument.GetFileSpecification(Broadside.Objects.CosObject? value) -> Broadside.PdfFileSpecification? +Broadside.PdfEmbeddedFile +Broadside.PdfEmbeddedFile.Decode() -> System.ReadOnlyMemory +Broadside.PdfEmbeddedFile.Decode(System.Buffers.IBufferWriter! output) -> void +Broadside.PdfEmbeddedFile.MediaType.get -> string! +Broadside.PdfEmbeddedFile.Parameters.get -> Broadside.PdfEmbeddedFileParameters? +Broadside.PdfEmbeddedFile.Reference.get -> Broadside.Objects.CosReference? +Broadside.PdfEmbeddedFile.Stream.get -> Broadside.Objects.CosStream! +Broadside.PdfEmbeddedFile.Subtype.get -> string? +Broadside.PdfEmbeddedFile.VerifyCheckSum() -> Broadside.PdfCheckSumStatus +Broadside.PdfEmbeddedFileParameters +Broadside.PdfEmbeddedFileParameters.CheckSum.get -> System.ReadOnlyMemory? +Broadside.PdfEmbeddedFileParameters.CreationDate.get -> Broadside.Objects.CosString? +Broadside.PdfEmbeddedFileParameters.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfEmbeddedFileParameters.Mac.get -> Broadside.Objects.CosDictionary? +Broadside.PdfEmbeddedFileParameters.ModificationDate.get -> Broadside.Objects.CosString? +Broadside.PdfEmbeddedFileParameters.Size.get -> long? +Broadside.PdfFileRelationship +Broadside.PdfFileRelationship.Alternative = 3 -> Broadside.PdfFileRelationship +Broadside.PdfFileRelationship.Data = 2 -> Broadside.PdfFileRelationship +Broadside.PdfFileRelationship.EncryptedPayload = 5 -> Broadside.PdfFileRelationship +Broadside.PdfFileRelationship.FormData = 6 -> Broadside.PdfFileRelationship +Broadside.PdfFileRelationship.Other = 8 -> Broadside.PdfFileRelationship +Broadside.PdfFileRelationship.Schema = 7 -> Broadside.PdfFileRelationship +Broadside.PdfFileRelationship.Source = 1 -> Broadside.PdfFileRelationship +Broadside.PdfFileRelationship.Supplement = 4 -> Broadside.PdfFileRelationship +Broadside.PdfFileRelationship.Unspecified = 0 -> Broadside.PdfFileRelationship +Broadside.PdfFileSpecification +Broadside.PdfFileSpecification.CollectionItem.get -> Broadside.PdfCollectionItem? +Broadside.PdfFileSpecification.Description.get -> string? +Broadside.PdfFileSpecification.Dictionary.get -> Broadside.Objects.CosDictionary? +Broadside.PdfFileSpecification.EmbeddedFile.get -> Broadside.PdfEmbeddedFile? +Broadside.PdfFileSpecification.EncryptedPayload.get -> Broadside.Objects.CosDictionary? +Broadside.PdfFileSpecification.FileIdentifier.get -> Broadside.Objects.CosArray? +Broadside.PdfFileSpecification.FileName.get -> string? +Broadside.PdfFileSpecification.FileNameString.get -> Broadside.Objects.CosString? +Broadside.PdfFileSpecification.FileSystem.get -> Broadside.Objects.CosName? +Broadside.PdfFileSpecification.IsAbsolute.get -> bool +Broadside.PdfFileSpecification.IsUrl.get -> bool +Broadside.PdfFileSpecification.IsVolatile.get -> bool +Broadside.PdfFileSpecification.PathComponents.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfFileSpecification.Reference.get -> Broadside.Objects.CosReference? +Broadside.PdfFileSpecification.RelatedFiles.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfFileSpecification.Relationship.get -> Broadside.PdfFileRelationship +Broadside.PdfFileSpecification.RelationshipName.get -> Broadside.Objects.CosName! +Broadside.PdfFileSpecification.SafeFileName.get -> string? +Broadside.PdfFileSpecification.Thumbnail.get -> Broadside.Objects.CosStream? +Broadside.PdfFileSpecification.Value.get -> Broadside.Objects.CosObject! +Broadside.PdfRelatedFile +Broadside.PdfRelatedFile.File.get -> Broadside.PdfEmbeddedFile! +Broadside.PdfRelatedFile.Name.get -> string! +Broadside.PdfRelatedFile.NameString.get -> Broadside.Objects.CosString! const Broadside.Objects.CosReference.MaxGeneration = 65535 -> int override Broadside.Objects.CosArray.IsDirty.get -> bool override Broadside.Objects.CosBoolean.Equals(object? obj) -> bool diff --git a/src/Broadside/ViewReading.cs b/src/Broadside/ViewReading.cs new file mode 100644 index 00000000..6b025e16 --- /dev/null +++ b/src/Broadside/ViewReading.cs @@ -0,0 +1,51 @@ +using Broadside.Diagnostics; +using Broadside.Objects; + +namespace Broadside; + +/// +/// Small lenient readers the issue #76 views share: every entry is resolved, a reference to nothing reads as absent, and a value of +/// the wrong type reads as absent too (the caller decides whether that is a diagnostic). Nothing here writes to COS. +/// +internal static class ViewReading +{ + /// The entry, resolved; when absent or a reference to nothing. + public static CosObject? Get(PdfDocument document, CosDictionary dictionary, CosName key) => + dictionary.TryGetValue(key, out CosObject? value) && document.Resolve(value) is not CosNull and var resolved ? resolved : null; + + /// The entry decoded as a text string (§7.9.2.2), or when absent or not a string. + public static string? Text(PdfDocument document, CosDictionary dictionary, CosName key) => + Get(document, dictionary, key) is CosString value ? value.DecodeText() : null; + + /// The entry as a name, or . + public static CosName? Name(PdfDocument document, CosDictionary dictionary, CosName key) => + Get(document, dictionary, key) as CosName; + + /// The entry as a boolean, or . + public static bool Boolean(PdfDocument document, CosDictionary dictionary, CosName key, bool fallback) => + Get(document, dictionary, key) is CosBoolean value ? value.Value : fallback; + + /// The entry as an integer, or ; a real holding an integral value is accepted. + public static long? Integer(PdfDocument document, CosDictionary dictionary, CosName key) => Get(document, dictionary, key) switch + { + CosInteger value => value.Value, + CosReal value when value.Value == Math.Floor(value.Value) && Math.Abs(value.Value) < long.MaxValue => (long)value.Value, + _ => null, + }; + + /// The entry as a number, or . + public static double? Number(PdfDocument document, CosDictionary dictionary, CosName key) => + Get(document, dictionary, key) is CosNumber value ? value.ToDouble() : null; + + /// The indirect reference an entry holds, or when the entry is direct or absent. + public static CosReference? ReferenceOf(CosDictionary dictionary, CosName key) => + dictionary.TryGetValue(key, out CosObject? value) ? value as CosReference : null; + + /// Whether the dictionary's Type is . + public static bool HasType(PdfDocument document, CosDictionary dictionary, CosName type) => + Name(document, dictionary, KnownNames.Type) is { } value && value.Equals(type); + + /// Records a lenient-mode warning; in strict mode it throws. + public static void Warn(PdfDocument document, string code, string message, CosReference? reference) => + document.DiagnosticSink.Report(code, DiagnosticSeverity.Warning, message, offset: null, reference); +} diff --git a/tests/Broadside.Tests/Files/FileSpecificationTests.cs b/tests/Broadside.Tests/Files/FileSpecificationTests.cs new file mode 100644 index 00000000..6d83629d --- /dev/null +++ b/tests/Broadside.Tests/Files/FileSpecificationTests.cs @@ -0,0 +1,234 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Tests.Document; + +namespace Broadside.Tests.Files; + +/// File specifications in string and dictionary form, embedded file streams and related files. ISO 32000-2 §7.11. +public class FileSpecificationTests +{ + private static PdfDocument OpenWith(params string[] extraObjects) => OpenWith(new PdfOptions(), extraObjects); + + private static PdfDocument OpenWith(PdfOptions options, params string[] extraObjects) => PdfDocument.Open( + new TestPdf().Build( + [ + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>", + .. extraObjects, + ]), + options); + + [Fact] + public void A_string_file_specification_splits_into_components_with_escaped_solidus_kept() + { + using PdfDocument document = OpenWith(); + + PdfFileSpecification spec = document.GetFileSpecification(new CosString("/HardDisk/in\\/out/Summary.pdf"u8))!; + + Assert.Null(spec.Dictionary); + Assert.Equal("/HardDisk/in\\/out/Summary.pdf", spec.FileName); + Assert.True(spec.IsAbsolute); + Assert.Equal(["HardDisk", "in/out", "Summary.pdf"], spec.PathComponents); + Assert.Equal("Summary.pdf", spec.SafeFileName); + Assert.Equal(PdfFileRelationship.Unspecified, spec.Relationship); + Assert.Null(spec.EmbeddedFile); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_relative_file_specification_keeps_its_parent_components_raw() + { + using PdfDocument document = OpenWith(); + + PdfFileSpecification spec = document.GetFileSpecification(new CosString("../../ArtFiles/Figure1.pdf"u8))!; + + Assert.False(spec.IsAbsolute); + Assert.Equal(["..", "..", "ArtFiles", "Figure1.pdf"], spec.PathComponents); + Assert.Equal("Figure1.pdf", spec.SafeFileName); + } + + [Theory] + [MemberData(nameof(UnsafeNames))] + public void An_unsafe_file_name_is_sanitised(string raw, string? expected) + { + using PdfDocument document = OpenWith(); + + PdfFileSpecification spec = document.GetFileSpecification(new CosString(System.Text.Encoding.Latin1.GetBytes(raw)))!; + + Assert.Equal(expected, spec.SafeFileName); + } + + public static TheoryData UnsafeNames => new() + { + { "C:\\Windows\\evil.exe", "evil.exe" }, + { "..", null }, + { "dir/", null }, + { "CON", "_CON" }, + { "lpt1.txt", "_lpt1.txt" }, + { "a*b?ce|f\"g:h.txt...", "a_b_c_d_e_f_g_h.txt" }, + { "nul\0byte.txt", "nul_byte.txt" }, + }; + + [Fact] + public void A_dictionary_prefers_UF_over_F_and_names_its_embedded_stream_by_the_same_key() + { + using PdfDocument document = OpenWith( + "<< /Type /Filespec /F (plain.txt) /UF /Desc (A note) /AFRelationship /Source /V true " + + "/ID [<01> <02>] /EF << /F 6 0 R /UF 5 0 R >> >>", + "<< /Type /EmbeddedFile /Subtype /text#2Fplain /Params << /Size 5 /CheckSum <5d41402abc4b2a76b9719d911017c592> >> /Length 5 >>\nstream\nhello\nendstream", + "<< /Length 3 >>\nstream\nold\nendstream"); + + PdfFileSpecification spec = document.GetFileSpecification(new CosReference(4, 0))!; + + Assert.Equal(new CosReference(4, 0), spec.Reference); + Assert.Equal("\u00e9.txt", spec.FileName); + Assert.Equal("\u00e9.txt", spec.SafeFileName); + Assert.Equal("A note", spec.Description); + Assert.True(spec.IsVolatile); + Assert.Equal(PdfFileRelationship.Source, spec.Relationship); + Assert.Equal(2, spec.FileIdentifier!.Count); + PdfEmbeddedFile file = spec.EmbeddedFile!; + Assert.Equal(new CosReference(5, 0), file.Reference); + Assert.Equal("text/plain", file.Subtype); + Assert.Equal("text/plain", file.MediaType); + Assert.Equal("hello"u8.ToArray(), file.Decode().ToArray()); + Assert.Equal(5, file.Parameters!.Size); + Assert.Equal(PdfCheckSumStatus.Matches, file.VerifyCheckSum()); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_wrong_checksum_is_a_result_not_a_diagnostic() + { + using PdfDocument document = OpenWith( + "<< /Type /Filespec /F (a.txt) /EF << /F 5 0 R >> >>", + "<< /Params << /CheckSum <00000000000000000000000000000000> >> /Length 5 >>\nstream\nhello\nendstream"); + + PdfEmbeddedFile file = document.GetFileSpecification(new CosReference(4, 0))!.EmbeddedFile!; + + Assert.Equal(PdfCheckSumStatus.DoesNotMatch, file.VerifyCheckSum()); + Assert.Null(file.Subtype); + Assert.Equal("application/octet-stream", file.MediaType); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Name_preference_falls_back_through_F_Unix_Mac_and_DOS() + { + using PdfDocument document = OpenWith( + "<< /DOS (DOS.TXT) /Mac (mac.txt) /Unix (unix.txt) >>", + "<< /DOS (DOS.TXT) /Mac (mac.txt) >>", + "<< /DOS (DOS.TXT) >>"); + + Assert.Equal("unix.txt", document.GetFileSpecification(new CosReference(4, 0))!.FileName); + Assert.Equal("mac.txt", document.GetFileSpecification(new CosReference(5, 0))!.FileName); + Assert.Equal("DOS.TXT", document.GetFileSpecification(new CosReference(6, 0))!.FileName); + } + + [Fact] + public void A_URL_file_specification_is_recognised_by_its_file_system() + { + using PdfDocument document = OpenWith("<< /FS /URL /F (https://example.com/a%20b.pdf) >>"); + + PdfFileSpecification spec = document.GetFileSpecification(new CosReference(4, 0))!; + + Assert.True(spec.IsUrl); + Assert.Equal("URL", spec.FileSystem!.Value); + Assert.Equal("https://example.com/a%20b.pdf", spec.FileName); + } + + [Fact] + public void A_second_class_relationship_reads_as_other_with_its_name() + { + using PdfDocument document = OpenWith("<< /F (a.txt) /AFRelationship /ABCD_Witness >>"); + + PdfFileSpecification spec = document.GetFileSpecification(new CosReference(4, 0))!; + + Assert.Equal(PdfFileRelationship.Other, spec.Relationship); + Assert.Equal("ABCD_Witness", spec.RelationshipName.Value); + } + + [Fact] + public void Related_files_pair_names_with_embedded_file_streams() + { + using PdfDocument document = OpenWith( + "<< /Type /Filespec /F (main.c) /EF << /F 5 0 R >> /RF << /F 6 0 R >> >>", + "<< /Length 4 >>\nstream\nmain\nendstream", + "[(util.h) 7 0 R]", + "<< /Length 4 >>\nstream\nutil\nendstream"); + + PdfRelatedFile related = Assert.Single(document.GetFileSpecification(new CosReference(4, 0))!.RelatedFiles); + + Assert.Equal("util.h", related.Name); + Assert.Equal("util"u8.ToArray(), related.File.Decode().ToArray()); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_malformed_related_files_array_keeps_its_well_formed_pairs_with_a_diagnostic() + { + using PdfDocument document = OpenWith( + "<< /Type /Filespec /F (main.c) /EF << /F 5 0 R >> /RF << /F [(util.h) 5 0 R (bad) 42 (odd)] >> >>", + "<< /Length 4 >>\nstream\nmain\nendstream"); + + PdfRelatedFile related = Assert.Single(document.GetFileSpecification(new CosReference(4, 0))!.RelatedFiles); + + Assert.Equal("util.h", related.Name); + Assert.Equal(["RelatedFilesInvalid"], document.Diagnostics.Select(diagnostic => diagnostic.Code)); + Assert.Equal(new CosReference(4, 0), document.Diagnostics[0].ObjectReference); + } + + [Fact] + public void An_EF_without_a_stream_is_reported_and_the_specification_is_still_readable() + { + using PdfDocument document = OpenWith("<< /Type /Filespec /F (gone.txt) /EF << /F 99 0 R >> >>"); + + PdfFileSpecification spec = document.GetFileSpecification(new CosReference(4, 0))!; + + Assert.Equal("gone.txt", spec.FileName); + Assert.Null(spec.EmbeddedFile); + Assert.Equal(["EmbeddedFileMissing"], document.Diagnostics.Select(diagnostic => diagnostic.Code)); + } + + [Fact] + public void Strict_mode_throws_for_an_EF_without_a_stream() + { + using PdfDocument document = OpenWith(new PdfOptions().UseStrict(), "<< /Type /Filespec /F (gone.txt) /EF << /F 99 0 R >> >>"); + + PdfFileSpecification spec = document.GetFileSpecification(new CosReference(4, 0))!; + + DiagnosticException exception = Assert.Throws(() => spec.EmbeddedFile); + Assert.Equal("EmbeddedFileMissing", exception.Diagnostic.Code); + } + + [Fact] + public void A_value_that_is_neither_a_string_nor_a_dictionary_is_not_a_file_specification() + { + using PdfDocument document = OpenWith(); + + Assert.Null(document.GetFileSpecification(new CosInteger(3))); + Assert.Null(document.GetFileSpecification(new CosReference(99, 0))); + } + + [Fact] + public void Reading_a_file_specification_leaves_every_object_clean() + { + using PdfDocument document = OpenWith( + "<< /Type /Filespec /F (main.c) /UF (main.c) /EF << /F 5 0 R >> /RF << /F 6 0 R >> /CI 8 0 R >>", + "<< /Params << /Size 4 /ModDate (D:20240101) >> /Length 4 >>\nstream\nmain\nendstream", + "[(util.h) 7 0 R]", + "<< /Length 4 >>\nstream\nutil\nendstream", + "<< /Type /CollectionItem /name (Main) >>"); + + PdfFileSpecification spec = document.GetFileSpecification(new CosReference(4, 0))!; + _ = (spec.FileName, spec.SafeFileName, spec.PathComponents, spec.Relationship, spec.Description, spec.IsVolatile, + spec.EmbeddedFile!.Parameters!.Size, spec.EmbeddedFile.MediaType, spec.EmbeddedFile.VerifyCheckSum(), spec.RelatedFiles, + spec.CollectionItem, spec.Thumbnail, spec.EncryptedPayload); + + for (int number = 1; number <= 8; number++) + { + Assert.False(document.Resolve(new CosReference(number, 0)).IsDirty); + } + } +} From 922792caf61d8e4db6a00dc2f97f83a20c47db7d Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:00:47 -0500 Subject: [PATCH 019/152] feat(document): XMP packet reader (#69) XmpPacket reads ISO 16684-1 packets with the BCL XmlReader (DTDs prohibited, no resolver, character limit), every property form of 7.5-7.9, and typed getters for the dc, xmp, pdf, pdfaid, pdfuaid and xmpMM properties. Co-Authored-By: Claude Opus 5.5 --- src/Broadside/Parsing/DiagnosticCodes.cs | 31 ++ src/Broadside/PublicAPI.Unshipped.txt | 50 +++ src/Broadside/XmpNamespaces.cs | 34 ++ src/Broadside/XmpPacket.cs | 197 ++++++++++++ src/Broadside/XmpPacketReader.cs | 298 ++++++++++++++++++ src/Broadside/XmpProperty.cs | 78 +++++ src/Broadside/XmpPropertyKind.cs | 21 ++ .../Document/XmpPacketTests.cs | 206 ++++++++++++ 8 files changed, 915 insertions(+) create mode 100644 src/Broadside/XmpNamespaces.cs create mode 100644 src/Broadside/XmpPacket.cs create mode 100644 src/Broadside/XmpPacketReader.cs create mode 100644 src/Broadside/XmpProperty.cs create mode 100644 src/Broadside/XmpPropertyKind.cs create mode 100644 tests/Broadside.Tests/Document/XmpPacketTests.cs diff --git a/src/Broadside/Parsing/DiagnosticCodes.cs b/src/Broadside/Parsing/DiagnosticCodes.cs index 38370fe5..f4fba51b 100644 --- a/src/Broadside/Parsing/DiagnosticCodes.cs +++ b/src/Broadside/Parsing/DiagnosticCodes.cs @@ -114,6 +114,37 @@ internal static class DiagnosticCodes public const string CatalogVersionNotName = nameof(CatalogVersionNotName); public const string CatalogVersionInvalid = nameof(CatalogVersionInvalid); public const string PagesMissing = nameof(PagesMissing); + public const string CatalogEntryInvalid = nameof(CatalogEntryInvalid); + public const string PageLayoutInvalid = nameof(PageLayoutInvalid); + public const string PageModeInvalid = nameof(PageModeInvalid); + public const string ViewerPreferencesInvalid = nameof(ViewerPreferencesInvalid); + public const string ViewerPreferenceInvalid = nameof(ViewerPreferenceInvalid); + public const string ExtensionsInvalid = nameof(ExtensionsInvalid); + public const string ExtensionsNotDirect = nameof(ExtensionsNotDirect); + public const string DeveloperExtensionInvalid = nameof(DeveloperExtensionInvalid); + public const string RequirementInvalid = nameof(RequirementInvalid); + + // Page labels (§12.4.2). + public const string PageLabelsMissingZeroKey = nameof(PageLabelsMissingZeroKey); + public const string PageLabelInvalid = nameof(PageLabelInvalid); + public const string PageLabelStyleInvalid = nameof(PageLabelStyleInvalid); + public const string PageLabelStartInvalid = nameof(PageLabelStartInvalid); + public const string PageLabelPrefixInvalid = nameof(PageLabelPrefixInvalid); + public const string PageLabelTooLong = nameof(PageLabelTooLong); + + // Document information, metadata and file identifiers (§7.9.4, §14.3, §14.4). + public const string InfoDictionaryInvalid = nameof(InfoDictionaryInvalid); + public const string InfoValueNotTextString = nameof(InfoValueNotTextString); + public const string InfoTrappedInvalid = nameof(InfoTrappedInvalid); + public const string DateInvalid = nameof(DateInvalid); + public const string DateUnreadable = nameof(DateUnreadable); + public const string MetadataStreamInvalid = nameof(MetadataStreamInvalid); + public const string MetadataStreamTypeInvalid = nameof(MetadataStreamTypeInvalid); + public const string XmpMalformed = nameof(XmpMalformed); + public const string XmpDtdProhibited = nameof(XmpDtdProhibited); + public const string XmpLeadingJunk = nameof(XmpLeadingJunk); + public const string XmpPropertyDuplicate = nameof(XmpPropertyDuplicate); + public const string FileIdentifierInvalid = nameof(FileIdentifierInvalid); // Page tree (§7.7.3). public const string PageTreeNodeTypeInvalid = nameof(PageTreeNodeTypeInvalid); diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index 0014eb43..d8b2a9f8 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -438,3 +438,53 @@ static Broadside.PdfDate.TryParse(string? text, out Broadside.PdfDate date) -> b static Broadside.XmpDate.operator !=(Broadside.XmpDate left, Broadside.XmpDate right) -> bool static Broadside.XmpDate.operator ==(Broadside.XmpDate left, Broadside.XmpDate right) -> bool static Broadside.XmpDate.TryParse(string? text, out Broadside.XmpDate date) -> bool +Broadside.XmpNamespaces +const Broadside.XmpNamespaces.DublinCore = "http://purl.org/dc/elements/1.1/" -> string! +const Broadside.XmpNamespaces.Pdf = "http://ns.adobe.com/pdf/1.3/" -> string! +const Broadside.XmpNamespaces.PdfAIdentification = "http://www.aiim.org/pdfa/ns/id/" -> string! +const Broadside.XmpNamespaces.PdfUAIdentification = "http://www.aiim.org/pdfua/ns/id/" -> string! +const Broadside.XmpNamespaces.Rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" -> string! +const Broadside.XmpNamespaces.Xmp = "http://ns.adobe.com/xap/1.0/" -> string! +const Broadside.XmpNamespaces.XmpMediaManagement = "http://ns.adobe.com/xap/1.0/mm/" -> string! +const Broadside.XmpNamespaces.XmpMeta = "adobe:ns:meta/" -> string! +Broadside.XmpPropertyKind +Broadside.XmpPropertyKind.Alternative = 4 -> Broadside.XmpPropertyKind +Broadside.XmpPropertyKind.OrderedArray = 3 -> Broadside.XmpPropertyKind +Broadside.XmpPropertyKind.Simple = 0 -> Broadside.XmpPropertyKind +Broadside.XmpPropertyKind.Structure = 1 -> Broadside.XmpPropertyKind +Broadside.XmpPropertyKind.UnorderedArray = 2 -> Broadside.XmpPropertyKind +Broadside.XmpProperty +Broadside.XmpProperty.Fields.get -> System.Collections.Generic.IReadOnlyList! +Broadside.XmpProperty.GetField(string! namespaceName, string! name) -> Broadside.XmpProperty? +Broadside.XmpProperty.Items.get -> System.Collections.Generic.IReadOnlyList! +Broadside.XmpProperty.Kind.get -> Broadside.XmpPropertyKind +Broadside.XmpProperty.Language.get -> string? +Broadside.XmpProperty.Name.get -> string! +Broadside.XmpProperty.NamespaceName.get -> string! +Broadside.XmpProperty.Qualifiers.get -> System.Collections.Generic.IReadOnlyList! +Broadside.XmpProperty.Value.get -> string? +Broadside.XmpPacket +Broadside.XmpPacket.About.get -> string? +Broadside.XmpPacket.CreateDate.get -> Broadside.XmpDate? +Broadside.XmpPacket.CreatorTool.get -> string? +Broadside.XmpPacket.Creators.get -> System.Collections.Generic.IReadOnlyList! +Broadside.XmpPacket.Description.get -> string? +Broadside.XmpPacket.DocumentId.get -> string? +Broadside.XmpPacket.Format.get -> string? +Broadside.XmpPacket.GetLanguageAlternative(string! namespaceName, string! name, string? language = null) -> string? +Broadside.XmpPacket.GetProperty(string! namespaceName, string! name) -> Broadside.XmpProperty? +Broadside.XmpPacket.GetText(string! namespaceName, string! name) -> string? +Broadside.XmpPacket.InstanceId.get -> string? +Broadside.XmpPacket.Keywords.get -> string? +Broadside.XmpPacket.MetadataDate.get -> Broadside.XmpDate? +Broadside.XmpPacket.ModifyDate.get -> Broadside.XmpDate? +Broadside.XmpPacket.PdfAConformance.get -> string? +Broadside.XmpPacket.PdfAPart.get -> int? +Broadside.XmpPacket.PdfUAPart.get -> int? +Broadside.XmpPacket.PdfVersion.get -> string? +Broadside.XmpPacket.Producer.get -> string? +Broadside.XmpPacket.Properties.get -> System.Collections.Generic.IReadOnlyList! +Broadside.XmpPacket.Subjects.get -> System.Collections.Generic.IReadOnlyList! +Broadside.XmpPacket.Title.get -> string? +Broadside.XmpPacket.Trapped.get -> string? +static Broadside.XmpPacket.TryParse(System.ReadOnlySpan data, out Broadside.XmpPacket? packet) -> bool diff --git a/src/Broadside/XmpNamespaces.cs b/src/Broadside/XmpNamespaces.cs new file mode 100644 index 00000000..709bb989 --- /dev/null +++ b/src/Broadside/XmpNamespaces.cs @@ -0,0 +1,34 @@ +namespace Broadside; + +/// The namespace URIs of the XMP schemas a PDF document's metadata commonly uses. +/// +/// Properties are identified by namespace URI and local name, never by prefix: a packet may bind any prefix to these URIs +/// (ISO 16684-1 §6.2). URIs from ISO 16684-1 §8.3-8.6 (dc, xmp, xmpMM), ISO 32000-2 §14.3.2 (pdf), ISO 19005 (pdfaid) and +/// ISO 14289-1 §5 (pdfuaid). +/// +public static class XmpNamespaces +{ + /// RDF, http://www.w3.org/1999/02/22-rdf-syntax-ns#: the syntax XMP is serialized in (ISO 16684-1 §7.4). + public const string Rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + + /// The x:xmpmeta wrapper element's namespace, adobe:ns:meta/ (ISO 16684-1 §7.3.3). + public const string XmpMeta = "adobe:ns:meta/"; + + /// Dublin Core, http://purl.org/dc/elements/1.1/, usually prefixed dc (ISO 16684-1 §8.3). + public const string DublinCore = "http://purl.org/dc/elements/1.1/"; + + /// XMP basic, http://ns.adobe.com/xap/1.0/, usually prefixed xmp (ISO 16684-1 §8.4). + public const string Xmp = "http://ns.adobe.com/xap/1.0/"; + + /// XMP media management, http://ns.adobe.com/xap/1.0/mm/, usually prefixed xmpMM (ISO 16684-1 §8.6). + public const string XmpMediaManagement = "http://ns.adobe.com/xap/1.0/mm/"; + + /// Adobe PDF, http://ns.adobe.com/pdf/1.3/, usually prefixed pdf (ISO 32000-2 §14.3.3, Table 349). + public const string Pdf = "http://ns.adobe.com/pdf/1.3/"; + + /// PDF/A identification, http://www.aiim.org/pdfa/ns/id/, usually prefixed pdfaid (ISO 19005). + public const string PdfAIdentification = "http://www.aiim.org/pdfa/ns/id/"; + + /// PDF/UA identification, http://www.aiim.org/pdfua/ns/id/, usually prefixed pdfuaid (ISO 14289-1 §5). + public const string PdfUAIdentification = "http://www.aiim.org/pdfua/ns/id/"; +} diff --git a/src/Broadside/XmpPacket.cs b/src/Broadside/XmpPacket.cs new file mode 100644 index 00000000..a8239339 --- /dev/null +++ b/src/Broadside/XmpPacket.cs @@ -0,0 +1,197 @@ +using System.Diagnostics.CodeAnalysis; +using System.Globalization; + +namespace Broadside; + +/// An XMP packet: the properties of one rdf:RDF element, with typed getters for the properties PDF files commonly use. +/// +/// +/// ISO 16684-1 §7. A packet is one rdf:RDF element, optionally inside an x:xmpmeta element and an +/// <?xpacket?> wrapper (§7.3), neither required. Its rdf:Description elements all describe the same resource +/// and their properties are merged; a property written twice keeps its first value. Properties are identified by namespace name and +/// local name (see ), never by prefix. Every form §7.5-7.9 allows is read: simple values as elements +/// or as attributes, structures as nested descriptions, rdf:parseType="Resource" or attributes, arrays as rdf:Bag, +/// rdf:Seq and rdf:Alt, and qualifiers written with rdf:value. +/// +/// +/// Reading (): a leading byte order mark selects UTF-8, UTF-16 or UTF-32 (§7.1; without one, UTF-16 is +/// recognized by the first character and anything else is read as UTF-8); bytes before the first < are skipped; reading +/// stops at the end of the rdf:RDF element, so the packet padding and whatever follows it are never read. The XML is read +/// with document type declarations refused (no entity is ever expanded and nothing outside the packet is fetched) and at most +/// 16 million characters. Malformed XML before the end of rdf:RDF makes the whole packet unreadable. +/// +/// Immutable: a snapshot of the bytes it was read from. Writing XMP is not supported yet. +/// +public sealed class XmpPacket +{ + private readonly Dictionary<(string NamespaceName, string Name), XmpProperty> _byName; + + internal XmpPacket(IReadOnlyList properties, string? about) + { + Properties = properties; + About = about; + _byName = new Dictionary<(string, string), XmpProperty>(properties.Count); + foreach (XmpProperty property in properties) + { + _ = _byName.TryAdd((property.NamespaceName, property.Name), property); + } + } + + /// Gets the top-level properties, in the order written. + public IReadOnlyList Properties { get; } + + /// Gets the rdf:about attribute of the descriptions (the empty string for a PDF document's own metadata), or when none has one. + /// ISO 16684-1 §7.4. + public string? About { get; } + + /// Gets the title: the default alternative of dc:title. + /// ISO 16684-1 §8.3; ISO 32000-2 §14.3.3 Table 349 maps the Info dictionary's Title to it. + public string? Title => GetLanguageAlternative(XmpNamespaces.DublinCore, "title"); + + /// Gets the description: the default alternative of dc:description (the Info dictionary's Subject). + /// ISO 16684-1 §8.3; ISO 32000-2 §14.3.3 Table 349. + public string? Description => GetLanguageAlternative(XmpNamespaces.DublinCore, "description"); + + /// Gets the creators, dc:creator, in order (the Info dictionary's Author); empty when absent. + /// ISO 16684-1 §8.3; ISO 32000-2 §14.3.3 Table 349. + public IReadOnlyList Creators => GetArrayValues(XmpNamespaces.DublinCore, "creator"); + + /// Gets the subjects, dc:subject; empty when absent. + /// ISO 16684-1 §8.3. + public IReadOnlyList Subjects => GetArrayValues(XmpNamespaces.DublinCore, "subject"); + + /// Gets the media type, dc:format, such as application/pdf. + /// ISO 16684-1 §8.3. + public string? Format => GetText(XmpNamespaces.DublinCore, "format"); + + /// Gets xmp:CreateDate (the Info dictionary's CreationDate), or when absent or not a date. + /// ISO 16684-1 §8.4 and §8.2.1.2. + public XmpDate? CreateDate => GetDate(XmpNamespaces.Xmp, "CreateDate"); + + /// Gets xmp:ModifyDate (the Info dictionary's ModDate), or when absent or not a date. + /// ISO 16684-1 §8.4 and §8.2.1.2. + public XmpDate? ModifyDate => GetDate(XmpNamespaces.Xmp, "ModifyDate"); + + /// Gets xmp:MetadataDate, or when absent or not a date. + /// ISO 16684-1 §8.4 and §8.2.1.2. + public XmpDate? MetadataDate => GetDate(XmpNamespaces.Xmp, "MetadataDate"); + + /// Gets xmp:CreatorTool, the tool that created the document (the Info dictionary's Creator). + /// ISO 16684-1 §8.4; ISO 32000-2 §14.3.3 Table 349. + public string? CreatorTool => GetText(XmpNamespaces.Xmp, "CreatorTool"); + + /// Gets pdf:Producer (the Info dictionary's Producer). + /// ISO 32000-2 §14.3.3 Table 349. + public string? Producer => GetText(XmpNamespaces.Pdf, "Producer"); + + /// Gets pdf:Keywords (the Info dictionary's Keywords). + /// ISO 32000-2 §14.3.3 Table 349. + public string? Keywords => GetText(XmpNamespaces.Pdf, "Keywords"); + + /// Gets pdf:PDFVersion. + /// ISO 32000-2 §14.3.2. + public string? PdfVersion => GetText(XmpNamespaces.Pdf, "PDFVersion"); + + /// Gets pdf:Trapped (the Info dictionary's Trapped): True, False or Unknown. + /// ISO 32000-2 §14.3.3 Table 349. + public string? Trapped => GetText(XmpNamespaces.Pdf, "Trapped"); + + /// Gets the PDF/A part the document claims, pdfaid:part, or . + /// ISO 19005. + public int? PdfAPart => GetInteger(XmpNamespaces.PdfAIdentification, "part"); + + /// Gets the PDF/A conformance level the document claims, pdfaid:conformance, such as B. + /// ISO 19005. + public string? PdfAConformance => GetText(XmpNamespaces.PdfAIdentification, "conformance"); + + /// Gets the PDF/UA part the document claims, pdfuaid:part, or . + /// ISO 14289-1 §5; ISO 14289-2 §6. + public int? PdfUAPart => GetInteger(XmpNamespaces.PdfUAIdentification, "part"); + + /// Gets xmpMM:DocumentID, the identifier of the document across its versions. + /// ISO 16684-1 §8.6. + public string? DocumentId => GetText(XmpNamespaces.XmpMediaManagement, "DocumentID"); + + /// Gets xmpMM:InstanceID, the identifier of this version of the document. + /// ISO 16684-1 §8.6. + public string? InstanceId => GetText(XmpNamespaces.XmpMediaManagement, "InstanceID"); + + /// Reads an XMP packet; never throws. + /// The packet's bytes, such as the decoded data of a metadata stream. + /// The packet, or when the bytes are not one. + /// when the bytes hold a readable rdf:RDF element. + /// ISO 16684-1 §7. See the type's remarks for what is accepted. + public static bool TryParse(ReadOnlySpan data, [NotNullWhen(true)] out XmpPacket? packet) + { + packet = XmpPacketReader.Read(data, report: null); + return packet is not null; + } + + /// Returns the top-level property with the given name. + /// The namespace name, such as . + /// The local name, such as title. + /// The property, or when the packet does not have it. + public XmpProperty? GetProperty(string namespaceName, string name) + { + ArgumentNullException.ThrowIfNull(namespaceName); + ArgumentNullException.ThrowIfNull(name); + return _byName.GetValueOrDefault((namespaceName, name)); + } + + /// Returns the text of a simple property, exactly as written. + /// The namespace name. + /// The local name. + /// The text, or when the property is absent or not simple. + public string? GetText(string namespaceName, string name) => GetProperty(namespaceName, name) is { Kind: XmpPropertyKind.Simple } property ? property.Value : null; + + /// Returns one alternative of a language alternative such as dc:title. + /// The namespace name. + /// The local name. + /// The language wanted, such as de; for the default. + /// + /// The item whose xml:lang is (compared without case), else the x-default item, else the + /// first item; the value itself when the property is simple; when absent. + /// + /// ISO 16684-1 §8.2.2.4. + public string? GetLanguageAlternative(string namespaceName, string name, string? language = null) + { + XmpProperty? property = GetProperty(namespaceName, name); + if (property is null || property.Kind == XmpPropertyKind.Structure) + { + return null; + } + + if (property.Kind == XmpPropertyKind.Simple) + { + return property.Value; + } + + XmpProperty? match = (language is null ? null : FindLanguage(property.Items, language)) ?? FindLanguage(property.Items, "x-default"); + return (match ?? (property.Items.Count > 0 ? property.Items[0] : null))?.Value; + } + + private static XmpProperty? FindLanguage(IReadOnlyList items, string language) + { + foreach (XmpProperty item in items) + { + if (string.Equals(item.Language, language, StringComparison.OrdinalIgnoreCase)) + { + return item; + } + } + + return null; + } + + private string[] GetArrayValues(string namespaceName, string name) => GetProperty(namespaceName, name) switch + { + null => [], + { Kind: XmpPropertyKind.Simple, Value: { } value } => [value], + { } array => [.. array.Items.Where(item => item.Value is not null).Select(item => item.Value!)], + }; + + private XmpDate? GetDate(string namespaceName, string name) => XmpDate.TryParse(GetText(namespaceName, name), out XmpDate date) ? date : null; + + private int? GetInteger(string namespaceName, string name) => + int.TryParse(GetText(namespaceName, name)?.Trim(), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out int value) ? value : null; +} diff --git a/src/Broadside/XmpPacketReader.cs b/src/Broadside/XmpPacketReader.cs new file mode 100644 index 00000000..2ac2a53e --- /dev/null +++ b/src/Broadside/XmpPacketReader.cs @@ -0,0 +1,298 @@ +using System.Text; +using System.Xml; +using System.Xml.Linq; +using Broadside.Diagnostics; +using Broadside.Parsing; + +namespace Broadside; + +/// Reads the bytes of an XMP packet into an (ISO 16684-1 §7); never throws. +/// +/// The XML is read by the BCL's with explicit settings: document type declarations prohibited, no resolver, +/// no entity expansion, a character limit, fragment conformance (the packet wrapper's processing instructions surround the +/// elements). Only the first rdf:RDF element is loaded; reading stops at its end tag. +/// +internal static class XmpPacketReader +{ + /// The most characters a packet may have; a larger one is not read. + internal const int MaxCharacters = 16 * 1024 * 1024; + + /// How deeply property values may nest (structures in arrays in structures ...); deeper values read as empty. + private const int MaxDepth = 64; + + private static readonly XNamespace RdfNamespace = XmpNamespaces.Rdf; + private static readonly XName About = RdfNamespace + "about"; + private static readonly XName ParseType = RdfNamespace + "parseType"; + private static readonly XName Resource = RdfNamespace + "resource"; + private static readonly XName Value = RdfNamespace + "value"; + private static readonly XName Lang = XNamespace.Xml + "lang"; + + /// Reads a packet. + /// The bytes. + /// Receives the deviations (code, severity, message); to ignore them. + /// The packet, or when the bytes hold no readable rdf:RDF element. + public static XmpPacket? Read(ReadOnlySpan data, Action? report) + { + string text = Decode(data); + int start = text.IndexOf('<', StringComparison.Ordinal); + if (start < 0) + { + report?.Invoke(DiagnosticCodes.XmpMalformed, DiagnosticSeverity.Error, "The metadata stream holds no XML markup; it is not an XMP packet."); + return null; + } + + if (text.AsSpan(0, start).ContainsAnyExcept(" \t\r\n")) + { + report?.Invoke( + DiagnosticCodes.XmpLeadingJunk, + DiagnosticSeverity.Warning, + "The XMP packet has bytes other than white-space before its first markup; they are skipped."); + } + + XElement? rdf; + try + { + rdf = LoadRdf(text, start); + } + catch (XmlException exception) + { + bool doctype = text.Contains("Decodes the bytes by their byte order mark (ISO 16684-1 §7.1), else by the first character, else as UTF-8. + private static string Decode(ReadOnlySpan data) + { + Encoding encoding; + int skip = 0; + if (data.StartsWith((ReadOnlySpan)[0xEF, 0xBB, 0xBF])) + { + (encoding, skip) = (Encoding.UTF8, 3); + } + else if (data.StartsWith((ReadOnlySpan)[0x00, 0x00, 0xFE, 0xFF])) + { + (encoding, skip) = (new UTF32Encoding(bigEndian: true, byteOrderMark: false), 4); + } + else if (data.StartsWith((ReadOnlySpan)[0xFF, 0xFE, 0x00, 0x00])) + { + (encoding, skip) = (new UTF32Encoding(bigEndian: false, byteOrderMark: false), 4); + } + else if (data.StartsWith((ReadOnlySpan)[0xFE, 0xFF])) + { + (encoding, skip) = (Encoding.BigEndianUnicode, 2); + } + else if (data.StartsWith((ReadOnlySpan)[0xFF, 0xFE])) + { + (encoding, skip) = (Encoding.Unicode, 2); + } + else if (data.StartsWith((ReadOnlySpan)[0x00, 0x00, 0x00, (byte)'<'])) + { + encoding = new UTF32Encoding(bigEndian: true, byteOrderMark: false); + } + else if (data.StartsWith((ReadOnlySpan)[(byte)'<', 0x00, 0x00, 0x00])) + { + encoding = new UTF32Encoding(bigEndian: false, byteOrderMark: false); + } + else if (data.StartsWith((ReadOnlySpan)[0x00, (byte)'<'])) + { + encoding = Encoding.BigEndianUnicode; + } + else if (data.StartsWith((ReadOnlySpan)[(byte)'<', 0x00])) + { + encoding = Encoding.Unicode; + } + else + { + encoding = Encoding.UTF8; + } + + data = data[skip..]; + + // A packet beyond the limit is not decoded whole: the XML reader stops at the limit anyway. + int maxBytes = encoding.GetMaxByteCount(MaxCharacters + 1); + return encoding.GetString(data.Length > maxBytes ? data[..maxBytes] : data); + } + + /// Loads the first rdf:RDF element, or returns when there is none. + private static XElement? LoadRdf(string text, int start) + { + var settings = new XmlReaderSettings + { + DtdProcessing = DtdProcessing.Prohibit, + XmlResolver = null, + MaxCharactersFromEntities = 1024, + MaxCharactersInDocument = MaxCharacters, + ConformanceLevel = ConformanceLevel.Fragment, + IgnoreComments = true, + IgnoreProcessingInstructions = true, + IgnoreWhitespace = false, + CheckCharacters = true, + CloseInput = true, + }; + using var input = new StringReader(start == 0 ? text : text[start..]); + using var reader = XmlReader.Create(input, settings); + while (reader.Read()) + { + if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "RDF" && reader.NamespaceURI == XmpNamespaces.Rdf) + { + using XmlReader subtree = reader.ReadSubtree(); + return XElement.Load(subtree, LoadOptions.PreserveWhitespace); + } + } + + return null; + } + + /// Merges the properties of every description in rdf:RDF (ISO 16684-1 §7.4); the first of two equal names wins. + private static XmpPacket Build(XElement rdf, Action? report) + { + var properties = new List(); + var names = new HashSet<(string, string)>(); + string? about = null; + foreach (XElement description in rdf.Elements()) + { + about ??= description.Attribute(About)?.Value; + foreach (XmpProperty property in ReadNode(description, depth: 0)) + { + if (names.Add((property.NamespaceName, property.Name))) + { + properties.Add(property); + } + else + { + report?.Invoke( + DiagnosticCodes.XmpPropertyDuplicate, + DiagnosticSeverity.Warning, + $"The XMP property {property.Name} ({property.NamespaceName}) is given more than once; the first value is used."); + } + } + } + + return new XmpPacket(properties, about); + } + + /// Reads the properties of a node element: its property attributes, then its property elements (§7.4, §7.9.2.2). + private static List ReadNode(XElement node, int depth) + { + var properties = new List(); + foreach (XAttribute attribute in PropertyAttributes(node)) + { + properties.Add(Simple(attribute.Name, attribute.Value, language: null)); + } + + foreach (XElement element in node.Elements()) + { + properties.Add(ReadProperty(element, depth + 1)); + } + + return properties; + } + + /// Reads one property element in any of the forms of ISO 16684-1 §7.5-7.9. + private static XmpProperty ReadProperty(XElement element, int depth) + { + XName name = element.Name; + string? language = element.Attribute(Lang)?.Value; + if (depth > MaxDepth) + { + return Simple(name, string.Empty, language); + } + + if (element.Attribute(Resource) is { } resource) + { + return Simple(name, resource.Value, language); + } + + string? parseType = element.Attribute(ParseType)?.Value; + if (parseType == "Resource") + { + // §7.9.2.4: the element is itself the structure's (or the qualified value's) description. + return FromNode(name, element, language, depth); + } + + XElement? child = element.Elements().FirstOrDefault(); + if (child is null) + { + List fields = [.. PropertyAttributes(element)]; + if (fields.Count > 0 && string.IsNullOrWhiteSpace(element.Value)) + { + // §7.9.2.5: a structure whose fields are all attributes of the property element. + return new XmpProperty(Uri(name), name.LocalName, XmpPropertyKind.Structure, null, language, [], [.. fields.Select(field => Simple(field.Name, field.Value, null))], []); + } + + return Simple(name, element.Value, language); + } + + if (child.Name.Namespace == RdfNamespace) + { + XmpPropertyKind? kind = child.Name.LocalName switch + { + "Bag" => XmpPropertyKind.UnorderedArray, + "Seq" => XmpPropertyKind.OrderedArray, + "Alt" => XmpPropertyKind.Alternative, + _ => null, + }; + if (kind is { } arrayKind) + { + XmpProperty[] items = [.. child.Elements(RdfNamespace + "li").Select(item => ReadProperty(item, depth + 1))]; + return new XmpProperty(Uri(name), name.LocalName, arrayKind, null, language, items, [], []); + } + } + + // A nested node element: a structure, or a qualified value when it has rdf:value (§7.6, §7.8). + return FromNode(name, child, language, depth); + } + + /// Reads a node element as a structure, or as a qualified value when it has rdf:value. + private static XmpProperty FromNode(XName name, XElement node, string? language, int depth) + { + if (node.Element(Value) is { } valueElement) + { + XmpProperty value = ReadProperty(valueElement, depth + 1); + List qualifiers = []; + foreach (XAttribute attribute in PropertyAttributes(node)) + { + qualifiers.Add(Simple(attribute.Name, attribute.Value, null)); + } + + foreach (XElement qualifier in node.Elements()) + { + if (qualifier != valueElement) + { + qualifiers.Add(ReadProperty(qualifier, depth + 1)); + } + } + + return new XmpProperty(Uri(name), name.LocalName, value.Kind, value.Value, value.Language ?? language, value.Items, value.Fields, qualifiers); + } + + return new XmpProperty(Uri(name), name.LocalName, XmpPropertyKind.Structure, null, language, [], ReadNode(node, depth), []); + } + + /// The attributes of an element that are properties: not namespace declarations, not RDF or XML syntax. + private static IEnumerable PropertyAttributes(XElement element) => + element.Attributes().Where(attribute => !attribute.IsNamespaceDeclaration + && attribute.Name.Namespace != RdfNamespace + && attribute.Name.Namespace != XNamespace.Xml + && attribute.Name.Namespace != XNamespace.None); + + private static XmpProperty Simple(XName name, string value, string? language) => + new(Uri(name), name.LocalName, XmpPropertyKind.Simple, value, language, [], [], []); + + private static string Uri(XName name) => name.NamespaceName; +} diff --git a/src/Broadside/XmpProperty.cs b/src/Broadside/XmpProperty.cs new file mode 100644 index 00000000..62f53b6d --- /dev/null +++ b/src/Broadside/XmpProperty.cs @@ -0,0 +1,78 @@ +namespace Broadside; + +/// One XMP property, structure field, array item or qualifier: a name and a value of one of the forms XMP allows. +/// +/// +/// ISO 16684-1 §6.3 and §7.5-7.8. A simple value's text is kept exactly, white-space included (§7.2); only the convenience getters of +/// interpret it. Array items are named rdf:li. The xml:lang qualifier is ; +/// the other qualifiers (written with rdf:value, §7.8) are . +/// +/// Immutable: a snapshot of the packet it was read from. +/// +public sealed class XmpProperty +{ + internal XmpProperty( + string namespaceName, + string name, + XmpPropertyKind kind, + string? value, + string? language, + IReadOnlyList items, + IReadOnlyList fields, + IReadOnlyList qualifiers) + { + NamespaceName = namespaceName; + Name = name; + Kind = kind; + Value = value; + Language = language; + Items = items; + Fields = fields; + Qualifiers = qualifiers; + } + + /// Gets the namespace name of the property's name, such as . + public string NamespaceName { get; } + + /// Gets the local name of the property, such as title; li for an array item. + public string Name { get; } + + /// Gets the form of the value. + public XmpPropertyKind Kind { get; } + + /// Gets the text of a simple value exactly as written; for a structure or an array. + public string? Value { get; } + + /// Gets the xml:lang qualifier, such as x-default or de, or . + /// ISO 16684-1 §7.8 and §8.2.2.4 (language alternatives). + public string? Language { get; } + + /// Gets the items of an array, in order; empty for any other form. + public IReadOnlyList Items { get; } + + /// Gets the fields of a structure, in the order written; empty for any other form. + public IReadOnlyList Fields { get; } + + /// Gets the qualifiers other than xml:lang. + public IReadOnlyList Qualifiers { get; } + + /// Returns the structure field with the given name. + /// The field's namespace name. + /// The field's local name. + /// The first field with that name, or . + public XmpProperty? GetField(string namespaceName, string name) => Find(Fields, namespaceName, name); + + /// Returns the first property of with the given name. + internal static XmpProperty? Find(IReadOnlyList properties, string namespaceName, string name) + { + foreach (XmpProperty property in properties) + { + if (string.Equals(property.Name, name, StringComparison.Ordinal) && string.Equals(property.NamespaceName, namespaceName, StringComparison.Ordinal)) + { + return property; + } + } + + return null; + } +} diff --git a/src/Broadside/XmpPropertyKind.cs b/src/Broadside/XmpPropertyKind.cs new file mode 100644 index 00000000..4b45f2ab --- /dev/null +++ b/src/Broadside/XmpPropertyKind.cs @@ -0,0 +1,21 @@ +namespace Broadside; + +/// The form of an XMP property value. +/// ISO 16684-1 §6.3 (data model) and §7.5-7.7 (serialization). +public enum XmpPropertyKind +{ + /// A simple value: text, or a URI written with rdf:resource. + Simple, + + /// A structure: named fields, each itself a property. + Structure, + + /// An unordered array, rdf:Bag. + UnorderedArray, + + /// An ordered array, rdf:Seq. + OrderedArray, + + /// An alternative array, rdf:Alt: alternatives of one value, such as one per language. + Alternative, +} diff --git a/tests/Broadside.Tests/Document/XmpPacketTests.cs b/tests/Broadside.Tests/Document/XmpPacketTests.cs new file mode 100644 index 00000000..eba1ce5b --- /dev/null +++ b/tests/Broadside.Tests/Document/XmpPacketTests.cs @@ -0,0 +1,206 @@ +using System.Text; + +namespace Broadside.Tests.Document; + +/// The XMP packet reader (ISO 16684-1 §7) over bytes, without a PDF: the seam #76 and the fuzz target use. +public class XmpPacketTests +{ + private const string Rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + + private static readonly string Forms = + "\n" + + "\n" + + " \n" + + " \n" + + " one, two\n" + + " spaced \n" + + " \n" + + " \n" + + " FormsFormen\n" + + " AdaGrace\n" + + " pdfxmp\n" + + " Resource form2\n" + + " 3\n" + + " \n" + + " \n" + + " 42mm\n" + + " \n" + + " \n" + + " uuid:0b2c7c5e-0000-4000-8000-000000000001\n" + + " uuid:0b2c7c5e-0000-4000-8000-000000000002\n" + + " \n" + + " \n" + + "\n" + + new string(' ', 2048) + + ""; + + [Fact] + public void A_packet_reads_every_property_form_into_one_model() + { + Assert.True(XmpPacket.TryParse(Encoding.UTF8.GetBytes(Forms), out XmpPacket? packet)); + + Assert.Equal(string.Empty, packet.About); + XmpProperty producer = packet.GetProperty(XmpNamespaces.Pdf, "Producer")!; + Assert.Equal(XmpPropertyKind.Simple, producer.Kind); + Assert.Equal("Broadside generate.py", producer.Value); + Assert.Equal(XmpNamespaces.Pdf, producer.NamespaceName); + Assert.Equal("Producer", producer.Name); + Assert.Equal(" spaced ", packet.GetProperty(XmpNamespaces.Xmp, "CreatorTool")!.Value); + + XmpProperty title = packet.GetProperty(XmpNamespaces.DublinCore, "title")!; + Assert.Equal(XmpPropertyKind.Alternative, title.Kind); + Assert.Equal(["x-default", "de"], title.Items.Select(item => item.Language)); + Assert.Equal(["Forms", "Formen"], title.Items.Select(item => item.Value)); + Assert.Equal(XmpPropertyKind.OrderedArray, packet.GetProperty(XmpNamespaces.DublinCore, "creator")!.Kind); + Assert.Equal(XmpPropertyKind.UnorderedArray, packet.GetProperty(XmpNamespaces.DublinCore, "subject")!.Kind); + + const string Ex = "http://example.com/ns/"; + XmpProperty resource = packet.GetProperty(Ex, "Resource")!; + Assert.Equal(XmpPropertyKind.Structure, resource.Kind); + Assert.Equal("Resource form", resource.GetField(Ex, "Name")!.Value); + Assert.Equal("2", resource.GetField(Ex, "Count")!.Value); + XmpProperty nested = packet.GetProperty(Ex, "Nested")!; + Assert.Equal(XmpPropertyKind.Structure, nested.Kind); + Assert.Equal(["Attribute field", "3"], nested.Fields.Select(field => field.Value)); + Assert.Equal("Shorthand", packet.GetProperty(Ex, "Short")!.GetField(Ex, "Name")!.Value); + Assert.Equal("http://example.com/", packet.GetProperty(Ex, "Link")!.Value); + + XmpProperty qualified = packet.GetProperty(Ex, "WithQualifier")!; + Assert.Equal(XmpPropertyKind.Simple, qualified.Kind); + Assert.Equal("42", qualified.Value); + Assert.Equal("mm", Assert.Single(qualified.Qualifiers).Value); + Assert.Null(packet.GetProperty(Ex, "Missing")); + Assert.Equal(17, packet.Properties.Count); + } + + [Fact] + public void The_common_properties_are_typed() + { + Assert.True(XmpPacket.TryParse(Encoding.UTF8.GetBytes(Forms), out XmpPacket? packet)); + + Assert.Equal("Forms", packet.Title); + Assert.Equal("Formen", packet.GetLanguageAlternative(XmpNamespaces.DublinCore, "title", "de")); + Assert.Equal("Forms", packet.GetLanguageAlternative(XmpNamespaces.DublinCore, "title", "fr")); + Assert.Equal(["Ada", "Grace"], packet.Creators); + Assert.Equal(["pdf", "xmp"], packet.Subjects); + Assert.Null(packet.Description); + Assert.Equal("Broadside generate.py", packet.Producer); + Assert.Equal("one, two", packet.Keywords); + Assert.Equal(" spaced ", packet.CreatorTool); + Assert.Equal(new DateTimeOffset(2014, 9, 24, 21, 23, 3, TimeSpan.FromHours(2)), packet.CreateDate!.Value.Value); + Assert.Null(packet.ModifyDate); + Assert.Equal(2, packet.PdfAPart); + Assert.Equal("B", packet.PdfAConformance); + Assert.Equal(1, packet.PdfUAPart); + Assert.Equal("uuid:0b2c7c5e-0000-4000-8000-000000000001", packet.DocumentId); + Assert.Equal("uuid:0b2c7c5e-0000-4000-8000-000000000002", packet.InstanceId); + } + + [Theory] + [InlineData("utf-16BE")] + [InlineData("utf-16LE")] + [InlineData("utf-32BE")] + [InlineData("utf-32LE")] + [InlineData("utf-8")] + public void A_packet_in_any_unicode_encoding_with_its_byte_order_mark_is_read(string encodingName) + { + Encoding encoding = encodingName switch + { + "utf-16BE" => new UnicodeEncoding(bigEndian: true, byteOrderMark: true), + "utf-16LE" => new UnicodeEncoding(bigEndian: false, byteOrderMark: true), + "utf-32BE" => new UTF32Encoding(bigEndian: true, byteOrderMark: true), + "utf-32LE" => new UTF32Encoding(bigEndian: false, byteOrderMark: true), + _ => new UTF8Encoding(encoderShouldEmitUTF8Identifier: true), + }; + byte[] bytes = [.. encoding.GetPreamble(), .. encoding.GetBytes(Title("Ünïcödé"))]; + + Assert.True(XmpPacket.TryParse(bytes, out XmpPacket? packet)); + Assert.Equal("Ünïcödé", packet.Title); + } + + [Fact] + public void A_utf_16_packet_without_a_byte_order_mark_is_recognized_by_its_first_character() + { + Assert.True(XmpPacket.TryParse(Encoding.BigEndianUnicode.GetBytes(Title("big")), out XmpPacket? big)); + Assert.True(XmpPacket.TryParse(Encoding.Unicode.GetBytes(Title("little")), out XmpPacket? little)); + + Assert.Equal("big", big.Title); + Assert.Equal("little", little.Title); + } + + [Fact] + public void Padding_and_bytes_after_the_rdf_element_are_never_read() + { + byte[] bytes = [.. Encoding.UTF8.GetBytes(Title("padded")), .. new byte[64], .. "" + + "bare"; + + Assert.True(XmpPacket.TryParse(Encoding.UTF8.GetBytes(bare), out XmpPacket? packet)); + Assert.Equal("bare", packet.Title); + Assert.Null(packet.About); + } + + [Fact] + public void A_property_given_twice_keeps_its_first_value() + { + string twice = "" + + "second"; + + Assert.True(XmpPacket.TryParse(Encoding.UTF8.GetBytes(twice), out XmpPacket? packet)); + Assert.Equal("first", packet.Producer); + Assert.Single(packet.Properties); + } + + [Fact] + public void Predefined_and_character_references_are_text() + { + Assert.True(XmpPacket.TryParse(Encoding.UTF8.GetBytes(Title("A & B ☺ <")), out XmpPacket? packet)); + + Assert.Equal("A & B ☺ <", packet.Title); + } + + [Theory] + [InlineData("]>")] + [InlineData("")] + public void A_document_type_declaration_is_refused_so_entities_never_expand(string doctype) + { + byte[] bytes = Encoding.UTF8.GetBytes(doctype + Title("&lol2;")); + + Assert.False(XmpPacket.TryParse(bytes, out XmpPacket? packet)); + Assert.Null(packet); + } + + [Theory] + [InlineData("")] + [InlineData("")] + [InlineData("")] + [InlineData("not xml at all")] + [InlineData("")] + public void Malformed_xml_or_a_packet_without_an_rdf_element_does_not_parse(string text) + { + Assert.False(XmpPacket.TryParse(Encoding.UTF8.GetBytes(text), out _)); + } + + private static string Title(string title) => + "" + + title + ""; +} From d8351578728a3b07927b229c882ef285a798e698 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:06:18 -0500 Subject: [PATCH 020/152] feat(navigation): generic name and number tree walkers (#70) First half of #70, landed early so #69 (page labels), #75 (ParentTree, IDTree) and #76 (EmbeddedFiles) can build on the trees. - PdfNameTree / PdfNumberTree: read-only live views (TryGetValue by CosString, bytes or text; TryGetFloor for number trees; ordered enumeration). PdfDocument.Names (PdfNameDictionary with GetTree and Dests), PdfDocument.GetNameTree / GetNumberTree for any root. - Internal NameTreeReader / NumberTreeReader over one walker: lookups descend by Limits (binary search), keys compare byte by byte (Annex J.3.3); any damage (stale or missing Limits, unsorted or duplicate keys, cycles, depth over 64, odd arrays, bad keys) is reported once per node and lookups fall back to an index of the whole tree, rebuilt when a node changes. First occurrence wins everywhere. - Internal Version stamp on CosArray, CosDictionary and CosStream, bumped on every public mutation, never on read or load: the rule for every cache derived from COS. - Internal TextStringEncoder (PDFDocEncoding, else UTF-16BE). - DiagnosticCodes and KnownNames are now partial; this ticket's codes and names live in *.Navigation.cs files. - Corpus: name-tree-deep.pdf, number-tree-deep.pdf, name-tree-broken.pdf. qpdf compares name tree keys as decoded text and warns on name-tree-deep.pdf; SaveTests allow exactly that warning. - Conformance: 7.9.6 and 7.9.7 done, 7.7.4 partial. Co-Authored-By: Claude Opus 5.5 --- docs/conformance/iso-32000-2.md | 6 +- src/Broadside/NameTreeReader.cs | 84 +++ src/Broadside/NumberTreeReader.cs | 69 ++ src/Broadside/Objects/CosArray.cs | 12 + src/Broadside/Objects/CosDictionary.cs | 12 + src/Broadside/Objects/CosStream.cs | 7 + .../Objects/KnownNames.Navigation.cs | 26 + src/Broadside/Objects/KnownNames.cs | 2 +- src/Broadside/Objects/TextStringEncoder.cs | 56 ++ .../Parsing/DiagnosticCodes.Navigation.cs | 29 + src/Broadside/Parsing/DiagnosticCodes.cs | 2 +- src/Broadside/PdfDocument.cs | 94 +++ src/Broadside/PdfNameDictionary.cs | 42 ++ src/Broadside/PdfNameTree.cs | 113 ++++ src/Broadside/PdfNumberTree.cs | 73 +++ src/Broadside/PublicAPI.Unshipped.txt | 22 + src/Broadside/TreeReader.cs | 610 ++++++++++++++++++ tests/Broadside.TestSupport/Corpus.cs | 3 + .../Document/WellFormedCorpusTests.cs | 7 +- .../Navigation/NameTreeTests.cs | 251 +++++++ .../Navigation/NumberTreeTests.cs | 130 ++++ ...pus_file_names_match_snapshot.verified.txt | 3 + tests/Broadside.Tests/Writing/SaveTests.cs | 24 +- tests/Corpus/README.md | 3 + tests/Corpus/generate.py | 88 +++ tests/Corpus/name-tree-broken.pdf | Bin 0 -> 992 bytes tests/Corpus/name-tree-deep.pdf | Bin 0 -> 8714 bytes tests/Corpus/number-tree-deep.pdf | Bin 0 -> 2204 bytes 28 files changed, 1761 insertions(+), 7 deletions(-) create mode 100644 src/Broadside/NameTreeReader.cs create mode 100644 src/Broadside/NumberTreeReader.cs create mode 100644 src/Broadside/Objects/KnownNames.Navigation.cs create mode 100644 src/Broadside/Objects/TextStringEncoder.cs create mode 100644 src/Broadside/Parsing/DiagnosticCodes.Navigation.cs create mode 100644 src/Broadside/PdfNameDictionary.cs create mode 100644 src/Broadside/PdfNameTree.cs create mode 100644 src/Broadside/PdfNumberTree.cs create mode 100644 src/Broadside/TreeReader.cs create mode 100644 tests/Broadside.Tests/Navigation/NameTreeTests.cs create mode 100644 tests/Broadside.Tests/Navigation/NumberTreeTests.cs create mode 100644 tests/Corpus/name-tree-broken.pdf create mode 100644 tests/Corpus/name-tree-deep.pdf create mode 100644 tests/Corpus/number-tree-deep.pdf diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index 22181c28..f18429c5 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -49,15 +49,15 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.7.1 | General | n/a | | | Introductory text | | 7.7.2 | Document catalog dictionary | partial | `PdfDocument`, `PdfVersion` | `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_catalog_version_written_as_a_number_is_read_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.A_malformed_catalog_version_is_ignored_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_catalog_without_its_type_is_read_with_a_diagnostic` | Type, Version (effective version = later of header and catalog) and Pages; the other Table 29 entries arrive with their features (outlines, names, AcroForm, ...) | | 7.7.3 | Page tree | done | `PdfPage`, `PdfPageCollection`, `PageTreeReader` | `Broadside.Tests.Document.OpenDocumentTests.Page_tree_inherited_pdf_pages_inherit_media_box_and_resources_from_the_intermediate_node`, `Broadside.Tests.Document.PageTreeTests.Pages_come_in_kids_order_depth_first_across_intermediate_nodes`, `Broadside.Tests.Document.PageTreeTests.The_nearest_ancestor_wins_and_values_are_inherited_as_is_without_merging`, `Broadside.Tests.Document.PageTreeTests.A_change_to_an_ancestor_node_shows_through_the_pages_that_inherit_from_it`, `Broadside.Tests.Document.PageTreeTests.Page_count_comes_from_the_kids_not_the_count_entry_which_is_checked`, `Broadside.Tests.Document.PageTreeTests.A_node_referenced_twice_is_read_once_with_a_diagnostic`, `Broadside.Tests.Document.PageAttributeTests.Crop_bleed_trim_and_art_boxes_default_to_the_media_box_through_the_crop_box`, `Broadside.Tests.Document.PageAttributeTests.Rotation_is_a_multiple_of_90_normalized_into_0_to_270` | 7.7.3.1 to 7.7.3.4: Kids walk with cycle guard, Count checked not trusted, Resources/MediaBox/CropBox/Rotate inherited as-is from the nearest node; page boxes, Rotate and UserUnit from Table 31; other Table 31 entries arrive with their features | -| 7.7.4 | Name dictionary | not started | | | | +| 7.7.4 | Name dictionary | partial | `PdfNameDictionary`, `PdfDocument` | `Broadside.Tests.Navigation.NameTreeTests.Name_tree_dests_pdf_maps_its_three_keys_to_their_destination_arrays_with_no_diagnostics`, `Broadside.Tests.Navigation.NameTreeTests.A_tree_root_that_is_not_a_dictionary_reads_as_absent_with_a_diagnostic` | `PdfDocument.Names`; every Table 32 entry is reachable as a name tree through `PdfNameDictionary.GetTree`, `Dests` by name; typed values arrive with their features (Dests destinations #70, EmbeddedFiles #76, JavaScript #73) | | 7.8 | Content streams and resources | not started | | | | | 7.9.1 | General | not started | | | | | 7.9.2 | String object types | partial | `CosString` | `Broadside.Tests.Objects.TextStringTests` | Text strings decode (PDFDocEncoding, UTF-16BE, UTF-8, language escapes removed); encoding text into a string pending | | 7.9.3 | Text streams | not started | | | | | 7.9.4 | Dates | not started | | | | | 7.9.5 | Rectangles | done | `PdfRectangle` | `Broadside.Tests.Document.PageAttributeTests.Rectangles_given_by_any_two_opposite_corners_are_normalized`, `Broadside.Tests.Document.PageAttributeTests.A_box_and_its_numbers_may_be_indirect_objects`, `Broadside.Tests.Document.PageAttributeTests.A_malformed_box_reads_as_its_default_with_a_diagnostic` | Any two opposite corners, normalized | -| 7.9.6 | Name trees | not started | | | | -| 7.9.7 | Number trees | not started | | | | +| 7.9.6 | Name trees | done | `PdfNameTree`, `NameTreeReader`, `TreeReader`, `PdfDocument` | `Broadside.Tests.Navigation.NameTreeTests.Name_tree_dests_pdf_maps_its_three_keys_to_their_destination_arrays_with_no_diagnostics`, `Broadside.Tests.Navigation.NameTreeTests.Every_key_of_a_four_level_tree_resolves_and_enumeration_returns_them_once_in_byte_order`, `Broadside.Tests.Navigation.NameTreeTests.Keys_are_compared_byte_by_byte_and_a_text_lookup_tries_pdf_doc_encoding_first`, `Broadside.Tests.Navigation.NameTreeTests.A_text_lookup_falls_back_to_utf_16_and_then_to_every_key_decoded`, `Broadside.Tests.Navigation.NameTreeTests.A_lookup_reads_one_path_from_the_root_and_not_the_whole_tree`, `Broadside.Tests.Navigation.NameTreeTests.A_damaged_tree_reports_each_defect_once_per_node_and_every_key_still_resolves`, `Broadside.Tests.Navigation.NameTreeTests.Lookups_of_a_damaged_tree_fall_back_to_the_whole_tree_and_agree_with_enumeration_on_duplicates`, `Broadside.Tests.Navigation.NameTreeTests.Strict_mode_throws_from_the_lookup_that_meets_the_damage_not_from_open`, `Broadside.Tests.Navigation.NameTreeTests.Reading_a_tree_writes_nothing_and_a_change_to_a_node_shows_in_the_next_lookup`, `Broadside.Tests.Navigation.NameTreeTests.Malformed_nodes_and_keys_are_repaired_or_skipped_with_a_diagnostic` | Read only (writing trees is Phase 4). Lookups descend by Limits (binary search over kids and leaf), keys compared byte by byte (Annex J.3.3); text lookups try PDFDocEncoding, UTF-16BE, then every key decoded. Damage (stale or missing Limits, unsorted or duplicate keys, cycles, depth over 64, odd Names, non-string keys) is reported once per node (`NameTree*` codes) and lookups fall back to an index of the whole tree, rebuilt when a node changes (internal container `Version`); first occurrence in tree order wins. `name-tree-dests.pdf`, `name-tree-deep.pdf`, `name-tree-broken.pdf`. qpdf compares decoded text, not bytes, and reports `name-tree-deep.pdf` as unsorted. | +| 7.9.7 | Number trees | done | `PdfNumberTree`, `NumberTreeReader`, `TreeReader`, `PdfDocument` | `Broadside.Tests.Navigation.NumberTreeTests.A_three_level_page_labels_tree_enumerates_its_keys_in_order_with_no_diagnostics`, `Broadside.Tests.Navigation.NumberTreeTests.Exact_lookups_find_keys_through_the_limits_and_miss_keys_between_them`, `Broadside.Tests.Navigation.NumberTreeTests.A_floor_lookup_finds_the_greatest_key_not_greater_than_the_one_asked_for`, `Broadside.Tests.Navigation.NumberTreeTests.Keys_that_are_not_integers_are_repaired_or_skipped_with_a_diagnostic`, `Broadside.Tests.Navigation.NumberTreeTests.A_cycle_through_the_kids_ends_with_a_diagnostic`, `Broadside.Tests.Navigation.NumberTreeTests.A_chain_deeper_than_the_cap_ends_with_a_diagnostic` | Read only. Same walker as 7.9.6 with 32-bit integer keys; `TryGetFloor` for ranges keyed by their first number (page labels, 12.4.2); an integral real key is used with a diagnostic, other keys skipped (`NumberTree*` codes). `number-tree-deep.pdf`. | | 7.10 | Functions | not started | | | | | 7.11 | File specifications | not started | | | | | 7.12 | Extensions dictionary | not started | | | | diff --git a/src/Broadside/NameTreeReader.cs b/src/Broadside/NameTreeReader.cs new file mode 100644 index 00000000..61d94e20 --- /dev/null +++ b/src/Broadside/NameTreeReader.cs @@ -0,0 +1,84 @@ +using System.Diagnostics.CodeAnalysis; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// Reads one name tree: keys are strings compared byte by byte. +/// +/// ISO 32000-2 §7.9.6, Table 36, and Annex J.3.3 (string comparison is a binary comparison of the bytes). Shorter keys sort before +/// longer keys with the same leading bytes, which is what +/// gives. A key written as a name is used by its bytes, with a diagnostic; any other key is skipped. One reader per tree root: +/// keeps them, so the flattened index of a damaged tree is built once. See . +/// +internal sealed class NameTreeReader : TreeReader +{ + private static readonly TreeCodes NameTreeCodes = new( + DiagnosticCodes.NameTreeNodeInvalid, + DiagnosticCodes.NameTreeLimitsInvalid, + DiagnosticCodes.NameTreeKeysUnsorted, + DiagnosticCodes.NameTreeDuplicateKey, + DiagnosticCodes.NameTreeKeyInvalid, + DiagnosticCodes.NameTreeCycle, + DiagnosticCodes.NameTreeTooDeep); + + /// Initializes a new instance of the class. + /// The root node dictionary. + /// The root's reference, for diagnostics; when the root is direct. + /// Resolves references through the document. + /// Where to report deviations. + /// The deepest level the walk descends to. + internal NameTreeReader(CosDictionary root, CosReference? rootReference, Func resolve, DiagnosticSink diagnostics, int maxDepth = DefaultMaxDepth) + : base(root, rootReference, resolve, diagnostics, maxDepth) + { + } + + /// + private protected override CosName EntriesKey => KnownNames.Names; + + /// + private protected override TreeCodes Codes => NameTreeCodes; + + /// + private protected override string Kind => "name tree"; + + /// + private protected override IComparer KeyComparer => ByteOrder.Instance; + + /// + private protected override IEqualityComparer KeyEquality => EqualityComparer.Default; + + /// Looks up the key with exactly these bytes. + /// The key's bytes. + /// The value, resolved one level, when found. + /// when the tree holds the key. + internal bool TryGetValue(ReadOnlySpan key, [MaybeNullWhen(false)] out CosObject value) => TryGetValue(new CosString(key), out value); + + /// + private protected override KeyState ReadKey(CosObject key, [MaybeNullWhen(false)] out CosString value, out string? message) + { + switch (key) + { + case CosString text: + value = text; + message = null; + return KeyState.Valid; + case CosName name: + value = new CosString(name.Bytes); + message = "A name tree key shall be a string; it is a name, whose bytes are used as the key."; + return KeyState.Repaired; + default: + value = null!; + message = "A name tree key is not a string; the pair is skipped."; + return KeyState.Invalid; + } + } + + /// Orders strings by their bytes (Annex J.3.3). + private sealed class ByteOrder : IComparer + { + public static readonly ByteOrder Instance = new(); + + public int Compare(CosString? x, CosString? y) => x!.Bytes.SequenceCompareTo(y!.Bytes); + } +} diff --git a/src/Broadside/NumberTreeReader.cs b/src/Broadside/NumberTreeReader.cs new file mode 100644 index 00000000..168fe217 --- /dev/null +++ b/src/Broadside/NumberTreeReader.cs @@ -0,0 +1,69 @@ +using System.Diagnostics.CodeAnalysis; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// Reads one number tree: keys are integers in ascending numerical order. +/// +/// ISO 32000-2 §7.9.7, Table 37. Keys are 32-bit: a key outside that range is skipped with a diagnostic, and a real holding an +/// integral value is used as that integer, with a diagnostic. One reader per tree root: keeps them. See +/// . +/// +internal sealed class NumberTreeReader : TreeReader +{ + private static readonly TreeCodes NumberTreeCodes = new( + DiagnosticCodes.NumberTreeNodeInvalid, + DiagnosticCodes.NumberTreeLimitsInvalid, + DiagnosticCodes.NumberTreeKeysUnsorted, + DiagnosticCodes.NumberTreeDuplicateKey, + DiagnosticCodes.NumberTreeKeyInvalid, + DiagnosticCodes.NumberTreeCycle, + DiagnosticCodes.NumberTreeTooDeep); + + /// Initializes a new instance of the class. + /// The root node dictionary. + /// The root's reference, for diagnostics; when the root is direct. + /// Resolves references through the document. + /// Where to report deviations. + /// The deepest level the walk descends to. + internal NumberTreeReader(CosDictionary root, CosReference? rootReference, Func resolve, DiagnosticSink diagnostics, int maxDepth = DefaultMaxDepth) + : base(root, rootReference, resolve, diagnostics, maxDepth) + { + } + + /// + private protected override CosName EntriesKey => KnownNames.Nums; + + /// + private protected override TreeCodes Codes => NumberTreeCodes; + + /// + private protected override string Kind => "number tree"; + + /// + private protected override IComparer KeyComparer => Comparer.Default; + + /// + private protected override IEqualityComparer KeyEquality => EqualityComparer.Default; + + /// + private protected override KeyState ReadKey(CosObject key, [MaybeNullWhen(false)] out int value, out string? message) + { + switch (key) + { + case CosInteger integer when integer.Value is >= int.MinValue and <= int.MaxValue: + value = (int)integer.Value; + message = null; + return KeyState.Valid; + case CosReal real when double.IsInteger(real.Value) && real.Value is >= int.MinValue and <= int.MaxValue: + value = (int)real.Value; + message = "A number tree key shall be an integer; it is a real holding an integral value, used as that integer."; + return KeyState.Repaired; + default: + value = 0; + message = "A number tree key is not an integer in the range a reader supports; the pair is skipped."; + return KeyState.Invalid; + } + } +} diff --git a/src/Broadside/Objects/CosArray.cs b/src/Broadside/Objects/CosArray.cs index 7a9e9367..26612c5d 100644 --- a/src/Broadside/Objects/CosArray.cs +++ b/src/Broadside/Objects/CosArray.cs @@ -54,6 +54,12 @@ public override bool IsDirty } } + /// + /// Gets a number that changes every time an element is added, replaced or removed through the public API, and never by reading + /// or loading: caches of state derived from the array record it and rebuild when it differs. + /// + internal int Version { get; private set; } + /// Gets the number of elements. public int Count => _items.Count; @@ -70,6 +76,7 @@ public CosObject this[int index] ArgumentNullException.ThrowIfNull(value); _items[index] = value; _changed = true; + Version++; } } @@ -80,6 +87,7 @@ public void Add(CosObject item) ArgumentNullException.ThrowIfNull(item); _items.Add(item); _changed = true; + Version++; } /// Inserts an element and marks the array dirty. @@ -90,6 +98,7 @@ public void Insert(int index, CosObject item) ArgumentNullException.ThrowIfNull(item); _items.Insert(index, item); _changed = true; + Version++; } /// Removes the element at and marks the array dirty. @@ -98,6 +107,7 @@ public void RemoveAt(int index) { _items.RemoveAt(index); _changed = true; + Version++; } /// Removes the first element equal to ; marks the array dirty when one was removed. @@ -107,6 +117,7 @@ public bool Remove(CosObject item) { bool removed = _items.Remove(item); _changed |= removed; + Version += removed ? 1 : 0; return removed; } @@ -114,6 +125,7 @@ public bool Remove(CosObject item) public void Clear() { _changed |= _items.Count > 0; + Version += _items.Count > 0 ? 1 : 0; _items.Clear(); } diff --git a/src/Broadside/Objects/CosDictionary.cs b/src/Broadside/Objects/CosDictionary.cs index b9157f57..d6d4e66f 100644 --- a/src/Broadside/Objects/CosDictionary.cs +++ b/src/Broadside/Objects/CosDictionary.cs @@ -45,6 +45,13 @@ public override bool IsDirty } } + /// + /// Gets a number that changes every time an entry is added, replaced or removed through the public API, and never by reading + /// or loading: caches of state derived from the dictionary record it and rebuild when it differs. Changes to the values + /// themselves are not counted; a cache records each container it depends on. + /// + internal int Version { get; private set; } + /// Gets the number of entries. public int Count => _entries.Count; @@ -85,6 +92,7 @@ public CosObject this[CosName key] _entries[key] = value; _changed = true; + Version++; } } @@ -108,6 +116,7 @@ public void Add(CosName key, CosObject value) _entries.Add(key, value); _changed = true; + Version++; } /// Removes the entry for ; marks the dictionary dirty when one was removed. @@ -117,6 +126,7 @@ public bool Remove(CosName key) { bool removed = _entries.Remove(key); _changed |= removed; + Version += removed ? 1 : 0; return removed; } @@ -124,6 +134,7 @@ public bool Remove(CosName key) public void Clear() { _changed |= _entries.Count > 0; + Version += _entries.Count > 0 ? 1 : 0; _entries.Clear(); } @@ -156,6 +167,7 @@ bool ICollection>.Remove(KeyValuePair>)_entries).Remove(item); _changed |= removed; + Version += removed ? 1 : 0; return removed; } diff --git a/src/Broadside/Objects/CosStream.cs b/src/Broadside/Objects/CosStream.cs index 25329f40..02d9b694 100644 --- a/src/Broadside/Objects/CosStream.cs +++ b/src/Broadside/Objects/CosStream.cs @@ -34,6 +34,12 @@ internal CosStream(CosDictionary dictionary, DeferredStreamData encodedData) _deferred = encodedData; } + /// + /// Gets a number that changes every time the data is replaced through the public API, and never by reading or loading. The + /// dictionary has its own . + /// + internal int Version { get; private set; } + /// Gets the stream dictionary. public CosDictionary Dictionary { get; } @@ -50,6 +56,7 @@ public ReadOnlyMemory EncodedData _encodedData = value; _deferred = null; _changed = true; + Version++; } } diff --git a/src/Broadside/Objects/KnownNames.Navigation.cs b/src/Broadside/Objects/KnownNames.Navigation.cs new file mode 100644 index 00000000..a478f83f --- /dev/null +++ b/src/Broadside/Objects/KnownNames.Navigation.cs @@ -0,0 +1,26 @@ +namespace Broadside.Objects; + +/// Names looked up by name trees, number trees, destinations, outlines and actions (issue #70). +internal static partial class KnownNames +{ + /// /Names, the catalog's name dictionary (§7.7.2, Table 29) and the pairs of a name tree node (§7.9.6, Table 36). + public static readonly CosName Names = new("Names"); + + /// /Nums, the pairs of a number tree node (§7.9.7, Table 37). + public static readonly CosName Nums = new("Nums"); + + /// /Limits, the least and greatest keys under a tree node (§7.9.6, Table 36; §7.9.7, Table 37). + public static readonly CosName Limits = new("Limits"); + + /// /Dests, the named destinations: a catalog dictionary (PDF 1.1) or a name dictionary tree (§7.7.4, §12.3.2.4). + public static readonly CosName Dests = new("Dests"); + + /// /S, the type of an action (§12.6.2, Table 196). + public static readonly CosName S = new("S"); + + /// /URI, the URI action type and its URI entry (§12.6.4.8, Table 210). + public static readonly CosName Uri = new("URI"); + + /// /IsMap, whether a URI action tracks the mouse position (§12.6.4.8, Table 210). + public static readonly CosName IsMap = new("IsMap"); +} diff --git a/src/Broadside/Objects/KnownNames.cs b/src/Broadside/Objects/KnownNames.cs index 9e835a0f..3de9ecd3 100644 --- a/src/Broadside/Objects/KnownNames.cs +++ b/src/Broadside/Objects/KnownNames.cs @@ -1,7 +1,7 @@ namespace Broadside.Objects; /// Names the library itself looks up, created once. Add a name here when code needs it, not before. -internal static class KnownNames +internal static partial class KnownNames { /// /Length, the stream dictionary entry that gives the extent of the data (ISO 32000-2 §7.3.8.2, Table 5). public static readonly CosName Length = new("Length"); diff --git a/src/Broadside/Objects/TextStringEncoder.cs b/src/Broadside/Objects/TextStringEncoder.cs new file mode 100644 index 00000000..a65a6611 --- /dev/null +++ b/src/Broadside/Objects/TextStringEncoder.cs @@ -0,0 +1,56 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text; + +namespace Broadside.Objects; + +/// Encodes text as the bytes of a text string: PDFDocEncoding when every character has a code, otherwise UTF-16BE with a byte order marker. +/// ISO 32000-2 §7.9.2.2 and Annex D, Table D.3. The inverse of for text it can decode. +internal static class TextStringEncoder +{ + private static readonly Dictionary PdfDocCodes = BuildPdfDocCodes(); + + /// Encodes in PDFDocEncoding. + /// The text. + /// The PDFDocEncoding bytes, when every character has a code. + /// when a character has no PDFDocEncoding code, or the bytes would start with a byte order marker. + public static bool TryEncodePdfDoc(string text, [NotNullWhen(true)] out byte[]? bytes) + { + var buffer = new byte[text.Length]; + for (int i = 0; i < text.Length; i++) + { + if (!PdfDocCodes.TryGetValue(text[i], out buffer[i])) + { + bytes = null; + return false; + } + } + + // A PDFDocEncoded string cannot start with a marker: it would decode as UTF-16BE or UTF-8. + if (buffer.AsSpan().StartsWith((ReadOnlySpan)[0xFE, 0xFF]) || buffer.AsSpan().StartsWith((ReadOnlySpan)[0xEF, 0xBB, 0xBF])) + { + bytes = null; + return false; + } + + bytes = buffer; + return true; + } + + /// Encodes as a text string: PDFDocEncoding when possible, otherwise UTF-16BE with the marker. + /// The text. + /// The bytes. + public static byte[] Encode(string text) => + TryEncodePdfDoc(text, out byte[]? bytes) ? bytes : [0xFE, 0xFF, .. Encoding.BigEndianUnicode.GetBytes(text)]; + + private static Dictionary BuildPdfDocCodes() + { + ReadOnlySpan table = TextStringDecoder.PdfDocEncodingTable; + var codes = new Dictionary(table.Length); + for (int code = 0; code < table.Length; code++) + { + codes.TryAdd(table[code], (byte)code); + } + + return codes; + } +} diff --git a/src/Broadside/Parsing/DiagnosticCodes.Navigation.cs b/src/Broadside/Parsing/DiagnosticCodes.Navigation.cs new file mode 100644 index 00000000..6a7ba175 --- /dev/null +++ b/src/Broadside/Parsing/DiagnosticCodes.Navigation.cs @@ -0,0 +1,29 @@ +namespace Broadside.Parsing; + +/// Diagnostic codes for name trees, number trees, destinations, outlines and actions (issue #70). +internal static partial class DiagnosticCodes +{ + // Name dictionary (§7.7.4). + public const string NameDictionaryInvalid = nameof(NameDictionaryInvalid); + + // Name trees (§7.9.6, Table 36). + public const string NameTreeNodeInvalid = nameof(NameTreeNodeInvalid); + public const string NameTreeLimitsInvalid = nameof(NameTreeLimitsInvalid); + public const string NameTreeKeysUnsorted = nameof(NameTreeKeysUnsorted); + public const string NameTreeDuplicateKey = nameof(NameTreeDuplicateKey); + public const string NameTreeKeyInvalid = nameof(NameTreeKeyInvalid); + public const string NameTreeCycle = nameof(NameTreeCycle); + public const string NameTreeTooDeep = nameof(NameTreeTooDeep); + + // Number trees (§7.9.7, Table 37). + public const string NumberTreeNodeInvalid = nameof(NumberTreeNodeInvalid); + public const string NumberTreeLimitsInvalid = nameof(NumberTreeLimitsInvalid); + public const string NumberTreeKeysUnsorted = nameof(NumberTreeKeysUnsorted); + public const string NumberTreeDuplicateKey = nameof(NumberTreeDuplicateKey); + public const string NumberTreeKeyInvalid = nameof(NumberTreeKeyInvalid); + public const string NumberTreeCycle = nameof(NumberTreeCycle); + public const string NumberTreeTooDeep = nameof(NumberTreeTooDeep); + + // Actions (§12.6.2, Table 196). + public const string ActionInvalid = nameof(ActionInvalid); +} diff --git a/src/Broadside/Parsing/DiagnosticCodes.cs b/src/Broadside/Parsing/DiagnosticCodes.cs index 38370fe5..c93ffb76 100644 --- a/src/Broadside/Parsing/DiagnosticCodes.cs +++ b/src/Broadside/Parsing/DiagnosticCodes.cs @@ -8,7 +8,7 @@ namespace Broadside.Parsing; /// Every ticket adds its own group here. The catalogue is internal while parallel tickets add codes; the codes reach users as /// strings. /// -internal static class DiagnosticCodes +internal static partial class DiagnosticCodes { // File header (ISO 32000-2 §7.5.2). public const string HeaderMissing = nameof(HeaderMissing); diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 5c0e9ec2..da14fec4 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -1,4 +1,5 @@ using System.Buffers; +using System.Runtime.CompilerServices; using Broadside.Diagnostics; using Broadside.Filters; using Broadside.IO; @@ -54,6 +55,8 @@ public sealed class PdfDocument : IDisposable private readonly DiagnosticSink _diagnostics; private readonly ObjectLoader _loader; private readonly StreamDecoder _streams; + private readonly ConditionalWeakTable _nameTrees = []; + private readonly ConditionalWeakTable _numberTrees = []; private PdfDocument( PdfSource source, @@ -111,6 +114,34 @@ public PdfVersion Version /// ISO 32000-2 §7.7.3. public PdfPageCollection Pages { get; } + /// Gets the document's name dictionary, or when the catalog has none. + /// + /// ISO 32000-2 §7.7.2, Table 29 (Names, PDF 1.2), and §7.7.4. Read from the catalog on every call. An entry that is not a + /// dictionary reads as none, with a diagnostic. + /// + public PdfNameDictionary? Names + { + get + { + if (!Catalog.TryGetValue(KnownNames.Names, out CosObject? entry)) + { + return null; + } + + if (Resolve(entry) is CosDictionary names) + { + return new PdfNameDictionary(this, names); + } + + _diagnostics.Report( + DiagnosticCodes.NameDictionaryInvalid, + DiagnosticSeverity.Warning, + "The catalog's Names entry is not a dictionary; the document is read as having no name dictionary.", + objectReference: entry as CosReference); + return null; + } + } + /// Gets the revisions of the file, oldest first: the original file, then one per incremental update. /// /// ISO 32000-2 §7.5.6. The document itself always shows the newest revision: for every object number the most recent @@ -344,6 +375,51 @@ public async Task SaveAsync(Stream stream, PdfSaveOptions? options = null, Cance /// ISO 32000-2 §7.3.10. public CosObject Resolve(CosObject? value) => _loader.Resolve(value); + /// Returns a view of the name tree whose root node is . + /// The root node dictionary, or a reference to it, from this document. + /// + /// The tree, read lazily; when is or resolves to null, or, + /// with a diagnostic, to something other than a dictionary. + /// + /// + /// ISO 32000-2 §7.9.6. For name trees the document model does not expose by name. Views of the same root share one reader, so + /// the index a damaged tree needs is built once per document. + /// + public PdfNameTree? GetNameTree(CosObject? root) => + GetNameTreeReader(root) is { } reader ? new PdfNameTree(reader) : null; + + /// Returns a view of the number tree whose root node is . + /// The root node dictionary, or a reference to it, from this document. + /// + /// The tree, read lazily; when is or resolves to null, or, + /// with a diagnostic, to something other than a dictionary. + /// + /// + /// ISO 32000-2 §7.9.7. For number trees such as the catalog's PageLabels or a structure tree's ParentTree. Views of + /// the same root share one reader. + /// + public PdfNumberTree? GetNumberTree(CosObject? root) => + GetNumberTreeReader(root) is { } reader ? new PdfNumberTree(reader) : null; + + /// Returns the document's reader for the name tree rooted at , creating it on first use. + /// The root node or a reference to it. + /// The reader; when the root does not resolve to a dictionary. + internal NameTreeReader? GetNameTreeReader(CosObject? root) => + ResolveTreeRoot(root, DiagnosticCodes.NameTreeNodeInvalid, "name tree") is { } node + ? _nameTrees.GetValue(node, dictionary => new NameTreeReader(dictionary, root as CosReference, Resolve, _diagnostics)) + : null; + + /// Returns the document's reader for the number tree rooted at , creating it on first use. + /// The root node or a reference to it. + /// The reader; when the root does not resolve to a dictionary. + internal NumberTreeReader? GetNumberTreeReader(CosObject? root) => + ResolveTreeRoot(root, DiagnosticCodes.NumberTreeNodeInvalid, "number tree") is { } node + ? _numberTrees.GetValue(node, dictionary => new NumberTreeReader(dictionary, root as CosReference, Resolve, _diagnostics)) + : null; + + /// Gets the diagnostics sink, for document-model views that report what they find on first read. + internal DiagnosticSink DiagnosticSink => _diagnostics; + /// Returns the data of decoded through the filters its Filter entry names. /// A stream of this document. /// The decoded data; for a stream without filters, its itself. @@ -374,6 +450,24 @@ public void DecodeStream(CosStream stream, IBufferWriter output) /// public void Dispose() => _source.Dispose(); + private CosDictionary? ResolveTreeRoot(CosObject? root, string code, string kind) + { + switch (Resolve(root)) + { + case CosDictionary dictionary: + return dictionary; + case CosNull: + return null; + default: + _diagnostics.Report( + code, + DiagnosticSeverity.Warning, + $"The root of a {kind} is not a dictionary; the tree is read as absent.", + objectReference: root as CosReference); + return null; + } + } + /// Builds the bytes of a new one-page document and opens them (issue #44). /// The engine's configuration. /// The document. diff --git a/src/Broadside/PdfNameDictionary.cs b/src/Broadside/PdfNameDictionary.cs new file mode 100644 index 00000000..67dcce88 --- /dev/null +++ b/src/Broadside/PdfNameDictionary.cs @@ -0,0 +1,42 @@ +using Broadside.Objects; + +namespace Broadside; + +/// The document's name dictionary: the name trees that map names to destinations, embedded files, scripts and more. A live view. +/// +/// ISO 32000-2 §7.7.4, Table 32 (PDF 1.2), reached through the catalog's Names entry (§7.7.2, Table 29). Every entry is a name +/// tree (§7.9.6): Dests (PDF 1.2), AP, JavaScript, Pages, Templates, IDS, URLS (PDF 1.3), +/// EmbeddedFiles, AlternatePresentations (PDF 1.4; deprecated in PDF 2.0) and Renditions (PDF 1.5). Each is +/// reachable through ; the typed views of their values arrive with their features. +/// +public sealed class PdfNameDictionary +{ + private readonly PdfDocument _document; + + internal PdfNameDictionary(PdfDocument document, CosDictionary dictionary) + { + _document = document; + Dictionary = dictionary; + } + + /// Gets the name dictionary. + /// ISO 32000-2 §7.7.4, Table 32. + public CosDictionary Dictionary { get; } + + /// Gets the tree of named destinations (string keys), or when there is none. + /// + /// ISO 32000-2 §7.7.4, Table 32 (PDF 1.2), and §12.3.2.4: each value is a destination array, or a dictionary whose D entry + /// is one. Named destinations of PDF 1.1 (name keys) are in the catalog's own Dests dictionary instead. + /// + public PdfNameTree? Dests => GetTree(KnownNames.Dests); + + /// Gets the name tree under , or when the entry is absent. + /// The entry, for example EmbeddedFiles or JavaScript. + /// The tree, read lazily; when the entry is absent or is not a dictionary (with a diagnostic). + /// ISO 32000-2 §7.7.4, Table 32, and §7.9.6. + public PdfNameTree? GetTree(CosName key) + { + ArgumentNullException.ThrowIfNull(key); + return Dictionary.TryGetValue(key, out CosObject? root) ? _document.GetNameTree(root) : null; + } +} diff --git a/src/Broadside/PdfNameTree.cs b/src/Broadside/PdfNameTree.cs new file mode 100644 index 00000000..5248659a --- /dev/null +++ b/src/Broadside/PdfNameTree.cs @@ -0,0 +1,113 @@ +using System.Collections; +using System.Diagnostics.CodeAnalysis; +using System.Text; +using Broadside.Objects; + +namespace Broadside; + +/// A name tree: a sorted map from string keys to objects, spread over a tree of node dictionaries. A read-only live view. +/// +/// +/// ISO 32000-2 §7.9.6, Table 36 (PDF 1.2). Keys are strings compared byte by byte (Annex J.3.3): (a) and the UTF-16BE key +/// <FEFF0061> are different keys even though both read as "a". The tree is read lazily: a lookup loads one node per +/// level, guided by each node's Limits; enumeration walks the whole tree in order. Values come back resolved one level (a +/// value stored as an indirect reference returns the object it refers to). +/// +/// +/// Damaged trees are read leniently. A node without usable Limits, a key outside its node's Limits, keys out of order, +/// a key that appears twice, a node reached twice (a cycle), a tree deeper than 64 levels, an odd-length Names array, and a key +/// that is not a string are each reported once per node as a diagnostic; lookups then fall back to an index of every key, built once +/// by walking the whole tree and kept until a node of the tree changes. When a key appears twice, the first occurrence in tree order +/// is the one both lookups and enumeration return. Diagnostics are reported when the damage is first read, so in strict mode the +/// lookup or enumeration that meets it throws a , not . +/// +/// Safe for concurrent reads while nobody changes the document. +/// +[SuppressMessage("Naming", "CA1710:Identifiers should have correct suffix", Justification = "The name is the ISO 32000-2 term (§7.9.6).")] +public sealed class PdfNameTree : IEnumerable> +{ + private readonly NameTreeReader _reader; + + internal PdfNameTree(NameTreeReader reader) => _reader = reader; + + /// Gets the root node dictionary. + /// ISO 32000-2 §7.9.6, Table 36. + public CosDictionary Root => _reader.Root; + + /// Gets the indirect reference to the root node, or when the root is a direct dictionary. + public CosReference? RootReference => _reader.RootReference; + + /// Looks up the key with the same bytes as . + /// The key. + /// The value, resolved one level, when found. + /// when the tree holds the key. + /// ISO 32000-2 §7.9.6 and Annex J.3.3: keys are compared byte by byte. + public bool TryGetValue(CosString key, [MaybeNullWhen(false)] out CosObject value) + { + ArgumentNullException.ThrowIfNull(key); + return _reader.TryGetValue(key, out value); + } + + /// Looks up the key whose bytes are . + /// The key's bytes. + /// The value, resolved one level, when found. + /// when the tree holds the key. + /// ISO 32000-2 §7.9.6 and Annex J.3.3. + public bool TryGetValue(ReadOnlySpan key, [MaybeNullWhen(false)] out CosObject value) => _reader.TryGetValue(key, out value); + + /// Looks up the key that reads as the text . + /// The key as text. + /// The value, resolved one level, when found. + /// when the tree holds a key that reads as . + /// + /// ISO 32000-2 §7.9.6 and §7.9.2.2: the file may encode a key in PDFDocEncoding or as UTF-16BE (or UTF-8) with a byte order + /// marker. The text is tried as PDFDocEncoding bytes (when every character has a code), then as UTF-16BE with the marker; when + /// neither is a key, every key is decoded and compared with the text ordinally, and the first match in tree order is returned. + /// + public bool TryGetValue(string key, [MaybeNullWhen(false)] out CosObject value) + { + ArgumentNullException.ThrowIfNull(key); + if (TextStringEncoder.TryEncodePdfDoc(key, out byte[]? encoded) && _reader.TryGetValue(encoded, out value)) + { + return true; + } + + byte[] utf16 = [0xFE, 0xFF, .. Encoding.BigEndianUnicode.GetBytes(key)]; + if (_reader.TryGetValue(utf16, out value)) + { + return true; + } + + foreach ((CosString candidate, CosObject found) in _reader.Enumerate()) + { + if (string.Equals(candidate.DecodeText(), key, StringComparison.Ordinal)) + { + value = found; + return true; + } + } + + value = null; + return false; + } + + /// Determines whether the tree holds the key with the same bytes as . + /// The key. + /// when the tree holds the key. + /// ISO 32000-2 §7.9.6. + public bool ContainsKey(CosString key) => TryGetValue(key, out _); + + /// Returns the keys and values in tree order (ascending byte order in a well-formed tree), each key once. + /// An enumerator that walks the tree; each enumeration walks it again. + /// ISO 32000-2 §7.9.6. + public IEnumerator> GetEnumerator() + { + foreach ((CosString key, CosObject value) in _reader.Enumerate()) + { + yield return new KeyValuePair(key, value); + } + } + + /// + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); +} diff --git a/src/Broadside/PdfNumberTree.cs b/src/Broadside/PdfNumberTree.cs new file mode 100644 index 00000000..b79959d8 --- /dev/null +++ b/src/Broadside/PdfNumberTree.cs @@ -0,0 +1,73 @@ +using System.Collections; +using System.Diagnostics.CodeAnalysis; +using Broadside.Objects; + +namespace Broadside; + +/// A number tree: a sorted map from integer keys to objects, spread over a tree of node dictionaries. A read-only live view. +/// +/// +/// ISO 32000-2 §7.9.7, Table 37 (PDF 1.3). Like with integer keys in ascending numerical order, held in +/// Nums arrays. Keys are 32-bit integers. Lookups are guided by each node's Limits; and +/// enumeration read the whole tree. Values come back resolved one level. +/// +/// +/// Damage is read leniently, as for : each deviation is reported once per node when it is first read (in +/// strict mode the lookup or enumeration that meets it throws), lookups fall back to an index of every key built once, and a key that +/// appears twice resolves to its first occurrence in tree order. A key written as a real with an integral value is used as that +/// integer, with a diagnostic; any other non-integer key is skipped. +/// +/// Safe for concurrent reads while nobody changes the document. +/// +[SuppressMessage("Naming", "CA1710:Identifiers should have correct suffix", Justification = "The name is the ISO 32000-2 term (§7.9.7).")] +public sealed class PdfNumberTree : IEnumerable> +{ + private readonly NumberTreeReader _reader; + + internal PdfNumberTree(NumberTreeReader reader) => _reader = reader; + + /// Gets the root node dictionary. + /// ISO 32000-2 §7.9.7, Table 37. + public CosDictionary Root => _reader.Root; + + /// Gets the indirect reference to the root node, or when the root is a direct dictionary. + public CosReference? RootReference => _reader.RootReference; + + /// Looks up . + /// The key. + /// The value, resolved one level, when found. + /// when the tree holds the key. + /// ISO 32000-2 §7.9.7. + public bool TryGetValue(int key, [MaybeNullWhen(false)] out CosObject value) => _reader.TryGetValue(key, out value); + + /// Finds the greatest key that is not greater than , and its value. + /// The key. + /// The greatest key in the tree not greater than . + /// Its value, resolved one level. + /// when the tree holds such a key. + /// + /// ISO 32000-2 §7.9.7. This is how a range keyed by its first number is found, as page labels are (§12.4.2). Reads the whole tree + /// once, then answers from its index until the tree changes. + /// + public bool TryGetFloor(int key, out int floorKey, [MaybeNullWhen(false)] out CosObject value) => _reader.TryGetFloor(key, out floorKey, out value); + + /// Determines whether the tree holds . + /// The key. + /// when the tree holds the key. + /// ISO 32000-2 §7.9.7. + public bool ContainsKey(int key) => TryGetValue(key, out _); + + /// Returns the keys and values in tree order (ascending in a well-formed tree), each key once. + /// An enumerator that walks the tree; each enumeration walks it again. + /// ISO 32000-2 §7.9.7. + public IEnumerator> GetEnumerator() + { + foreach ((int key, CosObject value) in _reader.Enumerate()) + { + yield return new KeyValuePair(key, value); + } + } + + /// + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); +} diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index a576dc7d..feb3fcc7 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -404,3 +404,25 @@ Broadside.Security.PublicKeySecurityHandler.Filter.get -> Broadside.Objects.CosN Broadside.Security.PublicKeySecurityHandler.PublicKeySecurityHandler() -> void Broadside.Security.PublicKeySecurityHandler.SubFilters.get -> System.Collections.Generic.IReadOnlyCollection! override Broadside.Security.PdfCertificateCredentials.ToString() -> string! +Broadside.PdfDocument.GetNameTree(Broadside.Objects.CosObject? root) -> Broadside.PdfNameTree? +Broadside.PdfDocument.GetNumberTree(Broadside.Objects.CosObject? root) -> Broadside.PdfNumberTree? +Broadside.PdfDocument.Names.get -> Broadside.PdfNameDictionary? +Broadside.PdfNameDictionary +Broadside.PdfNameDictionary.Dests.get -> Broadside.PdfNameTree? +Broadside.PdfNameDictionary.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfNameDictionary.GetTree(Broadside.Objects.CosName! key) -> Broadside.PdfNameTree? +Broadside.PdfNameTree +Broadside.PdfNameTree.ContainsKey(Broadside.Objects.CosString! key) -> bool +Broadside.PdfNameTree.GetEnumerator() -> System.Collections.Generic.IEnumerator>! +Broadside.PdfNameTree.Root.get -> Broadside.Objects.CosDictionary! +Broadside.PdfNameTree.RootReference.get -> Broadside.Objects.CosReference? +Broadside.PdfNameTree.TryGetValue(Broadside.Objects.CosString! key, out Broadside.Objects.CosObject! value) -> bool +Broadside.PdfNameTree.TryGetValue(string! key, out Broadside.Objects.CosObject! value) -> bool +Broadside.PdfNameTree.TryGetValue(System.ReadOnlySpan key, out Broadside.Objects.CosObject! value) -> bool +Broadside.PdfNumberTree +Broadside.PdfNumberTree.ContainsKey(int key) -> bool +Broadside.PdfNumberTree.GetEnumerator() -> System.Collections.Generic.IEnumerator>! +Broadside.PdfNumberTree.Root.get -> Broadside.Objects.CosDictionary! +Broadside.PdfNumberTree.RootReference.get -> Broadside.Objects.CosReference? +Broadside.PdfNumberTree.TryGetFloor(int key, out int floorKey, out Broadside.Objects.CosObject! value) -> bool +Broadside.PdfNumberTree.TryGetValue(int key, out Broadside.Objects.CosObject! value) -> bool diff --git a/src/Broadside/TreeReader.cs b/src/Broadside/TreeReader.cs new file mode 100644 index 00000000..83ef9976 --- /dev/null +++ b/src/Broadside/TreeReader.cs @@ -0,0 +1,610 @@ +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// +/// The walker shared by name trees and number trees: Limits-guided lookup, an in-order walk that checks the tree as it goes, and +/// a flattened index for trees whose Limits cannot be trusted. +/// +/// The key type: for name trees, for number trees. +/// +/// +/// ISO 32000-2 §7.9.6, Table 36, and §7.9.7, Table 37. A lookup descends from the root, at each level binary-searching the kids +/// by their Limits for the first one whose greatest key is not less than the key, then binary-searching the leaf. It loads +/// one node per level and reports nothing. When anything on that path is not as the clause requires (a node without usable +/// Limits, a malformed key, a level deeper than the cap) or the key is not found, the lookup falls back to the flattened +/// index: every key in the tree, de-duplicated, sorted. The index is built once by the checking walk and kept until a node it was +/// built from changes (each container's internal version), so stale Limits cost one full walk, not one per lookup. +/// +/// +/// The walk visits nodes in tree order (a root's own pairs, then its kids, depth first), with one visited set for the whole walk +/// and a depth cap, iteratively, so a cycle or a very deep chain ends. It reports each deviation once per node. A key seen +/// earlier in the walk is a duplicate and is skipped, so the first occurrence in tree order is the one every API returns. +/// +/// +/// Values are returned resolved one level: a value that is an indirect reference comes back as the object it refers to. +/// Thread-safe for concurrent reads (the index is built under a lock and published whole). +/// +/// +internal abstract class TreeReader + where TKey : notnull +{ + /// The deepest tree the reader descends into: deeper nodes are skipped with a diagnostic. + public const int DefaultMaxDepth = 64; + + private readonly Lock _gate = new(); + private volatile TreeIndex? _index; + private volatile bool _limitsUntrusted; + + /// Initializes a new instance of the class. + /// The tree's root node dictionary. + /// The root's reference, for diagnostics, or when it is direct. + /// Resolves references through the document. + /// Where to report deviations. + /// The deepest level the walk descends to; the root is level 0. + private protected TreeReader(CosDictionary root, CosReference? rootReference, Func resolve, DiagnosticSink diagnostics, int maxDepth) + { + ArgumentOutOfRangeException.ThrowIfNegative(maxDepth); + Root = root; + RootReference = rootReference; + Resolve = resolve; + Diagnostics = diagnostics; + MaxDepth = maxDepth; + } + + /// Gets the root node. + public CosDictionary Root { get; } + + /// Gets the root's reference, or when the root is a direct dictionary. + public CosReference? RootReference { get; } + + /// Gets the deepest level the walk descends to. + public int MaxDepth { get; } + + private protected Func Resolve { get; } + + private protected DiagnosticSink Diagnostics { get; } + + /// Gets the key of the array holding the pairs: Names or Nums. + private protected abstract CosName EntriesKey { get; } + + /// Gets the diagnostic codes for this kind of tree. + private protected abstract TreeCodes Codes { get; } + + /// Gets the name of the tree kind, for messages: "name tree" or "number tree". + private protected abstract string Kind { get; } + + /// Gets the comparer that orders keys as the clause sorts them. + private protected abstract IComparer KeyComparer { get; } + + /// Gets the comparer that decides key equality. + private protected abstract IEqualityComparer KeyEquality { get; } + + /// Looks up. + /// The key. + /// The value, resolved one level, when found. + /// when the tree holds the key. + public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out CosObject value) + { + if (!_limitsUntrusted && _index is null && TryDescend(key, out CosObject? found)) + { + value = Resolve(found); + return true; + } + + TreeIndex index = GetIndex(); + int position = index.Find(key, KeyComparer); + if (position < 0) + { + value = null; + return false; + } + + value = Resolve(index.Values[position]); + return true; + } + + /// Finds the greatest key not greater than , through the flattened index. + /// The key. + /// The greatest key in the tree that is not greater than . + /// Its value, resolved one level. + /// when the tree holds a key not greater than . + public bool TryGetFloor(TKey key, [MaybeNullWhen(false)] out TKey floorKey, [MaybeNullWhen(false)] out CosObject value) + { + TreeIndex index = GetIndex(); + int position = index.Find(key, KeyComparer); + if (position < 0) + { + position = ~position - 1; + } + + if (position < 0) + { + floorKey = default; + value = null; + return false; + } + + floorKey = index.Keys[position]; + value = Resolve(index.Values[position]); + return true; + } + + /// Walks the tree in tree order, checking it, and yields each key once with its value resolved one level. + /// The pairs. Each enumeration walks the tree again; it is a live view. + public IEnumerable<(TKey Key, CosObject Value)> Enumerate() + { + foreach ((TKey key, CosObject value) in Walk(stamps: null)) + { + yield return (key, Resolve(value)); + } + } + + /// Reads a key from the Names or Nums array. + /// The array element, resolved. + /// The key. + /// When the key is repaired or rejected, why. + /// + /// , (usable, with a diagnostic) or + /// (the pair is skipped with a diagnostic). + /// + private protected abstract KeyState ReadKey(CosObject key, [MaybeNullWhen(false)] out TKey value, out string? message); + + /// Gets the index, building it when there is none or a node it was built from has changed. + private TreeIndex GetIndex() + { + TreeIndex? index = _index; + if (index is not null && index.IsCurrent()) + { + return index; + } + + lock (_gate) + { + index = _index; + if (index is not null && index.IsCurrent()) + { + return index; + } + + var stamps = new List<(CosObject Container, int Version)>(); + var keys = new List(); + var values = new List(); + foreach ((TKey key, CosObject value) in Walk(stamps)) + { + keys.Add(key); + values.Add(value); + } + + TKey[] keyArray = [.. keys]; + CosObject[] valueArray = [.. values]; + + // Keys are unique after the walk, so the sort order is total. + Array.Sort(keyArray, valueArray, KeyComparer); + index = new TreeIndex(keyArray, valueArray, [.. stamps]); + _index = index; + return index; + } + } + + /// The Limits-guided descent. Fails, reporting nothing, on anything the clause does not allow. + private bool TryDescend(TKey key, [MaybeNullWhen(false)] out CosObject value) + { + value = null; + CosDictionary node = Root; + for (int depth = 0; depth <= MaxDepth; depth++) + { + if (node.TryGetValue(EntriesKey, out CosObject? entriesEntry)) + { + return Resolve(entriesEntry) is CosArray entries && TryFindInLeaf(entries, key, out value); + } + + if (!node.TryGetValue(KnownNames.Kids, out CosObject? kidsEntry) || Resolve(kidsEntry) is not CosArray kids || kids.Count == 0) + { + return false; + } + + // The first kid whose greatest key is not less than the key: with duplicates on a shared boundary that is the + // earliest kid in tree order. + int low = 0; + int high = kids.Count - 1; + CosDictionary? candidate = null; + TKey? candidateLeast = default; + while (low <= high) + { + int middle = low + ((high - low) / 2); + if (Resolve(kids[middle]) is not CosDictionary kid || !TryReadLimits(kid, out TKey? least, out TKey? greatest)) + { + return false; + } + + if (KeyComparer.Compare(greatest, key) >= 0) + { + candidate = kid; + candidateLeast = least; + high = middle - 1; + } + else + { + low = middle + 1; + } + } + + if (candidate is null || KeyComparer.Compare(candidateLeast!, key) > 0) + { + return false; + } + + node = candidate; + } + + return false; + } + + /// Binary-searches a leaf's pairs for the first occurrence of . + private bool TryFindInLeaf(CosArray entries, TKey key, [MaybeNullWhen(false)] out CosObject value) + { + value = null; + int low = 0; + int high = (entries.Count / 2) - 1; + int found = -1; + while (low <= high) + { + int middle = low + ((high - low) / 2); + if (ReadKey(Resolve(entries[2 * middle]), out TKey? probe, out _) != KeyState.Valid) + { + return false; + } + + int comparison = KeyComparer.Compare(probe, key); + if (comparison >= 0) + { + found = comparison == 0 ? middle : found; + high = middle - 1; + } + else + { + low = middle + 1; + } + } + + if (found < 0) + { + return false; + } + + value = entries[(2 * found) + 1]; + return true; + } + + /// Reads a node's Limits: an array of two valid keys, least first. + private bool TryReadLimits(CosDictionary node, [MaybeNullWhen(false)] out TKey least, [MaybeNullWhen(false)] out TKey greatest) + { + least = default; + greatest = default; + return node.TryGetValue(KnownNames.Limits, out CosObject? entry) + && Resolve(entry) is CosArray { Count: 2 } limits + && ReadKey(Resolve(limits[0]), out least, out _) == KeyState.Valid + && ReadKey(Resolve(limits[1]), out greatest, out _) == KeyState.Valid + && KeyComparer.Compare(least, greatest) <= 0; + } + + /// + /// The checking walk, in tree order. Yields each key once (the first occurrence) with its raw value. Records the version of every + /// container it reads the structure from when is given. + /// + private IEnumerable<(TKey Key, CosObject Value)> Walk(List<(CosObject Container, int Version)>? stamps) + { + var visitedReferences = new HashSet(); + var visitedNodes = new HashSet(ReferenceEqualityComparer.Instance); + var seen = new HashSet(KeyEquality); + bool hasPrevious = false; + TKey previous = default!; + bool anomalies = false; + + if (RootReference is not null) + { + visitedReferences.Add(RootReference); + } + + visitedNodes.Add(Root); + var stack = new Stack(); + stack.Push(new Frame(Root, RootReference, null, 0, IsRoot: true)); + while (stack.TryPop(out Frame frame)) + { + CosDictionary node = frame.Node; + stamps?.Add((node, node.Version)); + Bounds? bounds = CheckLimits(frame, ref anomalies); + bool hasEntries = node.TryGetValue(EntriesKey, out CosObject? entriesEntry); + bool hasKids = node.TryGetValue(KnownNames.Kids, out CosObject? kidsEntry); + if (hasEntries == hasKids) + { + anomalies = true; + Report( + Codes.NodeInvalid, + DiagnosticSeverity.Warning, + hasEntries + ? $"A {Kind} node has both Kids and {EntriesKey.Value}; its own pairs are read first, then its kids." + : $"A {Kind} node has neither Kids nor {EntriesKey.Value}; it holds no keys.", + frame.Reference); + } + + if (hasEntries) + { + if (Resolve(entriesEntry) is not CosArray entries) + { + anomalies = true; + Report(Codes.NodeInvalid, DiagnosticSeverity.Warning, $"A {Kind} node's {EntriesKey.Value} is not an array; it holds no keys.", frame.Reference); + } + else + { + stamps?.Add((entries, entries.Version)); + if (entries.Count % 2 != 0) + { + anomalies = true; + Report( + Codes.NodeInvalid, + DiagnosticSeverity.Warning, + $"A {Kind} node's {EntriesKey.Value} array has an odd number of elements; the last key has no value and is ignored.", + frame.Reference); + } + + for (int index = 0; index + 1 < entries.Count; index += 2) + { + KeyState state = ReadKey(Resolve(entries[index]), out TKey? key, out string? message); + if (state != KeyState.Valid) + { + anomalies = true; + Report(Codes.KeyInvalid, DiagnosticSeverity.Warning, message!, frame.Reference); + if (state == KeyState.Invalid) + { + continue; + } + } + + if (!IsWithin(key!, frame.Ancestors, bounds, frame.Reference)) + { + anomalies = true; + } + + if (!seen.Add(key!)) + { + anomalies = true; + Report( + Codes.DuplicateKey, + DiagnosticSeverity.Warning, + $"A {Kind} key appears more than once; the first occurrence in tree order is used.", + frame.Reference); + continue; + } + + if (hasPrevious && KeyComparer.Compare(key!, previous) < 0) + { + anomalies = true; + Report( + Codes.KeysUnsorted, + DiagnosticSeverity.Warning, + $"The keys of a {Kind} are not in ascending order; lookups fall back to reading the whole tree.", + frame.Reference); + } + + hasPrevious = true; + previous = key!; + yield return (key!, entries[index + 1]); + } + } + } + + if (hasKids) + { + foreach (Frame kid in ReadKids(frame, kidsEntry, bounds, visitedReferences, visitedNodes, stamps, ref anomalies)) + { + stack.Push(kid); + } + } + } + + if (anomalies) + { + _limitsUntrusted = true; + } + } + + /// Reads a node's kids for the walk; returns them in reverse order, ready to push. + private List ReadKids( + Frame frame, + CosObject? kidsEntry, + Bounds? bounds, + HashSet visitedReferences, + HashSet visitedNodes, + List<(CosObject Container, int Version)>? stamps, + ref bool anomalies) + { + var kids = new List(); + if (Resolve(kidsEntry) is not CosArray array) + { + anomalies = true; + Report(Codes.NodeInvalid, DiagnosticSeverity.Warning, $"A {Kind} node's Kids is not an array; it has no kids.", frame.Reference); + return kids; + } + + stamps?.Add((array, array.Version)); + if (frame.Depth >= MaxDepth) + { + anomalies = true; + Report( + Codes.TooDeep, + DiagnosticSeverity.Error, + string.Create(CultureInfo.InvariantCulture, $"The {Kind} is deeper than {MaxDepth} levels; the deeper nodes are skipped."), + frame.Reference); + return kids; + } + + var ancestors = bounds is null ? frame.Ancestors : new BoundsChain(bounds.Value, frame.Reference, frame.Ancestors); + foreach (CosObject kid in array) + { + var reference = kid as CosReference; + if (Resolve(kid) is not CosDictionary child) + { + anomalies = true; + Report(Codes.NodeInvalid, DiagnosticSeverity.Warning, $"A {Kind} Kids entry is not a node dictionary; it is skipped.", reference ?? frame.Reference); + continue; + } + + if (reference is null) + { + anomalies = true; + Report(Codes.NodeInvalid, DiagnosticSeverity.Warning, $"A {Kind} Kids entry shall be an indirect reference; it is a direct dictionary, used as is.", frame.Reference); + } + + if ((reference is not null && !visitedReferences.Add(reference)) || !visitedNodes.Add(child)) + { + anomalies = true; + Report( + Codes.Cycle, + DiagnosticSeverity.Error, + $"A {Kind} node is reached a second time (a cycle or a shared node); the repeat is skipped.", + reference ?? frame.Reference); + continue; + } + + kids.Add(new Frame(child, reference ?? frame.Reference, ancestors, frame.Depth + 1, IsRoot: false)); + } + + kids.Reverse(); + return kids; + } + + /// Checks a node's Limits entry; returns the bounds when they are usable. + private Bounds? CheckLimits(Frame frame, ref bool anomalies) + { + bool present = frame.Node.TryGetValue(KnownNames.Limits, out CosObject? entry); + if (frame.IsRoot) + { + if (present) + { + anomalies = true; + Report(Codes.LimitsInvalid, DiagnosticSeverity.Warning, $"The root of a {Kind} shall not have Limits; they are ignored.", frame.Reference); + } + + return null; + } + + if (present + && Resolve(entry) is CosArray { Count: 2 } limits + && ReadKey(Resolve(limits[0]), out TKey? least, out _) == KeyState.Valid + && ReadKey(Resolve(limits[1]), out TKey? greatest, out _) == KeyState.Valid + && KeyComparer.Compare(least, greatest) <= 0) + { + return new Bounds(least, greatest); + } + + anomalies = true; + Report( + Codes.LimitsInvalid, + DiagnosticSeverity.Warning, + present + ? $"A {Kind} node's Limits is not an array of its least and greatest keys; lookups fall back to reading the whole tree." + : $"A {Kind} node below the root has no Limits; lookups fall back to reading the whole tree.", + frame.Reference); + return null; + } + + /// Checks a key against the Limits of its leaf and of every ancestor that has usable ones; reports each node that misses it. + private bool IsWithin(TKey key, BoundsChain? ancestors, Bounds? own, CosReference? ownReference) + { + bool within = true; + if (own is { } bounds && !bounds.Contains(key, KeyComparer)) + { + within = false; + ReportStale(ownReference); + } + + for (BoundsChain? chain = ancestors; chain is not null; chain = chain.Next) + { + if (!chain.Bounds.Contains(key, KeyComparer)) + { + within = false; + ReportStale(chain.Reference); + } + } + + return within; + } + + private void ReportStale(CosReference? reference) => + Report( + Codes.LimitsInvalid, + DiagnosticSeverity.Warning, + $"A {Kind} key lies outside the Limits of a node that holds it; lookups fall back to reading the whole tree.", + reference); + + private void Report(string code, DiagnosticSeverity severity, string message, CosReference? reference) => + Diagnostics.Report(code, severity, message, objectReference: reference); + + /// How usable a key read from a tree is. + private protected enum KeyState + { + /// The key is of the type the clause requires. + Valid, + + /// The key is not of the required type but is used, with a diagnostic. + Repaired, + + /// The key cannot be used; the pair is skipped with a diagnostic. + Invalid, + } + + /// The diagnostic codes of one kind of tree. + private protected sealed record TreeCodes(string NodeInvalid, string LimitsInvalid, string KeysUnsorted, string DuplicateKey, string KeyInvalid, string Cycle, string TooDeep); + + /// A node waiting to be visited. + /// The node dictionary. + /// The node's reference, or the nearest indirect ancestor's when the node is direct. + /// The usable Limits of the nodes above it. + /// 0 for the root. + /// Whether this is the root. + private readonly record struct Frame(CosDictionary Node, CosReference? Reference, BoundsChain? Ancestors, int Depth, bool IsRoot); + + /// A node's least and greatest keys. + private readonly record struct Bounds(TKey Least, TKey Greatest) + { + public bool Contains(TKey key, IComparer comparer) => comparer.Compare(key, Least) >= 0 && comparer.Compare(key, Greatest) <= 0; + } + + /// The usable Limits of the nodes on the path to a node, nearest first. + private sealed record BoundsChain(Bounds Bounds, CosReference? Reference, BoundsChain? Next); + + /// Every key of the tree, sorted, with raw values; current while no container it was read from has changed. + private sealed class TreeIndex(TKey[] keys, CosObject[] values, (CosObject Container, int Version)[] stamps) + { + public TKey[] Keys => keys; + + public CosObject[] Values => values; + + public int Find(TKey key, IComparer comparer) => Array.BinarySearch(keys, key, comparer); + + public bool IsCurrent() + { + foreach ((CosObject container, int version) in stamps) + { + int current = container switch + { + CosDictionary dictionary => dictionary.Version, + CosArray array => array.Version, + _ => version, + }; + if (current != version) + { + return false; + } + } + + return true; + } + } +} diff --git a/tests/Broadside.TestSupport/Corpus.cs b/tests/Broadside.TestSupport/Corpus.cs index e98e5c47..d0ce8d5f 100644 --- a/tests/Broadside.TestSupport/Corpus.cs +++ b/tests/Broadside.TestSupport/Corpus.cs @@ -40,6 +40,8 @@ public static class Corpus "outline.pdf", "name-tree-dests.pdf", "metadata-xmp.pdf", + "name-tree-deep.pdf", + "number-tree-deep.pdf", ]; private static readonly string[] Malformed = @@ -52,6 +54,7 @@ public static class Corpus "encrypted-mac-tampered.pdf", "encrypted-owner-key-variant.pdf", "encrypted-rc4-length-missing.pdf", + "name-tree-broken.pdf", ]; private static readonly (string FileName, string UserPassword)[] PasswordProtected = diff --git a/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs b/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs index d633c4c6..82c81c59 100644 --- a/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs +++ b/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs @@ -14,7 +14,12 @@ public void A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics(str { using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName)); - int expectedPages = fileName is "page-tree-inherited.pdf" or "linearized.pdf" or "linearized-xref-stream.pdf" ? 2 : 1; + int expectedPages = fileName switch + { + "page-tree-inherited.pdf" or "linearized.pdf" or "linearized-xref-stream.pdf" => 2, + "number-tree-deep.pdf" => 12, + _ => 1, + }; Assert.Equal(expectedPages, document.Pages.Count); foreach (PdfPage page in document.Pages) { diff --git a/tests/Broadside.Tests/Navigation/NameTreeTests.cs b/tests/Broadside.Tests/Navigation/NameTreeTests.cs new file mode 100644 index 00000000..0bd8989d --- /dev/null +++ b/tests/Broadside.Tests/Navigation/NameTreeTests.cs @@ -0,0 +1,251 @@ +using System.Globalization; +using System.Text; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Tests.Document; +using Broadside.Tests.Hosting; +using Broadside.TestSupport; +using Microsoft.Extensions.Logging; + +namespace Broadside.Tests.Navigation; + +/// +/// Name trees (ISO 32000-2 §7.9.6, Table 36; Annex J.3.3) read through and +/// : Limits-guided lookups, byte-wise key order, lenient reading of damaged trees. +/// +public class NameTreeTests +{ + private static readonly CosName Dests = new("Dests"); + + [Fact] + public void Name_tree_dests_pdf_maps_its_three_keys_to_their_destination_arrays_with_no_diagnostics() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("name-tree-dests.pdf")); + + PdfNameTree tree = Assert.IsType(document.Names?.Dests); + + Assert.Equal(["alpha", "beta", "gamma"], tree.Select(entry => Encoding.ASCII.GetString(entry.Key.Bytes))); + Assert.True(tree.TryGetValue("alpha", out CosObject? alpha)); + Assert.Equal("[3 0 R /Fit]", alpha.ToString()); + Assert.True(tree.TryGetValue(new CosString("beta"u8), out CosObject? beta)); + Assert.Equal("[3 0 R /XYZ 0 792 0]", beta.ToString()); + Assert.True(tree.TryGetValue("gamma"u8, out CosObject? gamma)); + Assert.Equal("[3 0 R /FitH 792]", gamma.ToString()); + Assert.False(tree.TryGetValue("delta", out _)); + Assert.Same(tree.Root, document.GetNameTree(document.Names!.Dictionary[Dests])!.Root); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Every_key_of_a_four_level_tree_resolves_and_enumeration_returns_them_once_in_byte_order() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("name-tree-deep.pdf")); + PdfNameTree tree = document.Names!.Dests!; + + byte[][] expected = + [ + [0x18], "a"u8.ToArray(), "ab"u8.ToArray(), + .. Enumerable.Range(1, 193).Select(number => Encoding.ASCII.GetBytes(number.ToString("'n'000", CultureInfo.InvariantCulture))), + [0x80], [0xE9], [0xFE, 0xFF, 0x00, 0x61], [0xFE, 0xFF, 0x00, 0xE9], + ]; + + KeyValuePair[] entries = [.. tree]; + Assert.Equal(expected.Select(Convert.ToHexString), entries.Select(entry => Convert.ToHexString(entry.Key.Bytes))); + Assert.Equal(Enumerable.Range(0, 200), entries.Select(entry => Top(entry.Value))); + for (int index = 0; index < expected.Length; index++) + { + Assert.True(tree.TryGetValue(expected[index], out CosObject? value)); + Assert.Equal(index, Top(value)); + } + + Assert.False(tree.TryGetValue("n000"u8, out _)); + Assert.False(tree.TryGetValue("n194"u8, out _)); + Assert.False(tree.TryGetValue(ReadOnlySpan.Empty, out _)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Keys_are_compared_byte_by_byte_and_a_text_lookup_tries_pdf_doc_encoding_first() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("name-tree-deep.pdf")); + PdfNameTree tree = document.Names!.Dests!; + + // (a) and both read as "a" but are different keys; (a) is shorter-prefix-first before (ab). + Assert.True(tree.TryGetValue([0xFE, 0xFF, 0x00, 0x61], out CosObject? utf16)); + Assert.Equal(198, Top(utf16)); + Assert.True(tree.TryGetValue("a", out CosObject? text)); + Assert.Equal(1, Top(text)); + + // PDFDocEncoding 0x18 is the breve U+02D8: first in byte order although its text sorts after every ASCII letter. + Assert.True(tree.TryGetValue("˘", out CosObject? breve)); + Assert.Equal(0, Top(breve)); + Assert.True(tree.TryGetValue("•", out CosObject? bullet)); + Assert.Equal(196, Top(bullet)); + Assert.True(tree.TryGetValue("é", out CosObject? eAcute)); + Assert.Equal(197, Top(eAcute)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_text_lookup_falls_back_to_utf_16_and_then_to_every_key_decoded() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R /Names << /Dests 4 0 R >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>", + "<< /Names [ (utf-8) (utf-16)] >>"); + using PdfDocument document = PdfDocument.Open(file); + PdfNameTree tree = document.Names!.Dests!; + + Assert.True(tree.TryGetValue("中", out CosObject? utf16)); + Assert.Equal("(utf-16)", utf16.ToString()); + Assert.True(tree.TryGetValue("文", out CosObject? utf8)); + Assert.Equal("(utf-8)", utf8.ToString()); + Assert.False(tree.TryGetValue("斈", out _)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_lookup_reads_one_path_from_the_root_and_not_the_whole_tree() + { + using var logs = new CapturingLoggerProvider(); + using ILoggerFactory loggerFactory = LazyLoadingTests.TraceLogging(logs); + using PdfDocument document = PdfDocument.Open(Corpus.Path("name-tree-deep.pdf"), new PdfOptions().WithLoggerFactory(loggerFactory)); + PdfNameTree tree = document.Names!.Dests!; + int afterRoot = LazyLoadingTests.ParsedObjects(logs).Length; + + Assert.True(tree.TryGetValue("n150"u8, out CosObject? value)); + + // 28 nodes below the root (20 leaves, 5 + 2 intermediate nodes); a binary search over each node's kids touches a few per level. + Assert.Equal(152, Top(value)); // (n001) is at 3 + Assert.InRange(LazyLoadingTests.ParsedObjects(logs).Length - afterRoot, 3, 8); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_damaged_tree_reports_each_defect_once_per_node_and_every_key_still_resolves() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("name-tree-broken.pdf")); + PdfNameTree tree = document.Names!.Dests!; + Assert.Empty(document.Diagnostics); + + Assert.Equal(["a", "b", "d", "f", "e", "g", "h"], tree.Select(entry => Encoding.ASCII.GetString(entry.Key.Bytes))); + string[] expected = + [ + "NameTreeLimitsInvalid 7", // (d) outside leaf 7's Limits [(a) (c)] + "NameTreeKeysUnsorted 8", // (f) before (e) + "NameTreeLimitsInvalid 6", // intermediate node without Limits + "NameTreeCycle 4", // node 6 lists the root + "NameTreeNodeInvalid 9", // odd-length Names: the dangling (i) is ignored + "NameTreeDuplicateKey 9", // (g) again, after leaf 8's + ]; + Assert.Equal(expected, document.Diagnostics.Select(Describe)); + Assert.All(document.Diagnostics, diagnostic => Assert.True(diagnostic.Severity >= DiagnosticSeverity.Warning)); + + int[] tops = [.. "abdefgh".Select(key => Top(Lookup(tree, key)))]; + Assert.Equal([1, 2, 4, 5, 6, 7, 8], tops); + Assert.False(tree.TryGetValue("i", out _)); + Assert.False(tree.TryGetValue("c", out _)); + Assert.Equal(expected, document.Diagnostics.Select(Describe)); + } + + [Fact] + public void Lookups_of_a_damaged_tree_fall_back_to_the_whole_tree_and_agree_with_enumeration_on_duplicates() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("name-tree-broken.pdf")); + PdfNameTree tree = document.Names!.Dests!; + + // (d) lies outside its leaf's Limits, so the Limits-guided descent misses it; the fallback finds it and reports the damage. + Assert.Equal(4, Top(Lookup(tree, 'd'))); + Assert.Contains("NameTreeLimitsInvalid 7", document.Diagnostics.Select(Describe)); + + // (g) is in leaves 8 and 9: lookups and enumeration both give the first in tree order. + Assert.Equal(7, Top(Lookup(tree, 'g'))); + Assert.Equal(7, Top(tree.Single(entry => entry.Key.Bytes.SequenceEqual("g"u8)).Value)); + } + + [Fact] + public void Strict_mode_throws_from_the_lookup_that_meets_the_damage_not_from_open() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("name-tree-broken.pdf"), new PdfOptions().UseStrict()); + PdfNameTree tree = document.Names!.Dests!; + + // (a) is reached through intact nodes and Limits. + Assert.Equal(1, Top(Lookup(tree, 'a'))); + DiagnosticException error = Assert.Throws(() => tree.TryGetValue("d", out _)); + Assert.Equal("NameTreeLimitsInvalid 7", Describe(error.Diagnostic)); + Assert.Throws(() => tree.ToList()); + } + + [Fact] + public void Reading_a_tree_writes_nothing_and_a_change_to_a_node_shows_in_the_next_lookup() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("name-tree-broken.pdf")); + PdfNameTree tree = document.Names!.Dests!; + Assert.False(tree.TryGetValue("i", out _)); + _ = tree.ToList(); + + CosDictionary[] nodes = [.. Enumerable.Range(4, 6).Select(number => (CosDictionary)document.Resolve(new CosReference(number, 0)))]; + Assert.All(nodes, node => Assert.False(node.IsDirty)); + Assert.False(document.Catalog.IsDirty); + + // Leaf 9's dangling key (i) gets a value: the index built for the earlier lookups is stale and rebuilt. + var leaf = (CosArray)nodes[5][new CosName("Names")]; + leaf.Add(new CosArray([new CosReference(3, 0), new CosName("XYZ"), new CosInteger(0), new CosInteger(9), CosNull.Instance])); + + Assert.Equal(9, Top(Lookup(tree, 'i'))); + Assert.Equal(["a", "b", "d", "f", "e", "g", "h", "i"], tree.Select(entry => Encoding.ASCII.GetString(entry.Key.Bytes))); + } + + [Fact] + public void A_tree_root_that_is_not_a_dictionary_reads_as_absent_with_a_diagnostic() + { + byte[] file = TestPdf.OnePage(pageEntries: string.Empty, catalogEntries: "/Names << /Dests 42 /AP null >>"); + using PdfDocument document = PdfDocument.Open(file); + + Assert.Null(document.Names!.Dests); + Assert.Null(document.Names.GetTree(new CosName("AP"))); + Assert.Null(document.Names.GetTree(new CosName("EmbeddedFiles"))); + Assert.Equal(["NameTreeNodeInvalid -"], document.Diagnostics.Select(Describe)); + } + + [Fact] + public void Malformed_nodes_and_keys_are_repaired_or_skipped_with_a_diagnostic() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R /Names << /Dests 4 0 R >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>", + "<< /Limits [(a) (z)] /Names [(a) 1] /Kids [5 0 R << /Limits [(x) (x)] /Names [(x) 24] >> 6 0 R 7 0 R] >>", + "<< /Limits [(b) (c)] /Names [/b 2 3 (three) (c) 3] >>", + "<< >>", + "(not a node)"); + using PdfDocument document = PdfDocument.Open(file); + PdfNameTree tree = document.Names!.Dests!; + + Assert.Equal(["a", "b", "c", "x"], tree.Select(entry => Encoding.ASCII.GetString(entry.Key.Bytes))); + Assert.Equal( + [ + "NameTreeLimitsInvalid 4", // Limits on the root + "NameTreeNodeInvalid 4", // root with both Names and Kids (and a direct kid: once per node) + "NameTreeNodeInvalid 7", // a kid that is not a node + "NameTreeKeyInvalid 5", // /b used by its bytes; 3 skipped + "NameTreeLimitsInvalid 6", // a node below the root without Limits + "NameTreeNodeInvalid 6", // ... and with neither Kids nor Names + ], + document.Diagnostics.Select(Describe)); + Assert.Equal("24", Lookup(tree, 'x').ToString()); + Assert.Equal("2", Lookup(tree, 'b').ToString()); + } + + private static CosObject Lookup(PdfNameTree tree, char key) + { + Assert.True(tree.TryGetValue(key.ToString(), out CosObject? value), $"({key}) not found"); + return value; + } + + private static int Top(CosObject destination) => (int)Assert.IsType(Assert.IsType(destination)[3]).Value; + + private static string Describe(Diagnostic diagnostic) => + $"{diagnostic.Code} {diagnostic.ObjectReference?.ObjectNumber.ToString(CultureInfo.InvariantCulture) ?? "-"}"; +} diff --git a/tests/Broadside.Tests/Navigation/NumberTreeTests.cs b/tests/Broadside.Tests/Navigation/NumberTreeTests.cs new file mode 100644 index 00000000..116daea2 --- /dev/null +++ b/tests/Broadside.Tests/Navigation/NumberTreeTests.cs @@ -0,0 +1,130 @@ +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Tests.Document; +using Broadside.TestSupport; + +namespace Broadside.Tests.Navigation; + +/// Number trees (ISO 32000-2 §7.9.7, Table 37) read through . +public class NumberTreeTests +{ + private static readonly CosName PageLabels = new("PageLabels"); + + [Fact] + public void A_three_level_page_labels_tree_enumerates_its_keys_in_order_with_no_diagnostics() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("number-tree-deep.pdf")); + + PdfNumberTree tree = Labels(document); + + Assert.Equal([0, 1, 2, 4, 5, 7, 8, 10, 11], tree.Select(entry => entry.Key)); + Assert.Equal("<< /S /D /P (B-) /St 1 >>", tree.Last(entry => entry.Key == 10).Value.ToString()); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Exact_lookups_find_keys_through_the_limits_and_miss_keys_between_them() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("number-tree-deep.pdf")); + PdfNumberTree tree = Labels(document); + + Assert.True(tree.TryGetValue(7, out CosObject? seven)); + Assert.Equal("<< /S /a /P (x) >>", seven.ToString()); + Assert.True(tree.ContainsKey(0)); + Assert.True(tree.ContainsKey(11)); + Assert.False(tree.ContainsKey(3)); + Assert.False(tree.ContainsKey(12)); + Assert.False(tree.ContainsKey(-1)); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [InlineData(0, 0)] + [InlineData(3, 2)] + [InlineData(6, 5)] + [InlineData(9, 8)] + [InlineData(11, 11)] + [InlineData(1000, 11)] + public void A_floor_lookup_finds_the_greatest_key_not_greater_than_the_one_asked_for(int key, int expectedFloor) + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("number-tree-deep.pdf")); + PdfNumberTree tree = Labels(document); + + Assert.True(tree.TryGetFloor(key, out int floor, out CosObject? value)); + + Assert.Equal(expectedFloor, floor); + Assert.True(tree.TryGetValue(floor, out CosObject? exact)); + Assert.Same(exact, value); + Assert.False(tree.TryGetFloor(-1, out _, out _)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Keys_that_are_not_integers_are_repaired_or_skipped_with_a_diagnostic() + { + byte[] file = TestPdf.OnePage( + pageEntries: string.Empty, + catalogEntries: "/PageLabels << /Nums [0 (a) 2.0 (b) 1 (c) /x (d) 3000000000 (e) 3 (f)] >>"); + using PdfDocument document = PdfDocument.Open(file); + PdfNumberTree tree = Labels(document); + + Assert.Equal([0, 2, 1, 3], tree.Select(entry => entry.Key)); + Assert.Equal(["NumberTreeKeyInvalid", "NumberTreeKeysUnsorted"], document.Diagnostics.Select(diagnostic => diagnostic.Code)); + Assert.True(tree.TryGetValue(1, out CosObject? one)); + Assert.Equal("(c)", one.ToString()); + Assert.True(tree.TryGetFloor(2, out int floor, out _)); + Assert.Equal(2, floor); + } + + [Fact] + public void A_cycle_through_the_kids_ends_with_a_diagnostic() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R /PageLabels 4 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>", + "<< /Kids [5 0 R] >>", + "<< /Limits [0 9] /Kids [6 0 R 5 0 R] >>", + "<< /Limits [0 0] /Nums [0 (a)] >>"); + using PdfDocument document = PdfDocument.Open(file); + PdfNumberTree tree = Labels(document); + + Assert.Equal([0], tree.Select(entry => entry.Key)); + Assert.False(tree.TryGetValue(5, out _)); + Assert.Equal(["NumberTreeCycle 5"], document.Diagnostics.Select(Describe)); + } + + [Fact] + public void A_chain_deeper_than_the_cap_ends_with_a_diagnostic() + { + const int levels = 100; + var objects = new List + { + "<< /Type /Catalog /Pages 2 0 R /PageLabels 4 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>", + "<< /Kids [5 0 R] >>", + }; + for (int level = 1; level < levels; level++) + { + objects.Add(string.Create(CultureInfo.InvariantCulture, $"<< /Limits [0 0] /Kids [{5 + level} 0 R] >>")); + } + + objects.Add("<< /Limits [0 0] /Nums [0 (deep)] >>"); + using PdfDocument document = PdfDocument.Open(new TestPdf().Build([.. objects])); + PdfNumberTree tree = Labels(document); + + Assert.Empty(tree); + Assert.False(tree.TryGetValue(0, out _)); + Diagnostic tooDeep = Assert.Single(document.Diagnostics); + Assert.Equal("NumberTreeTooDeep", tooDeep.Code); + Assert.Equal(DiagnosticSeverity.Error, tooDeep.Severity); + } + + private static PdfNumberTree Labels(PdfDocument document) => + Assert.IsType(document.GetNumberTree(document.Catalog[PageLabels])); + + private static string Describe(Diagnostic diagnostic) => + $"{diagnostic.Code} {diagnostic.ObjectReference?.ObjectNumber.ToString(CultureInfo.InvariantCulture) ?? "-"}"; +} diff --git a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt index f9e9b5e1..89eff615 100644 --- a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt +++ b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt @@ -28,8 +28,11 @@ lzw-stream.pdf, metadata-xmp.pdf, missing-endobj.pdf, + name-tree-broken.pdf, + name-tree-deep.pdf, name-tree-dests.pdf, no-xref.pdf, + number-tree-deep.pdf, object-stream.pdf, outline.pdf, page-tree-inherited.pdf, diff --git a/tests/Broadside.Tests/Writing/SaveTests.cs b/tests/Broadside.Tests/Writing/SaveTests.cs index 4709e47c..beff1866 100644 --- a/tests/Broadside.Tests/Writing/SaveTests.cs +++ b/tests/Broadside.Tests/Writing/SaveTests.cs @@ -9,6 +9,18 @@ public class SaveTests { private static readonly PdfCrossReferenceLayout[] Layouts = Enum.GetValues(); + /// + /// Broken files whose damage is in a document-model structure read lazily (a name tree, an outline), not in the file structure: + /// they open without a diagnostic and save byte for byte, damage included, so qpdf reports it again. + /// + private static readonly HashSet DamagedInTheDocumentModel = new(StringComparer.Ordinal) { "name-tree-broken.pdf" }; + + /// + /// Well-formed files qpdf 12.4.2 warns about because it compares name tree keys as decoded text, not byte by byte as ISO 32000-2 + /// §7.9.6 requires (tests/Corpus/README.md). + /// + private static readonly HashSet QpdfComparesNameTreeKeysAsText = new(StringComparer.Ordinal) { "name-tree-deep.pdf" }; + /// Every unencrypted well-formed corpus file with every layout (encrypted files cannot be saved yet). public static TheoryData FilesAndLayouts { @@ -33,7 +45,7 @@ public static TheoryData BrokenFilesAndLayouts get { var data = new TheoryData(); - foreach (string file in Corpus.MalformedFileNames.Where(name => !name.StartsWith("encrypted-", StringComparison.Ordinal))) + foreach (string file in Corpus.MalformedFileNames.Where(name => !name.StartsWith("encrypted-", StringComparison.Ordinal) && !DamagedInTheDocumentModel.Contains(name))) { foreach (PdfCrossReferenceLayout layout in Layouts) { @@ -86,6 +98,16 @@ public void A_well_formed_file_saved_in_any_layout_passes_qpdf_check(string file (int exitCode, string output) = ExternalTool.Run("qpdf", Save(source, layout), "--check"); + if (QpdfComparesNameTreeKeysAsText.Contains(fileName)) + { + // Exit code 3: warnings only, and every warning is qpdf's text-order complaint. + Assert.True(exitCode == 3, output); + Assert.All( + output.Split('\n').Where(line => line.StartsWith("WARNING", StringComparison.Ordinal)), + line => Assert.Contains("keys are not sorted", line, StringComparison.Ordinal)); + return; + } + Assert.True(exitCode == 0, output); } diff --git a/tests/Corpus/README.md b/tests/Corpus/README.md index f693ab10..4093ee04 100644 --- a/tests/Corpus/README.md +++ b/tests/Corpus/README.md @@ -64,6 +64,8 @@ Verification was run with qpdf 12.4.2 (`qpdf --check`), poppler (`pdfinfo`, `pdf | `outline.pdf` | `/Outlines` root with two sibling items linked by `/First /Last /Next /Prev /Parent`, each with an explicit destination; `/PageMode /UseOutlines`. | 12.3.3, 12.3.2.2 | `qpdf --check`; `qpdf --json --json-key=outlines` lists both items with their destinations | clean | | `name-tree-dests.pdf` | `/Names << /Dests ... >>` name tree with a root `/Kids` node and two leaves carrying `/Limits` and `/Names` for `alpha`, `beta`, `gamma`. | 7.9.6, 12.3.2.3 | `qpdf --check` | clean | | `metadata-xmp.pdf` | Catalog `/Metadata` stream (`/Type /Metadata /Subtype /XML`) with a minimal XMP packet whose `dc:title` is `Broadside`, plus a trailer `/Info` dictionary with the same `/Title`. | 14.3.2, 14.3.3 | `pdfinfo` shows `Title: Broadside` | clean | +| `name-tree-deep.pdf` | `/Names << /Dests ... >>` name tree four levels deep (root `/Kids`, two levels of intermediate nodes, 20 leaves) holding 200 keys in byte order: `(a)` before `(ab)` (a key that is a prefix of another), PDFDocEncoding keys whose byte order differs from their text order (`<18>`, the breve, sorts first; `<80>` bullet before `` e-acute), and UTF-16BE keys with the byte order marker (`` also reads as "a"). Each value is `[3 0 R /XYZ 0 i null]`, `i` the key's position. | 7.9.6, Annex J.3.3, 12.3.2.4 | `qpdf --check` | qpdf 12.4.2 warns `keys are not sorted` on the root (object 31) because it compares keys as decoded text; the clause compares bytes, so for Broadside the file is clean | +| `number-tree-deep.pdf` | Twelve pages and a `/PageLabels` number tree three levels deep (root `/Kids`, two intermediate nodes, three leaves with `/Limits` and `/Nums`) with keys 0, 1, 2, 4, 5, 7, 8, 10, 11, so most pages fall between two keys. | 7.9.7, 12.4.2 | `qpdf --check`; `pdfinfo` reports 12 pages | clean | The crypt filter `/Length` entries in the R4 and R6 files are `16` and `32` (bytes), the form Acrobat and qpdf write and that Table 25 describes for the standard security handler; the same table also says the key "shall have the value of 128/256". Readers should accept both forms. @@ -81,6 +83,7 @@ Each file is `empty-page.pdf` (or `text-standard14.pdf`) with exactly one defect | `encrypted-mac-tampered.pdf` | `encrypted-mac.pdf` with one byte of a comment inside the MAC's byte range changed (`original` -> `Original`) after the MAC was computed. | ISO/TS 32004 6.6.2, B.2.2.3 | qpdf and poppler: clean (they do not check the MAC). | Open (the document is intact), record `IntegrityCodeMismatch` (Error, no offset or object): the file's digest does not match the token's `dataDigest`; `PdfSecurity.Integrity` is `Failed`. Strict mode throws it at open. | | `encrypted-owner-key-variant.pdf` | R3 40-bit RC4 whose `O` entry was computed rehashing only the first n bytes in Algorithm 3 step c (what qpdf and PDFBox write), not the whole digest the clause describes. | 7.6.4.4.2 Algorithm 3 step c | qpdf: clean, and `qpdf --password=owner` accepts the owner password. | Opens with the empty user password with no diagnostic. Opened with the owner password `owner`, record `OwnerPasswordKeyVariant` (Warning) and grant owner access. | | `encrypted-rc4-length-missing.pdf` | R3 (`/V 2`) RC4 with a 128-bit key but no `/Length` entry, so the key is 40 bits by Table 20's default. The case of qpdf's `bad-encryption-length.pdf`, which the real-world corpus gate (issue #47) found reported as "password required". | 7.6.2 Table 20 | qpdf (exit 3): `object 6 0 ... dictionary key /Length: operation for integer attempted on object of type null: returning 0`, then opens it (qpdf assumes 128 bits when Length is missing). pdfinfo and pdftotext: `Command Line Error: Incorrect password`. | No key of the default 40 bits authenticates, so 128 bits are tried: the empty user password authenticates, record `EncryptionKeyLengthInvalid` (Warning, no offset or object); `PdfSecurity.KeyLength` is 128 and the content decrypts to `RC4 128-bit (R3), no Length`. Strict mode throws it at open. | +| `name-tree-broken.pdf` | A `/Dests` name tree broken six ways: leaf 7's `/Limits [(a) (c)]` do not hold its key `(d)`; leaf 8's keys are out of order (`(f)` before `(e)`); intermediate node 6 has no `/Limits`; `(g)` is in leaf 8 and again in leaf 9; node 6's `/Kids` list the root 4 (a cycle); leaf 9's `/Names` has an odd length (a dangling `(i)`). | 7.9.6 | qpdf (exit 3): `keys are not sorted in validate` (object 4), `items array doesn't have enough elements` (object 9), `loop detected while traversing name/number tree` (object 4). pdfinfo: clean. | Opens with no diagnostic (the tree is read lazily). Walking the tree records, once per node and in this order: `NameTreeLimitsInvalid` 7, `NameTreeKeysUnsorted` 8, `NameTreeLimitsInvalid` 6, `NameTreeCycle` 4 (Error), `NameTreeNodeInvalid` 9, `NameTreeDuplicateKey` 9. Keys `a b d f e g h` resolve (`(g)` to leaf 8's value, the first in tree order); `(i)` has no value. Strict mode throws `NameTreeLimitsInvalid` 7 from the first lookup that needs the whole tree. | ## Password-protected files diff --git a/tests/Corpus/generate.py b/tests/Corpus/generate.py index 88922f6c..48e09520 100644 --- a/tests/Corpus/generate.py +++ b/tests/Corpus/generate.py @@ -1185,6 +1185,91 @@ def gen_name_tree_dests() -> bytes: ]) +def tree_key(key: bytes) -> bytes: + """A name-tree key as a PDF string: literal when printable ASCII, hexadecimal otherwise (7.3.4).""" + if all(0x20 <= b < 0x7F and b not in b"()\\" for b in key): + return b"(" + key + b")" + return b"<" + key.hex().upper().encode() + b">" + + +def build_tree(objects: list[tuple[int, bytes]], first_num: int, entries: list[tuple[bytes, bytes]], + fanouts: list[int], entries_key: bytes, key_bytes) -> int: + """7.9.6/7.9.7: lays sorted (key, value) pairs out as a balanced tree of indirect nodes, appended to + ``objects`` from ``first_num``. ``fanouts[0]`` pairs per leaf, then kids per node for each level up; + the root is written last, has only Kids and no Limits. Returns the root's object number.""" + num = first_num + level = [] # (num, least key, greatest key) + for i in range(0, len(entries), fanouts[0]): + chunk = entries[i:i + fanouts[0]] + pairs = b" ".join(key_bytes(k) + b" " + v for k, v in chunk) + objects.append((num, b"<< /Limits [%s %s] /%s [%s] >>" % ( + key_bytes(chunk[0][0]), key_bytes(chunk[-1][0]), entries_key, pairs))) + level.append((num, chunk[0][0], chunk[-1][0])) + num += 1 + for fanout in fanouts[1:]: + upper = [] + for i in range(0, len(level), fanout): + chunk = level[i:i + fanout] + kids = b" ".join(b"%d 0 R" % n for n, _, _ in chunk) + objects.append((num, b"<< /Limits [%s %s] /Kids [%s] >>" % ( + key_bytes(chunk[0][1]), key_bytes(chunk[-1][2]), kids))) + upper.append((num, chunk[0][1], chunk[-1][2])) + num += 1 + level = upper + objects.append((num, b"<< /Kids [%s] >>" % b" ".join(b"%d 0 R" % n for n, _, _ in level))) + return num + + +def gen_name_tree_deep() -> bytes: + """7.9.6, Table 36; 12.3.2.4: a Dests name tree four levels deep (root, two intermediate levels, + leaves) holding 200 keys, sorted byte by byte: a key that is a prefix of another ((a) before (ab)), + PDFDocEncoding keys whose byte order differs from their text order (<18> breve sorts before (A); + <80> bullet before e-acute), and UTF-16BE keys with the BOM ( also reads as "a"). + Each value is [3 0 R /XYZ 0 i null] where i is the key's position in byte order.""" + keys = [b"a", b"ab", b"\x18", b"\x80", b"\xe9", b"\xfe\xff\x00a", b"\xfe\xff\x00\xe9"] + keys += [b"n%03d" % i for i in range(1, 194)] + keys.sort() + entries = [(k, b"[3 0 R /XYZ 0 %d null]" % i) for i, k in enumerate(keys)] + objects = [(2, pages()), (3, page())] + root = build_tree(objects, 4, entries, [10, 4, 3], b"Names", tree_key) + return simple_file([(1, catalog(b" /Names << /Dests %d 0 R >>" % root))] + objects) + + +def gen_number_tree_deep() -> bytes: + """7.9.7, Table 37; 12.4.2: twelve pages whose /PageLabels number tree has three levels (root, + intermediate nodes, leaves) and nine keys, so a page between two keys takes the nearest lower key.""" + labels = [(0, b"<< /S /r >>"), (1, b"<< /S /D >>"), (2, b"<< /S /D /St 10 >>"), (4, b"<< /P (A-) >>"), + (5, b"<< /S /A >>"), (7, b"<< /S /a /P (x) >>"), (8, b"<< /S /R /St 4 >>"), + (10, b"<< /S /D /P (B-) /St 1 >>"), (11, b"<< /S /D >>")] + objects: list[tuple[int, bytes]] = [] + root = build_tree(objects, 3, [(str(k).encode(), v) for k, v in labels], [3, 2], b"Nums", + lambda k: k) + first_page = root + 1 + page_nums = list(range(first_page, first_page + 12)) + return simple_file([(1, catalog(b" /PageLabels %d 0 R" % root)), (2, pages(page_nums))] + + objects + [(n, page()) for n in page_nums]) + + +def gen_name_tree_broken() -> bytes: + """7.9.6, Table 36, broken six ways: leaf 7's Limits [(a) (c)] do not hold its key (d); leaf 8's + keys are not sorted ((f) before (e)); intermediate node 6 has no Limits; key (g) is in leaf 8 and + again in leaf 9; node 6's Kids list the root 4 (a cycle); leaf 9's Names array has an odd length + (a dangling key (i)). Every key still resolves.""" + def dest(top: int) -> bytes: + return b"[3 0 R /XYZ 0 %d null]" % top + return simple_file([ + (1, catalog(b" /Names << /Dests 4 0 R >>")), + (2, pages()), + (3, page()), + (4, b"<< /Kids [5 0 R 6 0 R] >>"), + (5, b"<< /Limits [(a) (g)] /Kids [7 0 R 8 0 R] >>"), + (6, b"<< /Kids [9 0 R 4 0 R] >>"), + (7, b"<< /Limits [(a) (c)] /Names [(a) %s (b) %s (d) %s] >>" % (dest(1), dest(2), dest(4))), + (8, b"<< /Limits [(e) (g)] /Names [(f) %s (e) %s (g) %s] >>" % (dest(6), dest(5), dest(7))), + (9, b"<< /Limits [(g) (i)] /Names [(g) %s (h) %s (i)] >>" % (dest(70), dest(8))), + ]) + + XMP = (b'\n' b'\n' b' \n' @@ -1249,6 +1334,9 @@ def gen_metadata_xmp() -> bytes: "outline.pdf": gen_outline, "name-tree-dests.pdf": gen_name_tree_dests, "metadata-xmp.pdf": gen_metadata_xmp, + "name-tree-deep.pdf": gen_name_tree_deep, + "number-tree-deep.pdf": gen_number_tree_deep, + "name-tree-broken.pdf": gen_name_tree_broken, } diff --git a/tests/Corpus/name-tree-broken.pdf b/tests/Corpus/name-tree-broken.pdf new file mode 100644 index 0000000000000000000000000000000000000000..871a3fd9250d8370294a448186f0415952563a9b GIT binary patch literal 992 zcmZuwOK*Ze5We#(=3;_}7FeDphC^$;^kr-hZHl)3$Si^!}Br)Yr#`d14Fk>0oNs0FF_`HX4J0*esgX`4Ek%{UNegWE z)Ab;}0`@$%o-tlCo>rS}`?m|td+;_TC zpga)T&*iI5s&~SnJFR5kjzlx-&OTJKmC2`W5~&U;oKNsriJgH?;m4uX7#ng~hzF_R+zUAO0?wP@0cqTT;l-<3Q}HYpRr`IuWWNGu c!;>#d`hw_|arV05Rntx$vd|cf?w;qyA3YQIq5uE@ literal 0 HcmV?d00001 diff --git a/tests/Corpus/name-tree-deep.pdf b/tests/Corpus/name-tree-deep.pdf new file mode 100644 index 0000000000000000000000000000000000000000..d055ddb31bf8270a922156536db087a09ecb5348 GIT binary patch literal 8714 zcmZ|V&2HQ_6b0bDpF*1e@uIbkB$5(fc+n=_^e>op(Kg6p(o6yuiCx$ZkoM_&NzPbD z_b`J1fiI~m&NpKX&&bbSy}14c-=;HkeRucv@3YIx?&7z9|2cFQ-|rvyAMZYN7q9jo z4iDX66L#Ij&-+jIL!R~G@bLK1jrqV`cXeg|&JMTla*sT9+pD&?_~GW=L-%^jN4&8U z+_7+R5j`-k;QnA!k4yOJ@a|^+-QAb&b#L<{hAu6G_1hgD?mplDRhPF}&_sQI zy!muv>wbNS`Ko(<+xO|*j;&9t7V84Li{JnF(~j%A+s_|AzUiLt&yPz#jo@kItsfdr zL)IUDaHPS(4^A{V`oTbhlOK#U82n(O!RQBP8ccq0se^CmWeN?>EIFTNP%!ARyd}kx zsU5WV6XMC$di63&v=Ca5EyNat3&92HLUcjA5MGck#1{l?I{t0c5RPqORN=u1=kiu~ zAYq8`K*ECv4!h;A8By2ifqamEy!b24vop3I1 zg+~$|MA)v1$E(I|KZ@{3!lMX}Bs_}nNW!BCk0d;b@JPa=2#+K@ittFnrsFjl!gE`A ztiqEM&gHG}M8cy8Pb55v@I=Cs2u~zDiSR_ilL${FJc;l`!jlM3Bs_`mM8c-yH5$T8 zTX?F%!3pQ`RydIGB*KA&g9rx_4k8>#IEZi{;UL0+go6kN5)L99NH~aaAYs$-8VzCl zq*`|*r=5d+riDrz9dRyii6apQA&x{Gg*Xy%6yiw4QHUcEM( ziHJ?dYqW@YLr%o063>n}m$$?-5ho#@iFg*`nTTg0o{4xC;+cqNA)bkN7UG$RXCa=6 zcoyQBh)u_9w1_#n5b<1z7e}1STjGU?XCYpQcoE`-h!-JVh7>wW^&f(TiET4hnn%=GF~Y=YzldH201CEJTy|Ch5FM5 z8jYAoIS-ATM?nvbphrm$jig6W4~?itSr3h@M`15Bd2F<>+i?#y?!m>qQg+ys_n>(X z6!@Tl50v<9sw|lzpH00K1#~xbP?c`^z^0yao z$*+_hHbp;Z^aEu-X!ZkzKbtB`ru1i1b(pX<{(6ah1n#~xeQ z?GR|K3bqS@rR=aN1wvCGCgsn*s6a}GC5R?UNsx~KV4TGRG z2u*{STG;J8Xsrsi%Y&utuqhDQ8DzrJP1WXvt?>|) z525)G6cBByHYaRNh@glFjfjXX>~==9Rt4K-#8P(H6cX(WvSdn$(3A*@iO`q`%852r zn-jJMMNm?NCPh$Gw5i&hur(`!!Xh**BDJvFY0+90Y?l^G*9L7~y6YIDNY)Ch`=(AbE%h274L*6O^wyncCo-S;n-tMvwz z?NBs3g2JPnMV3wJ(WdG!?X@*Ng7PCYKY{|JP1WY7U~@V5SANUz6d*6{Ny^{}`{)p% zQ%=EVrIIc!^j4BQ-4CoAz0W0$DD}s$x$C8=cFTLA zU6((kcU}2n(f%uUPdEMAS)f1u_SN83`&mXRt;+q>&N5H=sjPO>@hcnNW4fr@f@8<} zBrV~TR&~LaSnQ`w$FJ<_@@L=rO4ysWb}b*3yUs#L?rLG9{8v`J>Dt=99AA}V;5_!L z&(wlNX;jwCjckA3{AkWkxV60cY%NN-r&(@opKeDVPhDTVa)u4bm;1x}v%VXLv;OJP z#Sm;m{=Qplc6fetw`{y8&?~9+YS5LWUKYHWE(kGn=F$`ZBiF2$-FRFn0Ng`un!<#TXcPK%)f>C zv6{wcAIGkidJ7@GHrZDYQnM?(uLaxB_*%4$w67%#e!e#AYnf*Ivd_<3?A!jQ+T;EH y=HubM{2|A$H~$^%J!yX$ad(&h(jx!9*rn^?aex0<-m$aYv_E_H?By@lXa56D8B)jq literal 0 HcmV?d00001 diff --git a/tests/Corpus/number-tree-deep.pdf b/tests/Corpus/number-tree-deep.pdf new file mode 100644 index 0000000000000000000000000000000000000000..e996f699637fc397b9750b7cd3cc5c1fc282e40c GIT binary patch literal 2204 zcmcIm%TDV+4Bh7|yr~2W$T+V_B!t9sbGetQWrw;5bU;C+K}jn0^7Ys=O*5TgnPxMw zV;|ddY`2r??fn^^%K$+@{qhl9TtN8r|4Tu5Q+DO5eur>czN;1@GME|Rp?p!R7ILk* zybRQO$*yd12w^M*h7nDO?Z#xdZo3qXpXSc?VBUHUV`6yKwAzNuY;R~fklTklu2IDCuK)h3 zWmR6+Tjo?iM$F5Cxt*!D-ZZb&sB{~2Eki%(jynplKQkj`{QD%0a257!jC#lRV2lcE z&%~&}_5h3uY>&vO!1g4K3Vf`|(_8u&lecZuTR=M<1F?S~OVc=oHyCtO7eBBbbdqRy zbP>`VJGxlVq`10*n00iip#F4q8Eqy Date: Fri, 9 Oct 2026 16:10:45 -0500 Subject: [PATCH 021/152] feat(document): Info, XMP metadata, viewer preferences, extensions and requirements (#69) Live views over the catalog and trailer entries of ISO 32000-2 7.7.2, 7.12, 12.2, 12.11, 14.3 and 14.4, with lazy diagnostics, and five corpus files. Co-Authored-By: Claude Opus 5.5 --- src/Broadside/DictionaryView.cs | 102 ++++++ src/Broadside/PdfDeveloperExtension.cs | 61 ++++ src/Broadside/PdfDocument.Catalog.cs | 345 ++++++++++++++++++ src/Broadside/PdfDocument.cs | 2 +- src/Broadside/PdfDocumentInformation.cs | 153 ++++++++ src/Broadside/PdfDocumentProperties.cs | 52 +++ src/Broadside/PdfDuplex.cs | 15 + src/Broadside/PdfFileIdentifier.cs | 29 ++ src/Broadside/PdfMetadata.cs | 41 +++ src/Broadside/PdfPageBoundary.cs | 21 ++ src/Broadside/PdfPageLayout.cs | 24 ++ src/Broadside/PdfPageMode.cs | 24 ++ src/Broadside/PdfPageRange.cs | 48 +++ src/Broadside/PdfPrintScaling.cs | 12 + src/Broadside/PdfReadingDirection.cs | 12 + src/Broadside/PdfRequirement.cs | 105 ++++++ src/Broadside/PdfRequirementHandler.cs | 34 ++ src/Broadside/PdfTrapped.cs | 18 + src/Broadside/PdfViewerPreferences.cs | 275 ++++++++++++++ src/Broadside/PublicAPI.Unshipped.txt | 124 +++++++ tests/Broadside.TestSupport/Corpus.cs | 5 + .../Document/CatalogEntryTests.cs | 263 +++++++++++++ .../Document/DocumentInformationTests.cs | 332 +++++++++++++++++ ...pus_file_names_match_snapshot.verified.txt | 5 + tests/Corpus/README.md | 5 + tests/Corpus/catalog-version-extensions.pdf | Bin 0 -> 787 bytes tests/Corpus/generate.py | 104 ++++++ tests/Corpus/info-dictionary.pdf | Bin 0 -> 750 bytes tests/Corpus/metadata-xmp-forms.pdf | Bin 0 -> 3957 bytes tests/Corpus/page-labels.pdf | Bin 0 -> 1775 bytes tests/Corpus/viewer-preferences.pdf | Bin 0 -> 869 bytes 31 files changed, 2210 insertions(+), 1 deletion(-) create mode 100644 src/Broadside/DictionaryView.cs create mode 100644 src/Broadside/PdfDeveloperExtension.cs create mode 100644 src/Broadside/PdfDocument.Catalog.cs create mode 100644 src/Broadside/PdfDocumentInformation.cs create mode 100644 src/Broadside/PdfDocumentProperties.cs create mode 100644 src/Broadside/PdfDuplex.cs create mode 100644 src/Broadside/PdfFileIdentifier.cs create mode 100644 src/Broadside/PdfMetadata.cs create mode 100644 src/Broadside/PdfPageBoundary.cs create mode 100644 src/Broadside/PdfPageLayout.cs create mode 100644 src/Broadside/PdfPageMode.cs create mode 100644 src/Broadside/PdfPageRange.cs create mode 100644 src/Broadside/PdfPrintScaling.cs create mode 100644 src/Broadside/PdfReadingDirection.cs create mode 100644 src/Broadside/PdfRequirement.cs create mode 100644 src/Broadside/PdfRequirementHandler.cs create mode 100644 src/Broadside/PdfTrapped.cs create mode 100644 src/Broadside/PdfViewerPreferences.cs create mode 100644 tests/Broadside.Tests/Document/CatalogEntryTests.cs create mode 100644 tests/Broadside.Tests/Document/DocumentInformationTests.cs create mode 100644 tests/Corpus/catalog-version-extensions.pdf create mode 100644 tests/Corpus/info-dictionary.pdf create mode 100644 tests/Corpus/metadata-xmp-forms.pdf create mode 100644 tests/Corpus/page-labels.pdf create mode 100644 tests/Corpus/viewer-preferences.pdf diff --git a/src/Broadside/DictionaryView.cs b/src/Broadside/DictionaryView.cs new file mode 100644 index 00000000..b641bd86 --- /dev/null +++ b/src/Broadside/DictionaryView.cs @@ -0,0 +1,102 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// +/// Reads the entries of one dictionary for a document-model view: resolves references, applies defaults without writing them, and +/// reports a deviation against the dictionary's object (ADR 0004: views read through, never copy; ADR 0005: lenient with diagnostics). +/// +/// The document the dictionary belongs to. +/// The dictionary. +/// The object diagnostics are reported against: the dictionary's own reference, or the object holding it directly. +internal readonly record struct DictionaryView(PdfDocument Document, CosDictionary Dictionary, CosReference? Reference) +{ + /// Returns the entry for , resolved; when absent or a reference to nothing. + public CosObject? Get(CosName key) => + Dictionary.TryGetValue(key, out CosObject? value) && Document.Resolve(value) is not CosNull and var resolved ? resolved : null; + + /// Reports a deviation in the dictionary. + public void Report(string code, string message, DiagnosticSeverity severity = DiagnosticSeverity.Warning) => + Document.DiagnosticSink.Report(code, severity, message, objectReference: Reference); + + /// Reads a boolean entry; any other type reads as with a diagnostic. + public bool? ReadBoolean(CosName key, string code, bool? fallback) + { + switch (Get(key)) + { + case null: + return fallback; + case CosBoolean boolean: + return boolean.Value; + default: + Report(code, $"The {key.Value} entry shall be a boolean; it is ignored."); + return fallback; + } + } + + /// Reads a name entry from a fixed set; an unknown name or another type reads as with a diagnostic. + public T? ReadName(CosName key, string code, T? fallback, params ReadOnlySpan<(string Name, T Value)> names) + where T : struct, Enum + { + CosObject? value = Get(key); + if (value is null) + { + return fallback; + } + + if (value is CosName name) + { + foreach ((string text, T member) in names) + { + if (string.Equals(name.Value, text, StringComparison.Ordinal)) + { + return member; + } + } + } + + Report(code, $"The {key.Value} entry is not one of the names the specification defines for it; the default is used."); + return fallback; + } + + /// Reads a text string entry (§7.9.2.2); a name or number reads as its text and anything else as null, with a diagnostic. + public string? ReadText(CosName key, string code) + { + switch (Get(key)) + { + case null: + return null; + case CosString text: + return text.DecodeText(); + case CosName name: + Report(code, $"The {key.Value} entry shall be a text string; it is a name, read as its text."); + return name.Value; + case CosInteger integer: + Report(code, $"The {key.Value} entry shall be a text string; it is a number, read as its text."); + return integer.Value.ToString(System.Globalization.CultureInfo.InvariantCulture); + case CosReal real: + Report(code, $"The {key.Value} entry shall be a text string; it is a number, read as its text."); + return real.Value.ToString(System.Globalization.CultureInfo.InvariantCulture); + default: + Report(code, $"The {key.Value} entry shall be a text string; it is ignored."); + return null; + } + } + + /// Reads an integer entry; anything else reads as null with a diagnostic. + public int? ReadInteger(CosName key, string code) + { + switch (Get(key)) + { + case null: + return null; + case CosInteger { Value: >= int.MinValue and <= int.MaxValue } integer: + return (int)integer.Value; + default: + Report(code, $"The {key.Value} entry shall be an integer; it is ignored."); + return null; + } + } +} diff --git a/src/Broadside/PdfDeveloperExtension.cs b/src/Broadside/PdfDeveloperExtension.cs new file mode 100644 index 00000000..86f94f2a --- /dev/null +++ b/src/Broadside/PdfDeveloperExtension.cs @@ -0,0 +1,61 @@ +using Broadside.Objects; + +namespace Broadside; + +/// One developer extension the document declares: an entry of the catalog's Extensions dictionary. +/// +/// +/// ISO 32000-2 §7.12, Tables 48 and 49. Each key of the extensions dictionary other than Type is a registered developer +/// prefix (Annex E), such as ADBE or ISO_; its value is a developer extensions dictionary or, in PDF 2.0, an array of +/// them (ISO/TS 32001 and its siblings declare themselves as /ISO_ [...]). Each dictionary in an array is one extension. +/// +/// +/// A live view over the developer extensions dictionary. A missing or malformed BaseVersion or ExtensionLevel (both +/// required) reads as , reported when is read. +/// +/// +public sealed class PdfDeveloperExtension +{ + private static readonly CosName BaseVersionKey = new("BaseVersion"); + private static readonly CosName UrlKey = new("URL"); + private static readonly CosName ExtensionRevisionKey = new("ExtensionRevision"); + + private readonly PdfDocument _document; + + internal PdfDeveloperExtension(PdfDocument document, CosName prefix, CosDictionary dictionary) + { + _document = document; + Prefix = prefix; + Dictionary = dictionary; + } + + /// Gets the developer prefix the extension is declared under, such as ADBE or ISO_. + /// ISO 32000-2 §7.12.2, Table 48, and Annex E. + public CosName Prefix { get; } + + /// Gets the developer extensions dictionary. + /// ISO 32000-2 §7.12.3, Table 49. + public CosDictionary Dictionary { get; } + + /// Gets the PDF version the extension applies to (BaseVersion), or when missing or malformed. + /// ISO 32000-2 §7.12.4. + public PdfVersion? BaseVersion => ReadBaseVersion(_document, Dictionary); + + /// Gets the developer's extension level (ExtensionLevel), or when missing or not an integer. + /// ISO 32000-2 §7.12.5. + public int? ExtensionLevel => ReadExtensionLevel(_document, Dictionary); + + /// Gets the URL of the extension's documentation (URL, PDF 2.0), or when absent or not an absolute URI. + /// ISO 32000-2 §7.12.3, Table 49. The raw string stays in . + public Uri? Url => _document.Resolve(Dictionary.GetValueOrDefault(UrlKey)) is CosString url && Uri.TryCreate(url.DecodeText(), UriKind.Absolute, out Uri? uri) ? uri : null; + + /// Gets further revision information on the extension level (ExtensionRevision, PDF 2.0), or . + /// ISO 32000-2 §7.12.6. + public string? ExtensionRevision => _document.Resolve(Dictionary.GetValueOrDefault(ExtensionRevisionKey)) is CosString revision ? revision.DecodeText() : null; + + internal static PdfVersion? ReadBaseVersion(PdfDocument document, CosDictionary dictionary) => + document.Resolve(dictionary.GetValueOrDefault(BaseVersionKey)) is CosName name && PdfVersion.TryParse(name.Bytes, out PdfVersion version) ? version : null; + + internal static int? ReadExtensionLevel(PdfDocument document, CosDictionary dictionary) => + document.Resolve(dictionary.GetValueOrDefault(KnownNames.ExtensionLevel)) is CosInteger { Value: >= int.MinValue and <= int.MaxValue } level ? (int)level.Value : null; +} diff --git a/src/Broadside/PdfDocument.Catalog.cs b/src/Broadside/PdfDocument.Catalog.cs new file mode 100644 index 00000000..e90596fb --- /dev/null +++ b/src/Broadside/PdfDocument.Catalog.cs @@ -0,0 +1,345 @@ +using Broadside.Caching; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// The document-level entries of the catalog and the trailer (issue #69): ISO 32000-2 §7.7.2, §7.12, §12.2, §12.11, §14.3, §14.4. +public sealed partial class PdfDocument +{ + private static readonly CosName PageLayoutKey = new("PageLayout"); + private static readonly CosName PageModeKey = new("PageMode"); + private static readonly CosName ViewerPreferencesKey = new("ViewerPreferences"); + private static readonly CosName LangKey = new("Lang"); + private static readonly CosName MetadataKey = new("Metadata"); + private static readonly CosName RequirementsKey = new("Requirements"); + private static readonly CosName MetadataType = new("Metadata"); + private static readonly CosName SubtypeKey = new("Subtype"); + private static readonly CosName XmlSubtype = new("XML"); + + private readonly OnceCache _xmpPackets = new(); + + /// Gets the version the file header states, or when the header has no valid version. + /// ISO 32000-2 §7.5.2. is the version the document conforms to. + public PdfVersion? HeaderVersion => _loader.Header.Version; + + /// Gets the catalog's Version entry, or when it has none (or none that is a version). + /// + /// ISO 32000-2 §7.7.2, Table 29 (PDF 1.4): it overrides the header when later, so an incremental update can raise the version + /// without rewriting the header. Read from the catalog on every call. is the version the document conforms to. + /// + public PdfVersion? CatalogVersion => ReadCatalogVersion(Catalog, diagnostics: null); + + /// Gets how a viewer lays the pages out when the document opens (PageLayout). Default . + /// ISO 32000-2 §7.7.2, Table 29. An unknown name reads as the default with a PageLayoutInvalid diagnostic. + public PdfPageLayout PageLayout => CatalogView.ReadName( + PageLayoutKey, + DiagnosticCodes.PageLayoutInvalid, + PdfPageLayout.SinglePage, + ("SinglePage", PdfPageLayout.SinglePage), + ("OneColumn", PdfPageLayout.OneColumn), + ("TwoColumnLeft", PdfPageLayout.TwoColumnLeft), + ("TwoColumnRight", PdfPageLayout.TwoColumnRight), + ("TwoPageLeft", PdfPageLayout.TwoPageLeft), + ("TwoPageRight", PdfPageLayout.TwoPageRight))!.Value; + + /// Gets which panel a viewer shows when the document opens (PageMode). Default . + /// ISO 32000-2 §7.7.2, Table 29. An unknown name reads as the default with a PageModeInvalid diagnostic. + public PdfPageMode PageMode => CatalogView.ReadName( + PageModeKey, + DiagnosticCodes.PageModeInvalid, + PdfPageMode.UseNone, + ("UseNone", PdfPageMode.UseNone), + ("UseOutlines", PdfPageMode.UseOutlines), + ("UseThumbs", PdfPageMode.UseThumbs), + ("FullScreen", PdfPageMode.FullScreen), + ("UseOC", PdfPageMode.UseOC), + ("UseAttachments", PdfPageMode.UseAttachments))!.Value; + + /// + /// Gets the viewer preferences (ViewerPreferences), or when the catalog has none: the viewer's own + /// preferences then apply. + /// + /// ISO 32000-2 §7.7.2, Table 29, and §12.2. An entry that is not a dictionary is ignored with a ViewerPreferencesInvalid diagnostic. + public PdfViewerPreferences? ViewerPreferences + { + get + { + Catalog.TryGetValue(ViewerPreferencesKey, out CosObject? entry); + switch (Resolve(entry)) + { + case CosNull: + return null; + case CosDictionary preferences: + return new PdfViewerPreferences(this, preferences, entry as CosReference ?? CatalogReference); + default: + CatalogView.Report(DiagnosticCodes.ViewerPreferencesInvalid, "The catalog's ViewerPreferences entry shall be a dictionary; it is ignored."); + return null; + } + } + } + + /// Gets the natural language of the document's text (Lang), such as en-US, or when unknown. + /// ISO 32000-2 §7.7.2, Table 29 (PDF 1.4), and §14.9.2. Not checked against BCP 47. + public string? Language => CatalogView.ReadText(LangKey, DiagnosticCodes.CatalogEntryInvalid); + + /// Gets the developer extensions the document declares (Extensions), in the order written; empty when none. + /// + /// ISO 32000-2 §7.12, Tables 48 and 49. A prefix whose value is an array (PDF 2.0) contributes one extension per dictionary in it. + /// Deviations are reported when this property is read: an entry that is not a dictionary (ExtensionsInvalid), a prefix value + /// that is neither a developer extensions dictionary nor an array of them or that lacks a required entry + /// (DeveloperExtensionInvalid), and indirect references where everything "shall be direct objects" (ExtensionsNotDirect). + /// + public IReadOnlyList Extensions + { + get + { + Catalog.TryGetValue(KnownNames.Extensions, out CosObject? entry); + CosObject value = Resolve(entry); + if (value is CosNull) + { + return []; + } + + DictionaryView catalog = CatalogView; + if (value is not CosDictionary extensions) + { + catalog.Report(DiagnosticCodes.ExtensionsInvalid, "The catalog's Extensions entry shall be a dictionary; it is ignored."); + return []; + } + + bool indirect = entry is CosReference; + var result = new List(); + foreach (KeyValuePair pair in extensions) + { + if (KnownNames.Type.Equals(pair.Key)) + { + continue; + } + + indirect |= pair.Value is CosReference; + switch (Resolve(pair.Value)) + { + case CosDictionary dictionary: + AddExtension(pair.Key, dictionary); + break; + case CosArray array: + foreach (CosObject element in array) + { + indirect |= element is CosReference; + if (Resolve(element) is CosDictionary item) + { + AddExtension(pair.Key, item); + } + else + { + ReportExtension(pair.Key); + } + } + + break; + default: + ReportExtension(pair.Key); + break; + } + } + + if (indirect) + { + catalog.Report(DiagnosticCodes.ExtensionsNotDirect, "The extensions dictionary and the developer extensions dictionaries shall be direct objects; they are read through their references."); + } + + return result; + + void AddExtension(CosName prefix, CosDictionary dictionary) + { + if (PdfDeveloperExtension.ReadBaseVersion(this, dictionary) is null || PdfDeveloperExtension.ReadExtensionLevel(this, dictionary) is null) + { + ReportExtension(prefix); + } + + result.Add(new PdfDeveloperExtension(this, prefix, dictionary)); + } + + void ReportExtension(CosName prefix) => catalog.Report( + DiagnosticCodes.DeveloperExtensionInvalid, + $"The developer extension {prefix.Value} shall be a dictionary, or an array of dictionaries, with a BaseVersion name and an ExtensionLevel integer."); + } + } + + /// Gets the requirements the document places on an interactive processor (Requirements, PDF 1.7); empty when none. + /// + /// ISO 32000-2 §7.7.2, Table 29, and §12.11. Exposed, never evaluated. An entry that is not an array of requirement dictionaries, + /// a requirement without its type or with a penalty outside 0 to 100, and handlers that are not dictionaries are reported as + /// RequirementInvalid when this property is read; elements that are not dictionaries are skipped. + /// + public IReadOnlyList Requirements + { + get + { + CosObject value = Resolve(Catalog.GetValueOrDefault(RequirementsKey)); + if (value is CosNull) + { + return []; + } + + const string Message = "The catalog's Requirements entry shall be an array of requirement dictionaries, each with a type and a penalty from 0 to 100 (Table 273)."; + if (value is not CosArray array) + { + CatalogView.Report(DiagnosticCodes.RequirementInvalid, Message); + return []; + } + + var requirements = new List(array.Count); + bool invalid = false; + foreach (CosObject element in array) + { + if (Resolve(element) is CosDictionary dictionary) + { + invalid |= !PdfRequirement.IsWellFormed(this, dictionary); + requirements.Add(new PdfRequirement(this, dictionary)); + } + else + { + invalid = true; + } + } + + if (invalid) + { + CatalogView.Report(DiagnosticCodes.RequirementInvalid, Message); + } + + return requirements; + } + } + + /// Gets the document information dictionary (the trailer's Info), or when the document has none. + /// + /// ISO 32000-2 §14.3.3 and §7.5.5, Table 15. An entry that is not a dictionary is ignored with an InfoDictionaryInvalid + /// diagnostic. resolves it against the XMP metadata. + /// + public PdfDocumentInformation? Information + { + get + { + Trailer.TryGetValue(KnownNames.Info, out CosObject? entry); + switch (Resolve(entry)) + { + case CosNull: + return null; + case CosDictionary info: + return new PdfDocumentInformation(this, info, entry as CosReference); + default: + _diagnostics.Report( + DiagnosticCodes.InfoDictionaryInvalid, + DiagnosticSeverity.Warning, + "The trailer's Info entry shall refer to the document information dictionary; it is ignored.", + objectReference: entry as CosReference); + return null; + } + } + } + + /// Gets the document's metadata stream (the catalog's Metadata), or when the document has none. + /// + /// ISO 32000-2 §14.3.2, Table 347. An entry that is not a stream is ignored with a MetadataStreamInvalid diagnostic; a + /// stream whose Type is not Metadata or whose Subtype is not XML is read with a + /// MetadataStreamTypeInvalid diagnostic. + /// + public PdfMetadata? Metadata + { + get + { + Catalog.TryGetValue(MetadataKey, out CosObject? entry); + switch (Resolve(entry)) + { + case CosNull: + return null; + case CosStream stream: + CosReference? reference = entry as CosReference; + if (!MetadataType.Equals(Resolve(stream.Dictionary.GetValueOrDefault(KnownNames.Type))) + || !XmlSubtype.Equals(Resolve(stream.Dictionary.GetValueOrDefault(SubtypeKey)))) + { + _diagnostics.Report( + DiagnosticCodes.MetadataStreamTypeInvalid, + DiagnosticSeverity.Warning, + "A metadata stream shall have Type Metadata and Subtype XML; it is read as XMP anyway.", + objectReference: reference); + } + + return new PdfMetadata(this, stream, reference); + default: + CatalogView.Report(DiagnosticCodes.MetadataStreamInvalid, "The catalog's Metadata entry shall be a metadata stream; it is ignored."); + return null; + } + } + } + + /// Gets the common document properties, each from the XMP metadata when it has it and from the Info dictionary otherwise. + /// ISO 32000-2 §14.3.1, §14.3.3 and §14.3.4. + public PdfDocumentProperties Properties => new(this); + + /// Gets the file identifier (the trailer's ID), or when the trailer has none or it is not two strings. + /// + /// ISO 32000-2 §14.4 and §7.5.5, Table 15: an array of two byte strings, each at least 16 bytes. Shorter strings are kept as they + /// are; an entry that is not two strings is ignored. Both are reported as FileIdentifierInvalid. + /// + public PdfFileIdentifier? FileIdentifier + { + get + { + CosObject value = Resolve(Trailer.GetValueOrDefault(KnownNames.ID)); + if (value is CosNull) + { + return null; + } + + if (value is not CosArray { Count: 2 } array || Resolve(array[0]) is not CosString permanent || Resolve(array[1]) is not CosString changing) + { + _diagnostics.Report(DiagnosticCodes.FileIdentifierInvalid, DiagnosticSeverity.Warning, "The trailer's ID entry shall be an array of two byte strings; it is ignored."); + return null; + } + + if (permanent.Bytes.Length < 16 || changing.Bytes.Length < 16) + { + _diagnostics.Report(DiagnosticCodes.FileIdentifierInvalid, DiagnosticSeverity.Warning, "Each file identifier shall be at least 16 bytes long; the shorter ones are used as they are."); + } + + return new PdfFileIdentifier(permanent.Bytes.ToArray(), changing.Bytes.ToArray()); + } + } + + /// Gets the sink the document's views report deviations to. + internal DiagnosticSink DiagnosticSink => _diagnostics; + + /// Gets the indirect reference to the catalog, when the trailer has one. + internal CosReference? CatalogReference => Trailer.GetValueOrDefault(KnownNames.Root) as CosReference; + + private DictionaryView CatalogView => new(this, Catalog, CatalogReference); + + /// + /// Returns the XMP packet of a metadata stream: parsed once and kept while the stream is unchanged, parsed again on every read once it + /// has been changed (dirty tracking is sticky, so a changed stream is never served from the cache). + /// + internal XmpPacket? ReadXmpPacket(CosStream stream, CosReference? reference) + { + return stream.IsDirty + ? Parse((stream, reference, this)) + : _xmpPackets.GetOrCreate( + stream, + (stream, reference, this), + static (_, state) => new Created(Parse(state)), + static (_, _) => null); + + static XmpPacket? Parse((CosStream Stream, CosReference? Reference, PdfDocument Document) state) + { + ReadOnlyMemory data = state.Document.DecodeStream(state.Stream); + DiagnosticSink sink = state.Document._diagnostics; + return XmpPacketReader.Read( + data.Span, + (code, severity, message) => sink.Report(code, severity, message, objectReference: state.Reference)); + } + } +} diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 5c0e9ec2..5f0a9f25 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -46,7 +46,7 @@ namespace Broadside; /// . /// /// -public sealed class PdfDocument : IDisposable +public sealed partial class PdfDocument : IDisposable { private static readonly PdfVersion Pdf20 = new(2, 0); diff --git a/src/Broadside/PdfDocumentInformation.cs b/src/Broadside/PdfDocumentInformation.cs new file mode 100644 index 00000000..438c2558 --- /dev/null +++ b/src/Broadside/PdfDocumentInformation.cs @@ -0,0 +1,153 @@ +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// The document information dictionary: a live view over the trailer's Info entry. +/// +/// +/// ISO 32000-2 §14.3.3, Table 349. Every entry is a text string except the two dates (§7.9.4) and Trapped (a name); keys the +/// table does not define are allowed and "shall be text strings". PDF 2.0 deprecates every entry except CreationDate and +/// ModDate in favour of the XMP metadata stream (); +/// resolves the two sources. +/// +/// +/// Every property reads the dictionary when called; nothing is ever written to it. A value of the wrong type is read as its text +/// where it has one (a name, a number) and otherwise as absent, and a date that does not follow §7.9.4 is repaired when it can be; +/// each records a diagnostic the first time it is read (in strict mode, the property throws). The raw text of a date that cannot +/// be read stays available through . +/// +/// +public sealed class PdfDocumentInformation +{ + private static readonly CosName TitleKey = new("Title"); + private static readonly CosName AuthorKey = new("Author"); + private static readonly CosName SubjectKey = new("Subject"); + private static readonly CosName KeywordsKey = new("Keywords"); + private static readonly CosName CreatorKey = new("Creator"); + private static readonly CosName ProducerKey = new("Producer"); + private static readonly CosName CreationDateKey = new("CreationDate"); + private static readonly CosName ModDateKey = new("ModDate"); + private static readonly CosName TrappedKey = new("Trapped"); + + private readonly DictionaryView _view; + + internal PdfDocumentInformation(PdfDocument document, CosDictionary dictionary, CosReference? reference) + { + _view = new DictionaryView(document, dictionary, reference); + } + + /// Gets the document information dictionary. + /// ISO 32000-2 §14.3.3, Table 349. + public CosDictionary Dictionary => _view.Dictionary; + + /// Gets the document's title (Title, PDF 1.1; deprecated in PDF 2.0 for dc:title). + /// ISO 32000-2 §14.3.3, Table 349. + public string? Title => ReadText(TitleKey); + + /// Gets the name of the person who created the document (Author; deprecated in PDF 2.0 for dc:creator). + /// ISO 32000-2 §14.3.3, Table 349. + public string? Author => ReadText(AuthorKey); + + /// Gets the subject of the document (Subject, PDF 1.1; deprecated in PDF 2.0 for dc:description). + /// ISO 32000-2 §14.3.3, Table 349. + public string? Subject => ReadText(SubjectKey); + + /// Gets the keywords associated with the document (Keywords, PDF 1.1; deprecated in PDF 2.0 for pdf:Keywords). + /// ISO 32000-2 §14.3.3, Table 349. + public string? Keywords => ReadText(KeywordsKey); + + /// + /// Gets the name of the application that created the original document, when it was converted to PDF (Creator; deprecated + /// in PDF 2.0 for xmp:CreatorTool). + /// + /// ISO 32000-2 §14.3.3, Table 349. + public string? Creator => ReadText(CreatorKey); + + /// Gets the name of the application that converted the document to PDF (Producer; deprecated in PDF 2.0 for pdf:Producer). + /// ISO 32000-2 §14.3.3, Table 349. + public string? Producer => ReadText(ProducerKey); + + /// Gets the date and time the document was created (CreationDate), or when absent or not a date. + /// ISO 32000-2 §14.3.3, Table 349, and §7.9.4. + public PdfDate? CreationDate => ReadDate(CreationDateKey); + + /// Gets the date and time the document was most recently modified (ModDate, PDF 1.1), or when absent or not a date. + /// ISO 32000-2 §14.3.3, Table 349, and §7.9.4. + public PdfDate? ModificationDate => ReadDate(ModDateKey); + + /// Gets whether the document includes trapping information (Trapped, PDF 1.3; deprecated in PDF 2.0). Default . + /// + /// ISO 32000-2 §14.3.3, Table 349. The value is a name; a boolean or a string spelling True or False is read as that + /// value with a diagnostic, anything else as with a diagnostic. + /// + public PdfTrapped Trapped + { + get + { + CosObject? value = _view.Get(TrappedKey); + (string? spelled, bool isName) = value switch + { + null => ("Unknown", true), + CosName name => (name.Value, true), + CosBoolean boolean => (boolean.Value ? "True" : "False", false), + CosString text => (text.DecodeText(), false), + _ => (null, false), + }; + PdfTrapped? trapped = spelled switch + { + "True" => PdfTrapped.True, + "False" => PdfTrapped.False, + "Unknown" => PdfTrapped.Unknown, + _ => null, + }; + if (trapped is null) + { + _view.Report(DiagnosticCodes.InfoTrappedInvalid, "The Info dictionary's Trapped entry shall be /True, /False or /Unknown; it is read as /Unknown."); + return PdfTrapped.Unknown; + } + + if (!isName) + { + _view.Report(DiagnosticCodes.InfoTrappedInvalid, "The Info dictionary's Trapped entry shall be a name; it is a boolean or a string, read as the name it spells."); + } + + return trapped.Value; + } + } + + /// Returns the text of any entry, such as a custom key: a text string decoded per §7.9.2.2. + /// The key, such as Title or a custom key. + /// The text, or when the entry is absent or has no text. + /// ISO 32000-2 §14.3.3, Table 349: keys the table does not define "shall be text strings". + public string? GetText(string key) => ReadText(new CosName(key)); + + /// Returns the date an entry holds, such as a custom key with a date value. + /// The key. + /// The date, or when the entry is absent or not a date. + /// ISO 32000-2 §7.9.4. + public PdfDate? GetDate(string key) => ReadDate(new CosName(key)); + + private string? ReadText(CosName key) => _view.ReadText(key, DiagnosticCodes.InfoValueNotTextString); + + private PdfDate? ReadDate(CosName key) + { + string? text = ReadText(key); + if (text is null) + { + return null; + } + + switch (PdfDate.Parse(text, out PdfDate date)) + { + case DateParseOutcome.Valid: + return date; + case DateParseOutcome.Repaired: + _view.Report(DiagnosticCodes.DateInvalid, $"The Info dictionary's {key.Value} entry does not follow the date format of §7.9.4; it is read with the deviating fields repaired."); + return date; + default: + _view.Report(DiagnosticCodes.DateUnreadable, $"The Info dictionary's {key.Value} entry is not a date (§7.9.4); its text is kept, its date is unknown."); + return null; + } + } +} diff --git a/src/Broadside/PdfDocumentProperties.cs b/src/Broadside/PdfDocumentProperties.cs new file mode 100644 index 00000000..254cc351 --- /dev/null +++ b/src/Broadside/PdfDocumentProperties.cs @@ -0,0 +1,52 @@ +namespace Broadside; + +/// The common document properties, each taken from the XMP metadata when it has it and from the Info dictionary otherwise. +/// +/// +/// ISO 32000-2 §14.3.1 ("The preferred method in PDF 2.0" is the metadata stream), §14.3.3 Table 349 (which XMP property each Info +/// entry corresponds to) and §14.3.4 (when the two disagree, which one a reader uses is its own decision). Each property comes from +/// the readable XMP packet of when that packet has the property, else from +/// . Disagreement is not a deviation and is not reported. +/// +/// Reads both sources on every call. Use and to see each one. +/// +public sealed class PdfDocumentProperties +{ + private readonly PdfDocument _document; + + internal PdfDocumentProperties(PdfDocument document) => _document = document; + + /// Gets the title: dc:title (default language), else Title. + /// ISO 32000-2 §14.3.3, Table 349. + public string? Title => Packet?.Title ?? _document.Information?.Title; + + /// Gets the author: the items of dc:creator joined by "; ", else Author. + /// ISO 32000-2 §14.3.3, Table 349. + public string? Author => Packet?.Creators is { Count: > 0 } creators ? string.Join("; ", creators) : _document.Information?.Author; + + /// Gets the subject: dc:description (default language), else Subject. + /// ISO 32000-2 §14.3.3, Table 349. + public string? Subject => Packet?.Description ?? _document.Information?.Subject; + + /// Gets the keywords: pdf:Keywords, else Keywords. + /// ISO 32000-2 §14.3.3, Table 349. + public string? Keywords => Packet?.Keywords ?? _document.Information?.Keywords; + + /// Gets the application that created the original document: xmp:CreatorTool, else Creator. + /// ISO 32000-2 §14.3.3, Table 349. + public string? Creator => Packet?.CreatorTool ?? _document.Information?.Creator; + + /// Gets the application that produced the PDF: pdf:Producer, else Producer. + /// ISO 32000-2 §14.3.3, Table 349. + public string? Producer => Packet?.Producer ?? _document.Information?.Producer; + + /// Gets the creation date: xmp:CreateDate, else CreationDate. + /// ISO 32000-2 §14.3.3, Table 349. An XMP date without a time zone is its local time with a zero offset (). + public DateTimeOffset? CreationDate => Packet?.CreateDate?.Value ?? _document.Information?.CreationDate?.Value; + + /// Gets the modification date: xmp:ModifyDate, else ModDate. + /// ISO 32000-2 §14.3.3, Table 349. + public DateTimeOffset? ModificationDate => Packet?.ModifyDate?.Value ?? _document.Information?.ModificationDate?.Value; + + private XmpPacket? Packet => _document.Metadata?.Packet; +} diff --git a/src/Broadside/PdfDuplex.cs b/src/Broadside/PdfDuplex.cs new file mode 100644 index 00000000..10fe0cef --- /dev/null +++ b/src/Broadside/PdfDuplex.cs @@ -0,0 +1,15 @@ +namespace Broadside; + +/// The paper handling a print dialog starts with: the viewer preference Duplex. +/// ISO 32000-2 §12.2, Table 147 (PDF 1.7). The default is implementation dependent. +public enum PdfDuplex +{ + /// Single-sided (Simplex). + Simplex, + + /// Double-sided, flipping on the short edge of the sheet (DuplexFlipShortEdge). + DuplexFlipShortEdge, + + /// Double-sided, flipping on the long edge of the sheet (DuplexFlipLongEdge). + DuplexFlipLongEdge, +} diff --git a/src/Broadside/PdfFileIdentifier.cs b/src/Broadside/PdfFileIdentifier.cs new file mode 100644 index 00000000..9aeff06c --- /dev/null +++ b/src/Broadside/PdfFileIdentifier.cs @@ -0,0 +1,29 @@ +namespace Broadside; + +/// The file identifier: the two byte strings of the trailer's ID entry. +/// +/// ISO 32000-2 §14.4 and §7.5.5, Table 15. The first identifier is permanent, set when the file is first written; the second changes +/// with every revision. Each "shall have a minimum length of 16 bytes"; shorter ones (some producers write 8) are kept as they are, +/// with a FileIdentifierInvalid diagnostic. The ID is required in PDF 2.0 and in encrypted files, where it is never +/// encrypted. Read when is called; the bytes are a snapshot. +/// +public sealed class PdfFileIdentifier +{ + internal PdfFileIdentifier(ReadOnlyMemory permanent, ReadOnlyMemory changing) + { + Permanent = permanent; + Changing = changing; + } + + /// Gets the permanent identifier, ID[0], based on the file's contents when it was created. + /// ISO 32000-2 §14.4. + public ReadOnlyMemory Permanent { get; } + + /// Gets the changing identifier, ID[1], based on the file's contents when it was last updated. + /// ISO 32000-2 §14.4. + public ReadOnlyMemory Changing { get; } + + /// Returns both identifiers in hexadecimal, as a trailer writes them. + /// The text, such as [<0123...> <4567...>]. + public override string ToString() => $"[<{Convert.ToHexString(Permanent.Span)}> <{Convert.ToHexString(Changing.Span)}>]"; +} diff --git a/src/Broadside/PdfMetadata.cs b/src/Broadside/PdfMetadata.cs new file mode 100644 index 00000000..a4888c96 --- /dev/null +++ b/src/Broadside/PdfMetadata.cs @@ -0,0 +1,41 @@ +using Broadside.Objects; + +namespace Broadside; + +/// The document's metadata stream: a live view over the catalog's Metadata entry and the XMP packet it holds. +/// +/// +/// ISO 32000-2 §14.3.2, Tables 347 and 348: a stream with Type Metadata and Subtype XML holding XMP +/// (ISO 16684-1); in PDF 2.0 the preferred place for document metadata. A stream without the right Type or Subtype is +/// still read, with a MetadataStreamTypeInvalid diagnostic. +/// +/// +/// is parsed on first use and kept: an immutable snapshot of the stream. When the stream is changed (its data +/// replaced or its dictionary edited), the next read parses it again. A packet that cannot be read is with an +/// XmpMalformed or XmpDtdProhibited diagnostic; the Info dictionary stays readable. +/// +/// +public sealed class PdfMetadata +{ + private readonly PdfDocument _document; + private readonly CosReference? _reference; + + internal PdfMetadata(PdfDocument document, CosStream stream, CosReference? reference) + { + _document = document; + _reference = reference; + Stream = stream; + } + + /// Gets the metadata stream. + /// ISO 32000-2 §14.3.2, Table 347. + public CosStream Stream { get; } + + /// Gets the stream's data, decoded through its filters: the XMP packet's bytes. Decoded on every call. + /// ISO 32000-2 §14.3.2 and §7.4. + public ReadOnlyMemory Data => _document.DecodeStream(Stream); + + /// Gets the XMP packet the stream holds, or when it cannot be read. + /// ISO 32000-2 §14.3.2; ISO 16684-1 §7. See for what is accepted. + public XmpPacket? Packet => _document.ReadXmpPacket(Stream, _reference); +} diff --git a/src/Broadside/PdfPageBoundary.cs b/src/Broadside/PdfPageBoundary.cs new file mode 100644 index 00000000..beff224e --- /dev/null +++ b/src/Broadside/PdfPageBoundary.cs @@ -0,0 +1,21 @@ +namespace Broadside; + +/// A page boundary, named by its key in the page object: what the viewer preferences ViewArea, ViewClip, PrintArea and PrintClip select. +/// ISO 32000-2 §12.2, Table 147 (PDF 1.4, deprecated in PDF 2.0), and §14.11.2. The default is . +public enum PdfPageBoundary +{ + /// The crop box (the default). + CropBox, + + /// The media box. + MediaBox, + + /// The bleed box. + BleedBox, + + /// The trim box. + TrimBox, + + /// The art box. + ArtBox, +} diff --git a/src/Broadside/PdfPageLayout.cs b/src/Broadside/PdfPageLayout.cs new file mode 100644 index 00000000..55a3ef9e --- /dev/null +++ b/src/Broadside/PdfPageLayout.cs @@ -0,0 +1,24 @@ +namespace Broadside; + +/// How a viewer lays the pages out when the document opens: the catalog's PageLayout entry. +/// ISO 32000-2 §7.7.2, Table 29. The default is . +public enum PdfPageLayout +{ + /// One page at a time (SinglePage, the default). + SinglePage, + + /// The pages in one column (OneColumn). + OneColumn, + + /// The pages in two columns, odd-numbered pages on the left (TwoColumnLeft). + TwoColumnLeft, + + /// The pages in two columns, odd-numbered pages on the right (TwoColumnRight). + TwoColumnRight, + + /// Two pages at a time, odd-numbered pages on the left (TwoPageLeft, PDF 1.5). + TwoPageLeft, + + /// Two pages at a time, odd-numbered pages on the right (TwoPageRight, PDF 1.5). + TwoPageRight, +} diff --git a/src/Broadside/PdfPageMode.cs b/src/Broadside/PdfPageMode.cs new file mode 100644 index 00000000..dae589c3 --- /dev/null +++ b/src/Broadside/PdfPageMode.cs @@ -0,0 +1,24 @@ +namespace Broadside; + +/// Which panel a viewer shows next to the pages: the catalog's PageMode entry and the viewer preference NonFullScreenPageMode. +/// ISO 32000-2 §7.7.2, Table 29, and §12.2, Table 147. The default is . +public enum PdfPageMode +{ + /// Neither the outline nor thumbnails (UseNone, the default). + UseNone, + + /// The document outline (UseOutlines). + UseOutlines, + + /// Thumbnail images (UseThumbs). + UseThumbs, + + /// Full-screen mode, no menu bar, window controls or other windows (FullScreen; not a valid NonFullScreenPageMode). + FullScreen, + + /// The optional content group panel (UseOC, PDF 1.5). + UseOC, + + /// The attachments panel (UseAttachments, PDF 1.6; not a valid NonFullScreenPageMode). + UseAttachments, +} diff --git a/src/Broadside/PdfPageRange.cs b/src/Broadside/PdfPageRange.cs new file mode 100644 index 00000000..a383fd70 --- /dev/null +++ b/src/Broadside/PdfPageRange.cs @@ -0,0 +1,48 @@ +using System.Globalization; + +namespace Broadside; + +/// A range of pages, first to last, numbered from 1: one pair of the viewer preference PrintPageRange. +/// ISO 32000-2 §12.2, Table 147 (PDF 1.7). Unlike page indices elsewhere in PDF, these numbers start at 1. +public readonly struct PdfPageRange : IEquatable +{ + /// Initializes a new instance of the struct. + /// The first page, numbered from 1. + /// The last page, numbered from 1. + public PdfPageRange(int first, int last) + { + First = first; + Last = last; + } + + /// Gets the first page of the range, numbered from 1. + public int First { get; } + + /// Gets the last page of the range, numbered from 1. + public int Last { get; } + + /// Returns whether two ranges are equal. + /// The first range. + /// The second range. + /// when they are equal. + public static bool operator ==(PdfPageRange left, PdfPageRange right) => left.Equals(right); + + /// Returns whether two ranges differ. + /// The first range. + /// The second range. + /// when they differ. + public static bool operator !=(PdfPageRange left, PdfPageRange right) => !left.Equals(right); + + /// + public bool Equals(PdfPageRange other) => First == other.First && Last == other.Last; + + /// + public override bool Equals(object? obj) => obj is PdfPageRange other && Equals(other); + + /// + public override int GetHashCode() => HashCode.Combine(First, Last); + + /// Returns the range as first-last. + /// The text. + public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"{First}-{Last}"); +} diff --git a/src/Broadside/PdfPrintScaling.cs b/src/Broadside/PdfPrintScaling.cs new file mode 100644 index 00000000..050dfca2 --- /dev/null +++ b/src/Broadside/PdfPrintScaling.cs @@ -0,0 +1,12 @@ +namespace Broadside; + +/// The page scaling a print dialog starts with: the viewer preference PrintScaling. +/// ISO 32000-2 §12.2, Table 147 (PDF 1.6). The default, and the value an unrecognized name reads as, is . +public enum PdfPrintScaling +{ + /// No page scaling (None). + None, + + /// The viewer's default print scaling (AppDefault, the default). + AppDefault, +} diff --git a/src/Broadside/PdfReadingDirection.cs b/src/Broadside/PdfReadingDirection.cs new file mode 100644 index 00000000..39bcb0df --- /dev/null +++ b/src/Broadside/PdfReadingDirection.cs @@ -0,0 +1,12 @@ +namespace Broadside; + +/// The predominant order of text, which places pages side by side: the viewer preference Direction. +/// ISO 32000-2 §12.2, Table 147 (PDF 1.3). The default is . +public enum PdfReadingDirection +{ + /// Left to right (L2R, the default). + LeftToRight, + + /// Right to left, vertical writing systems included (R2L). + RightToLeft, +} diff --git a/src/Broadside/PdfRequirement.cs b/src/Broadside/PdfRequirement.cs new file mode 100644 index 00000000..aa0cb87b --- /dev/null +++ b/src/Broadside/PdfRequirement.cs @@ -0,0 +1,105 @@ +using Broadside.Objects; + +namespace Broadside; + +/// One requirement the document places on an interactive processor: an element of the catalog's Requirements array. +/// +/// +/// ISO 32000-2 §12.11, Tables 273 to 276. A requirement names a feature the processor should support for the document to work as +/// intended (Table 275: EnableJavaScripts, DigSig, Encryption and others; the list is open), how much the +/// experience suffers without it, and handlers that check it. Requirements are exposed, never evaluated: evaluating them would run +/// JavaScript, which is out of scope. +/// +/// A live view over the requirement dictionary; deviations are reported when is read. +/// +public sealed class PdfRequirement +{ + private static readonly CosName SKey = new("S"); + private static readonly CosName VKey = new("V"); + private static readonly CosName PenaltyKey = new("Penalty"); + private static readonly CosName RHKey = new("RH"); + + private readonly PdfDocument _document; + + internal PdfRequirement(PdfDocument document, CosDictionary dictionary) + { + _document = document; + Dictionary = dictionary; + } + + /// Gets the requirement dictionary. + /// ISO 32000-2 §12.11.2, Table 273. + public CosDictionary Dictionary { get; } + + /// Gets the type of the requirement (S), such as EnableJavaScripts, or when missing. + /// ISO 32000-2 §12.11.2, Table 273, and Table 275 (the table's reference to Table 276 is an erratum). + public CosName? RequirementType => _document.Resolve(Dictionary.GetValueOrDefault(SKey)) as CosName; + + /// Gets the version of the feature required (V, PDF 2.0): a name, or an extensions dictionary; when absent. + /// ISO 32000-2 §12.11.2, Table 273. + public CosObject? Version => _document.Resolve(Dictionary.GetValueOrDefault(VKey)) is not CosNull and var version ? version : null; + + /// Gets how much the experience degrades without the feature, 0 to 100 (Penalty, PDF 2.0). Default 100. + /// ISO 32000-2 §12.11.2, Table 273. A value outside 0 to 100 is clamped into it. + public int Penalty => ReadPenalty(_document, Dictionary, out _); + + /// Gets the handlers that check the requirement (RH: one handler dictionary or an array of them); empty when absent. + /// ISO 32000-2 §12.11.3, Table 276. A handler of an unknown type shall be ignored by the processor; it is still listed here. + public IReadOnlyList Handlers + { + get + { + CosObject value = _document.Resolve(Dictionary.GetValueOrDefault(RHKey)); + IEnumerable elements = value switch + { + CosDictionary => [value], + CosArray array => array, + _ => [], + }; + var handlers = new List(); + foreach (CosObject element in elements) + { + if (_document.Resolve(element) is CosDictionary handler) + { + handlers.Add(new PdfRequirementHandler(_document, handler)); + } + } + + return handlers; + } + } + + /// Reads Penalty, clamped; says whether it was absent or an integer in range. + internal static int ReadPenalty(PdfDocument document, CosDictionary dictionary, out bool valid) + { + switch (document.Resolve(dictionary.GetValueOrDefault(PenaltyKey))) + { + case CosNull: + valid = true; + return 100; + case CosInteger { Value: >= 0 and <= 100 } penalty: + valid = true; + return (int)penalty.Value; + case CosNumber number: + valid = false; + return (int)Math.Clamp(Math.Round(number.ToDouble()), 0, 100); + default: + valid = false; + return 100; + } + } + + /// Whether the requirement dictionary has the entries Table 273 requires with the right types. + internal static bool IsWellFormed(PdfDocument document, CosDictionary dictionary) + { + _ = ReadPenalty(document, dictionary, out bool penaltyValid); + CosObject handlers = document.Resolve(dictionary.GetValueOrDefault(RHKey)); + bool handlersValid = handlers switch + { + CosNull or CosDictionary => true, + CosArray array => array.All(element => document.Resolve(element) is CosDictionary), + _ => false, + }; + return penaltyValid && handlersValid && document.Resolve(dictionary.GetValueOrDefault(SKey)) is CosName; + } +} diff --git a/src/Broadside/PdfRequirementHandler.cs b/src/Broadside/PdfRequirementHandler.cs new file mode 100644 index 00000000..affbfc99 --- /dev/null +++ b/src/Broadside/PdfRequirementHandler.cs @@ -0,0 +1,34 @@ +using Broadside.Objects; + +namespace Broadside; + +/// A handler that checks a requirement: an element of a requirement's RH entry. +/// +/// ISO 32000-2 §12.11.3, Table 276. Type JS names a document-level JavaScript () that decides whether the +/// requirement is met; NoOp does nothing. Exposed, never run. A live view over the handler dictionary. +/// +public sealed class PdfRequirementHandler +{ + private static readonly CosName SKey = new("S"); + private static readonly CosName ScriptKey = new("Script"); + + private readonly PdfDocument _document; + + internal PdfRequirementHandler(PdfDocument document, CosDictionary dictionary) + { + _document = document; + Dictionary = dictionary; + } + + /// Gets the handler dictionary. + /// ISO 32000-2 §12.11.3, Table 276. + public CosDictionary Dictionary { get; } + + /// Gets the type of the handler (S): JS or NoOp; when missing. + /// ISO 32000-2 §12.11.3, Table 276. A processor ignores a handler of a type it does not know. + public CosName? HandlerType => _document.Resolve(Dictionary.GetValueOrDefault(SKey)) as CosName; + + /// Gets the name of the document-level JavaScript a JS handler runs (Script), or . + /// ISO 32000-2 §12.11.3, Table 276; the script is in the JavaScript name tree (§7.7.4). + public string? Script => _document.Resolve(Dictionary.GetValueOrDefault(ScriptKey)) is CosString script ? script.DecodeText() : null; +} diff --git a/src/Broadside/PdfTrapped.cs b/src/Broadside/PdfTrapped.cs new file mode 100644 index 00000000..3bf87df0 --- /dev/null +++ b/src/Broadside/PdfTrapped.cs @@ -0,0 +1,18 @@ +namespace Broadside; + +/// Whether the document has been modified to include trapping information: the Info dictionary's Trapped entry. +/// +/// ISO 32000-2 §14.3.3, Table 349 (PDF 1.3; deprecated in PDF 2.0, use pdf:Trapped in XMP). A name, not a boolean; the +/// default is . +/// +public enum PdfTrapped +{ + /// Unknown, or only partly trapped (Unknown, the default). + Unknown, + + /// Fully trapped (True). + True, + + /// Not trapped (False). + False, +} diff --git a/src/Broadside/PdfViewerPreferences.cs b/src/Broadside/PdfViewerPreferences.cs new file mode 100644 index 00000000..c7c4672a --- /dev/null +++ b/src/Broadside/PdfViewerPreferences.cs @@ -0,0 +1,275 @@ +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// How the document asks to be presented on the screen and in print: a live view over the catalog's ViewerPreferences dictionary. +/// +/// +/// ISO 32000-2 §12.2, Tables 147 and 148. Every property reads the dictionary when called and returns the default Table 147 gives +/// when the entry is absent; nothing is ever written to the dictionary. A malformed entry reads as its default and records a +/// ViewerPreferenceInvalid diagnostic the first time it is read (in strict mode, the property throws). Keys the table does +/// not define are ignored: a dictionary may carry private keys. +/// +/// +/// The entries a viewer applies itself (the print entries in particular) are only preferences: Table 147 lets the user override all of +/// them, except the ones names. +/// +/// +public sealed class PdfViewerPreferences +{ + private static readonly CosName HideToolbarKey = new("HideToolbar"); + private static readonly CosName HideMenubarKey = new("HideMenubar"); + private static readonly CosName HideWindowUIKey = new("HideWindowUI"); + private static readonly CosName FitWindowKey = new("FitWindow"); + private static readonly CosName CenterWindowKey = new("CenterWindow"); + private static readonly CosName DisplayDocTitleKey = new("DisplayDocTitle"); + private static readonly CosName NonFullScreenPageModeKey = new("NonFullScreenPageMode"); + private static readonly CosName DirectionKey = new("Direction"); + private static readonly CosName ViewAreaKey = new("ViewArea"); + private static readonly CosName ViewClipKey = new("ViewClip"); + private static readonly CosName PrintAreaKey = new("PrintArea"); + private static readonly CosName PrintClipKey = new("PrintClip"); + private static readonly CosName PrintScalingKey = new("PrintScaling"); + private static readonly CosName DuplexKey = new("Duplex"); + private static readonly CosName PickTrayByPdfSizeKey = new("PickTrayByPDFSize"); + private static readonly CosName PrintPageRangeKey = new("PrintPageRange"); + private static readonly CosName NumCopiesKey = new("NumCopies"); + private static readonly CosName EnforceKey = new("Enforce"); + + private readonly DictionaryView _view; + + internal PdfViewerPreferences(PdfDocument document, CosDictionary dictionary, CosReference? reference) + { + _view = new DictionaryView(document, dictionary, reference); + } + + /// Gets the viewer preferences dictionary. + /// ISO 32000-2 §12.2, Table 147. + public CosDictionary Dictionary => _view.Dictionary; + + /// Gets a value indicating whether the viewer hides its tool bars while the document is active (HideToolbar). Default . + /// ISO 32000-2 §12.2, Table 147. + public bool HideToolbar => ReadFlag(HideToolbarKey); + + /// Gets a value indicating whether the viewer hides its menu bar while the document is active (HideMenubar). Default . + /// ISO 32000-2 §12.2, Table 147. + public bool HideMenubar => ReadFlag(HideMenubarKey); + + /// Gets a value indicating whether the viewer hides the window's user interface elements, leaving only the contents (HideWindowUI). Default . + /// ISO 32000-2 §12.2, Table 147. + public bool HideWindowUI => ReadFlag(HideWindowUIKey); + + /// Gets a value indicating whether the window is resized to fit the first displayed page (FitWindow). Default . + /// ISO 32000-2 §12.2, Table 147. + public bool FitWindow => ReadFlag(FitWindowKey); + + /// Gets a value indicating whether the window is centred on the screen (CenterWindow). Default . + /// ISO 32000-2 §12.2, Table 147. + public bool CenterWindow => ReadFlag(CenterWindowKey); + + /// + /// Gets a value indicating whether the title bar shows the document's title (dc:title of its XMP metadata) instead of the + /// file name (DisplayDocTitle, PDF 1.4). Default . + /// + /// ISO 32000-2 §12.2, Table 147. + public bool DisplayDocTitle => ReadFlag(DisplayDocTitleKey); + + /// + /// Gets the page mode used on leaving full-screen mode (NonFullScreenPageMode): (the + /// default), , or . + /// + /// + /// ISO 32000-2 §12.2, Table 147. Meaningful only when the catalog's page mode is ; it "shall + /// be ignored otherwise", which is the caller's to apply: the value is returned whatever the page mode. + /// + public PdfPageMode NonFullScreenPageMode => _view.ReadName( + NonFullScreenPageModeKey, + DiagnosticCodes.ViewerPreferenceInvalid, + PdfPageMode.UseNone, + ("UseNone", PdfPageMode.UseNone), + ("UseOutlines", PdfPageMode.UseOutlines), + ("UseThumbs", PdfPageMode.UseThumbs), + ("UseOC", PdfPageMode.UseOC))!.Value; + + /// Gets the predominant order of text, which places pages side by side (Direction, PDF 1.3). Default left to right. + /// ISO 32000-2 §12.2, Table 147. + public PdfReadingDirection Direction => _view.ReadName( + DirectionKey, + DiagnosticCodes.ViewerPreferenceInvalid, + PdfReadingDirection.LeftToRight, + ("L2R", PdfReadingDirection.LeftToRight), + ("R2L", PdfReadingDirection.RightToLeft))!.Value; + + /// Gets the page boundary displayed on the screen (ViewArea, PDF 1.4, deprecated in PDF 2.0). Default the crop box. + /// ISO 32000-2 §12.2, Table 147. A boundary the page does not define takes its default from Table 31. + public PdfPageBoundary ViewArea => ReadBoundary(ViewAreaKey); + + /// Gets the page boundary page contents are clipped to on the screen (ViewClip, PDF 1.4, deprecated in PDF 2.0). Default the crop box. + /// ISO 32000-2 §12.2, Table 147. + public PdfPageBoundary ViewClip => ReadBoundary(ViewClipKey); + + /// Gets the page boundary rendered when printing (PrintArea, PDF 1.4, deprecated in PDF 2.0). Default the crop box. + /// ISO 32000-2 §12.2, Table 147. + public PdfPageBoundary PrintArea => ReadBoundary(PrintAreaKey); + + /// Gets the page boundary page contents are clipped to when printing (PrintClip, PDF 1.4, deprecated in PDF 2.0). Default the crop box. + /// ISO 32000-2 §12.2, Table 147. + public PdfPageBoundary PrintClip => ReadBoundary(PrintClipKey); + + /// Gets the page scaling a print dialog starts with (PrintScaling, PDF 1.6). Default . + /// ISO 32000-2 §12.2, Table 147: "If this entry has an unrecognised value, AppDefault shall be used." + public PdfPrintScaling PrintScaling => ReadPrintScaling() ?? PdfPrintScaling.AppDefault; + + /// Gets the paper handling a print dialog starts with (Duplex, PDF 1.7), or : implementation dependent. + /// ISO 32000-2 §12.2, Table 147. + public PdfDuplex? Duplex => _view.ReadName( + DuplexKey, + DiagnosticCodes.ViewerPreferenceInvalid, + null, + ("Simplex", PdfDuplex.Simplex), + ("DuplexFlipShortEdge", PdfDuplex.DuplexFlipShortEdge), + ("DuplexFlipLongEdge", PdfDuplex.DuplexFlipLongEdge)); + + /// + /// Gets a value indicating whether the page size selects the input paper tray (PickTrayByPDFSize, PDF 1.7), or + /// : implementation dependent. + /// + /// ISO 32000-2 §12.2, Table 147. + public bool? PickTrayByPdfSize => _view.ReadBoolean(PickTrayByPdfSizeKey, DiagnosticCodes.ViewerPreferenceInvalid, null); + + /// + /// Gets the page ranges a print dialog starts with (PrintPageRange, PDF 1.7), numbered from 1, or : + /// implementation dependent. + /// + /// + /// ISO 32000-2 §12.2, Table 147: an even number of integers read in pairs, first and last page. A pair that is not two positive + /// integers with first not after last, and an element left over from an odd count, are dropped with a diagnostic. + /// + public IReadOnlyList? PrintPageRange + { + get + { + CosObject? value = _view.Get(PrintPageRangeKey); + if (value is null) + { + return null; + } + + if (value is not CosArray array) + { + Invalid(PrintPageRangeKey); + return null; + } + + var ranges = new List(array.Count / 2); + bool dropped = array.Count % 2 != 0; + for (int index = 0; index + 1 < array.Count; index += 2) + { + if (_view.Document.Resolve(array[index]) is CosInteger { Value: >= 1 and <= int.MaxValue } first + && _view.Document.Resolve(array[index + 1]) is CosInteger { Value: >= 1 and <= int.MaxValue } last + && first.Value <= last.Value) + { + ranges.Add(new PdfPageRange((int)first.Value, (int)last.Value)); + } + else + { + dropped = true; + } + } + + if (dropped) + { + Invalid(PrintPageRangeKey); + } + + return ranges; + } + } + + /// Gets the number of copies a print dialog starts with (NumCopies, PDF 1.7), or : implementation dependent, typically 1. + /// ISO 32000-2 §12.2, Table 147. A value that is not a positive integer is ignored with a diagnostic. + public int? NumCopies + { + get + { + int? copies = _view.ReadInteger(NumCopiesKey, DiagnosticCodes.ViewerPreferenceInvalid); + if (copies is < 1) + { + Invalid(NumCopiesKey); + return null; + } + + return copies; + } + } + + /// Gets the names of the preferences the viewer shall enforce, which the user cannot override (Enforce, PDF 2.0); empty when absent. + /// + /// ISO 32000-2 §12.2, Tables 147 and 148. The only name Table 148 defines is PrintScaling, valid only when + /// is given and not AppDefault. Other names are returned as written, with a diagnostic; elements + /// that are not names are dropped with a diagnostic. + /// + public IReadOnlyList Enforce + { + get + { + CosObject? value = _view.Get(EnforceKey); + if (value is null) + { + return []; + } + + if (value is not CosArray array) + { + Invalid(EnforceKey); + return []; + } + + var names = new List(array.Count); + bool invalid = false; + foreach (CosObject element in array) + { + if (_view.Document.Resolve(element) is CosName name) + { + names.Add(name); + invalid |= !PrintScalingKey.Equals(name) || ReadPrintScaling() is not PdfPrintScaling.None; + } + else + { + invalid = true; + } + } + + if (invalid) + { + Invalid(EnforceKey); + } + + return names; + } + } + + private bool ReadFlag(CosName key) => _view.ReadBoolean(key, DiagnosticCodes.ViewerPreferenceInvalid, false)!.Value; + + private PdfPageBoundary ReadBoundary(CosName key) => _view.ReadName( + key, + DiagnosticCodes.ViewerPreferenceInvalid, + PdfPageBoundary.CropBox, + ("CropBox", PdfPageBoundary.CropBox), + ("MediaBox", PdfPageBoundary.MediaBox), + ("BleedBox", PdfPageBoundary.BleedBox), + ("TrimBox", PdfPageBoundary.TrimBox), + ("ArtBox", PdfPageBoundary.ArtBox))!.Value; + + /// The valid PrintScaling value, or null when absent or unrecognised (reported). + private PdfPrintScaling? ReadPrintScaling() => _view.ReadName( + PrintScalingKey, + DiagnosticCodes.ViewerPreferenceInvalid, + null, + ("None", PdfPrintScaling.None), + ("AppDefault", PdfPrintScaling.AppDefault)); + + private void Invalid(CosName key) => + _view.Report(DiagnosticCodes.ViewerPreferenceInvalid, $"The viewer preference {key.Value} does not have a value Table 147 allows; it is read as its default."); +} diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index d8b2a9f8..e1b3ac16 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -488,3 +488,127 @@ Broadside.XmpPacket.Subjects.get -> System.Collections.Generic.IReadOnlyList string? Broadside.XmpPacket.Trapped.get -> string? static Broadside.XmpPacket.TryParse(System.ReadOnlySpan data, out Broadside.XmpPacket? packet) -> bool +Broadside.PdfDeveloperExtension +Broadside.PdfDeveloperExtension.BaseVersion.get -> Broadside.PdfVersion? +Broadside.PdfDeveloperExtension.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfDeveloperExtension.ExtensionLevel.get -> int? +Broadside.PdfDeveloperExtension.ExtensionRevision.get -> string? +Broadside.PdfDeveloperExtension.Prefix.get -> Broadside.Objects.CosName! +Broadside.PdfDeveloperExtension.Url.get -> System.Uri? +Broadside.PdfDocument.CatalogVersion.get -> Broadside.PdfVersion? +Broadside.PdfDocument.Extensions.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfDocument.FileIdentifier.get -> Broadside.PdfFileIdentifier? +Broadside.PdfDocument.HeaderVersion.get -> Broadside.PdfVersion? +Broadside.PdfDocument.Information.get -> Broadside.PdfDocumentInformation? +Broadside.PdfDocument.Language.get -> string? +Broadside.PdfDocument.Metadata.get -> Broadside.PdfMetadata? +Broadside.PdfDocument.PageLayout.get -> Broadside.PdfPageLayout +Broadside.PdfDocument.PageMode.get -> Broadside.PdfPageMode +Broadside.PdfDocument.Properties.get -> Broadside.PdfDocumentProperties! +Broadside.PdfDocument.Requirements.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfDocument.ViewerPreferences.get -> Broadside.PdfViewerPreferences? +Broadside.PdfDocumentInformation +Broadside.PdfDocumentInformation.Author.get -> string? +Broadside.PdfDocumentInformation.CreationDate.get -> Broadside.PdfDate? +Broadside.PdfDocumentInformation.Creator.get -> string? +Broadside.PdfDocumentInformation.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfDocumentInformation.GetDate(string! key) -> Broadside.PdfDate? +Broadside.PdfDocumentInformation.GetText(string! key) -> string? +Broadside.PdfDocumentInformation.Keywords.get -> string? +Broadside.PdfDocumentInformation.ModificationDate.get -> Broadside.PdfDate? +Broadside.PdfDocumentInformation.Producer.get -> string? +Broadside.PdfDocumentInformation.Subject.get -> string? +Broadside.PdfDocumentInformation.Title.get -> string? +Broadside.PdfDocumentInformation.Trapped.get -> Broadside.PdfTrapped +Broadside.PdfDocumentProperties +Broadside.PdfDocumentProperties.Author.get -> string? +Broadside.PdfDocumentProperties.CreationDate.get -> System.DateTimeOffset? +Broadside.PdfDocumentProperties.Creator.get -> string? +Broadside.PdfDocumentProperties.Keywords.get -> string? +Broadside.PdfDocumentProperties.ModificationDate.get -> System.DateTimeOffset? +Broadside.PdfDocumentProperties.Producer.get -> string? +Broadside.PdfDocumentProperties.Subject.get -> string? +Broadside.PdfDocumentProperties.Title.get -> string? +Broadside.PdfDuplex +Broadside.PdfDuplex.DuplexFlipLongEdge = 2 -> Broadside.PdfDuplex +Broadside.PdfDuplex.DuplexFlipShortEdge = 1 -> Broadside.PdfDuplex +Broadside.PdfDuplex.Simplex = 0 -> Broadside.PdfDuplex +Broadside.PdfFileIdentifier +Broadside.PdfFileIdentifier.Changing.get -> System.ReadOnlyMemory +Broadside.PdfFileIdentifier.Permanent.get -> System.ReadOnlyMemory +Broadside.PdfMetadata +Broadside.PdfMetadata.Data.get -> System.ReadOnlyMemory +Broadside.PdfMetadata.Packet.get -> Broadside.XmpPacket? +Broadside.PdfMetadata.Stream.get -> Broadside.Objects.CosStream! +Broadside.PdfPageBoundary +Broadside.PdfPageBoundary.ArtBox = 4 -> Broadside.PdfPageBoundary +Broadside.PdfPageBoundary.BleedBox = 2 -> Broadside.PdfPageBoundary +Broadside.PdfPageBoundary.CropBox = 0 -> Broadside.PdfPageBoundary +Broadside.PdfPageBoundary.MediaBox = 1 -> Broadside.PdfPageBoundary +Broadside.PdfPageBoundary.TrimBox = 3 -> Broadside.PdfPageBoundary +Broadside.PdfPageLayout +Broadside.PdfPageLayout.OneColumn = 1 -> Broadside.PdfPageLayout +Broadside.PdfPageLayout.SinglePage = 0 -> Broadside.PdfPageLayout +Broadside.PdfPageLayout.TwoColumnLeft = 2 -> Broadside.PdfPageLayout +Broadside.PdfPageLayout.TwoColumnRight = 3 -> Broadside.PdfPageLayout +Broadside.PdfPageLayout.TwoPageLeft = 4 -> Broadside.PdfPageLayout +Broadside.PdfPageLayout.TwoPageRight = 5 -> Broadside.PdfPageLayout +Broadside.PdfPageMode +Broadside.PdfPageMode.FullScreen = 3 -> Broadside.PdfPageMode +Broadside.PdfPageMode.UseAttachments = 5 -> Broadside.PdfPageMode +Broadside.PdfPageMode.UseNone = 0 -> Broadside.PdfPageMode +Broadside.PdfPageMode.UseOC = 4 -> Broadside.PdfPageMode +Broadside.PdfPageMode.UseOutlines = 1 -> Broadside.PdfPageMode +Broadside.PdfPageMode.UseThumbs = 2 -> Broadside.PdfPageMode +Broadside.PdfPageRange +Broadside.PdfPageRange.Equals(Broadside.PdfPageRange other) -> bool +Broadside.PdfPageRange.First.get -> int +Broadside.PdfPageRange.Last.get -> int +Broadside.PdfPageRange.PdfPageRange() -> void +Broadside.PdfPageRange.PdfPageRange(int first, int last) -> void +Broadside.PdfPrintScaling +Broadside.PdfPrintScaling.AppDefault = 1 -> Broadside.PdfPrintScaling +Broadside.PdfPrintScaling.None = 0 -> Broadside.PdfPrintScaling +Broadside.PdfReadingDirection +Broadside.PdfReadingDirection.LeftToRight = 0 -> Broadside.PdfReadingDirection +Broadside.PdfReadingDirection.RightToLeft = 1 -> Broadside.PdfReadingDirection +Broadside.PdfRequirement +Broadside.PdfRequirement.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfRequirement.Handlers.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfRequirement.Penalty.get -> int +Broadside.PdfRequirement.RequirementType.get -> Broadside.Objects.CosName? +Broadside.PdfRequirement.Version.get -> Broadside.Objects.CosObject? +Broadside.PdfRequirementHandler +Broadside.PdfRequirementHandler.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfRequirementHandler.HandlerType.get -> Broadside.Objects.CosName? +Broadside.PdfRequirementHandler.Script.get -> string? +Broadside.PdfTrapped +Broadside.PdfTrapped.False = 2 -> Broadside.PdfTrapped +Broadside.PdfTrapped.True = 1 -> Broadside.PdfTrapped +Broadside.PdfTrapped.Unknown = 0 -> Broadside.PdfTrapped +Broadside.PdfViewerPreferences +Broadside.PdfViewerPreferences.CenterWindow.get -> bool +Broadside.PdfViewerPreferences.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfViewerPreferences.Direction.get -> Broadside.PdfReadingDirection +Broadside.PdfViewerPreferences.DisplayDocTitle.get -> bool +Broadside.PdfViewerPreferences.Duplex.get -> Broadside.PdfDuplex? +Broadside.PdfViewerPreferences.Enforce.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfViewerPreferences.FitWindow.get -> bool +Broadside.PdfViewerPreferences.HideMenubar.get -> bool +Broadside.PdfViewerPreferences.HideToolbar.get -> bool +Broadside.PdfViewerPreferences.HideWindowUI.get -> bool +Broadside.PdfViewerPreferences.NonFullScreenPageMode.get -> Broadside.PdfPageMode +Broadside.PdfViewerPreferences.NumCopies.get -> int? +Broadside.PdfViewerPreferences.PickTrayByPdfSize.get -> bool? +Broadside.PdfViewerPreferences.PrintArea.get -> Broadside.PdfPageBoundary +Broadside.PdfViewerPreferences.PrintClip.get -> Broadside.PdfPageBoundary +Broadside.PdfViewerPreferences.PrintPageRange.get -> System.Collections.Generic.IReadOnlyList? +Broadside.PdfViewerPreferences.PrintScaling.get -> Broadside.PdfPrintScaling +Broadside.PdfViewerPreferences.ViewArea.get -> Broadside.PdfPageBoundary +Broadside.PdfViewerPreferences.ViewClip.get -> Broadside.PdfPageBoundary +override Broadside.PdfFileIdentifier.ToString() -> string! +override Broadside.PdfPageRange.Equals(object? obj) -> bool +override Broadside.PdfPageRange.GetHashCode() -> int +override Broadside.PdfPageRange.ToString() -> string! +static Broadside.PdfPageRange.operator !=(Broadside.PdfPageRange left, Broadside.PdfPageRange right) -> bool +static Broadside.PdfPageRange.operator ==(Broadside.PdfPageRange left, Broadside.PdfPageRange right) -> bool diff --git a/tests/Broadside.TestSupport/Corpus.cs b/tests/Broadside.TestSupport/Corpus.cs index e98e5c47..e171165c 100644 --- a/tests/Broadside.TestSupport/Corpus.cs +++ b/tests/Broadside.TestSupport/Corpus.cs @@ -40,6 +40,11 @@ public static class Corpus "outline.pdf", "name-tree-dests.pdf", "metadata-xmp.pdf", + "metadata-xmp-forms.pdf", + "info-dictionary.pdf", + "viewer-preferences.pdf", + "catalog-version-extensions.pdf", + "page-labels.pdf", ]; private static readonly string[] Malformed = diff --git a/tests/Broadside.Tests/Document/CatalogEntryTests.cs b/tests/Broadside.Tests/Document/CatalogEntryTests.cs new file mode 100644 index 00000000..b520dbfe --- /dev/null +++ b/tests/Broadside.Tests/Document/CatalogEntryTests.cs @@ -0,0 +1,263 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// +/// The catalog entries a viewer reads before showing a page: Version, Extensions, Requirements, Lang, PageLayout, PageMode and +/// ViewerPreferences. ISO 32000-2 §7.7.2 Table 29, §7.12, §12.2, §12.11. +/// +public class CatalogEntryTests +{ + [Fact] + public void Viewer_preferences_pdf_types_every_table_147_entry() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("viewer-preferences.pdf")); + PdfViewerPreferences preferences = document.ViewerPreferences!; + + Assert.True(preferences.HideToolbar); + Assert.True(preferences.HideMenubar); + Assert.True(preferences.HideWindowUI); + Assert.True(preferences.FitWindow); + Assert.True(preferences.CenterWindow); + Assert.True(preferences.DisplayDocTitle); + Assert.Equal(PdfPageMode.UseOutlines, preferences.NonFullScreenPageMode); + Assert.Equal(PdfReadingDirection.RightToLeft, preferences.Direction); + Assert.Equal(PdfPageBoundary.MediaBox, preferences.ViewArea); + Assert.Equal(PdfPageBoundary.BleedBox, preferences.ViewClip); + Assert.Equal(PdfPageBoundary.TrimBox, preferences.PrintArea); + Assert.Equal(PdfPageBoundary.ArtBox, preferences.PrintClip); + Assert.Equal(PdfPrintScaling.None, preferences.PrintScaling); + Assert.Equal(PdfDuplex.DuplexFlipLongEdge, preferences.Duplex); + Assert.True(preferences.PickTrayByPdfSize); + Assert.Equal([new PdfPageRange(1, 1), new PdfPageRange(1, 1)], preferences.PrintPageRange); + Assert.Equal(2, preferences.NumCopies); + Assert.Equal([new CosName("PrintScaling")], preferences.Enforce); + Assert.Equal(PdfPageLayout.TwoPageRight, document.PageLayout); + Assert.Equal(PdfPageMode.UseOC, document.PageMode); + Assert.Empty(document.Diagnostics); + Assert.False(document.Catalog.IsDirty); + } + + [Fact] + public void Empty_page_pdf_has_the_default_layout_and_mode_and_no_viewer_preferences() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + + Assert.Equal(PdfPageLayout.SinglePage, document.PageLayout); + Assert.Equal(PdfPageMode.UseNone, document.PageMode); + Assert.Null(document.ViewerPreferences); + Assert.Null(document.Language); + Assert.Empty(document.Extensions); + Assert.Empty(document.Requirements); + Assert.Equal(new PdfVersion(1, 7), document.HeaderVersion); + Assert.Null(document.CatalogVersion); + Assert.Equal(new PdfVersion(1, 7), document.Version); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Outline_pdf_opens_with_the_outline_visible() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("outline.pdf")); + + Assert.Equal(PdfPageMode.UseOutlines, document.PageMode); + } + + [Fact] + public void An_empty_viewer_preferences_dictionary_reads_every_default() + { + using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", "/ViewerPreferences << >>")); + PdfViewerPreferences preferences = document.ViewerPreferences!; + + Assert.False(preferences.HideToolbar || preferences.HideMenubar || preferences.HideWindowUI || preferences.FitWindow + || preferences.CenterWindow || preferences.DisplayDocTitle); + Assert.Equal(PdfPageMode.UseNone, preferences.NonFullScreenPageMode); + Assert.Equal(PdfReadingDirection.LeftToRight, preferences.Direction); + Assert.Equal(PdfPageBoundary.CropBox, preferences.ViewArea); + Assert.Equal(PdfPageBoundary.CropBox, preferences.ViewClip); + Assert.Equal(PdfPageBoundary.CropBox, preferences.PrintArea); + Assert.Equal(PdfPageBoundary.CropBox, preferences.PrintClip); + Assert.Equal(PdfPrintScaling.AppDefault, preferences.PrintScaling); + Assert.Null(preferences.Duplex); + Assert.Null(preferences.PickTrayByPdfSize); + Assert.Null(preferences.PrintPageRange); + Assert.Null(preferences.NumCopies); + Assert.Empty(preferences.Enforce); + Assert.Empty(preferences.Dictionary); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [InlineData("/HideToolbar /true")] + [InlineData("/NonFullScreenPageMode /FullScreen")] + [InlineData("/Direction /TopToBottom")] + [InlineData("/ViewArea /PageBox")] + [InlineData("/PrintScaling /Fit")] + [InlineData("/Duplex /Triplex")] + [InlineData("/NumCopies 0")] + [InlineData("/PrintPageRange [1 2 3]")] + [InlineData("/PrintPageRange [3 2]")] + [InlineData("/Enforce [/HideToolbar]")] + [InlineData("/Enforce [/PrintScaling]")] + public void A_malformed_viewer_preference_reads_as_its_default_with_a_warning(string entry) + { + using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", $"/ViewerPreferences << {entry} >>")); + PdfViewerPreferences preferences = document.ViewerPreferences!; + + Assert.False(preferences.HideToolbar); + Assert.Equal(PdfPageMode.UseNone, preferences.NonFullScreenPageMode); + Assert.Equal(PdfReadingDirection.LeftToRight, preferences.Direction); + Assert.Equal(PdfPageBoundary.CropBox, preferences.ViewArea); + Assert.Equal(PdfPrintScaling.AppDefault, preferences.PrintScaling); + Assert.Null(preferences.Duplex); + Assert.Null(preferences.NumCopies); + Assert.True(preferences.PrintPageRange is null or { Count: 0 } or [{ First: 1, Last: 2 }]); + _ = preferences.Enforce; + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("ViewerPreferenceInvalid", diagnostic.Code); + Assert.Equal(new CosReference(1, 0), diagnostic.ObjectReference); + } + + [Fact] + public void Unknown_viewer_preference_keys_are_ignored() + { + using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", "/ViewerPreferences << /AcmeZoom 3 >>")); + + Assert.False(document.ViewerPreferences!.FitWindow); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [InlineData("/PageLayout /Spread", "PageLayoutInvalid")] + [InlineData("/PageMode (UseOutlines)", "PageModeInvalid")] + [InlineData("/ViewerPreferences [1]", "ViewerPreferencesInvalid")] + public void An_unknown_layout_mode_or_preferences_entry_reads_as_the_default_with_a_warning(string entry, string code) + { + using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", entry)); + + Assert.Equal(PdfPageLayout.SinglePage, document.PageLayout); + Assert.Equal(PdfPageMode.UseNone, document.PageMode); + Assert.Null(document.ViewerPreferences); + Assert.Equal(code, Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void The_language_is_a_text_string() + { + using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", "/Lang (de-CH)")); + + Assert.Equal("de-CH", document.Language); + } + + [Fact] + public void Catalog_version_extensions_pdf_exposes_its_version_extensions_and_requirements() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("catalog-version-extensions.pdf")); + + Assert.Equal(new PdfVersion(1, 7), document.HeaderVersion); + Assert.Equal(new PdfVersion(2, 0), document.CatalogVersion); + Assert.Equal(new PdfVersion(2, 0), document.Version); + + Assert.Equal(2, document.Extensions.Count); + PdfDeveloperExtension adobe = document.Extensions[0]; + Assert.Equal(new CosName("ADBE"), adobe.Prefix); + Assert.Equal(new PdfVersion(1, 7), adobe.BaseVersion); + Assert.Equal(3, adobe.ExtensionLevel); + Assert.Null(adobe.Url); + Assert.Null(adobe.ExtensionRevision); + PdfDeveloperExtension iso = document.Extensions[1]; + Assert.Equal(new CosName("ISO_"), iso.Prefix); + Assert.Equal(new PdfVersion(2, 0), iso.BaseVersion); + Assert.Equal(32001, iso.ExtensionLevel); + Assert.Equal(":2022", iso.ExtensionRevision); + Assert.Equal(new Uri("https://www.iso.org/standard/45874.html"), iso.Url); + + PdfRequirement requirement = Assert.Single(document.Requirements); + Assert.Equal(new CosName("EnableJavaScripts"), requirement.RequirementType); + Assert.Equal(50, requirement.Penalty); + Assert.Null(requirement.Version); + PdfRequirementHandler handler = Assert.Single(requirement.Handlers); + Assert.Equal(new CosName("NoOp"), handler.HandlerType); + Assert.Null(handler.Script); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Pdf20_header_pdf_is_version_2_0_from_the_header_and_the_catalog() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("pdf20-header.pdf")); + + Assert.Equal(new PdfVersion(2, 0), document.HeaderVersion); + Assert.Equal(new PdfVersion(2, 0), document.CatalogVersion); + Assert.NotNull(document.FileIdentifier); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_requirement_takes_the_default_penalty_and_handlers_given_as_an_array() + { + using PdfDocument document = PdfDocument.Open(TestPdf.OnePage( + "/MediaBox [0 0 612 792]", + "/Requirements [<< /S /Navigation /RH [<< /S /JS /Script (check) >> << /S /NoOp >>] >>]")); + PdfRequirement requirement = Assert.Single(document.Requirements); + + Assert.Equal(100, requirement.Penalty); + Assert.Equal(["check", null], requirement.Handlers.Select(h => h.Script)); + Assert.Equal(new CosName("JS"), requirement.Handlers[0].HandlerType); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [InlineData("/Requirements << /S /Navigation >>")] + [InlineData("/Requirements [(x) << /S /Navigation >>]")] + [InlineData("/Requirements [<< /S /Navigation /Penalty 101 >>]")] + [InlineData("/Requirements [<< /Penalty 1 >>]")] + public void A_malformed_requirement_is_reported(string entry) + { + using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", entry)); + + Assert.All(document.Requirements, requirement => Assert.InRange(requirement.Penalty, 0, 100)); + Assert.Equal("RequirementInvalid", Assert.Single(document.Diagnostics).Code); + } + + [Theory] + [InlineData("/Extensions [1]", "ExtensionsInvalid", 0)] + [InlineData("/Extensions << /ADBE 5 >>", "DeveloperExtensionInvalid", 0)] + [InlineData("/Extensions << /ADBE << /ExtensionLevel 3 >> >>", "DeveloperExtensionInvalid", 1)] + [InlineData("/Extensions << /ADBE << /BaseVersion /1.7 /ExtensionLevel 3.5 >> >>", "DeveloperExtensionInvalid", 1)] + public void A_malformed_extensions_entry_is_reported(string entry, string code, int count) + { + using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", entry)); + + Assert.Equal(count, document.Extensions.Count); + Assert.Equal(code, Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void Extensions_given_through_indirect_references_are_read_with_a_warning() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R /Extensions 4 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>", + "<< /ADBE << /BaseVersion /1.7 /ExtensionLevel 8 >> >>"); + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal(8, Assert.Single(document.Extensions).ExtensionLevel); + Assert.Equal("ExtensionsNotDirect", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void Reading_every_catalog_entry_changes_nothing() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("catalog-version-extensions.pdf")); + + _ = (document.Extensions, document.Requirements, document.PageLayout, document.PageMode, document.ViewerPreferences, document.Language); + _ = (document.Information, document.Metadata, document.Properties.Title, document.FileIdentifier); + + Assert.False(document.Catalog.IsDirty); + Assert.False(document.Trailer.IsDirty); + } +} diff --git a/tests/Broadside.Tests/Document/DocumentInformationTests.cs b/tests/Broadside.Tests/Document/DocumentInformationTests.cs new file mode 100644 index 00000000..bf6300a0 --- /dev/null +++ b/tests/Broadside.Tests/Document/DocumentInformationTests.cs @@ -0,0 +1,332 @@ +using System.Text; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// The Info dictionary, the document's XMP metadata and the file identifier. ISO 32000-2 §14.3, §14.4, §7.9.4. +public class DocumentInformationTests +{ + [Fact] + public void Metadata_xmp_pdf_yields_its_title_from_the_info_dictionary_and_from_xmp() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("metadata-xmp.pdf")); + + Assert.Equal("Broadside", document.Information!.Title); + Assert.Equal("Broadside", document.Metadata!.Packet!.Title); + Assert.Equal("Broadside", document.Properties.Title); + Assert.Equal(new CosName("Metadata"), document.Metadata.Stream.Dictionary[new CosName("Type")]); + Assert.StartsWith("", "/Title (still here)"); + using PdfDocument document = PdfDocument.Open(file); + + Assert.Null(document.Metadata!.Packet); + Assert.Null(document.Metadata.Packet); + Assert.Equal("still here", document.Properties.Title); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("XmpMalformed", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity); + Assert.Equal(new CosReference(4, 0), diagnostic.ObjectReference); + } + + [Fact] + public void A_packet_with_a_document_type_declaration_is_refused() + { + byte[] file = WithMetadata("]>" + Title("&a;"), info: null); + using PdfDocument document = PdfDocument.Open(file); + + Assert.Null(document.Metadata!.Packet); + Assert.Equal("XmpDtdProhibited", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void Junk_before_the_packet_and_a_duplicate_property_are_read_with_warnings() + { + string twice = "" + + ""; + using PdfDocument document = PdfDocument.Open(WithMetadata("junk" + twice, info: null)); + + Assert.Equal("first", document.Metadata!.Packet!.Producer); + Assert.Equal(["XmpLeadingJunk", "XmpPropertyDuplicate"], document.Diagnostics.Select(d => d.Code)); + } + + [Fact] + public void A_metadata_stream_without_its_type_and_subtype_is_read_with_a_warning() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R /Metadata 4 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>", + Stream(string.Empty, Title("untyped"))); + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal("untyped", document.Metadata!.Packet!.Title); + Assert.Equal("MetadataStreamTypeInvalid", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_metadata_entry_that_is_not_a_stream_is_ignored_with_a_warning() + { + using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", "/Metadata << /Type /Metadata >>")); + + Assert.Null(document.Metadata); + Assert.Equal("MetadataStreamInvalid", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void The_parsed_packet_is_a_snapshot_until_the_stream_changes() + { + using PdfDocument document = PdfDocument.Open(WithMetadata(Title("before"), info: null)); + XmpPacket first = document.Metadata!.Packet!; + + Assert.Same(first, document.Metadata.Packet); + document.Metadata.Stream.EncodedData = Encoding.UTF8.GetBytes(Title("after")); + + Assert.Equal("after", document.Metadata.Packet!.Title); + Assert.Equal("before", first.Title); + } + + [Fact] + public void Info_values_that_are_not_text_strings_are_read_with_a_warning() + { + using PdfDocument document = PdfDocument.Open(WithInfo("/Title /NameTitle /Author 42 /Subject [1] /Trapped true")); + PdfDocumentInformation info = document.Information!; + + Assert.Equal("NameTitle", info.Title); + Assert.Equal("42", info.Author); + Assert.Null(info.Subject); + Assert.Equal(PdfTrapped.True, info.Trapped); + Assert.Equal(["InfoValueNotTextString", "InfoTrappedInvalid"], document.Diagnostics.Select(d => d.Code).Distinct()); + Assert.All(document.Diagnostics, d => Assert.Equal(new CosReference(4, 0), d.ObjectReference)); + } + + [Theory] + [InlineData("/Trapped /False", PdfTrapped.False)] + [InlineData("/Trapped /Unknown", PdfTrapped.Unknown)] + [InlineData("", PdfTrapped.Unknown)] + public void Trapped_is_a_name_that_defaults_to_unknown(string entry, PdfTrapped expected) + { + using PdfDocument document = PdfDocument.Open(WithInfo(entry)); + + Assert.Equal(expected, document.Information!.Trapped); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [InlineData("(20140924212303Z)", "DateInvalid", true)] + [InlineData("(D:20140924212303+0100)", "DateInvalid", true)] + [InlineData("(Monday, March 3, 1997)", "DateUnreadable", false)] + [InlineData("(D:191001223195200-08'00')", "DateUnreadable", false)] + public void A_date_that_deviates_is_read_with_a_warning_and_one_that_cannot_be_read_keeps_its_text(string value, string code, bool readable) + { + using PdfDocument document = PdfDocument.Open(WithInfo("/ModDate " + value)); + PdfDocumentInformation info = document.Information!; + + Assert.Equal(readable, info.ModificationDate.HasValue); + Assert.Equal(value[1..^1], info.GetText("ModDate")); + Assert.Equal(code, Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_utf_16_date_string_is_decoded_before_it_is_parsed() + { + string hex = Convert.ToHexString([0xFE, 0xFF, .. Encoding.BigEndianUnicode.GetBytes("D:2014")]); + using PdfDocument document = PdfDocument.Open(WithInfo($"/CreationDate <{hex}>")); + + Assert.Equal(2014, document.Information!.CreationDate!.Value.Value.Year); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Strict_mode_throws_from_the_member_that_reads_a_deviating_value() + { + byte[] file = WithInfo("/Title /NameTitle"); + using PdfDocument document = PdfDocument.Open(file, new PdfOptions().UseStrict()); + + PdfDocumentInformation info = document.Information!; + DiagnosticException exception = Assert.Throws(() => info.Title); + Assert.Equal("InfoValueNotTextString", exception.Diagnostic.Code); + } + + [Fact] + public void An_info_entry_that_is_not_a_dictionary_is_ignored_with_a_warning() + { + byte[] file = new TestPdf { TrailerEntries = "/Info 4 0 R" }.Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>", + "(not a dictionary)"); + using PdfDocument document = PdfDocument.Open(file); + + Assert.Null(document.Information); + Assert.Equal("InfoDictionaryInvalid", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void Catalog_version_extensions_pdf_has_two_different_file_identifiers() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("catalog-version-extensions.pdf")); + PdfFileIdentifier id = document.FileIdentifier!; + + Assert.Equal(16, id.Permanent.Length); + Assert.Equal(16, id.Changing.Length); + Assert.False(id.Permanent.Span.SequenceEqual(id.Changing.Span)); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [InlineData("encrypted-rc4-40.pdf")] + [InlineData("encrypted-aes-256.pdf")] + public void An_encrypted_file_has_its_identifier_unencrypted(string fileName) + { + using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName)); + PdfFileIdentifier id = document.FileIdentifier!; + + Assert.True(id.Permanent.Span.SequenceEqual(id.Changing.Span)); + Assert.Equal(16, id.Permanent.Length); + CosString raw = Assert.IsType(((CosArray)document.Trailer[new CosName("ID")])[0]); + Assert.True(raw.Bytes.SequenceEqual(id.Permanent.Span)); + } + + [Fact] + public void A_file_without_an_identifier_has_none() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + + Assert.Null(document.FileIdentifier); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [InlineData("/ID [<0123> <0123>]", true)] + [InlineData("/ID [<00112233445566778899AABBCCDDEEFF>]", false)] + [InlineData("/ID (one)", false)] + public void A_malformed_identifier_is_reported(string entry, bool exposed) + { + byte[] file = new TestPdf { TrailerEntries = entry }.Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>"); + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal(exposed, document.FileIdentifier is not null); + Assert.Equal("FileIdentifierInvalid", Assert.Single(document.Diagnostics).Code); + } + + private static byte[] WithInfo(string entries) => + new TestPdf { TrailerEntries = "/Info 4 0 R" }.Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>", + $"<< {entries} >>"); + + private static byte[] WithMetadata(string packet, string? info) + { + string[] objects = + [ + "<< /Type /Catalog /Pages 2 0 R /Metadata 4 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>", + Stream("/Type /Metadata /Subtype /XML", packet), + .. info is null ? Array.Empty() : [$"<< {info} >>"], + ]; + return new TestPdf { TrailerEntries = info is null ? string.Empty : "/Info 5 0 R" }.Build(objects); + } + + private static string Stream(string entries, string data) => + $"<< {entries} /Length {Encoding.UTF8.GetByteCount(data)} >>\nstream\n{data}\nendstream"; + + private static string Title(string title) => + "" + + "" + + title + ""; +} diff --git a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt index f9e9b5e1..a07db3f5 100644 --- a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt +++ b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt @@ -3,6 +3,7 @@ ascii85-stream.pdf, asciihex-stream.pdf, broken-xref-offsets.pdf, + catalog-version-extensions.pdf, empty-page.pdf, encrypted-aes-128.pdf, encrypted-aes-256.pdf, @@ -22,16 +23,19 @@ flate-stream.pdf, hybrid-xref.pdf, incremental-update.pdf, + info-dictionary.pdf, inline-image.pdf, linearized-xref-stream.pdf, linearized.pdf, lzw-stream.pdf, + metadata-xmp-forms.pdf, metadata-xmp.pdf, missing-endobj.pdf, name-tree-dests.pdf, no-xref.pdf, object-stream.pdf, outline.pdf, + page-labels.pdf, page-tree-inherited.pdf, pdf20-header.pdf, png-predictor.pdf, @@ -39,6 +43,7 @@ startxref-wrong.pdf, text-standard14.pdf, text-truetype-embedded.pdf, + viewer-preferences.pdf, wrong-stream-length.pdf, xref-stream.pdf ] \ No newline at end of file diff --git a/tests/Corpus/README.md b/tests/Corpus/README.md index f693ab10..44edd879 100644 --- a/tests/Corpus/README.md +++ b/tests/Corpus/README.md @@ -64,6 +64,11 @@ Verification was run with qpdf 12.4.2 (`qpdf --check`), poppler (`pdfinfo`, `pdf | `outline.pdf` | `/Outlines` root with two sibling items linked by `/First /Last /Next /Prev /Parent`, each with an explicit destination; `/PageMode /UseOutlines`. | 12.3.3, 12.3.2.2 | `qpdf --check`; `qpdf --json --json-key=outlines` lists both items with their destinations | clean | | `name-tree-dests.pdf` | `/Names << /Dests ... >>` name tree with a root `/Kids` node and two leaves carrying `/Limits` and `/Names` for `alpha`, `beta`, `gamma`. | 7.9.6, 12.3.2.3 | `qpdf --check` | clean | | `metadata-xmp.pdf` | Catalog `/Metadata` stream (`/Type /Metadata /Subtype /XML`) with a minimal XMP packet whose `dc:title` is `Broadside`, plus a trailer `/Info` dictionary with the same `/Title`. | 14.3.2, 14.3.3 | `pdfinfo` shows `Title: Broadside` | clean | +| `metadata-xmp-forms.pdf` | Catalog `/Metadata` stream whose XMP packet uses every serialization form: three `rdf:Description` elements, simple properties as attributes (`pdf:Producer`, `xmp:CreateDate`, `pdfaid:part`, `pdfaid:conformance`, `pdfuaid:part`) and as elements (`pdf:Keywords`, `xmpMM:DocumentID`, `xmpMM:InstanceID`), `dc:title` as an `rdf:Alt` in two languages with `x-default` first, `dc:creator` as an `rdf:Seq` of two, `dc:subject` as an `rdf:Bag`, an `rdf:parseType="Resource"` structure; UTF-8 byte order mark in the `begin` attribute and 2 KB of padding before ``. | 14.3.2; ISO 16684-1 7.3-7.9 | `qpdf --check`; `pdfinfo -meta` prints the packet | clean; pdfinfo `Metadata Stream: yes` | +| `info-dictionary.pdf` | Trailer `/Info` with every Table 349 key: a UTF-16BE `/Title` with its byte order marker (`Broadside – Info`), `/Author`, `/Subject`, `/Keywords`, `/Creator`, `/Producer`, `/CreationDate (D:20140314124211+01'00)`, `/ModDate (D:20140924212303Z)`, `/Trapped /True`, and two custom keys, one holding a date in the legacy form with a terminating apostrophe (`D:19981223195200-08'00'`). | 7.9.2.2, 7.9.4, 14.3.3 | `qpdf --check`; `pdfinfo`, `pdfinfo -isodates` | clean; pdfinfo `Title: Broadside – Info`, `CreationDate: 2014-03-14T12:42:11+01`, `ModDate: 2014-09-24T21:23:03Z`, `Custom Metadata: yes` | +| `viewer-preferences.pdf` | Catalog `/ViewerPreferences` with every Table 147 entry set to a value other than its default (`/PrintPageRange [1 1 1 1]`, `/NumCopies 2`, `/PrintScaling /None`, `/Enforce [/PrintScaling]`, ...), `/PageLayout /TwoPageRight`, `/PageMode /UseOC`; `%PDF-2.0` with a trailer `/ID`. | 7.7.2 Table 29, 12.2 Tables 147-148 | `qpdf --check`, `pdfinfo` | clean | +| `catalog-version-extensions.pdf` | `%PDF-1.7` header with catalog `/Version /2.0`; `/Extensions` with an `ADBE` developer extensions dictionary (level 3) and an `ISO_` array holding the ISO/TS 32001 declaration (`/ExtensionLevel 32001 /ExtensionRevision (:2022) /URL ...`); `/Requirements` with one `EnableJavaScripts` requirement (`/Penalty 50`, a `NoOp` handler); trailer `/ID` with two different identifiers. | 7.7.2 Table 29, 7.12 Tables 48-49, 12.11 Tables 273-274, 14.4 | `qpdf --check`, `pdfinfo` | clean; qpdf `PDF Version: 1.7 extension level 3`, pdfinfo `PDF version: 2.0` | +| `page-labels.pdf` | Twelve pages with a `/PageLabels` number tree whose root holds `/Nums` (no `/Kids`): lowercase roman from 0, decimal from 3, uppercase roman from 5 with `/St 4`, uppercase letters from 7 with `/St 26`, lowercase letters from 9 with `/St 52` and `/P (A-)`, a prefix-only range from 11. Labels: `i ii iii 1 2 IV V Z AA A-zz A-aaa Cover`. | 7.9.7, 12.4.2 Table 161 | `qpdf --check`; `qpdf --json --json-key=pagelabels` | clean; qpdf lists the six ranges (index, `/S`, `/St`, `/P`) | The crypt filter `/Length` entries in the R4 and R6 files are `16` and `32` (bytes), the form Acrobat and qpdf write and that Table 25 describes for the standard security handler; the same table also says the key "shall have the value of 128/256". Readers should accept both forms. diff --git a/tests/Corpus/catalog-version-extensions.pdf b/tests/Corpus/catalog-version-extensions.pdf new file mode 100644 index 0000000000000000000000000000000000000000..b7b5456b400cb364513b77544be231d52f89dd2b GIT binary patch literal 787 zcmZWn-EW&P5P#>dxR*%n!>}=6LKQ_?mQ?N5E)m)GQdN@)mz0TOW}J`iuixP=3DNw5 zxbyGh?&rZ`dix>p6E6S`I{)R3M!>$kH3;mJvZ~S>U<^xNkAGZ( z^Ps1Y;jVP9uWkev;u_fZ>;bM`tZmvG#`gQYU$)xUX2V*m>Oz@Nio>urm$cO+S%anP@N z-gH{;k{;GYmrA$%%XHpDVPDFEoP=FA&lH*7))oQ+AAw!xe_)rXp&^c;K4MX-i9Wy+ zr~5Jxkfeh6GHmtMtSEg-#F;ws9t^HM4w1)C2V@+FF|6TSOTl%aKGh;Yj=IyY4N3J_ zvqqJ)3-=C}$|5LaDuYl;OjCiWNYpAtKIBQt$1o~l9_Fcx l^GF2=&*LPePmqUF bytes: ], trailer_extra=b" /Info 5 0 R") +def gen_info_dictionary() -> bytes: + """14.3.3 Table 349: every key, a custom key, Trapped as a name; 7.9.4 dates with an offset, with Z and in the + legacy form with the terminating apostrophe (NOTE 2); 7.9.2.2 a UTF-16BE title with its byte order marker.""" + title = b"\xfe\xff" + "Broadside – Info".encode("utf-16-be") + return simple_file([ + (1, catalog()), + (2, pages()), + (3, page()), + (4, b"<< /Title <" + title.hex().upper().encode() + b"> /Author (Ada Lovelace) /Subject (Document information)" + b" /Keywords (info, metadata) /Creator (generate.py) /Producer (Broadside corpus)" + b" /CreationDate (D:20140314124211+01'00) /ModDate (D:20140924212303Z) /Trapped /True" + b" /Printed (D:19981223195200-08'00') /Department (Corpus) >>"), + ], trailer_extra=b" /Info 4 0 R") + + +XMP_FORMS = (b'\n' + b'\n' + b' \n' + b' \n' + b' xmp, forms\n' + b' \n' + b' \n' + b' XMP forms' + b'XMP-Formen\n' + b' Ada LovelaceGrace Hopper\n' + b' pdfxmp\n' + b' parseType2\n' + b' \n' + b' \n' + b' uuid:6b1f3c2e-69a0-4c6b-9d1e-000000000069\n' + b' uuid:6b1f3c2e-69a0-4c6b-9d1e-000000000070\n' + b' \n' + b' \n' + b'\n' + + b' ' * 2048 + b'\n' + b'') + + +def gen_metadata_xmp_forms() -> bytes: + """14.3.2 metadata stream; ISO 16684-1 7.3 packet wrapper with padding, 7.5-7.7 attribute and element forms, + arrays of the three kinds, a language alternative, a parseType="Resource" structure, several rdf:Description.""" + return simple_file([ + (1, catalog(b" /Metadata 4 0 R")), + (2, pages()), + (3, page()), + (4, stream(b"/Type /Metadata /Subtype /XML", XMP_FORMS)), + ]) + + +def gen_viewer_preferences() -> bytes: + """12.2 Tables 147 and 148: every viewer preference with a value other than its default, Enforce (PDF 2.0); + 7.7.2 Table 29 PageLayout and PageMode.""" + id0 = file_id("viewer-preferences").hex().encode() + prefs = (b"<< /HideToolbar true /HideMenubar true /HideWindowUI true /FitWindow true /CenterWindow true" + b" /DisplayDocTitle true /NonFullScreenPageMode /UseOutlines /Direction /R2L /ViewArea /MediaBox" + b" /ViewClip /BleedBox /PrintArea /TrimBox /PrintClip /ArtBox /PrintScaling /None" + b" /Duplex /DuplexFlipLongEdge /PickTrayByPDFSize true /PrintPageRange [1 1 1 1] /NumCopies 2" + b" /Enforce [/PrintScaling] >>") + return simple_file([ + (1, catalog(b" /ViewerPreferences " + prefs + b" /PageLayout /TwoPageRight /PageMode /UseOC")), + (2, pages()), + (3, page()), + ], version="2.0", trailer_extra=b" /ID [<%s> <%s>]" % (id0, id0)) + + +def gen_catalog_version_extensions() -> bytes: + """7.7.2 Table 29 Version later than the header; 7.12 Tables 48-49 developer extensions as a dictionary and, in + PDF 2.0, as an array (the ISO/TS 32001 declaration); 12.11 Tables 273-274 Requirements; 14.4 distinct IDs.""" + id0 = file_id("catalog-version-extensions").hex().encode() + id1 = hashlib.md5(b"broadside-corpus:catalog-version-extensions:changed").hexdigest().encode() + extra = (b" /Version /2.0 /Extensions << /Type /Extensions /ADBE << /BaseVersion /1.7 /ExtensionLevel 3 >>" + b" /ISO_ [<< /Type /DeveloperExtensions /BaseVersion /2.0 /ExtensionLevel 32001 /ExtensionRevision (:2022)" + b" /URL (https://www.iso.org/standard/45874.html) >>] >>" + b" /Requirements [<< /Type /Requirement /S /EnableJavaScripts /Penalty 50 /RH << /Type /ReqHandler /S /NoOp >> >>]") + return simple_file([ + (1, catalog(extra)), + (2, pages()), + (3, page()), + ], version="1.7", trailer_extra=b" /ID [<%s> <%s>]" % (id0, id1)) + + +def gen_page_labels() -> bytes: + """12.4.2 Table 161: page label ranges of every numbering style, St, P, a prefix-only range; 7.9.7 a number tree + whose root holds Nums.""" + count = 12 + kids = list(range(3, 3 + count)) + labels = (b" /PageLabels << /Nums [0 << /S /r >> 3 << /S /D >> 5 << /Type /PageLabel /S /R /St 4 >>" + b" 7 << /S /A /St 26 >> 9 << /S /a /St 52 /P (A-) >> 11 << /P (Cover) >>] >>") + return simple_file([ + (1, catalog(labels)), + (2, pages(kids=kids)), + ] + [(k, page()) for k in kids]) + + FILES = { "empty-page.pdf": gen_empty_page, "pdf20-header.pdf": gen_pdf20_header, @@ -1249,6 +1348,11 @@ def gen_metadata_xmp() -> bytes: "outline.pdf": gen_outline, "name-tree-dests.pdf": gen_name_tree_dests, "metadata-xmp.pdf": gen_metadata_xmp, + "metadata-xmp-forms.pdf": gen_metadata_xmp_forms, + "info-dictionary.pdf": gen_info_dictionary, + "viewer-preferences.pdf": gen_viewer_preferences, + "catalog-version-extensions.pdf": gen_catalog_version_extensions, + "page-labels.pdf": gen_page_labels, } diff --git a/tests/Corpus/info-dictionary.pdf b/tests/Corpus/info-dictionary.pdf new file mode 100644 index 0000000000000000000000000000000000000000..9ff023a8676dddbfbfc8266c465f6001e0897ebb GIT binary patch literal 750 zcmZWnVQ< zvERLWzFgj5IWI2d)hLoA$UeVBlL^I-yOt@Q8E-arP4UvKxg!O_Jx!+(H&q~p^T&b% zFTSm-j-HZ0{{H=g84VaS{phHD&ydblUP^fa8?vfqZ@>t1@@P4E)AfQ+0L4R9e^e-TxXW&q2qXU(s+X5}8VsDk(n;c_9R7 zceeV#$U|BsBKe8rqcd&GRoL|S#YUb3i(h)=`I5fTmMi zk+BQek@qgzFFc_1JrboCs!RNSB?)0wRG^WUR>uW-a~=_3z?{UWvE zF6xS^K$b{X+&W70QYIw0q9s!MbiEowP9>MOtUBlGHcCer=W`fH@`q_2^)6 zOt<<`Q?e{8%n{N$TGliZ)9FD``)~H`*A7V3dOg8^x8sVUZ#u+{kOAy!-!!5A=Cahy z!b*;eT^O;BKiGLghnXPJO7d2p_t&emZP8}2@wNf?!C8dNb0*Ja)4&_9m2bVtM^UqtK=%k$RmWq3K_WlE>pRPW~LIWcfz;Kaa*ffEBK2L5jh z91UbRawhg(k6XAJ#gP!21vnLd uCG))_-$t=42W5ulyX*e?5488YP_=2<@Sd+GCse~#q7?*vavfIR=jDR{ZGPPye_UmW614eV4(t{zd z&a?AkyS>?D+Lu>}CqaN&zIwwU_)lN&8vJq56kD?ae^zXC4FNjj?c%Oj>TM0=`mlei z;aTwiIrtT18H9(`gjR}IEhRDWX7JG&+2##I9V=IOf z3h(DUu9T4#R|X+gUdJyC{^ZhBMY+`#f34=_w?_SNVj6=J7@I7oAzU{_)v&rU5~5WV{==E5;u+hAxUgcNL0qe5c=X$~ldWj)YsH@j%P7NK9?*)_pJIn+K_ ze)DGL&AjQA#r!V)5=RNdV0OQw@fg_Vd_-V5cU+kRu#z9JhLi{^U_T|E(3TeWXi*Ca z_>6C|!i_O%$1OP9P_{>wsGD2lMe53&o*yryxpXaZ`Oi^1v^P*8>!af5!ibG@3NOST zM$a3i*1{rcuWxB8YWiH`Q{$A>B#RZ&qHxk^V5@Y|Du1xZfi1C;d}`iXELZXfY^o5e zfR$Ei*Ah2YzI9kje6X&A)`C+v+7St&{zY?CNM+maoC+_DKFq2E#Y!puY%D)d&$RNj z{QEIVXy->*aZS8!0^xn7n$25ojxy|?&Gg<_L2(umE{$JdGHDH3@Uv+gd3Q3Qm^}QV zzuVR1#Ey_0AfLURw|;vrt?j$4YS{L@+oT~kjdrA{OZ1V?iM|!xgZns>>x#EA@rOwY zqx+QVt*|x?%@NLqw0Cvi>7=3<22p%{V3=k74EE4r_Yk6>uUHmmpRpm0=O52=mP>^; zTz1&|fMgisrwSMSSip9?+l@w|+6j^LlTkVx^aUUElf6j3R+w>t6Zk*Hn-SHHTNh>- MW^vT(&7S7bKZxfETL1t6 literal 0 HcmV?d00001 From 74c59ea9f739a451c26332ff69133ea95ee7fdbe Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:11:02 -0500 Subject: [PATCH 022/152] feat(model): optional content groups, memberships, configurations and visibility (#76) PdfOptionalContentProperties (PdfDocument.OptionalContent), groups, usage, configurations with Order tree, memberships with parsed visibility expressions compiled to allocation-free programs, immutable states (default per 8.11.4.5, alternate configurations, set-OCG-state arrays, auto-state and engine-parity usage application) and the marked-content tracker. New corpus file optional-content.pdf. Co-Authored-By: Claude Opus 5.5 --- src/Broadside/PdfDocument.cs | 29 + .../PdfOptionalContentConfiguration.cs | 157 +++++ src/Broadside/PdfOptionalContentEnums.cs | 74 +++ src/Broadside/PdfOptionalContentGroup.cs | 56 ++ src/Broadside/PdfOptionalContentMembership.cs | 44 ++ src/Broadside/PdfOptionalContentOrderItem.cs | 32 + src/Broadside/PdfOptionalContentProperties.cs | 565 ++++++++++++++++++ src/Broadside/PdfOptionalContentState.cs | 154 +++++ src/Broadside/PdfOptionalContentTracker.cs | 123 ++++ src/Broadside/PdfOptionalContentUsage.cs | 91 +++ .../PdfOptionalContentUsageApplication.cs | 46 ++ .../PdfOptionalContentUsageContext.cs | 16 + src/Broadside/PdfVisibilityExpression.cs | 31 + src/Broadside/PublicAPI.Unshipped.txt | 116 ++++ src/Broadside/VisibilityProgram.cs | 161 +++++ tests/Broadside.TestSupport/Corpus.cs | 1 + .../OptionalContent/OptionalContentPdf.cs | 15 + .../OptionalContent/OptionalContentTests.cs | 289 +++++++++ ...pus_file_names_match_snapshot.verified.txt | 1 + tests/Corpus/README.md | 1 + tests/Corpus/generate.py | 39 ++ tests/Corpus/optional-content.pdf | Bin 0 -> 1806 bytes 22 files changed, 2041 insertions(+) create mode 100644 src/Broadside/PdfOptionalContentConfiguration.cs create mode 100644 src/Broadside/PdfOptionalContentEnums.cs create mode 100644 src/Broadside/PdfOptionalContentGroup.cs create mode 100644 src/Broadside/PdfOptionalContentMembership.cs create mode 100644 src/Broadside/PdfOptionalContentOrderItem.cs create mode 100644 src/Broadside/PdfOptionalContentProperties.cs create mode 100644 src/Broadside/PdfOptionalContentState.cs create mode 100644 src/Broadside/PdfOptionalContentTracker.cs create mode 100644 src/Broadside/PdfOptionalContentUsage.cs create mode 100644 src/Broadside/PdfOptionalContentUsageApplication.cs create mode 100644 src/Broadside/PdfOptionalContentUsageContext.cs create mode 100644 src/Broadside/PdfVisibilityExpression.cs create mode 100644 src/Broadside/VisibilityProgram.cs create mode 100644 tests/Broadside.Tests/OptionalContent/OptionalContentPdf.cs create mode 100644 tests/Broadside.Tests/OptionalContent/OptionalContentTests.cs create mode 100644 tests/Corpus/optional-content.pdf diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index cc956b8f..295a2319 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -54,6 +54,7 @@ public sealed class PdfDocument : IDisposable private readonly DiagnosticSink _diagnostics; private readonly ObjectLoader _loader; private readonly StreamDecoder _streams; + private PdfOptionalContentProperties? _optionalContent; private PdfDocument( PdfSource source, @@ -347,6 +348,34 @@ public async Task SaveAsync(Stream stream, PdfSaveOptions? options = null, Cance /// ISO 32000-2 §7.3.10. public CosObject Resolve(CosObject? value) => _loader.Resolve(value); + /// Gets the document's optional content (layers), or when the catalog has no OCProperties. + /// + /// ISO 32000-2 §8.11 and §7.7.2, Table 29 (PDF 1.5). Without OCProperties every optional content structure is ignored and all + /// content is visible (§8.11.4.2). The same view is returned while the catalog's OCProperties is the same dictionary; its + /// group list is a snapshot taken on first use. + /// + public PdfOptionalContentProperties? OptionalContent + { + get + { + if (Resolve(Catalog.TryGetValue(FileAndLayerNames.OCProperties, out CosObject? entry) ? entry : null) is not CosDictionary dictionary) + { + return null; + } + + PdfOptionalContentProperties? cached = Volatile.Read(ref _optionalContent); + if (cached is not null && ReferenceEquals(cached.Dictionary, dictionary)) + { + return cached; + } + + CosReference? reference = entry as CosReference ?? (Trailer.TryGetValue(KnownNames.Root, out CosObject? root) ? root as CosReference : null); + var created = new PdfOptionalContentProperties(this, dictionary, reference); + PdfOptionalContentProperties? raced = Interlocked.CompareExchange(ref _optionalContent, created, cached); + return raced == cached ? created : (ReferenceEquals(raced!.Dictionary, dictionary) ? raced : created); + } + } + /// Returns a view over a file specification held by , resolving it first. /// A file specification string or dictionary, or a reference to one, of this document. /// The view, or when the value is neither a string nor a dictionary. diff --git a/src/Broadside/PdfOptionalContentConfiguration.cs b/src/Broadside/PdfOptionalContentConfiguration.cs new file mode 100644 index 00000000..5ad6c379 --- /dev/null +++ b/src/Broadside/PdfOptionalContentConfiguration.cs @@ -0,0 +1,157 @@ +using Broadside.Objects; + +namespace Broadside; + +/// +/// An optional content configuration: initial group states and presentation for a user interface. The default configuration +/// (D) or an alternate one (Configs). A live view over the configuration dictionary. +/// +/// +/// ISO 32000-2 §8.11.4.3, Table 99. Defaults are returned, never written: BaseState ON, Intent View, +/// ListMode AllPages, Locked empty; Order and RBGroups are empty in the default configuration and the +/// default configuration's values in the others. +/// +public sealed class PdfOptionalContentConfiguration +{ + private const int MaxOrderDepth = 32; + + private readonly PdfOptionalContentProperties _properties; + + internal PdfOptionalContentConfiguration(PdfOptionalContentProperties properties, CosDictionary dictionary, CosReference? reference, bool isDefault) + { + _properties = properties; + Dictionary = dictionary; + Reference = reference; + IsDefault = isDefault; + } + + /// Gets the configuration dictionary. For a document whose D entry is missing, an empty dictionary not attached to the document. + /// ISO 32000-2 §8.11.4.3, Table 99. + public CosDictionary Dictionary { get; } + + /// Gets the indirect reference to the configuration, or when it is direct. + public CosReference? Reference { get; } + + /// Gets a value indicating whether this is the default configuration (D). + /// ISO 32000-2 §8.11.4.2, Table 98. + public bool IsDefault { get; } + + /// Gets the name of the configuration for a user interface (Name), or . + /// ISO 32000-2 §8.11.4.3, Table 99. + public string? Name => ViewReading.Text(_properties.Document, Dictionary, FileAndLayerNames.Name); + + /// Gets the application or feature that created the configuration (Creator), or . + /// ISO 32000-2 §8.11.4.3, Table 99. + public string? Creator => ViewReading.Text(_properties.Document, Dictionary, FileAndLayerNames.Creator); + + /// Gets the state every group starts from when the configuration is applied (BaseState), as written; ON when absent or unknown. + /// ISO 32000-2 §8.11.4.3, Table 99. In the default configuration it shall be ON; state computation reports and honours OFF, and reads Unchanged as ON. + public PdfOptionalContentBaseState BaseState => ViewReading.Name(_properties.Document, Dictionary, FileAndLayerNames.BaseState)?.Value switch + { + "OFF" => PdfOptionalContentBaseState.Off, + "Unchanged" => PdfOptionalContentBaseState.Unchanged, + _ => PdfOptionalContentBaseState.On, + }; + + /// Gets the groups turned ON after is applied (ON). + /// ISO 32000-2 §8.11.4.3, Table 99. + public IReadOnlyList On => _properties.ReadGroupList(ViewReading.Get(_properties.Document, Dictionary, FileAndLayerNames.ON)); + + /// Gets the groups turned OFF after is applied (OFF). + /// ISO 32000-2 §8.11.4.3, Table 99. A group shall not be in both ON and OFF; state computation applies OFF last. + public IReadOnlyList Off => _properties.ReadGroupList(ViewReading.Get(_properties.Document, Dictionary, FileAndLayerNames.OFF)); + + /// + /// Gets the intents whose groups count when computing visibility (Intent, a name or an array): View when absent; + /// All means every intent; an empty list means no group counts and all content is visible. + /// + /// ISO 32000-2 §8.11.4.3, Table 99, and §8.11.2.3. In the default configuration it shall be View. + public IReadOnlyList Intents => PdfOptionalContentGroup.ReadIntents(_properties.Document, Dictionary); + + /// Gets the auto-state usage application dictionaries (AS). + /// ISO 32000-2 §8.11.4.3, Table 99, and §8.11.4.4, Table 101. + public IReadOnlyList AutoStates => ViewReading.Get(_properties.Document, Dictionary, FileAndLayerNames.AS) is CosArray array + ? [.. array.Select(_properties.Document.Resolve).OfType().Select(item => new PdfOptionalContentUsageApplication(_properties, item))] + : []; + + /// Gets the presentation order of the groups for a user interface (Order), as a tree. + /// ISO 32000-2 §8.11.4.3, Table 99. Absent: empty in the default configuration, the default configuration's order in the others. Nesting deeper than 32 levels is cut off, and an array reached a second time (a cycle or a shared array) is read once. + public IReadOnlyList Order => + FromSelfOrDefault(FileAndLayerNames.Order) is CosArray array ? ReadOrder(array, start: 0, depth: 0, []) : []; + + /// Gets the display mode of (ListMode). + /// ISO 32000-2 §8.11.4.3, Table 99. + public PdfOptionalContentListMode ListMode => + ViewReading.Name(_properties.Document, Dictionary, FileAndLayerNames.ListMode) is { Value: "VisiblePages" } ? PdfOptionalContentListMode.VisiblePages : PdfOptionalContentListMode.AllPages; + + /// Gets the radio-button collections (RBGroups): at most one group of each is ON at a time. + /// ISO 32000-2 §8.11.4.3, Table 99. Absent: empty in the default configuration, the default configuration's in the others. + public IReadOnlyList> RadioButtonGroups => FromSelfOrDefault(FileAndLayerNames.RBGroups) is CosArray array + ? [.. array.Select(_properties.Document.Resolve).OfType().Select(_properties.ReadGroupList)] + : []; + + /// Gets the groups a user interface shall not let the user change (Locked, PDF 1.6). + /// ISO 32000-2 §8.11.4.3, Table 99. Default empty. + public IReadOnlyList Locked => _properties.ReadGroupList(ViewReading.Get(_properties.Document, Dictionary, FileAndLayerNames.Locked)); + + /// + public override string ToString() => Name ?? (IsDefault ? "D" : "Configuration"); + + private CosObject? FromSelfOrDefault(CosName key) => + ViewReading.Get(_properties.Document, Dictionary, key) + ?? (IsDefault ? null : ViewReading.Get(_properties.Document, _properties.DefaultConfigurationDictionary, key)); + + private List ReadOrder(CosArray array, int start, int depth, HashSet visited) + { + var items = new List(); + if (depth >= MaxOrderDepth || !visited.Add(array)) + { + return items; + } + + var pendingChildren = new List(); + PdfOptionalContentGroup? pendingGroup = null; + for (int index = start; index < array.Count; index++) + { + switch (_properties.Document.Resolve(array[index])) + { + case CosDictionary dictionary when _properties.FindGroup(dictionary) is { } group: + Flush(items, ref pendingGroup, pendingChildren); + pendingGroup = group; + break; + case CosArray nested: + string? label = nested.Count > 0 && _properties.Document.Resolve(nested[0]) is CosString text ? text.DecodeText() : null; + if (label is not null) + { + Flush(items, ref pendingGroup, pendingChildren); + var members = ReadOrder(nested, 1, depth + 1, visited); + items.Add(new PdfOptionalContentOrderItem(null, label, members)); + } + else if (pendingGroup is not null && pendingChildren.Count == 0) + { + pendingChildren.AddRange(ReadOrder(nested, 0, depth + 1, visited)); + } + else + { + Flush(items, ref pendingGroup, pendingChildren); + items.Add(new PdfOptionalContentOrderItem(null, null, ReadOrder(nested, 0, depth + 1, visited))); + } + + break; + } + } + + Flush(items, ref pendingGroup, pendingChildren); + return items; + } + + private static void Flush(List items, ref PdfOptionalContentGroup? pendingGroup, List pendingChildren) + { + if (pendingGroup is not null) + { + items.Add(new PdfOptionalContentOrderItem(pendingGroup, null, [.. pendingChildren])); + pendingGroup = null; + pendingChildren.Clear(); + } + } +} diff --git a/src/Broadside/PdfOptionalContentEnums.cs b/src/Broadside/PdfOptionalContentEnums.cs new file mode 100644 index 00000000..e1e51779 --- /dev/null +++ b/src/Broadside/PdfOptionalContentEnums.cs @@ -0,0 +1,74 @@ +namespace Broadside; + +/// How a configuration initializes the states of all groups before its ON and OFF arrays apply (BaseState). +/// ISO 32000-2 §8.11.4.3, Table 99. Default ; in the default configuration it shall be . +public enum PdfOptionalContentBaseState +{ + /// Every group is turned ON. + On, + + /// Every group is turned OFF. + Off, + + /// Every group keeps its current state. + Unchanged, +} + +/// Which groups of the Order array a user interface displays (ListMode). +/// ISO 32000-2 §8.11.4.3, Table 99. Default . +public enum PdfOptionalContentListMode +{ + /// Every group in the Order array. + AllPages, + + /// Only groups referenced by one or more visible pages. + VisiblePages, +} + +/// The visibility policy of a membership dictionary without a visibility expression (P). +/// ISO 32000-2 §8.11.2.2, Table 97. Default . +public enum PdfVisibilityPolicy +{ + /// Visible only if every group in OCGs is ON. + AllOn, + + /// Visible if any group in OCGs is ON. + AnyOn, + + /// Visible if any group in OCGs is OFF. + AnyOff, + + /// Visible only if every group in OCGs is OFF. + AllOff, +} + +/// The kind of node in a visibility expression. +/// ISO 32000-2 §8.11.2.2 (PDF 1.6): an array whose first element is And, Or or Not; operands are groups or nested expressions. +public enum PdfVisibilityOperator +{ + /// A leaf: one optional content group, true when it is ON. + Group, + + /// True when every operand is true. + And, + + /// True when any operand is true. + Or, + + /// True when its single operand is false. + Not, +} + +/// The situation a usage application dictionary applies to (Event). +/// ISO 32000-2 §8.11.4.4, Table 101. +public enum PdfOptionalContentEvent +{ + /// Interactive viewing. + View, + + /// Printing. + Print, + + /// Exporting to a format without optional content. + Export, +} diff --git a/src/Broadside/PdfOptionalContentGroup.cs b/src/Broadside/PdfOptionalContentGroup.cs new file mode 100644 index 00000000..8b68e438 --- /dev/null +++ b/src/Broadside/PdfOptionalContentGroup.cs @@ -0,0 +1,56 @@ +using Broadside.Objects; + +namespace Broadside; + +/// An optional content group: a collection of graphics that can be made visible or invisible. A live view over its dictionary. +/// +/// ISO 32000-2 §8.11.2.1 (PDF 1.5), Table 96. A group's state (ON or OFF) is not stored in the file; it lives in a +/// . Only groups listed in the optional content properties' OCGs array are optional +/// content (§8.11.3.2). Its Metadata entry is reported by PdfDocument.EnumerateObjectMetadata. +/// +public sealed class PdfOptionalContentGroup +{ + private readonly PdfDocument _document; + + internal PdfOptionalContentGroup(PdfDocument document, CosDictionary dictionary, CosReference? reference, int ordinal) + { + _document = document; + Dictionary = dictionary; + Reference = reference; + Ordinal = ordinal; + } + + /// Gets the optional content group dictionary. + /// ISO 32000-2 §8.11.2.1, Table 96. + public CosDictionary Dictionary { get; } + + /// Gets the indirect reference to the group (groups shall be indirect objects), or . + public CosReference? Reference { get; } + + /// Gets the name of the group for a user interface (Name); empty when missing. + /// ISO 32000-2 §8.11.2.1, Table 96 (required). + public string Name => ViewReading.Text(_document, Dictionary, FileAndLayerNames.Name) ?? string.Empty; + + /// Gets the intended uses of the group (Intent, a name or an array of names): View when absent. + /// ISO 32000-2 §8.11.2.1, Table 96, and §8.11.2.3. View and Design are defined; second-class names may appear. + public IReadOnlyList Intents => ReadIntents(_document, Dictionary); + + /// Gets the usage dictionary describing the nature of the group's content (Usage), or . + /// ISO 32000-2 §8.11.2.1, Table 96, and §8.11.4.4, Table 100. + public PdfOptionalContentUsage? Usage => + ViewReading.Get(_document, Dictionary, FileAndLayerNames.Usage) is CosDictionary usage ? new PdfOptionalContentUsage(_document, usage) : null; + + /// Gets the group's position in the optional content properties' group list. + internal int Ordinal { get; } + + /// + public override string ToString() => Name; + + /// Reads an Intent entry (a name or an array of names); View when absent or unusable. + internal static CosName[] ReadIntents(PdfDocument document, CosDictionary dictionary) => ViewReading.Get(document, dictionary, FileAndLayerNames.Intent) switch + { + CosName name => [name], + CosArray array => [.. array.Select(document.Resolve).OfType()], + _ => [FileAndLayerNames.View], + }; +} diff --git a/src/Broadside/PdfOptionalContentMembership.cs b/src/Broadside/PdfOptionalContentMembership.cs new file mode 100644 index 00000000..6d92cbb8 --- /dev/null +++ b/src/Broadside/PdfOptionalContentMembership.cs @@ -0,0 +1,44 @@ +using Broadside.Objects; + +namespace Broadside; + +/// +/// An optional content membership dictionary: content whose visibility depends on several groups through a policy or a visibility +/// expression. A live view over its dictionary. +/// +/// +/// ISO 32000-2 §8.11.2.2 (PDF 1.5), Table 97. A visibility expression (VE, PDF 1.6) takes precedence over OCGs and +/// P; an invalid expression falls back to them. Without usable groups the membership has no effect: content is visible. +/// +public sealed class PdfOptionalContentMembership +{ + private readonly PdfOptionalContentProperties _properties; + + internal PdfOptionalContentMembership(PdfOptionalContentProperties properties, CosDictionary dictionary, CosReference? reference) + { + _properties = properties; + Dictionary = dictionary; + Reference = reference; + } + + /// Gets the membership dictionary. + /// ISO 32000-2 §8.11.2.2, Table 97. + public CosDictionary Dictionary { get; } + + /// Gets the indirect reference to the dictionary, or . + public CosReference? Reference { get; } + + /// Gets the groups whose states the policy combines (OCGs, a dictionary or an array); null and deleted entries are ignored. + /// ISO 32000-2 §8.11.2.2, Table 97. + public IReadOnlyList Groups => + _properties.ReadGroupList(ViewReading.Get(_properties.Document, Dictionary, FileAndLayerNames.OCGs), Reference); + + /// Gets the visibility policy (P); when absent or unknown. + /// ISO 32000-2 §8.11.2.2, Table 97. An unknown name is reported as VisibilityPolicyInvalid when visibility is computed. + public PdfVisibilityPolicy Policy => PdfOptionalContentProperties.ReadPolicy(ViewReading.Name(_properties.Document, Dictionary, FileAndLayerNames.P)) ?? PdfVisibilityPolicy.AnyOn; + + /// Gets the parsed visibility expression (VE), or when absent or invalid. + /// ISO 32000-2 §8.11.2.2, Table 97 (PDF 1.6). + public PdfVisibilityExpression? VisibilityExpression => + ViewReading.Get(_properties.Document, Dictionary, FileAndLayerNames.VE) is CosArray array ? _properties.ParseExpression(array, Reference) : null; +} diff --git a/src/Broadside/PdfOptionalContentOrderItem.cs b/src/Broadside/PdfOptionalContentOrderItem.cs new file mode 100644 index 00000000..8ab1dc45 --- /dev/null +++ b/src/Broadside/PdfOptionalContentOrderItem.cs @@ -0,0 +1,32 @@ +namespace Broadside; + +/// +/// One node of a configuration's Order tree, as a user interface presents it: a group (whose children are its sublayers), +/// a labelled collection, or an unlabelled list. +/// +/// +/// ISO 32000-2 §8.11.4.3, Table 99 and Examples 1 and 2. A nested array whose first element is a text string is a labelled +/// collection (, not nesting of content); a nested array without a label that follows a group holds that +/// group's sublayers; any other nested array is an unlabelled list. Exposed as written; groups not listed are not added. +/// +public sealed class PdfOptionalContentOrderItem +{ + internal PdfOptionalContentOrderItem(PdfOptionalContentGroup? group, string? label, IReadOnlyList children) + { + Group = group; + Label = label; + Children = children; + } + + /// Gets the group this node presents, or for a collection or list. + public PdfOptionalContentGroup? Group { get; } + + /// Gets the non-selectable label of a collection, or . + public string? Label { get; } + + /// Gets the nodes under this one: a group's sublayers or a collection's members. + public IReadOnlyList Children { get; } + + /// + public override string ToString() => Group?.Name ?? Label ?? "[]"; +} diff --git a/src/Broadside/PdfOptionalContentProperties.cs b/src/Broadside/PdfOptionalContentProperties.cs new file mode 100644 index 00000000..ff455975 --- /dev/null +++ b/src/Broadside/PdfOptionalContentProperties.cs @@ -0,0 +1,565 @@ +using Broadside.Caching; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// +/// The document's optional content properties: every optional content group, the default and alternate configurations, and the +/// visibility computation over them. +/// +/// +/// +/// ISO 32000-2 §8.11 (PDF 1.5), §8.11.4.2, Table 98. Read from the catalog's OCProperties; when it is absent there is no +/// optional content and every optional content structure is ignored ( is +/// ; all content is visible). +/// +/// +/// The group list (OCGs), each group's intents and each membership dictionary's compiled visibility are read once, when first +/// needed, and kept as a snapshot: returns a new view after OCProperties is replaced. +/// Everything else (configurations, names, usage) reads the COS objects on every call. Nothing is ever written to the file: +/// a missing D reads as an empty configuration with a diagnostic. +/// +/// +/// Visibility (§8.11.2, §8.11.3): content marked with a group listed in OCGs is visible when the group is ON; with a +/// membership dictionary, when its visibility expression or policy says so. Content marked with anything else (a group not listed, +/// a dictionary that is neither) is not optional content and is visible. Nested optional content is visible only when every +/// level is (). allocates nothing once a membership is compiled. +/// +/// +public sealed class PdfOptionalContentProperties +{ + private const int MaxExpressionDepth = 32; + private const int MaxExpressionNodes = 4096; + + private readonly CosReference? _reference; + private readonly PdfOptionalContentGroup[] _groups; + private readonly Dictionary _byDictionary = new(ReferenceEqualityComparer.Instance); + private readonly OnceCache _programs = new(); + private readonly CosDictionary _missingDefault = new(); + + internal PdfOptionalContentProperties(PdfDocument document, CosDictionary dictionary, CosReference? reference) + { + Document = document; + Dictionary = dictionary; + _reference = reference; + var groups = new List(); + if (ViewReading.Get(document, dictionary, FileAndLayerNames.OCGs) is CosArray array) + { + foreach (CosObject entry in array) + { + switch (document.Resolve(entry)) + { + case CosDictionary group when !_byDictionary.ContainsKey(group): + if (ViewReading.Name(document, group, KnownNames.Type) is { } type && !type.Equals(FileAndLayerNames.OCG)) + { + Warn(DiagnosticCodes.OptionalContentGroupInvalid, $"An OCGs entry is a /{type.Value} dictionary, not an optional content group; it is ignored.", entry as CosReference); + break; + } + + if (!group.ContainsKey(KnownNames.Type)) + { + Warn(DiagnosticCodes.OptionalContentGroupInvalid, "An optional content group has no Type entry; it is read as an optional content group.", entry as CosReference); + } + + var view = new PdfOptionalContentGroup(document, group, entry as CosReference, groups.Count); + groups.Add(view); + _byDictionary.Add(group, view); + break; + case CosDictionary or CosNull: + break; + default: + Warn(DiagnosticCodes.OptionalContentGroupInvalid, "An OCGs entry is not a dictionary; it is ignored.", entry as CosReference); + break; + } + } + } + else + { + Warn(DiagnosticCodes.OptionalContentGroupsMissing, "The optional content properties have no OCGs array; no group is optional content and all content is visible.", null); + } + + _groups = [.. groups]; + GroupIntents = [.. _groups.Select(group => PdfOptionalContentGroup.ReadIntents(document, group.Dictionary))]; + } + + /// Gets the optional content properties dictionary (OCProperties). + /// ISO 32000-2 §8.11.4.2, Table 98. + public CosDictionary Dictionary { get; } + + /// Gets every optional content group, in the order of OCGs (duplicates once). + /// ISO 32000-2 §8.11.4.2, Table 98: every optional content group shall be listed. + public IReadOnlyList Groups => _groups; + + /// Gets the default configuration (D), which sets the initial states. + /// ISO 32000-2 §8.11.4.2, Table 98 (required). When missing, an empty configuration (all defaults) with an OptionalContentConfigMissing diagnostic. + public PdfOptionalContentConfiguration DefaultConfiguration + { + get + { + if (ViewReading.Get(Document, Dictionary, FileAndLayerNames.D) is CosDictionary configuration) + { + return new PdfOptionalContentConfiguration(this, configuration, ViewReading.ReferenceOf(Dictionary, FileAndLayerNames.D), isDefault: true); + } + + Warn(DiagnosticCodes.OptionalContentConfigMissing, "The optional content properties have no default configuration D; an empty one is used (every group ON).", null); + return new PdfOptionalContentConfiguration(this, _missingDefault, null, isDefault: true); + } + } + + /// Gets the alternate configurations (Configs). + /// ISO 32000-2 §8.11.4.2, Table 98. + public IReadOnlyList Configurations => ViewReading.Get(Document, Dictionary, FileAndLayerNames.Configs) is CosArray array + ? [.. array.Where(entry => Document.Resolve(entry) is CosDictionary).Select(entry => new PdfOptionalContentConfiguration(this, (CosDictionary)Document.Resolve(entry), entry as CosReference, isDefault: false))] + : []; + + /// Gets the document. + internal PdfDocument Document { get; } + + /// Gets each group's intents by ordinal, read once. + internal CosName[][] GroupIntents { get; } + + /// Gets D, or an empty dictionary when it is missing (no diagnostic). + internal CosDictionary DefaultConfigurationDictionary => + ViewReading.Get(Document, Dictionary, FileAndLayerNames.D) as CosDictionary ?? _missingDefault; + + /// Returns the listed group is (or refers to), or . + /// A group dictionary or a reference to one. + /// The group, or when the value is not a group listed in OCGs. + /// ISO 32000-2 §8.11.4.2, Table 98. + public PdfOptionalContentGroup? FindGroup(CosObject? value) => + Document.Resolve(value) is CosDictionary dictionary && _byDictionary.TryGetValue(dictionary, out PdfOptionalContentGroup? group) ? group : null; + + /// Returns a view over the membership dictionary is (or refers to), or . + /// A membership dictionary or a reference to one. + /// The view, or when the value is not a dictionary of type OCMD. + /// ISO 32000-2 §8.11.2.2, Table 97. + public PdfOptionalContentMembership? FindMembership(CosObject? value) => + Document.Resolve(value) is CosDictionary dictionary && ViewReading.HasType(Document, dictionary, FileAndLayerNames.OCMD) + ? new PdfOptionalContentMembership(this, dictionary, value as CosReference) + : null; + + /// Computes the initial states from the default configuration: BaseState, then ON, then OFF. + /// The states every processor starts from, with the default configuration's intents. + /// + /// ISO 32000-2 §8.11.4.5 steps a and b. Usage and auto-state entries are not applied (that is for interactive processors and + /// an explicit step: ). A BaseState other than ON in D is reported and honoured + /// (OFF) or read as ON (Unchanged); a group in both ON and OFF is reported and ends OFF; an Intent other + /// than View in D is reported and honoured. + /// + public PdfOptionalContentState GetDefaultStates() => ComputeStates(DefaultConfiguration, current: null); + + /// Computes the states gives when applied over . + /// The default configuration or one of . + /// The states a BaseState of Unchanged keeps; the default states when . + /// The new states, with the configuration's intents. + /// ISO 32000-2 §8.11.4.3, Table 99, and §8.11.4.5. + public PdfOptionalContentState GetStates(PdfOptionalContentConfiguration configuration, PdfOptionalContentState? current = null) + { + ArgumentNullException.ThrowIfNull(configuration); + if (current is not null) + { + CheckState(current); + } + + return ComputeStates(configuration, current); + } + + /// Returns whether content marked with is visible under . + /// + /// The value of an OC entry (XObject, annotation) or the property list of an /OC marked-content section: a group, + /// a membership dictionary, or a reference to one. and anything else is not optional content: visible. + /// + /// States from this properties view. + /// only when the content is optional and hidden. + /// was computed by another properties view. + /// + /// ISO 32000-2 §8.11.2, §8.11.3.2 and §8.11.3.3. A group listed in OCGs gives its state, or has no effect when its intent + /// does not count (§8.11.2.3). A membership dictionary evaluates its visibility expression, else its policy over its groups; a + /// malformed expression falls back to the policy (VisibilityExpressionInvalid). A group dictionary not listed in + /// OCGs is not optional content (OptionalContentGroupNotListed). Allocation-free once the membership is compiled. + /// + public bool IsVisible(CosObject? ocgOrOcmd, PdfOptionalContentState state) + { + CheckState(state); + if (Document.Resolve(ocgOrOcmd) is not CosDictionary dictionary) + { + return true; + } + + if (_byDictionary.TryGetValue(dictionary, out PdfOptionalContentGroup? group)) + { + return !state.Effective[group.Ordinal] || state.On[group.Ordinal]; + } + + VisibilityProgram program = _programs.GetOrCreate( + dictionary, + (Properties: this, Reference: ocgOrOcmd as CosReference), + static (dictionary, context) => new Created(context.Properties.Compile(dictionary, context.Reference)), + static (_, _) => VisibilityProgram.AlwaysVisible); + return program.Evaluate(state.On, state.Effective); + } + + /// + /// Applies the auto-state (AS) entries of the state's configuration whose Event is : + /// each listed group's usage categories give a recommended state, and a group is ON only when all its recommendations are. + /// + /// The current states. + /// View when displaying, Print or Export for the duration of those operations. + /// The external factors: zoom, language, user. A category whose factor is not supplied recommends nothing. + /// The new states; groups without any recommendation keep theirs. + /// + /// ISO 32000-2 §8.11.4.4 and §8.11.4.5. Categories: View, Print, Export (the usage's state; Print without PrintState leaves the + /// group unchanged), Zoom (ON when min ≤ zoom < max), User (ON on an exact name match), Language (ON on an exact match; else, + /// when no group of the entry matches exactly, ON for partial matches that are Preferred; otherwise OFF). + /// + public PdfOptionalContentState ApplyAutoStates(PdfOptionalContentState state, PdfOptionalContentEvent usageEvent, PdfOptionalContentUsageContext context) + { + CheckState(state); + ArgumentNullException.ThrowIfNull(context); + var recommendation = new bool?[_groups.Length]; + foreach (PdfOptionalContentUsageApplication application in state.Configuration.AutoStates) + { + if (application.Event != usageEvent) + { + continue; + } + + IReadOnlyList groups = application.Groups; + IReadOnlyList categories = application.Categories; + bool anyExactLanguage = context.Language is { } wanted + && groups.Any(group => group.Usage?.Language is { } language && string.Equals(language, wanted, StringComparison.OrdinalIgnoreCase)); + foreach (PdfOptionalContentGroup group in groups) + { + PdfOptionalContentUsage? usage = group.Usage; + foreach (CosName category in categories) + { + bool? recommended = Recommend(category.Value, usage, context, anyExactLanguage); + if (recommended is { } value) + { + recommendation[group.Ordinal] = (recommendation[group.Ordinal] ?? true) && value; + } + } + } + } + + bool[] states = state.CopyStates(); + for (int ordinal = 0; ordinal < states.Length; ordinal++) + { + if (recommendation[ordinal] is { } value) + { + states[ordinal] = value; + } + } + + return new PdfOptionalContentState(this, state.Configuration, states, [.. state.Intents]); + } + + /// + /// Applies every group's usage state for (ViewState, PrintState or ExportState) + /// whether or not an auto-state entry asks for it, as pdf.js and PDFBox do. Not the specification's behaviour: for engine parity only. + /// + /// The current states. + /// Which usage state to apply. + /// The new states. + /// ISO 32000-2 §8.11.4.4 says usage states apply only through AS ("If no AS entry is present, states shall not be automatically adjusted"). + public PdfOptionalContentState ApplyUsageStates(PdfOptionalContentState state, PdfOptionalContentEvent usageEvent) + { + CheckState(state); + bool[] states = state.CopyStates(); + foreach (PdfOptionalContentGroup group in _groups) + { + PdfOptionalContentUsage? usage = group.Usage; + bool? value = usageEvent switch + { + PdfOptionalContentEvent.View => usage?.ViewState, + PdfOptionalContentEvent.Print => usage?.PrintState, + _ => usage?.ExportState, + }; + if (value is { } on) + { + states[group.Ordinal] = on; + } + } + + return new PdfOptionalContentState(this, state.Configuration, states, [.. state.Intents]); + } + + /// Reads a visibility policy name; when absent or unknown. + internal static PdfVisibilityPolicy? ReadPolicy(CosName? name) => name?.Value switch + { + "AllOn" => PdfVisibilityPolicy.AllOn, + "AnyOn" => PdfVisibilityPolicy.AnyOn, + "AnyOff" => PdfVisibilityPolicy.AnyOff, + "AllOff" => PdfVisibilityPolicy.AllOff, + _ => null, + }; + + /// + /// Reads a group or an array of groups, keeping listed groups in order. Null and deleted entries are skipped silently; a group + /// dictionary not listed in OCGs is reported (OptionalContentGroupNotListed) and skipped; anything else is + /// reported (OptionalContentGroupInvalid) and skipped. + /// + internal IReadOnlyList ReadGroupList(CosObject? value) => ReadGroupList(value, null); + + /// + internal IReadOnlyList ReadGroupList(CosObject? value, CosReference? owner) + { + var groups = new List(); + switch (value) + { + case CosDictionary: + Add(value); + break; + case CosArray array: + foreach (CosObject entry in array) + { + Add(entry); + } + + break; + } + + return groups; + + void Add(CosObject entry) + { + switch (Document.Resolve(entry)) + { + case CosNull: + break; + case CosDictionary dictionary when _byDictionary.TryGetValue(dictionary, out PdfOptionalContentGroup? group): + groups.Add(group); + break; + case CosDictionary dictionary when !ViewReading.HasType(Document, dictionary, FileAndLayerNames.OCMD): + Warn(DiagnosticCodes.OptionalContentGroupNotListed, "An optional content group is not listed in OCProperties OCGs; it is not optional content.", entry as CosReference ?? owner); + break; + default: + Warn(DiagnosticCodes.OptionalContentGroupInvalid, "An entry that shall be an optional content group is not one; it is ignored.", entry as CosReference ?? owner); + break; + } + } + } + + /// Parses a visibility expression; (with a diagnostic) when it is unusable. + internal PdfVisibilityExpression? ParseExpression(CosArray array, CosReference? owner) + { + int nodes = 0; + var path = new HashSet(ReferenceEqualityComparer.Instance); + string? problem = null; + PdfVisibilityExpression? expression = ParseNode(array, 0); + if (problem is not null) + { + Warn(DiagnosticCodes.VisibilityExpressionInvalid, problem, owner); + } + + return expression; + + PdfVisibilityExpression? ParseNode(CosArray node, int depth) + { + if (depth >= MaxExpressionDepth || ++nodes > MaxExpressionNodes) + { + problem = "A visibility expression nests too deeply; the OCGs and P entries are used instead."; + return null; + } + + if (!path.Add(node)) + { + problem = "A visibility expression contains itself; the OCGs and P entries are used instead."; + return null; + } + + try + { + PdfVisibilityOperator? @operator = node.Count > 0 && Document.Resolve(node[0]) is CosName name + ? name.Value switch + { + "And" => PdfVisibilityOperator.And, + "Or" => PdfVisibilityOperator.Or, + "Not" => PdfVisibilityOperator.Not, + _ => null, + } + : null; + if (@operator is null) + { + problem = "A visibility expression does not start with And, Or or Not; the OCGs and P entries are used instead."; + return null; + } + + var operands = new List(); + for (int index = 1; index < node.Count; index++) + { + switch (Document.Resolve(node[index])) + { + case CosNull: + break; + case CosArray nested: + PdfVisibilityExpression? operand = ParseNode(nested, depth + 1); + if (operand is null) + { + return null; + } + + operands.Add(operand); + break; + case CosDictionary dictionary when _byDictionary.TryGetValue(dictionary, out PdfOptionalContentGroup? group): + operands.Add(new PdfVisibilityExpression(PdfVisibilityOperator.Group, group, [])); + break; + case CosDictionary: + Warn(DiagnosticCodes.OptionalContentGroupNotListed, "A visibility expression names a group not listed in OCProperties OCGs; the operand has no effect.", node[index] as CosReference ?? owner); + break; + default: + problem ??= "A visibility expression operand is neither a group nor an expression; it is ignored."; + break; + } + } + + if (@operator == PdfVisibilityOperator.Not && node.Count != 2) + { + problem ??= "A Not visibility expression shall have exactly one operand; the first one is used."; + if (operands.Count > 1) + { + operands.RemoveRange(1, operands.Count - 1); + } + } + + return new PdfVisibilityExpression(@operator.Value, null, operands); + } + finally + { + path.Remove(node); + } + } + } + + /// Compiles the visibility of a dictionary that is not a listed group. + private VisibilityProgram Compile(CosDictionary dictionary, CosReference? reference) + { + CosName? type = ViewReading.Name(Document, dictionary, KnownNames.Type); + if (type is not null && type.Equals(FileAndLayerNames.OCG)) + { + Warn(DiagnosticCodes.OptionalContentGroupNotListed, "Content refers to an optional content group not listed in OCProperties OCGs; it is not optional content and is visible.", reference); + return VisibilityProgram.AlwaysVisible; + } + + if (type is null || !type.Equals(FileAndLayerNames.OCMD)) + { + return VisibilityProgram.AlwaysVisible; + } + + if (ViewReading.Get(Document, dictionary, FileAndLayerNames.VE) is CosArray expression && ParseExpression(expression, reference) is { } parsed) + { + return VisibilityProgram.Compile(parsed); + } + + CosName? policyName = ViewReading.Name(Document, dictionary, FileAndLayerNames.P); + PdfVisibilityPolicy? policy = ReadPolicy(policyName); + if (policyName is not null && policy is null) + { + Warn(DiagnosticCodes.VisibilityPolicyInvalid, $"The visibility policy /{policyName.Value} is not AllOn, AnyOn, AnyOff or AllOff; AnyOn is used.", reference); + } + + return VisibilityProgram.Compile(ReadGroupList(ViewReading.Get(Document, dictionary, FileAndLayerNames.OCGs), reference), policy ?? PdfVisibilityPolicy.AnyOn); + } + + private PdfOptionalContentState ComputeStates(PdfOptionalContentConfiguration configuration, PdfOptionalContentState? current) + { + CosReference? where = configuration.Reference ?? _reference; + PdfOptionalContentBaseState baseState = configuration.BaseState; + CosName? written = ViewReading.Name(Document, configuration.Dictionary, FileAndLayerNames.BaseState); + if (configuration.IsDefault && written is not null && baseState != PdfOptionalContentBaseState.On) + { + Warn(DiagnosticCodes.OptionalContentBaseStateInvalid, $"The default configuration's BaseState shall be ON, not /{written.Value}; {(baseState == PdfOptionalContentBaseState.Off ? "OFF is honoured" : "ON is used")}.", where); + if (baseState == PdfOptionalContentBaseState.Unchanged) + { + baseState = PdfOptionalContentBaseState.On; + } + } + + IReadOnlyList intents = configuration.Intents; + if (configuration.IsDefault && ViewReading.Get(Document, configuration.Dictionary, FileAndLayerNames.Intent) is not null + && !(intents.Count == 1 && intents[0].Equals(FileAndLayerNames.View))) + { + Warn(DiagnosticCodes.OptionalContentIntentInvalid, "The default configuration's Intent shall be View; the written intent is honoured.", where); + } + + bool[] states; + if (baseState == PdfOptionalContentBaseState.Unchanged) + { + states = (current ?? ComputeStates(DefaultConfiguration, null)).CopyStates(); + } + else + { + states = new bool[_groups.Length]; + Array.Fill(states, baseState == PdfOptionalContentBaseState.On); + } + + var on = new HashSet(); + foreach (PdfOptionalContentGroup group in configuration.On) + { + states[group.Ordinal] = true; + on.Add(group.Ordinal); + } + + foreach (PdfOptionalContentGroup group in configuration.Off) + { + if (on.Contains(group.Ordinal)) + { + Warn(DiagnosticCodes.OptionalContentGroupOnAndOff, $"The group '{group.Name}' is in both the ON and the OFF array of a configuration; OFF is applied last.", where); + } + + states[group.Ordinal] = false; + } + + return new PdfOptionalContentState(this, configuration, states, [.. intents]); + } + + private void CheckState(PdfOptionalContentState state) + { + ArgumentNullException.ThrowIfNull(state); + if (!ReferenceEquals(state.Properties, this)) + { + throw new ArgumentException("The state was computed by another optional content properties view.", nameof(state)); + } + } + + private void Warn(string code, string message, CosReference? reference) => ViewReading.Warn(Document, code, message, reference ?? _reference); + + private static bool? Recommend(string category, PdfOptionalContentUsage? usage, PdfOptionalContentUsageContext context, bool anyExactLanguage) + { + if (usage is null) + { + return null; + } + + switch (category) + { + case "View": + return usage.ViewState; + case "Print": + return usage.PrintState; + case "Export": + return usage.ExportState; + case "Zoom": + return usage.ZoomMin is { } min && context.Zoom is { } zoom ? zoom >= min && zoom < (usage.ZoomMax ?? double.PositiveInfinity) : null; + case "User": + IReadOnlyList names = usage.UserNames; + return names.Count > 0 && context.UserNames is { } users ? names.Any(users.Contains) : null; + case "Language": + if (usage.Language is not { } language || context.Language is not { } wanted) + { + return null; + } + + if (string.Equals(language, wanted, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + return !anyExactLanguage && usage.LanguagePreferred + && string.Equals(language.Split('-')[0], wanted.Split('-')[0], StringComparison.OrdinalIgnoreCase); + default: + return null; + } + } +} diff --git a/src/Broadside/PdfOptionalContentState.cs b/src/Broadside/PdfOptionalContentState.cs new file mode 100644 index 00000000..88753a83 --- /dev/null +++ b/src/Broadside/PdfOptionalContentState.cs @@ -0,0 +1,154 @@ +using Broadside.Objects; + +namespace Broadside; + +/// +/// The ON/OFF states of every optional content group, plus the intents that decide which groups count: an immutable snapshot. +/// +/// +/// +/// ISO 32000-2 §8.11.2.1: states are not part of the file; a processor holds them. They start from a configuration +/// (, §8.11.4.5) and change through a user interface or set-OCG-state +/// actions (§12.6.4.13, ). Every change returns a new snapshot, so concurrent renders with different layer +/// settings over one document are safe. +/// +/// +/// §8.11.2.3: a group counts only when one of its intents is among (All matches every intent); a group +/// that does not count has no effect on visibility, and an empty intent list makes all content visible. +/// +/// +public sealed class PdfOptionalContentState +{ + private readonly bool[] _on; + private readonly bool[] _effective; + private readonly CosName[] _intents; + + internal PdfOptionalContentState(PdfOptionalContentProperties properties, PdfOptionalContentConfiguration configuration, bool[] on, CosName[] intents) + { + Properties = properties; + Configuration = configuration; + _on = on; + _intents = intents; + _effective = new bool[on.Length]; + bool all = Array.Exists(intents, intent => intent.Equals(FileAndLayerNames.All)); + for (int ordinal = 0; ordinal < on.Length; ordinal++) + { + CosName[] groupIntents = properties.GroupIntents[ordinal]; + _effective[ordinal] = all || Array.Exists(groupIntents, intent => intent.Equals(FileAndLayerNames.All) ? intents.Length > 0 : Array.IndexOf(intents, intent) >= 0); + } + } + + /// Gets the configuration the snapshot was computed from; its radio-button groups and auto-state entries apply to it. + /// ISO 32000-2 §8.11.4.3. + public PdfOptionalContentConfiguration Configuration { get; } + + /// Gets the intents whose groups count when computing visibility, from the configuration's Intent unless replaced. + /// ISO 32000-2 §8.11.2.3 and §8.11.4.3, Table 99. + public IReadOnlyList Intents => _intents; + + /// Gets the properties the groups belong to. + internal PdfOptionalContentProperties Properties { get; } + + /// Gets the states by group ordinal. + internal ReadOnlySpan On => _on; + + /// Gets, by group ordinal, whether the group counts under . + internal ReadOnlySpan Effective => _effective; + + /// Returns whether is ON. + /// A group of the same optional content properties. + /// when ON. + /// The group belongs to another document or properties view. + /// ISO 32000-2 §8.11.2.1. + public bool IsOn(PdfOptionalContentGroup group) => _on[Check(group)]; + + /// Returns a snapshot with set to . + /// A group of the same optional content properties. + /// The new state. + /// The new snapshot; this one is unchanged. + /// The group belongs to another document or properties view. + /// ISO 32000-2 §8.11.2.1. Radio-button groups are not applied; use for that. + public PdfOptionalContentState With(PdfOptionalContentGroup group, bool on) + { + int ordinal = Check(group); + bool[] states = (bool[])_on.Clone(); + states[ordinal] = on; + return new PdfOptionalContentState(Properties, Configuration, states, _intents); + } + + /// Returns a snapshot that uses to decide which groups count. + /// The intents; All for every intent; empty to make all content visible. + /// The new snapshot. + /// ISO 32000-2 §8.11.2.3. + public PdfOptionalContentState WithIntents(IEnumerable intents) + { + ArgumentNullException.ThrowIfNull(intents); + return new PdfOptionalContentState(Properties, Configuration, _on, [.. intents]); + } + + /// + /// Applies a set-OCG-state array ([/ON g1 /OFF g2 /Toggle g3 ...]): each name sets how the groups after it change. + /// + /// The State array of a set-OCG-state action. + /// + /// The action's PreserveRB (default ): turning a group ON turns OFF the other groups of every + /// radio-button collection of that holds it. + /// + /// The new snapshot. Entries that are neither a state name nor a listed group are ignored. + /// ISO 32000-2 §12.6.4.13, Table 216. The action itself is typed elsewhere; this applies its data. + public PdfOptionalContentState Apply(CosArray state, bool preserveRadioButtons = true) + { + ArgumentNullException.ThrowIfNull(state); + bool[] states = (bool[])_on.Clone(); + IReadOnlyList> radio = preserveRadioButtons ? Configuration.RadioButtonGroups : []; + string mode = "ON"; + foreach (CosObject item in state) + { + switch (Properties.Document.Resolve(item)) + { + case CosName name when name.Value is "ON" or "OFF" or "Toggle": + mode = name.Value; + break; + case CosDictionary dictionary when Properties.FindGroup(dictionary) is { } group: + bool value = mode switch + { + "ON" => true, + "OFF" => false, + _ => !states[group.Ordinal], + }; + states[group.Ordinal] = value; + if (value) + { + foreach (IReadOnlyList collection in radio) + { + if (collection.Contains(group)) + { + foreach (PdfOptionalContentGroup other in collection) + { + states[other.Ordinal] = other == group; + } + } + } + } + + break; + } + } + + return new PdfOptionalContentState(Properties, Configuration, states, _intents); + } + + /// Returns a copy of the state array, for the properties view's state computations. + internal bool[] CopyStates() => (bool[])_on.Clone(); + + private int Check(PdfOptionalContentGroup group) + { + ArgumentNullException.ThrowIfNull(group); + if (!ReferenceEquals(Properties.FindGroup(group.Dictionary), group)) + { + throw new ArgumentException("The group does not belong to the optional content properties this state was computed for.", nameof(group)); + } + + return group.Ordinal; + } +} diff --git a/src/Broadside/PdfOptionalContentTracker.cs b/src/Broadside/PdfOptionalContentTracker.cs new file mode 100644 index 00000000..7ac56efb --- /dev/null +++ b/src/Broadside/PdfOptionalContentTracker.cs @@ -0,0 +1,123 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// +/// Follows the marked-content nesting of a content stream and answers whether the current position is visible: the seam a content +/// interpreter calls on every BDC, BMC and EMC, and before drawing an optional XObject or annotation. +/// +/// +/// +/// ISO 32000-2 §8.11.3. A section is optional content when its tag is OC and its property list is a group or membership +/// dictionary (§8.11.3.2); other tags nest transparently. Content is visible only when every enclosing optional section is +/// (§8.11.2.1); use one tracker across a form XObject's content so the invoking section's visibility carries into it. Hidden content +/// is not drawn but its graphics state changes still apply (§8.11.3.1): that is the caller's part. +/// +/// +/// Not thread-safe: one tracker per interpretation. Pushing and popping allocate nothing after the nesting reached its maximum once. +/// +/// +public sealed class PdfOptionalContentTracker +{ + private static readonly CosName OC = FileAndLayerNames.OC; + + private readonly PdfOptionalContentProperties? _properties; + private readonly PdfOptionalContentState? _state; + private bool[] _hidden = new bool[16]; + private int _hiddenCount; + + /// Initializes a new instance of the class. + /// The document's optional content (); when it has none: everything is visible. + /// The group states to honour; the default states when . + public PdfOptionalContentTracker(PdfOptionalContentProperties? properties, PdfOptionalContentState? state) + { + _properties = properties; + _state = properties is null ? null : state ?? properties.GetDefaultStates(); + } + + /// Gets a value indicating whether content at the current nesting is visible. + /// ISO 32000-2 §8.11.2.1: visible only when every enclosing optional section is. + public bool IsVisible => _hiddenCount == 0; + + /// Gets the current marked-content nesting depth. + public int Depth { get; private set; } + + /// Enters a marked-content section (BDC or BMC). + /// The marked-content tag. + /// The resolved property list (a BDC operand or the named resource it names), or for BMC. + /// + /// when an /OC section's property list was written inline instead of as a named resource, which + /// §8.11.3.2 forbids; it is still honoured, with an OptionalContentInlineProperties diagnostic. + /// + /// ISO 32000-2 §8.11.3.2 and §14.6. + public void BeginMarkedContent(CosName tag, CosObject? properties, bool inlineProperties = false) + { + ArgumentNullException.ThrowIfNull(tag); + bool hidden = false; + if (_properties is not null && tag.Equals(OC)) + { + if (inlineProperties) + { + _properties.Document.DiagnosticSink.ReportOnce( + DiagnosticCodes.OptionalContentInlineProperties, + DiagnosticSeverity.Warning, + "An /OC marked-content section has an inline property list; it shall be a named resource. It is honoured."); + } + + hidden = !_properties.IsVisible(properties, _state!); + } + + if (Depth == _hidden.Length) + { + Array.Resize(ref _hidden, _hidden.Length * 2); + } + + _hidden[Depth++] = hidden; + if (hidden) + { + _hiddenCount++; + } + } + + /// Leaves the innermost marked-content section (EMC). An EMC without a section is ignored. + /// ISO 32000-2 §14.6. + public void EndMarkedContent() + { + if (Depth == 0) + { + return; + } + + if (_hidden[--Depth]) + { + _hiddenCount--; + } + } + + /// + /// Returns whether an XObject or annotation with the given dictionary is visible here: the current nesting is visible and its + /// OC entry, if any, says so. An annotation's flags are the caller's concern. + /// + /// A form or image XObject's stream dictionary, or an annotation dictionary. + /// when it shall be drawn. + /// ISO 32000-2 §8.11.3.3 (Tables 87, 93 and 166, OC, PDF 1.5). + public bool IsObjectVisible(CosDictionary dictionary) + { + ArgumentNullException.ThrowIfNull(dictionary); + if (!IsVisible) + { + return false; + } + + return _properties is null || !dictionary.TryGetValue(OC, out CosObject? value) || _properties.IsVisible(value, _state!); + } + + /// Forgets every open section, for reuse with another content stream. + public void Reset() + { + Depth = 0; + _hiddenCount = 0; + } +} diff --git a/src/Broadside/PdfOptionalContentUsage.cs b/src/Broadside/PdfOptionalContentUsage.cs new file mode 100644 index 00000000..3b819a4c --- /dev/null +++ b/src/Broadside/PdfOptionalContentUsage.cs @@ -0,0 +1,91 @@ +using Broadside.Objects; + +namespace Broadside; + +/// The usage dictionary of an optional content group: what its content is for. A live view; exposed as data. +/// +/// ISO 32000-2 §8.11.4.4, Table 100. The entries drive automatic state changes only through the auto-state (AS) entries of a +/// configuration (); reading them changes nothing. +/// +public sealed class PdfOptionalContentUsage +{ + private readonly PdfDocument _document; + + internal PdfOptionalContentUsage(PdfDocument document, CosDictionary dictionary) + { + _document = document; + Dictionary = dictionary; + } + + /// Gets the usage dictionary. + /// ISO 32000-2 §8.11.4.4, Table 100. + public CosDictionary Dictionary { get; } + + /// Gets the application that created the group (CreatorInfo Creator), or . + /// ISO 32000-2 §8.11.4.4, Table 100. + public string? Creator => Sub(FileAndLayerNames.CreatorInfo) is { } info ? ViewReading.Text(_document, info, FileAndLayerNames.Creator) : null; + + /// Gets the kind of content per the creator (CreatorInfo Subtype, such as Artwork or Technical), or . + /// ISO 32000-2 §8.11.4.4, Table 100. + public CosName? CreatorSubtype => Sub(FileAndLayerNames.CreatorInfo) is { } info ? ViewReading.Name(_document, info, FileAndLayerNames.Subtype) : null; + + /// Gets the language and locale of the content (Language Lang, such as es-MX), or . + /// ISO 32000-2 §8.11.4.4, Table 100, and §14.9.2. + public string? Language => Sub(FileAndLayerNames.Language) is { } language ? ViewReading.Text(_document, language, FileAndLayerNames.Lang) : null; + + /// Gets a value indicating whether the group is preferred on a partial language match (Language Preferred ON). Default . + /// ISO 32000-2 §8.11.4.4, Table 100. + public bool LanguagePreferred => Sub(FileAndLayerNames.Language) is { } language && State(language, FileAndLayerNames.Preferred) == true; + + /// Gets the recommended state when exporting (Export ExportState), or . + /// ISO 32000-2 §8.11.4.4, Table 100. + public bool? ExportState => Sub(FileAndLayerNames.Export) is { } export ? State(export, FileAndLayerNames.ExportState) : null; + + /// Gets the minimum magnification at which the group is ON (Zoom min, default 0), or without a Zoom entry. + /// ISO 32000-2 §8.11.4.4, Table 100. + public double? ZoomMin => Sub(FileAndLayerNames.Zoom) is { } zoom ? ViewReading.Number(_document, zoom, FileAndLayerNames.Min) ?? 0 : null; + + /// Gets the magnification below which the group is ON (Zoom max), or when absent (infinity). + /// ISO 32000-2 §8.11.4.4, Table 100. + public double? ZoomMax => Sub(FileAndLayerNames.Zoom) is { } zoom ? ViewReading.Number(_document, zoom, FileAndLayerNames.Max) : null; + + /// Gets the kind of printed content (Print Subtype, such as Trapping or Watermark), or . + /// ISO 32000-2 §8.11.4.4, Table 100. + public CosName? PrintSubtype => Sub(FileAndLayerNames.Print) is { } print ? ViewReading.Name(_document, print, FileAndLayerNames.Subtype) : null; + + /// Gets the state when printing (Print PrintState), or . + /// ISO 32000-2 §8.11.4.4, Table 100. + public bool? PrintState => Sub(FileAndLayerNames.Print) is { } print ? State(print, FileAndLayerNames.PrintState) : null; + + /// Gets the state when the document is first opened (View ViewState), or . + /// ISO 32000-2 §8.11.4.4, Table 100. Applied only through an auto-state entry with the View category. + public bool? ViewState => Sub(FileAndLayerNames.View) is { } view ? State(view, FileAndLayerNames.ViewState) : null; + + /// Gets how is interpreted (User Type: Ind, Ttl or Org), or . + /// ISO 32000-2 §8.11.4.4, Table 100. + public CosName? UserType => Sub(FileAndLayerNames.User) is { } user ? ViewReading.Name(_document, user, KnownNames.Type) : null; + + /// Gets the individuals, titles or organisations the content is for (User Name, a text string or an array). + /// ISO 32000-2 §8.11.4.4, Table 100. + public IReadOnlyList UserNames => Sub(FileAndLayerNames.User) is { } user + ? ViewReading.Get(_document, user, FileAndLayerNames.Name) switch + { + CosString name => [name.DecodeText()], + CosArray names => [.. names.Select(_document.Resolve).OfType().Select(name => name.DecodeText())], + _ => [], + } + : []; + + /// Gets the kind of pagination artifact (PageElement Subtype: HF, FG, BG or L), or . + /// ISO 32000-2 §8.11.4.4, Table 100. + public CosName? PageElement => Sub(FileAndLayerNames.PageElement) is { } element ? ViewReading.Name(_document, element, FileAndLayerNames.Subtype) : null; + + private CosDictionary? Sub(CosName key) => ViewReading.Get(_document, Dictionary, key) as CosDictionary; + + private bool? State(CosDictionary dictionary, CosName key) => ViewReading.Name(_document, dictionary, key)?.Value switch + { + "ON" => true, + "OFF" => false, + _ => null, + }; +} diff --git a/src/Broadside/PdfOptionalContentUsageApplication.cs b/src/Broadside/PdfOptionalContentUsageApplication.cs new file mode 100644 index 00000000..4b4973a5 --- /dev/null +++ b/src/Broadside/PdfOptionalContentUsageApplication.cs @@ -0,0 +1,46 @@ +using Broadside.Objects; + +namespace Broadside; + +/// +/// A usage application dictionary from a configuration's auto-state (AS) array: which groups have their states set from +/// which usage categories, and when. A live view. +/// +/// ISO 32000-2 §8.11.4.4, Table 101. +public sealed class PdfOptionalContentUsageApplication +{ + private readonly PdfOptionalContentProperties _properties; + + internal PdfOptionalContentUsageApplication(PdfOptionalContentProperties properties, CosDictionary dictionary) + { + _properties = properties; + Dictionary = dictionary; + } + + /// Gets the usage application dictionary. + /// ISO 32000-2 §8.11.4.4, Table 101. + public CosDictionary Dictionary { get; } + + /// Gets the situation the dictionary applies to (Event), or when missing or unknown. + /// ISO 32000-2 §8.11.4.4, Table 101 (required: View, Print or Export). + public PdfOptionalContentEvent? Event => ViewReading.Name(_properties.Document, Dictionary, FileAndLayerNames.Event)?.Value switch + { + "View" => PdfOptionalContentEvent.View, + "Print" => PdfOptionalContentEvent.Print, + "Export" => PdfOptionalContentEvent.Export, + _ => null, + }; + + /// Gets the groups whose states are managed (OCGs, default empty). + /// ISO 32000-2 §8.11.4.4, Table 101. + public IReadOnlyList Groups => _properties.ReadGroupList(ViewReading.Get(_properties.Document, Dictionary, FileAndLayerNames.OCGs)); + + /// Gets the usage dictionary entries to consult (Category, such as View, Zoom or Language). + /// ISO 32000-2 §8.11.4.4, Table 101 (required). + public IReadOnlyList Categories => ViewReading.Get(_properties.Document, Dictionary, FileAndLayerNames.Category) switch + { + CosArray array => [.. array.Select(_properties.Document.Resolve).OfType()], + CosName name => [name], + _ => [], + }; +} diff --git a/src/Broadside/PdfOptionalContentUsageContext.cs b/src/Broadside/PdfOptionalContentUsageContext.cs new file mode 100644 index 00000000..5fa7530d --- /dev/null +++ b/src/Broadside/PdfOptionalContentUsageContext.cs @@ -0,0 +1,16 @@ +namespace Broadside; + +/// The external factors auto-state entries consult: magnification, language and user. +/// ISO 32000-2 §8.11.4.4. A factor left makes its category recommend nothing. +public sealed class PdfOptionalContentUsageContext +{ + /// Gets the current magnification factor (1.0 is 100 %), for the Zoom category. + public double? Zoom { get; init; } + + /// Gets the application's language and locale (such as en-US), for the Language category. + /// ISO 32000-2 §14.9.2. + public string? Language { get; init; } + + /// Gets the user's names, titles and organisations, for the User category (exact match). + public IReadOnlyCollection? UserNames { get; init; } +} diff --git a/src/Broadside/PdfVisibilityExpression.cs b/src/Broadside/PdfVisibilityExpression.cs new file mode 100644 index 00000000..17d94b11 --- /dev/null +++ b/src/Broadside/PdfVisibilityExpression.cs @@ -0,0 +1,31 @@ +namespace Broadside; + +/// A parsed visibility expression of a membership dictionary: a boolean expression over optional content group states. +/// +/// ISO 32000-2 §8.11.2.2 (PDF 1.6), Table 97 VE. The array [/Or 1 0 R [/Not 2 0 R]] parses to an +/// node with a group leaf and a node. Operands that are null, deleted, or not listed groups +/// are dropped (they have no effect); an operator left without operands has no effect on visibility. +/// +public sealed class PdfVisibilityExpression +{ + internal PdfVisibilityExpression(PdfVisibilityOperator @operator, PdfOptionalContentGroup? group, IReadOnlyList operands) + { + Operator = @operator; + Group = group; + Operands = operands; + } + + /// Gets the kind of node. + public PdfVisibilityOperator Operator { get; } + + /// Gets the group of a leaf, else . + public PdfOptionalContentGroup? Group { get; } + + /// Gets the operands of an operator node; empty for a leaf. + public IReadOnlyList Operands { get; } + + /// + public override string ToString() => Operator == PdfVisibilityOperator.Group + ? Group!.Name + : $"{Operator}({string.Join(", ", Operands)})"; +} diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index 3960d15b..d9f66ecd 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -79,6 +79,7 @@ Broadside.PdfCollectionItemValue.Number.get -> double? Broadside.PdfCollectionItemValue.Prefix.get -> string? Broadside.PdfCollectionItemValue.Text.get -> string? Broadside.PdfDocument.GetFileSpecification(Broadside.Objects.CosObject? value) -> Broadside.PdfFileSpecification? +Broadside.PdfDocument.OptionalContent.get -> Broadside.PdfOptionalContentProperties? Broadside.PdfEmbeddedFile Broadside.PdfEmbeddedFile.Decode() -> System.ReadOnlyMemory Broadside.PdfEmbeddedFile.Decode(System.Buffers.IBufferWriter! output) -> void @@ -126,10 +127,121 @@ Broadside.PdfFileSpecification.RelationshipName.get -> Broadside.Objects.CosName Broadside.PdfFileSpecification.SafeFileName.get -> string? Broadside.PdfFileSpecification.Thumbnail.get -> Broadside.Objects.CosStream? Broadside.PdfFileSpecification.Value.get -> Broadside.Objects.CosObject! +Broadside.PdfOptionalContentBaseState +Broadside.PdfOptionalContentBaseState.Off = 1 -> Broadside.PdfOptionalContentBaseState +Broadside.PdfOptionalContentBaseState.On = 0 -> Broadside.PdfOptionalContentBaseState +Broadside.PdfOptionalContentBaseState.Unchanged = 2 -> Broadside.PdfOptionalContentBaseState +Broadside.PdfOptionalContentConfiguration +Broadside.PdfOptionalContentConfiguration.AutoStates.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfOptionalContentConfiguration.BaseState.get -> Broadside.PdfOptionalContentBaseState +Broadside.PdfOptionalContentConfiguration.Creator.get -> string? +Broadside.PdfOptionalContentConfiguration.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfOptionalContentConfiguration.Intents.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfOptionalContentConfiguration.IsDefault.get -> bool +Broadside.PdfOptionalContentConfiguration.ListMode.get -> Broadside.PdfOptionalContentListMode +Broadside.PdfOptionalContentConfiguration.Locked.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfOptionalContentConfiguration.Name.get -> string? +Broadside.PdfOptionalContentConfiguration.Off.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfOptionalContentConfiguration.On.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfOptionalContentConfiguration.Order.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfOptionalContentConfiguration.RadioButtonGroups.get -> System.Collections.Generic.IReadOnlyList!>! +Broadside.PdfOptionalContentConfiguration.Reference.get -> Broadside.Objects.CosReference? +Broadside.PdfOptionalContentEvent +Broadside.PdfOptionalContentEvent.Export = 2 -> Broadside.PdfOptionalContentEvent +Broadside.PdfOptionalContentEvent.Print = 1 -> Broadside.PdfOptionalContentEvent +Broadside.PdfOptionalContentEvent.View = 0 -> Broadside.PdfOptionalContentEvent +Broadside.PdfOptionalContentGroup +Broadside.PdfOptionalContentGroup.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfOptionalContentGroup.Intents.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfOptionalContentGroup.Name.get -> string! +Broadside.PdfOptionalContentGroup.Reference.get -> Broadside.Objects.CosReference? +Broadside.PdfOptionalContentGroup.Usage.get -> Broadside.PdfOptionalContentUsage? +Broadside.PdfOptionalContentListMode +Broadside.PdfOptionalContentListMode.AllPages = 0 -> Broadside.PdfOptionalContentListMode +Broadside.PdfOptionalContentListMode.VisiblePages = 1 -> Broadside.PdfOptionalContentListMode +Broadside.PdfOptionalContentMembership +Broadside.PdfOptionalContentMembership.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfOptionalContentMembership.Groups.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfOptionalContentMembership.Policy.get -> Broadside.PdfVisibilityPolicy +Broadside.PdfOptionalContentMembership.Reference.get -> Broadside.Objects.CosReference? +Broadside.PdfOptionalContentMembership.VisibilityExpression.get -> Broadside.PdfVisibilityExpression? +Broadside.PdfOptionalContentOrderItem +Broadside.PdfOptionalContentOrderItem.Children.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfOptionalContentOrderItem.Group.get -> Broadside.PdfOptionalContentGroup? +Broadside.PdfOptionalContentOrderItem.Label.get -> string? +Broadside.PdfOptionalContentProperties +Broadside.PdfOptionalContentProperties.ApplyAutoStates(Broadside.PdfOptionalContentState! state, Broadside.PdfOptionalContentEvent usageEvent, Broadside.PdfOptionalContentUsageContext! context) -> Broadside.PdfOptionalContentState! +Broadside.PdfOptionalContentProperties.ApplyUsageStates(Broadside.PdfOptionalContentState! state, Broadside.PdfOptionalContentEvent usageEvent) -> Broadside.PdfOptionalContentState! +Broadside.PdfOptionalContentProperties.Configurations.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfOptionalContentProperties.DefaultConfiguration.get -> Broadside.PdfOptionalContentConfiguration! +Broadside.PdfOptionalContentProperties.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfOptionalContentProperties.FindGroup(Broadside.Objects.CosObject? value) -> Broadside.PdfOptionalContentGroup? +Broadside.PdfOptionalContentProperties.FindMembership(Broadside.Objects.CosObject? value) -> Broadside.PdfOptionalContentMembership? +Broadside.PdfOptionalContentProperties.GetDefaultStates() -> Broadside.PdfOptionalContentState! +Broadside.PdfOptionalContentProperties.GetStates(Broadside.PdfOptionalContentConfiguration! configuration, Broadside.PdfOptionalContentState? current = null) -> Broadside.PdfOptionalContentState! +Broadside.PdfOptionalContentProperties.Groups.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfOptionalContentProperties.IsVisible(Broadside.Objects.CosObject? ocgOrOcmd, Broadside.PdfOptionalContentState! state) -> bool +Broadside.PdfOptionalContentState +Broadside.PdfOptionalContentState.Apply(Broadside.Objects.CosArray! state, bool preserveRadioButtons = true) -> Broadside.PdfOptionalContentState! +Broadside.PdfOptionalContentState.Configuration.get -> Broadside.PdfOptionalContentConfiguration! +Broadside.PdfOptionalContentState.Intents.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfOptionalContentState.IsOn(Broadside.PdfOptionalContentGroup! group) -> bool +Broadside.PdfOptionalContentState.With(Broadside.PdfOptionalContentGroup! group, bool on) -> Broadside.PdfOptionalContentState! +Broadside.PdfOptionalContentState.WithIntents(System.Collections.Generic.IEnumerable! intents) -> Broadside.PdfOptionalContentState! +Broadside.PdfOptionalContentTracker +Broadside.PdfOptionalContentTracker.BeginMarkedContent(Broadside.Objects.CosName! tag, Broadside.Objects.CosObject? properties, bool inlineProperties = false) -> void +Broadside.PdfOptionalContentTracker.Depth.get -> int +Broadside.PdfOptionalContentTracker.EndMarkedContent() -> void +Broadside.PdfOptionalContentTracker.IsObjectVisible(Broadside.Objects.CosDictionary! dictionary) -> bool +Broadside.PdfOptionalContentTracker.IsVisible.get -> bool +Broadside.PdfOptionalContentTracker.PdfOptionalContentTracker(Broadside.PdfOptionalContentProperties? properties, Broadside.PdfOptionalContentState? state) -> void +Broadside.PdfOptionalContentTracker.Reset() -> void +Broadside.PdfOptionalContentUsage +Broadside.PdfOptionalContentUsage.Creator.get -> string? +Broadside.PdfOptionalContentUsage.CreatorSubtype.get -> Broadside.Objects.CosName? +Broadside.PdfOptionalContentUsage.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfOptionalContentUsage.ExportState.get -> bool? +Broadside.PdfOptionalContentUsage.Language.get -> string? +Broadside.PdfOptionalContentUsage.LanguagePreferred.get -> bool +Broadside.PdfOptionalContentUsage.PageElement.get -> Broadside.Objects.CosName? +Broadside.PdfOptionalContentUsage.PrintState.get -> bool? +Broadside.PdfOptionalContentUsage.PrintSubtype.get -> Broadside.Objects.CosName? +Broadside.PdfOptionalContentUsage.UserNames.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfOptionalContentUsage.UserType.get -> Broadside.Objects.CosName? +Broadside.PdfOptionalContentUsage.ViewState.get -> bool? +Broadside.PdfOptionalContentUsage.ZoomMax.get -> double? +Broadside.PdfOptionalContentUsage.ZoomMin.get -> double? +Broadside.PdfOptionalContentUsageApplication +Broadside.PdfOptionalContentUsageApplication.Categories.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfOptionalContentUsageApplication.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfOptionalContentUsageApplication.Event.get -> Broadside.PdfOptionalContentEvent? +Broadside.PdfOptionalContentUsageApplication.Groups.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfOptionalContentUsageContext +Broadside.PdfOptionalContentUsageContext.Language.get -> string? +Broadside.PdfOptionalContentUsageContext.Language.init -> void +Broadside.PdfOptionalContentUsageContext.PdfOptionalContentUsageContext() -> void +Broadside.PdfOptionalContentUsageContext.UserNames.get -> System.Collections.Generic.IReadOnlyCollection? +Broadside.PdfOptionalContentUsageContext.UserNames.init -> void +Broadside.PdfOptionalContentUsageContext.Zoom.get -> double? +Broadside.PdfOptionalContentUsageContext.Zoom.init -> void Broadside.PdfRelatedFile Broadside.PdfRelatedFile.File.get -> Broadside.PdfEmbeddedFile! Broadside.PdfRelatedFile.Name.get -> string! Broadside.PdfRelatedFile.NameString.get -> Broadside.Objects.CosString! +Broadside.PdfVisibilityExpression +Broadside.PdfVisibilityExpression.Group.get -> Broadside.PdfOptionalContentGroup? +Broadside.PdfVisibilityExpression.Operands.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfVisibilityExpression.Operator.get -> Broadside.PdfVisibilityOperator +Broadside.PdfVisibilityOperator +Broadside.PdfVisibilityOperator.And = 1 -> Broadside.PdfVisibilityOperator +Broadside.PdfVisibilityOperator.Group = 0 -> Broadside.PdfVisibilityOperator +Broadside.PdfVisibilityOperator.Not = 3 -> Broadside.PdfVisibilityOperator +Broadside.PdfVisibilityOperator.Or = 2 -> Broadside.PdfVisibilityOperator +Broadside.PdfVisibilityPolicy +Broadside.PdfVisibilityPolicy.AllOff = 3 -> Broadside.PdfVisibilityPolicy +Broadside.PdfVisibilityPolicy.AllOn = 0 -> Broadside.PdfVisibilityPolicy +Broadside.PdfVisibilityPolicy.AnyOff = 2 -> Broadside.PdfVisibilityPolicy +Broadside.PdfVisibilityPolicy.AnyOn = 1 -> Broadside.PdfVisibilityPolicy const Broadside.Objects.CosReference.MaxGeneration = 65535 -> int override Broadside.Objects.CosArray.IsDirty.get -> bool override Broadside.Objects.CosBoolean.Equals(object? obj) -> bool @@ -149,6 +261,10 @@ override Broadside.Objects.CosReference.GetHashCode() -> int override Broadside.Objects.CosStream.IsDirty.get -> bool override Broadside.Objects.CosString.Equals(object? obj) -> bool override Broadside.Objects.CosString.GetHashCode() -> int +override Broadside.PdfOptionalContentConfiguration.ToString() -> string! +override Broadside.PdfOptionalContentGroup.ToString() -> string! +override Broadside.PdfOptionalContentOrderItem.ToString() -> string! +override Broadside.PdfVisibilityExpression.ToString() -> string! static Broadside.Objects.CosBoolean.False.get -> Broadside.Objects.CosBoolean! static Broadside.Objects.CosBoolean.True.get -> Broadside.Objects.CosBoolean! static Broadside.Objects.CosNull.Instance.get -> Broadside.Objects.CosNull! diff --git a/src/Broadside/VisibilityProgram.cs b/src/Broadside/VisibilityProgram.cs new file mode 100644 index 00000000..1515646f --- /dev/null +++ b/src/Broadside/VisibilityProgram.cs @@ -0,0 +1,161 @@ +using System.Buffers; + +namespace Broadside; + +/// +/// A membership dictionary's visibility compiled once into postfix instructions over group ordinals, so evaluating it per marked-content +/// section or XObject allocates nothing (ISO 32000-2 §8.11.2.2). Values are three-valued: ON, OFF, or no effect (a group whose intent +/// the configuration does not use, §8.11.2.3); operators skip operands without effect, and a result without effect is visible. +/// +internal sealed class VisibilityProgram +{ + private const int StackAllocLimit = 256; + + private readonly Instruction[] _code; + private readonly int _maxStack; + + private VisibilityProgram(Instruction[] code, int maxStack) + { + _code = code; + _maxStack = maxStack; + } + + /// Gets a program for content that is not optional, or whose optionality has no usable group: always visible. + public static VisibilityProgram AlwaysVisible { get; } = new([new Instruction(Operation.And, 0)], 1); + + /// The operations. + internal enum Operation : byte + { + /// Push the state of group . + Group, + + /// Pop values, push their conjunction. + And, + + /// Pop values, push their disjunction. + Or, + + /// Negate the top value. + Not, + } + + /// Compiles a parsed expression. + public static VisibilityProgram Compile(PdfVisibilityExpression expression) + { + var code = new List(); + int depth = 0; + int max = 0; + Emit(expression); + return new VisibilityProgram([.. code], Math.Max(max, 1)); + + void Emit(PdfVisibilityExpression node) + { + switch (node.Operator) + { + case PdfVisibilityOperator.Group: + code.Add(new Instruction(Operation.Group, node.Group!.Ordinal)); + max = Math.Max(max, ++depth); + break; + case PdfVisibilityOperator.Not when node.Operands.Count == 1: + Emit(node.Operands[0]); + code.Add(new Instruction(Operation.Not, 0)); + break; + default: + var operation = node.Operator == PdfVisibilityOperator.Or ? Operation.Or : Operation.And; + int count = node.Operator == PdfVisibilityOperator.Not ? 0 : node.Operands.Count; + for (int index = 0; index < count; index++) + { + Emit(node.Operands[index]); + } + + code.Add(new Instruction(operation, count)); + depth -= count; + max = Math.Max(max, ++depth); + break; + } + } + } + + /// Compiles a policy over a group list (§8.11.2.2 Table 97 P). + public static VisibilityProgram Compile(IReadOnlyList groups, PdfVisibilityPolicy policy) + { + if (groups.Count == 0) + { + return AlwaysVisible; + } + + bool negate = policy is PdfVisibilityPolicy.AnyOff or PdfVisibilityPolicy.AllOff; + var code = new List(groups.Count * 2 + 1); + foreach (PdfOptionalContentGroup group in groups) + { + code.Add(new Instruction(Operation.Group, group.Ordinal)); + if (negate) + { + code.Add(new Instruction(Operation.Not, 0)); + } + } + + code.Add(new Instruction(policy is PdfVisibilityPolicy.AllOn or PdfVisibilityPolicy.AllOff ? Operation.And : Operation.Or, groups.Count)); + return new VisibilityProgram([.. code], groups.Count); + } + + /// Evaluates the program: unless the result is OFF. + public bool Evaluate(ReadOnlySpan on, ReadOnlySpan effective) + { + sbyte[]? rented = null; + Span stack = _maxStack <= StackAllocLimit + ? stackalloc sbyte[StackAllocLimit] + : (rented = ArrayPool.Shared.Rent(_maxStack)); + try + { + int top = 0; + foreach (Instruction instruction in _code) + { + switch (instruction.Operation) + { + case Operation.Group: + int ordinal = instruction.Operand; + stack[top++] = !effective[ordinal] ? (sbyte)-1 : on[ordinal] ? (sbyte)1 : (sbyte)0; + break; + case Operation.Not: + if (stack[top - 1] >= 0) + { + stack[top - 1] = (sbyte)(1 - stack[top - 1]); + } + + break; + default: + int count = instruction.Operand; + sbyte result = -1; + for (int index = top - count; index < top; index++) + { + sbyte value = stack[index]; + if (value < 0) + { + continue; + } + + result = result < 0 ? value + : instruction.Operation == Operation.And ? (sbyte)(result & value) : (sbyte)(result | value); + } + + top -= count; + stack[top++] = result; + break; + } + } + + return stack[0] != 0; + } + finally + { + if (rented is not null) + { + ArrayPool.Shared.Return(rented); + } + } + } + + /// One instruction. + internal readonly record struct Instruction(Operation Operation, int Operand); +} diff --git a/tests/Broadside.TestSupport/Corpus.cs b/tests/Broadside.TestSupport/Corpus.cs index e98e5c47..0db8ca23 100644 --- a/tests/Broadside.TestSupport/Corpus.cs +++ b/tests/Broadside.TestSupport/Corpus.cs @@ -40,6 +40,7 @@ public static class Corpus "outline.pdf", "name-tree-dests.pdf", "metadata-xmp.pdf", + "optional-content.pdf", ]; private static readonly string[] Malformed = diff --git a/tests/Broadside.Tests/OptionalContent/OptionalContentPdf.cs b/tests/Broadside.Tests/OptionalContent/OptionalContentPdf.cs new file mode 100644 index 00000000..dd4ccefc --- /dev/null +++ b/tests/Broadside.Tests/OptionalContent/OptionalContentPdf.cs @@ -0,0 +1,15 @@ +using Broadside.Tests.Document; + +namespace Broadside.Tests.OptionalContent; + +/// Builds a one-page file whose catalog carries /OCProperties with the given entries; extra objects start at number 4. +internal static class OptionalContentPdf +{ + public static byte[] Build(string ocPropertiesEntries, params string[] objects) => new TestPdf().Build( + [ + $"<< /Type /Catalog /Pages 2 0 R /OCProperties << {ocPropertiesEntries} >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>", + .. objects, + ]); +} diff --git a/tests/Broadside.Tests/OptionalContent/OptionalContentTests.cs b/tests/Broadside.Tests/OptionalContent/OptionalContentTests.cs new file mode 100644 index 00000000..a3975569 --- /dev/null +++ b/tests/Broadside.Tests/OptionalContent/OptionalContentTests.cs @@ -0,0 +1,289 @@ +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.OptionalContent; + +/// Optional content groups, membership dictionaries, configurations and visibility. ISO 32000-2 §8.11. +public class OptionalContentTests +{ + private static PdfDocument OpenCorpus() => PdfDocument.Open(Corpus.Path("optional-content.pdf")); + + private static CosObject Property(PdfDocument document, string name) => + ((CosDictionary)document.Resolve(document.Pages[0].Resources![new CosName("Properties")]))[new CosName(name)]; + + [Fact] + public void Groups_are_read_from_OCGs_in_order_with_names_intents_and_usage() + { + using PdfDocument document = OpenCorpus(); + + PdfOptionalContentProperties properties = document.OptionalContent!; + + Assert.Equal(["A", "B", "C", "D2"], properties.Groups.Select(group => group.Name)); + Assert.Equal(new CosReference(5, 0), properties.Groups[0].Reference); + Assert.Equal(["View"], properties.Groups[0].Intents.Select(intent => intent.Value)); + Assert.Equal(["Design"], properties.Groups[2].Intents.Select(intent => intent.Value)); + Assert.Equal("Broadside", properties.Groups[2].Usage!.Creator); + Assert.Equal("Technical", properties.Groups[2].Usage!.CreatorSubtype!.Value); + Assert.False(properties.Groups[3].Usage!.ViewState); + Assert.Equal(1.5, properties.Groups[3].Usage!.ZoomMin); + Assert.Null(properties.Groups[3].Usage!.ZoomMax); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void The_default_configuration_is_typed() + { + using PdfDocument document = OpenCorpus(); + PdfOptionalContentProperties properties = document.OptionalContent!; + + PdfOptionalContentConfiguration configuration = properties.DefaultConfiguration; + + Assert.Equal("Default", configuration.Name); + Assert.Equal("Broadside corpus", configuration.Creator); + Assert.Equal(PdfOptionalContentBaseState.On, configuration.BaseState); + Assert.Empty(configuration.On); + Assert.Equal(["B"], configuration.Off.Select(group => group.Name)); + Assert.Equal(["View"], configuration.Intents.Select(intent => intent.Value)); + Assert.Equal(PdfOptionalContentListMode.AllPages, configuration.ListMode); + Assert.Equal(["A", "B"], Assert.Single(configuration.RadioButtonGroups).Select(group => group.Name)); + Assert.Equal(["C"], configuration.Locked.Select(group => group.Name)); + Assert.Empty(configuration.AutoStates); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void The_order_tree_keeps_labels_and_unlabelled_nesting_as_written() + { + using PdfDocument document = OpenCorpus(); + + IReadOnlyList order = document.OptionalContent!.DefaultConfiguration.Order; + + Assert.Equal(3, order.Count); + Assert.Equal("A", order[0].Group!.Name); + Assert.Empty(order[0].Children); + Assert.Null(order[1].Group); + Assert.Equal("Labelled", order[1].Label); + Assert.Equal(["B", "C"], order[1].Children.Select(child => child.Group!.Name)); + Assert.Null(order[2].Group); + Assert.Null(order[2].Label); + Assert.Equal("D2", Assert.Single(order[2].Children).Group!.Name); + } + + [Fact] + public void A_layer_followed_by_an_unlabelled_array_has_sublayers() + { + byte[] file = OptionalContentPdf.Build( + "/OCGs [4 0 R 5 0 R 6 0 R] /D << /Order [4 0 R [5 0 R 6 0 R]] >>", + "<< /Type /OCG /Name (Layer 1) >>", "<< /Type /OCG /Name (Sublayer A) >>", "<< /Type /OCG /Name (Sublayer B) >>"); + using PdfDocument document = PdfDocument.Open(file); + + PdfOptionalContentOrderItem layer = Assert.Single(document.OptionalContent!.DefaultConfiguration.Order); + + Assert.Equal("Layer 1", layer.Group!.Name); + Assert.Equal(["Sublayer A", "Sublayer B"], layer.Children.Select(child => child.Group!.Name)); + } + + [Fact] + public void Alternate_configurations_are_typed_and_inherit_order_and_radio_buttons_from_D() + { + using PdfDocument document = OpenCorpus(); + + PdfOptionalContentConfiguration alternate = Assert.Single(document.OptionalContent!.Configurations); + + Assert.Equal("Only C", alternate.Name); + Assert.Equal(PdfOptionalContentBaseState.Off, alternate.BaseState); + Assert.Equal(["C"], alternate.On.Select(group => group.Name)); + Assert.Equal(["All"], alternate.Intents.Select(intent => intent.Value)); + Assert.Equal(PdfOptionalContentListMode.VisiblePages, alternate.ListMode); + Assert.Equal(3, alternate.Order.Count); + Assert.Single(alternate.RadioButtonGroups); + Assert.Empty(alternate.Locked); + } + + [Fact] + public void Default_states_follow_BaseState_then_ON_then_OFF_and_ignore_usage_without_AS() + { + using PdfDocument document = OpenCorpus(); + PdfOptionalContentProperties properties = document.OptionalContent!; + + PdfOptionalContentState state = properties.GetDefaultStates(); + + Assert.Equal([true, false, true, true], properties.Groups.Select(state.IsOn)); + } + + [Fact] + public void Visibility_of_each_section_XObject_and_annotation_follows_the_default_state_and_intent() + { + using PdfDocument document = OpenCorpus(); + PdfOptionalContentProperties properties = document.OptionalContent!; + PdfOptionalContentState state = properties.GetDefaultStates(); + CosDictionary form = (CosDictionary)((CosStream)document.Resolve(new CosReference(11, 0))).Dictionary; + var annotation = (CosDictionary)document.Resolve(new CosReference(12, 0)); + + Assert.True(properties.IsVisible(Property(document, "a"), state)); + Assert.False(properties.IsVisible(Property(document, "m1"), state)); + Assert.True(properties.IsVisible(Property(document, "m2"), state)); + Assert.False(properties.IsVisible(form[new CosName("OC")], state)); + Assert.True(properties.IsVisible(annotation[new CosName("OC")], state)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_tracker_hides_content_nested_inside_a_hidden_section() + { + using PdfDocument document = OpenCorpus(); + PdfOptionalContentProperties properties = document.OptionalContent!; + var tracker = new PdfOptionalContentTracker(properties, properties.GetDefaultStates()); + var oc = new CosName("OC"); + + tracker.BeginMarkedContent(oc, Property(document, "a")); + Assert.True(tracker.IsVisible); + tracker.EndMarkedContent(); + + tracker.BeginMarkedContent(oc, Property(document, "b")); + Assert.False(tracker.IsVisible); + tracker.BeginMarkedContent(new CosName("Span"), null); + tracker.BeginMarkedContent(oc, Property(document, "a")); + Assert.False(tracker.IsVisible); + tracker.EndMarkedContent(); + tracker.EndMarkedContent(); + tracker.EndMarkedContent(); + Assert.True(tracker.IsVisible); + Assert.Equal(0, tracker.Depth); + + Assert.False(tracker.IsObjectVisible(((CosStream)document.Resolve(new CosReference(11, 0))).Dictionary)); + Assert.True(tracker.IsObjectVisible((CosDictionary)document.Resolve(new CosReference(12, 0)))); + } + + [Fact] + public void An_unbalanced_EMC_is_ignored_by_the_tracker() + { + var tracker = new PdfOptionalContentTracker(null, null); + + tracker.EndMarkedContent(); + + Assert.True(tracker.IsVisible); + Assert.Equal(0, tracker.Depth); + } + + [Fact] + public void An_alternate_configuration_with_intent_All_makes_the_design_group_count() + { + using PdfDocument document = OpenCorpus(); + PdfOptionalContentProperties properties = document.OptionalContent!; + + PdfOptionalContentState state = properties.GetStates(properties.Configurations[0]); + + Assert.Equal([false, false, true, false], properties.Groups.Select(state.IsOn)); + Assert.True(properties.IsVisible(new CosReference(7, 0), state)); + Assert.False(properties.IsVisible(new CosReference(5, 0), state)); + Assert.True(properties.IsVisible(new CosReference(10, 0), state)); + Assert.False(properties.IsVisible(new CosReference(9, 0), properties.GetDefaultStates())); + } + + [Fact] + public void An_Unchanged_base_state_keeps_the_current_states() + { + byte[] file = OptionalContentPdf.Build( + "/OCGs [4 0 R 5 0 R] /D << /OFF [5 0 R] >> /Configs [<< /BaseState /Unchanged /ON [5 0 R] >>]", + "<< /Type /OCG /Name (A) >>", "<< /Type /OCG /Name (B) >>"); + using PdfDocument document = PdfDocument.Open(file); + PdfOptionalContentProperties properties = document.OptionalContent!; + PdfOptionalContentState current = properties.GetDefaultStates().With(properties.Groups[0], on: false); + + PdfOptionalContentState state = properties.GetStates(properties.Configurations[0], current); + + Assert.Equal([false, true], properties.Groups.Select(state.IsOn)); + } + + [Fact] + public void A_state_is_an_immutable_snapshot() + { + using PdfDocument document = OpenCorpus(); + PdfOptionalContentProperties properties = document.OptionalContent!; + PdfOptionalContentState original = properties.GetDefaultStates(); + + PdfOptionalContentState changed = original.With(properties.Groups[1], on: true); + + Assert.False(original.IsOn(properties.Groups[1])); + Assert.True(changed.IsOn(properties.Groups[1])); + Assert.True(properties.IsVisible(Property(document, "b"), changed)); + Assert.False(properties.IsVisible(Property(document, "b"), original)); + } + + [Fact] + public void A_set_OCG_state_array_turns_groups_on_off_and_toggles_honouring_radio_buttons() + { + using PdfDocument document = OpenCorpus(); + PdfOptionalContentProperties properties = document.OptionalContent!; + PdfOptionalContentState state = properties.GetDefaultStates(); + var array = new CosArray([new CosName("ON"), new CosReference(6, 0), new CosName("Toggle"), new CosReference(8, 0)]); + + PdfOptionalContentState applied = state.Apply(array); + PdfOptionalContentState withoutRadio = state.Apply(array, preserveRadioButtons: false); + + Assert.Equal([false, true, true, false], properties.Groups.Select(applied.IsOn)); + Assert.Equal([true, true, true, false], properties.Groups.Select(withoutRadio.IsOn)); + } + + [Fact] + public void An_empty_configuration_intent_makes_all_content_visible() + { + using PdfDocument document = OpenCorpus(); + PdfOptionalContentProperties properties = document.OptionalContent!; + + PdfOptionalContentState state = properties.GetDefaultStates().WithIntents([]); + + Assert.True(properties.IsVisible(Property(document, "b"), state)); + Assert.True(properties.IsVisible(Property(document, "m1"), state)); + } + + [Fact] + public void Usage_states_can_be_applied_for_engine_parity_without_an_AS_entry() + { + using PdfDocument document = OpenCorpus(); + PdfOptionalContentProperties properties = document.OptionalContent!; + + PdfOptionalContentState state = properties.ApplyUsageStates(properties.GetDefaultStates(), PdfOptionalContentEvent.View); + + Assert.Equal([true, false, true, false], properties.Groups.Select(state.IsOn)); + } + + [Fact] + public void A_document_without_OCProperties_has_no_optional_content() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + + Assert.Null(document.OptionalContent); + } + + [Fact] + public void The_properties_view_is_shared_while_OCProperties_is_the_same_dictionary() + { + using PdfDocument document = OpenCorpus(); + + Assert.Same(document.OptionalContent, document.OptionalContent); + } + + [Fact] + public void Reading_optional_content_leaves_every_object_clean() + { + using PdfDocument document = OpenCorpus(); + PdfOptionalContentProperties properties = document.OptionalContent!; + + PdfOptionalContentState state = properties.GetStates(properties.Configurations[0], properties.GetDefaultStates()); + _ = properties.DefaultConfiguration.Order; + foreach (PdfOptionalContentGroup group in properties.Groups) + { + _ = (group.Name, group.Intents, group.Usage?.ViewState); + } + + for (int number = 1; number <= 12; number++) + { + properties.IsVisible(new CosReference(number, 0), state); + Assert.False(document.Resolve(new CosReference(number, 0)).IsDirty); + } + + Assert.False(document.Catalog.IsDirty); + } +} diff --git a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt index f9e9b5e1..41565c84 100644 --- a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt +++ b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt @@ -31,6 +31,7 @@ name-tree-dests.pdf, no-xref.pdf, object-stream.pdf, + optional-content.pdf, outline.pdf, page-tree-inherited.pdf, pdf20-header.pdf, diff --git a/tests/Corpus/README.md b/tests/Corpus/README.md index f693ab10..dbe07dc9 100644 --- a/tests/Corpus/README.md +++ b/tests/Corpus/README.md @@ -64,6 +64,7 @@ Verification was run with qpdf 12.4.2 (`qpdf --check`), poppler (`pdfinfo`, `pdf | `outline.pdf` | `/Outlines` root with two sibling items linked by `/First /Last /Next /Prev /Parent`, each with an explicit destination; `/PageMode /UseOutlines`. | 12.3.3, 12.3.2.2 | `qpdf --check`; `qpdf --json --json-key=outlines` lists both items with their destinations | clean | | `name-tree-dests.pdf` | `/Names << /Dests ... >>` name tree with a root `/Kids` node and two leaves carrying `/Limits` and `/Names` for `alpha`, `beta`, `gamma`. | 7.9.6, 12.3.2.3 | `qpdf --check` | clean | | `metadata-xmp.pdf` | Catalog `/Metadata` stream (`/Type /Metadata /Subtype /XML`) with a minimal XMP packet whose `dc:title` is `Broadside`, plus a trailer `/Info` dictionary with the same `/Title`. | 14.3.2, 14.3.3 | `pdfinfo` shows `Title: Broadside` | clean | +| `optional-content.pdf` | `/OCProperties` with groups A, B (OFF in `D`), C (`/Intent /Design`) and D2 (`/Usage /View /ViewState /OFF`, no `AS`); OCMD `/OCGs [A B] /P /AllOff` and OCMD `/VE [/Or A [/Not B]]`; `/OC` sections `/a`, `/m1`, `/m2`, `/a` nested in `/b`; a form XObject with `/OC B`; a Square annotation with `/OC C`; `D` with `Order` (label and unlabelled nesting), `RBGroups`, `Locked`; one alternate configuration (`/BaseState /OFF /ON [C] /Intent /All`). Expected default: A ON, B OFF, C ON (no effect under View), D2 ON; sections a visible, m1 hidden, m2 visible, nested hidden, form hidden, annotation visible. | 8.11 | `qpdf --check`, `pdfinfo` | clean; one Letter page | The crypt filter `/Length` entries in the R4 and R6 files are `16` and `32` (bytes), the form Acrobat and qpdf write and that Table 25 describes for the standard security handler; the same table also says the key "shall have the value of 128/256". Readers should accept both forms. diff --git a/tests/Corpus/generate.py b/tests/Corpus/generate.py index 88922f6c..49b29e85 100644 --- a/tests/Corpus/generate.py +++ b/tests/Corpus/generate.py @@ -1206,6 +1206,44 @@ def gen_metadata_xmp() -> bytes: ], trailer_extra=b" /Info 5 0 R") +# --------------------------------------------------------------------------- +# Optional content, files, associated files, object metadata, declarations (issue #76) +# --------------------------------------------------------------------------- + + +def gen_optional_content() -> bytes: + """8.11: four groups (A, B in D's OFF, C with Intent Design, D2 with a View usage OFF but no AS), + OCMD 9 (/OCGs [A B] /P /AllOff) and OCMD 10 (/VE [/Or A [/Not B]]), content sections /OC /a, /m1, /m2 + and /a nested in /b, a form XObject with /OC B, an annotation with /OC C; D carries Order (a label and + an unlabelled nested array), RBGroups and Locked; Configs has one alternate configuration + (8.11.4.3 Table 99: BaseState OFF, ON [C], Intent All).""" + content = (b"/OC /a BDC 0 0 10 10 re f EMC\n" + b"/OC /m1 BDC 20 0 10 10 re f EMC\n" + b"/OC /m2 BDC 40 0 10 10 re f EMC\n" + b"/OC /b BDC /OC /a BDC 60 0 10 10 re f EMC EMC\n" + b"/Fm Do\n") + ocprops = (b" /OCProperties << /OCGs [5 0 R 6 0 R 7 0 R 8 0 R]" + b" /D << /Name (Default) /Creator (Broadside corpus) /OFF [6 0 R]" + b" /Order [5 0 R [(Labelled) 6 0 R 7 0 R] [8 0 R]] /RBGroups [[5 0 R 6 0 R]] /Locked [7 0 R] >>" + b" /Configs [<< /Name (Only C) /BaseState /OFF /ON [7 0 R] /Intent /All /ListMode /VisiblePages >>] >>") + return simple_file([ + (1, catalog(ocprops)), + (2, pages()), + (3, page(contents=4, resources=False, + extra=b" /Resources << /Properties << /a 5 0 R /b 6 0 R /m1 9 0 R /m2 10 0 R >>" + b" /XObject << /Fm 11 0 R >> >> /Annots [12 0 R]")), + (4, stream(b"", content)), + (5, b"<< /Type /OCG /Name (A) >>"), + (6, b"<< /Type /OCG /Name (B) >>"), + (7, b"<< /Type /OCG /Name (C) /Intent /Design /Usage << /CreatorInfo << /Creator (Broadside) /Subtype /Technical >> >> >>"), + (8, b"<< /Type /OCG /Name (D2) /Usage << /View << /ViewState /OFF >> /Zoom << /min 1.5 >> >> >>"), + (9, b"<< /Type /OCMD /OCGs [5 0 R 6 0 R] /P /AllOff >>"), + (10, b"<< /Type /OCMD /VE [/Or 5 0 R [/Not 6 0 R]] >>"), + (11, stream(b"/Type /XObject /Subtype /Form /BBox [0 0 10 10] /OC 6 0 R", b"80 0 10 10 re f")), + (12, b"<< /Type /Annot /Subtype /Square /Rect [100 100 200 200] /OC 7 0 R >>"), + ]) + + FILES = { "empty-page.pdf": gen_empty_page, "pdf20-header.pdf": gen_pdf20_header, @@ -1249,6 +1287,7 @@ def gen_metadata_xmp() -> bytes: "outline.pdf": gen_outline, "name-tree-dests.pdf": gen_name_tree_dests, "metadata-xmp.pdf": gen_metadata_xmp, + "optional-content.pdf": gen_optional_content, } diff --git a/tests/Corpus/optional-content.pdf b/tests/Corpus/optional-content.pdf new file mode 100644 index 0000000000000000000000000000000000000000..10ed99e733791ef896f3cfa8dc9dbf04af08fbd9 GIT binary patch literal 1806 zcmZ`)+iu!G5PkPo%uA%?p;@oFOA%7QA&MGe6w;`w#lwOZ;?(xi^`a*I`p&FvFeV_d zVCQyb=A7kX=1;!y>z>2G1+{#4Zf=0Rd~PMMu`nW08(=fBkvVwi@C+;%&$QY~ZDKql z=U{xFL)fv_u6_3Gvro?jFyDGTiB!U+FV|w1m@7=Kr7%jvfVEHar#x8e~ z0w?}h3(fU5%M?}&5riedp%(&C_JWg>*~Yv9Z}+I%+#n}X2MGmCz{nq?t4k&EttG7C zZaOZkh>6VJS-WTL?Q`~}HP;GtPd$rj*qN^!T11Ji+$BxvcqJ%5DHDAn|ktyTSZOg+W#-5Qfo`&4ES~Dq!3Z6S!n8`$eNc45_o2H7OdB`sahg_ zmEiRbLcB9d8i(vjnS#l90~}ar*?Jsa@%b>OiP9-v1A9qXCL$i>XL0xJ`Ahv(^z9#0 z>6AKF6UVi!TxtuN|Jk9mNvbHYkh>%S7wK+41%l#^J#_S;<=R2NmgDYU(Cu_u9Td*t z4ChWS$o6NgE?zH Date: Fri, 9 Oct 2026 16:18:57 -0500 Subject: [PATCH 023/152] feat(model): portable collections with schema, sort, colours, split and folders (#76) PdfDocument.Collection (PdfCollection) with typed View, initial document, schema fields, sort (padded ascending flags), colours, split defaults by view and the Folders tree (Child/Next walk with cycle and duplicate-ID diagnostics); file-to-folder by the key prefix. Co-Authored-By: Claude Opus 5.5 --- src/Broadside/PdfCollection.cs | 189 ++++++++++ src/Broadside/PdfCollectionFolder.cs | 97 +++++ src/Broadside/PdfCollectionTypes.cs | 345 ++++++++++++++++++ src/Broadside/PdfDocument.cs | 7 + src/Broadside/PublicAPI.Unshipped.txt | 95 +++++ .../Broadside.Tests/Files/CollectionTests.cs | 145 ++++++++ 6 files changed, 878 insertions(+) create mode 100644 src/Broadside/PdfCollection.cs create mode 100644 src/Broadside/PdfCollectionFolder.cs create mode 100644 src/Broadside/PdfCollectionTypes.cs create mode 100644 tests/Broadside.Tests/Files/CollectionTests.cs diff --git a/src/Broadside/PdfCollection.cs b/src/Broadside/PdfCollection.cs new file mode 100644 index 00000000..89ed2b78 --- /dev/null +++ b/src/Broadside/PdfCollection.cs @@ -0,0 +1,189 @@ +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// A portable collection (portfolio): how a user interface presents the document's embedded files. A live view. +/// +/// +/// ISO 32000-2 §12.3.5 (PDF 1.7), Tables 153-159, reached through the catalog's Collection entry (§7.7.2, Table 29). The +/// files are the entries of the EmbeddedFiles name tree (); each file's values for the schema +/// fields are in its collection item (). +/// +/// +/// Folders (PDF 2.0) are walked from Folders through Child and Next each time is read; +/// a folder reached twice (a cycle) is skipped with CollectionFolderCycle, and of folders sharing an ID the first one found +/// keeps it (CollectionFolderIdDuplicate). +/// +/// +public sealed class PdfCollection +{ + private readonly PdfDocument _document; + + internal PdfCollection(PdfDocument document, CosDictionary dictionary, CosReference? reference) + { + _document = document; + Dictionary = dictionary; + Reference = reference; + } + + /// Gets the collection dictionary. + /// ISO 32000-2 §12.3.5, Table 153. + public CosDictionary Dictionary { get; } + + /// Gets the indirect reference to the collection dictionary, or . + public CosReference? Reference { get; } + + /// Gets the initial presentation (View, default details). + /// + /// ISO 32000-2 §12.3.5, Table 153. The navigator view (C, PDF 2.0) requires a Navigator entry; without one it + /// reads as details with a CollectionInvalid diagnostic. + /// + public PdfCollectionView View + { + get + { + switch (ViewReading.Name(_document, Dictionary, FileAndLayerNames.View)?.Value) + { + case "T": + return PdfCollectionView.Tile; + case "H": + return PdfCollectionView.Hidden; + case "C" when Navigator is not null: + return PdfCollectionView.Navigator; + case "C": + ViewReading.Warn(_document, DiagnosticCodes.CollectionInvalid, "The collection's View is C (navigator) but it has no Navigator; details view is used.", Reference); + return PdfCollectionView.Details; + default: + return PdfCollectionView.Details; + } + } + } + + /// Gets the EmbeddedFiles key of the document shown first (D), or for the collection itself. + /// ISO 32000-2 §12.3.5, Table 153. A key that matches no file means the first file. + public string? InitialDocument => ViewReading.Text(_document, Dictionary, FileAndLayerNames.D); + + /// Gets the navigator dictionary (Navigator, PDF 2.0), as is, or . + /// ISO 32000-2 §12.3.5, Table 153. Navigators are parse-and-preserve. + public CosDictionary? Navigator => ViewReading.Get(_document, Dictionary, FileAndLayerNames.Navigator) as CosDictionary; + + /// Gets the schema fields (Schema), in the order they are stored; see for the column order. + /// ISO 32000-2 §12.3.5, Tables 154 and 155. Entries that are not dictionaries are skipped. + public IReadOnlyList Schema => ViewReading.Get(_document, Dictionary, FileAndLayerNames.Schema) is CosDictionary schema + ? [.. schema.Where(entry => !entry.Key.Equals(KnownNames.Type) && _document.Resolve(entry.Value) is CosDictionary) + .Select(entry => new PdfCollectionField(_document, entry.Key, (CosDictionary)_document.Resolve(entry.Value)))] + : []; + + /// Gets the sort order (Sort), or . + /// ISO 32000-2 §12.3.5, Table 156. + public PdfCollectionSort? Sort => ViewReading.Get(_document, Dictionary, FileAndLayerNames.Sort) is CosDictionary sort ? new PdfCollectionSort(_document, sort) : null; + + /// Gets the user-interface colours (Colors, PDF 2.0), or . + /// ISO 32000-2 §12.3.5, Table 157. + public PdfCollectionColors? Colors => ViewReading.Get(_document, Dictionary, FileAndLayerNames.Colors) is CosDictionary colors ? new PdfCollectionColors(_document, colors) : null; + + /// Gets the split of the user interface (Split, PDF 2.0), with the defaults the view implies. + /// ISO 32000-2 §12.3.5, Table 158. + public PdfCollectionSplit Split + { + get + { + PdfCollectionView view = View; + PdfCollectionSplitDirection fallback = view switch + { + PdfCollectionView.Details => PdfCollectionSplitDirection.Horizontal, + PdfCollectionView.Tile => PdfCollectionSplitDirection.Vertical, + _ => PdfCollectionSplitDirection.None, + }; + if (ViewReading.Get(_document, Dictionary, FileAndLayerNames.Split) is not CosDictionary split) + { + return new PdfCollectionSplit(fallback, null); + } + + PdfCollectionSplitDirection direction = ViewReading.Name(_document, split, FileAndLayerNames.Direction)?.Value switch + { + "H" => PdfCollectionSplitDirection.Horizontal, + "V" => PdfCollectionSplitDirection.Vertical, + "N" => PdfCollectionSplitDirection.None, + _ => fallback, + }; + return new PdfCollectionSplit(direction, ViewReading.Number(_document, split, FileAndLayerNames.Position)); + } + } + + /// Gets the root folder (Folders, PDF 2.0) with its subtree, or when the collection has no folders. + /// ISO 32000-2 §12.3.5, Table 159. + public PdfCollectionFolder? RootFolder => BuildFolders(out _); + + /// Returns the folder with ID , or . + /// The folder ID. + /// The first folder found with that ID. + /// ISO 32000-2 §12.3.5, Table 159. + public PdfCollectionFolder? FindFolder(int id) + { + BuildFolders(out Dictionary byId); + return byId.GetValueOrDefault(id); + } + + /// Returns the folder an embedded file belongs to: the folder its key's <id> prefix names, else the root folder. + /// An entry of . + /// The folder; when the collection has no folders. + /// ISO 32000-2 §12.3.5, "Folders": a key without a valid folder prefix, or naming no folder, places the file in the root. + public PdfCollectionFolder? GetFolder(PdfEmbeddedFileEntry file) + { + ArgumentNullException.ThrowIfNull(file); + PdfCollectionFolder? root = BuildFolders(out Dictionary byId); + return file.FolderId is { } id && byId.TryGetValue(id, out PdfCollectionFolder? folder) ? folder : root; + } + + private PdfCollectionFolder? BuildFolders(out Dictionary byId) + { + byId = []; + if (!Dictionary.TryGetValue(FileAndLayerNames.Folders, out CosObject? entry) || _document.Resolve(entry) is not CosDictionary rootDictionary) + { + return null; + } + + var root = new PdfCollectionFolder(_document, rootDictionary, entry as CosReference, null); + var visited = new HashSet(ReferenceEqualityComparer.Instance) { rootDictionary }; + var pending = new Stack(); + pending.Push(root); + Register(root, byId); + while (pending.TryPop(out PdfCollectionFolder? folder)) + { + folder.Dictionary.TryGetValue(FileAndLayerNames.Child, out CosObject? link); + var siblings = new List(); + while (link is not null && _document.Resolve(link) is CosDictionary child) + { + if (!visited.Add(child)) + { + ViewReading.Warn(_document, DiagnosticCodes.CollectionFolderCycle, "A collection folder's Child or Next leads back to a folder already reached; the link is ignored.", folder.Reference ?? Reference); + break; + } + + var view = new PdfCollectionFolder(_document, child, link as CosReference, folder); + folder.AddChild(view); + Register(view, byId); + siblings.Add(view); + child.TryGetValue(FileAndLayerNames.Next, out link); + } + + for (int index = siblings.Count - 1; index >= 0; index--) + { + pending.Push(siblings[index]); + } + } + + return root; + + void Register(PdfCollectionFolder folder, Dictionary index) + { + int id = folder.Id; + if (id >= 0 && !index.TryAdd(id, folder)) + { + ViewReading.Warn(_document, DiagnosticCodes.CollectionFolderIdDuplicate, $"Two collection folders have the ID {id}; the first one found keeps it.", folder.Reference ?? Reference); + } + } + } +} diff --git a/src/Broadside/PdfCollectionFolder.cs b/src/Broadside/PdfCollectionFolder.cs new file mode 100644 index 00000000..f9317fdf --- /dev/null +++ b/src/Broadside/PdfCollectionFolder.cs @@ -0,0 +1,97 @@ +using Broadside.Objects; + +namespace Broadside; + +/// A folder of a portable collection. Its entries are read live; its place in the tree is a snapshot of the walk that found it. +/// +/// ISO 32000-2 §12.3.5 (PDF 2.0), Table 159, "Folders". The tree is reached from the collection's Folders root through +/// Child (first child) and Next (next sibling); and reflect that walk, +/// not the Parent entries. A file belongs to a folder through the <id> prefix of its EmbeddedFiles key. +/// +public sealed class PdfCollectionFolder +{ + private readonly PdfDocument _document; + private readonly List _children = []; + + internal PdfCollectionFolder(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfCollectionFolder? parent) + { + _document = document; + Dictionary = dictionary; + Reference = reference; + Parent = parent; + } + + /// Gets the folder dictionary. + /// ISO 32000-2 §12.3.5, Table 159. + public CosDictionary Dictionary { get; } + + /// Gets the indirect reference to the folder, or . + public CosReference? Reference { get; } + + /// Gets the folder's ID (ID, a non-negative integer unique in the collection), or -1 when missing or invalid. + /// ISO 32000-2 §12.3.5, Table 159 (required). + public int Id => ViewReading.Integer(_document, Dictionary, FileAndLayerNames.ID) is { } id and >= 0 and <= int.MaxValue ? (int)id : -1; + + /// Gets the folder's name (Name); empty when missing. + /// ISO 32000-2 §12.3.5, Table 159 (required; file-name rules apply). + public string Name => ViewReading.Text(_document, Dictionary, FileAndLayerNames.Name) ?? string.Empty; + + /// Gets the folder's description (Desc), or . + /// ISO 32000-2 §12.3.5, Table 159. + public string? Description => ViewReading.Text(_document, Dictionary, FileAndLayerNames.Desc); + + /// Gets the folder this one was found under, or for the root. + /// ISO 32000-2 §12.3.5, Table 159 (Parent). + public PdfCollectionFolder? Parent { get; } + + /// Gets the subfolders, in Child/Next order. + /// ISO 32000-2 §12.3.5, Table 159 (Child, Next). + public IReadOnlyList Children => _children; + + /// Gets the folder's collection item (CI), or . + /// ISO 32000-2 §12.3.5, Table 159, and §7.11.6. + public PdfCollectionItem? CollectionItem => + ViewReading.Get(_document, Dictionary, FileAndLayerNames.CI) is CosDictionary item ? new PdfCollectionItem(_document, item) : null; + + /// Gets the creation date as written (CreationDate), or . + /// ISO 32000-2 §12.3.5, Table 159, and §7.9.4. + public CosString? CreationDate => ViewReading.Get(_document, Dictionary, FileAndLayerNames.CreationDate) as CosString; + + /// Gets the modification date as written (ModDate), or . + /// ISO 32000-2 §12.3.5, Table 159, and §7.9.4. + public CosString? ModificationDate => ViewReading.Get(_document, Dictionary, FileAndLayerNames.ModDate) as CosString; + + /// Gets the folder's thumbnail image (Thumb), or . + /// ISO 32000-2 §12.3.5, Table 159, and §12.3.4. + public CosStream? Thumbnail => ViewReading.Get(_document, Dictionary, FileAndLayerNames.Thumb) as CosStream; + + /// Gets the ranges of IDs free for new folders (Free, root folder only). + /// ISO 32000-2 §12.3.5, Table 159: an array of pairs of integers. + public IReadOnlyList FreeIds + { + get + { + if (ViewReading.Get(_document, Dictionary, FileAndLayerNames.Free) is not CosArray array) + { + return []; + } + + var ranges = new List(array.Count / 2); + for (int index = 0; index + 1 < array.Count; index += 2) + { + if (_document.Resolve(array[index]) is CosInteger { Value: >= 0 and <= int.MaxValue } low + && _document.Resolve(array[index + 1]) is CosInteger { Value: >= 0 and <= int.MaxValue } high) + { + ranges.Add(new PdfCollectionIdRange((int)low.Value, (int)high.Value)); + } + } + + return ranges; + } + } + + /// + public override string ToString() => Name; + + internal void AddChild(PdfCollectionFolder child) => _children.Add(child); +} diff --git a/src/Broadside/PdfCollectionTypes.cs b/src/Broadside/PdfCollectionTypes.cs new file mode 100644 index 00000000..3b2ef1e1 --- /dev/null +++ b/src/Broadside/PdfCollectionTypes.cs @@ -0,0 +1,345 @@ +using System.Globalization; +using Broadside.Objects; + +namespace Broadside; + +/// How a portable collection is first presented (View). +/// ISO 32000-2 §12.3.5, Table 153. Default . +public enum PdfCollectionView +{ + /// Details mode: a multi-column list (D). + Details, + + /// Tile mode: icons and summary information (T). + Tile, + + /// Hidden: the collection list is not shown initially (H). + Hidden, + + /// Navigator (C, PDF 2.0): presented by the collection's Navigator. + Navigator, +} + +/// The kind of data a collection schema field shows (Subtype). +/// ISO 32000-2 §12.3.5, Table 155. +public enum PdfCollectionFieldType +{ + /// A text field from the collection item (S). + Text, + + /// A date field from the collection item (D). + Date, + + /// A number field from the collection item (N). + Number, + + /// The file name of the embedded file (F). + FileName, + + /// The file specification's description (Desc). + Description, + + /// The embedded file's modification date (ModDate). + ModificationDate, + + /// The embedded file's creation date (CreationDate). + CreationDate, + + /// The embedded file's size (Size). + Size, + + /// The length of the embedded file stream (CompressedSize, PDF 2.0). + CompressedSize, + + /// A missing or unknown subtype; see . + Unknown, +} + +/// How a collection's user interface is split between the file list and the preview (Split Direction). +/// ISO 32000-2 §12.3.5, Table 158 (PDF 2.0). +public enum PdfCollectionSplitDirection +{ + /// Split horizontally (H). + Horizontal, + + /// Split vertically (V). + Vertical, + + /// Not split (N): the file list only. + None, +} + +/// An RGB colour of a collection's user interface, each component 0 to 1. +/// ISO 32000-2 §12.3.5, Table 157 (PDF 2.0): an array of three numbers in DeviceRGB. +public readonly struct PdfCollectionColor : IEquatable +{ + /// Initializes a new instance of the struct. + /// The red component. + /// The green component. + /// The blue component. + public PdfCollectionColor(double red, double green, double blue) + { + Red = red; + Green = green; + Blue = blue; + } + + /// Gets the red component. + public double Red { get; } + + /// Gets the green component. + public double Green { get; } + + /// Gets the blue component. + public double Blue { get; } + + /// Compares two values. + /// The first value. + /// The second value. + /// when equal. + public static bool operator ==(PdfCollectionColor left, PdfCollectionColor right) => left.Equals(right); + + /// Compares two values. + /// The first value. + /// The second value. + /// when different. + public static bool operator !=(PdfCollectionColor left, PdfCollectionColor right) => !left.Equals(right); + + /// + public bool Equals(PdfCollectionColor other) => Red.Equals(other.Red) && Green.Equals(other.Green) && Blue.Equals(other.Blue); + + /// + public override bool Equals(object? obj) => obj is PdfCollectionColor other && Equals(other); + + /// + public override int GetHashCode() => HashCode.Combine(Red, Green, Blue); + + /// + public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"[{Red} {Green} {Blue}]"); +} + +/// A range of folder IDs that are free for new folders. +/// ISO 32000-2 §12.3.5, Table 159 (Free, PDF 2.0). +public readonly struct PdfCollectionIdRange : IEquatable +{ + /// Initializes a new instance of the struct. + /// The lowest free ID. + /// The highest free ID. + public PdfCollectionIdRange(int low, int high) + { + Low = low; + High = high; + } + + /// Gets the lowest free ID. + public int Low { get; } + + /// Gets the highest free ID. + public int High { get; } + + /// Compares two values. + /// The first value. + /// The second value. + /// when equal. + public static bool operator ==(PdfCollectionIdRange left, PdfCollectionIdRange right) => left.Equals(right); + + /// Compares two values. + /// The first value. + /// The second value. + /// when different. + public static bool operator !=(PdfCollectionIdRange left, PdfCollectionIdRange right) => !left.Equals(right); + + /// + public bool Equals(PdfCollectionIdRange other) => Low.Equals(other.Low) && High.Equals(other.High); + + /// + public override bool Equals(object? obj) => obj is PdfCollectionIdRange other && Equals(other); + + /// + public override int GetHashCode() => HashCode.Combine(Low, High); + + /// + public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"[{Low} {High}]"); +} + +/// A field of a collection schema: a column of the details view. A live view over the field dictionary. +/// ISO 32000-2 §12.3.5, Tables 154 and 155. +public sealed class PdfCollectionField +{ + private readonly PdfDocument _document; + + internal PdfCollectionField(PdfDocument document, CosName key, CosDictionary dictionary) + { + _document = document; + Key = key.Value; + Dictionary = dictionary; + } + + /// Gets the field's key in the schema, which collection items use for their values. + /// ISO 32000-2 §12.3.5, Table 154. + public string Key { get; } + + /// Gets the collection field dictionary. + /// ISO 32000-2 §12.3.5, Table 155. + public CosDictionary Dictionary { get; } + + /// Gets the kind of data the field shows (Subtype). + /// ISO 32000-2 §12.3.5, Table 155 (required). + public PdfCollectionFieldType Type => TypeName?.Value switch + { + "S" => PdfCollectionFieldType.Text, + "D" => PdfCollectionFieldType.Date, + "N" => PdfCollectionFieldType.Number, + "F" => PdfCollectionFieldType.FileName, + "Desc" => PdfCollectionFieldType.Description, + "ModDate" => PdfCollectionFieldType.ModificationDate, + "CreationDate" => PdfCollectionFieldType.CreationDate, + "Size" => PdfCollectionFieldType.Size, + "CompressedSize" => PdfCollectionFieldType.CompressedSize, + _ => PdfCollectionFieldType.Unknown, + }; + + /// Gets the Subtype name as written, or . + /// ISO 32000-2 §12.3.5, Table 155. + public CosName? TypeName => ViewReading.Name(_document, Dictionary, FileAndLayerNames.Subtype); + + /// Gets the field's name for the user interface (N); empty when missing. + /// ISO 32000-2 §12.3.5, Table 155 (required). + public string Name => ViewReading.Text(_document, Dictionary, FileAndLayerNames.N) ?? string.Empty; + + /// Gets the field's relative position among the columns (O), or . + /// ISO 32000-2 §12.3.5, Table 155. + public int? Order => ViewReading.Integer(_document, Dictionary, FileAndLayerNames.O) is { } order and >= int.MinValue and <= int.MaxValue ? (int)order : null; + + /// Gets a value indicating whether the field is shown initially (V, default ). + /// ISO 32000-2 §12.3.5, Table 155. + public bool IsVisible => ViewReading.Boolean(_document, Dictionary, FileAndLayerNames.V, fallback: true); + + /// Gets a value indicating whether the user interface offers to edit the field (E, default ). + /// ISO 32000-2 §12.3.5, Table 155. + public bool IsEditable => ViewReading.Boolean(_document, Dictionary, FileAndLayerNames.E, fallback: false); + + /// + public override string ToString() => Key; +} + +/// The sort order of a collection's files. A live view over the collection sort dictionary. +/// ISO 32000-2 §12.3.5, Table 156. +public sealed class PdfCollectionSort +{ + private readonly PdfDocument _document; + + internal PdfCollectionSort(PdfDocument document, CosDictionary dictionary) + { + _document = document; + Dictionary = dictionary; + } + + /// Gets the collection sort dictionary. + /// ISO 32000-2 §12.3.5, Table 156. + public CosDictionary Dictionary { get; } + + /// Gets the schema field keys to sort by, primary first; later keys break ties (S, a name or an array). + /// ISO 32000-2 §12.3.5, Table 156 (required). + public IReadOnlyList Keys => ViewReading.Get(_document, Dictionary, FileAndLayerNames.S) switch + { + CosName name => [name.Value], + CosArray array => [.. array.Select(_document.Resolve).OfType().Select(name => name.Value)], + _ => [], + }; + + /// + /// Gets, per entry of , whether that key sorts ascending (A, a boolean or an array; default + /// ). A short array is padded with ; extra entries are ignored. + /// + /// ISO 32000-2 §12.3.5, Table 156. + public IReadOnlyList Ascending + { + get + { + int count = Keys.Count; + var flags = new bool[count]; + Array.Fill(flags, true); + switch (ViewReading.Get(_document, Dictionary, FileAndLayerNames.A)) + { + case CosBoolean single when count > 0: + flags[0] = single.Value; + break; + case CosArray array: + for (int index = 0; index < Math.Min(count, array.Count); index++) + { + flags[index] = _document.Resolve(array[index]) is not CosBoolean { Value: false }; + } + + break; + } + + return flags; + } + } +} + +/// The colours of a collection's user interface. A live view over the collection colours dictionary. +/// ISO 32000-2 §12.3.5, Table 157 (PDF 2.0). An entry that is not three numbers reads as . +public sealed class PdfCollectionColors +{ + private readonly PdfDocument _document; + + internal PdfCollectionColors(PdfDocument document, CosDictionary dictionary) + { + _document = document; + Dictionary = dictionary; + } + + /// Gets the collection colours dictionary. + /// ISO 32000-2 §12.3.5, Table 157. + public CosDictionary Dictionary { get; } + + /// Gets the background colour (Background). + /// ISO 32000-2 §12.3.5, Table 157. + public PdfCollectionColor? Background => Read(FileAndLayerNames.Background); + + /// Gets the background colour of a card (CardBackground). + /// ISO 32000-2 §12.3.5, Table 157. + public PdfCollectionColor? CardBackground => Read(FileAndLayerNames.CardBackground); + + /// Gets the border colour of a card (CardBorder). + /// ISO 32000-2 §12.3.5, Table 157. + public PdfCollectionColor? CardBorder => Read(FileAndLayerNames.CardBorder); + + /// Gets the colour of primary text (PrimaryText). + /// ISO 32000-2 §12.3.5, Table 157. + public PdfCollectionColor? PrimaryText => Read(FileAndLayerNames.PrimaryText); + + /// Gets the colour of secondary text (SecondaryText). + /// ISO 32000-2 §12.3.5, Table 157. + public PdfCollectionColor? SecondaryText => Read(FileAndLayerNames.SecondaryText); + + private PdfCollectionColor? Read(CosName key) => + ViewReading.Get(_document, Dictionary, key) is CosArray { Count: 3 } array + && _document.Resolve(array[0]) is CosNumber red && _document.Resolve(array[1]) is CosNumber green && _document.Resolve(array[2]) is CosNumber blue + ? new PdfCollectionColor(red.ToDouble(), green.ToDouble(), blue.ToDouble()) + : null; +} + +/// The split of a collection's user interface: direction and position, with the defaults applied. +/// +/// ISO 32000-2 §12.3.5, Table 158 (PDF 2.0). Without a Split entry the direction follows the view: horizontal for details, +/// vertical for tile, none for hidden and navigator. +/// +public sealed class PdfCollectionSplit +{ + internal PdfCollectionSplit(PdfCollectionSplitDirection direction, double? position) + { + Direction = direction; + Position = position; + } + + /// Gets the split direction (Direction). + /// ISO 32000-2 §12.3.5, Table 158. + public PdfCollectionSplitDirection Direction { get; } + + /// Gets the split position as a percentage, 0 to 100 (Position), or ; ignored for . + /// ISO 32000-2 §12.3.5, Table 158. + public double? Position { get; } +} diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index cdb84da1..9768d35e 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -480,6 +480,13 @@ public IReadOnlyList EmbeddedFiles } } + /// Gets the document's portable collection (Collection), or when it is not a portfolio. + /// ISO 32000-2 §7.7.2, Table 29 (PDF 1.7), and §12.3.5. Read from the catalog on every call. + public PdfCollection? Collection => + Resolve(Catalog.TryGetValue(FileAndLayerNames.Collection, out CosObject? entry) ? entry : null) is CosDictionary dictionary + ? new PdfCollection(this, dictionary, entry as CosReference) + : null; + /// Returns a view over a file specification held by , resolving it first. /// A file specification string or dictionary, or a reference to one, of this document. /// The view, or when the value is neither a string nor a dictionary. diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index 7f8e9b7f..129dc950 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -69,6 +69,72 @@ Broadside.PdfCheckSumStatus Broadside.PdfCheckSumStatus.Absent = 0 -> Broadside.PdfCheckSumStatus Broadside.PdfCheckSumStatus.DoesNotMatch = 2 -> Broadside.PdfCheckSumStatus Broadside.PdfCheckSumStatus.Matches = 1 -> Broadside.PdfCheckSumStatus +Broadside.PdfCollection +Broadside.PdfCollection.Colors.get -> Broadside.PdfCollectionColors? +Broadside.PdfCollection.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfCollection.FindFolder(int id) -> Broadside.PdfCollectionFolder? +Broadside.PdfCollection.GetFolder(Broadside.PdfEmbeddedFileEntry! file) -> Broadside.PdfCollectionFolder? +Broadside.PdfCollection.InitialDocument.get -> string? +Broadside.PdfCollection.Navigator.get -> Broadside.Objects.CosDictionary? +Broadside.PdfCollection.Reference.get -> Broadside.Objects.CosReference? +Broadside.PdfCollection.RootFolder.get -> Broadside.PdfCollectionFolder? +Broadside.PdfCollection.Schema.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfCollection.Sort.get -> Broadside.PdfCollectionSort? +Broadside.PdfCollection.Split.get -> Broadside.PdfCollectionSplit! +Broadside.PdfCollection.View.get -> Broadside.PdfCollectionView +Broadside.PdfCollectionColor +Broadside.PdfCollectionColor.Blue.get -> double +Broadside.PdfCollectionColor.Equals(Broadside.PdfCollectionColor other) -> bool +Broadside.PdfCollectionColor.Green.get -> double +Broadside.PdfCollectionColor.PdfCollectionColor() -> void +Broadside.PdfCollectionColor.PdfCollectionColor(double red, double green, double blue) -> void +Broadside.PdfCollectionColor.Red.get -> double +Broadside.PdfCollectionColors +Broadside.PdfCollectionColors.Background.get -> Broadside.PdfCollectionColor? +Broadside.PdfCollectionColors.CardBackground.get -> Broadside.PdfCollectionColor? +Broadside.PdfCollectionColors.CardBorder.get -> Broadside.PdfCollectionColor? +Broadside.PdfCollectionColors.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfCollectionColors.PrimaryText.get -> Broadside.PdfCollectionColor? +Broadside.PdfCollectionColors.SecondaryText.get -> Broadside.PdfCollectionColor? +Broadside.PdfCollectionField +Broadside.PdfCollectionField.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfCollectionField.IsEditable.get -> bool +Broadside.PdfCollectionField.IsVisible.get -> bool +Broadside.PdfCollectionField.Key.get -> string! +Broadside.PdfCollectionField.Name.get -> string! +Broadside.PdfCollectionField.Order.get -> int? +Broadside.PdfCollectionField.Type.get -> Broadside.PdfCollectionFieldType +Broadside.PdfCollectionField.TypeName.get -> Broadside.Objects.CosName? +Broadside.PdfCollectionFieldType +Broadside.PdfCollectionFieldType.CompressedSize = 8 -> Broadside.PdfCollectionFieldType +Broadside.PdfCollectionFieldType.CreationDate = 6 -> Broadside.PdfCollectionFieldType +Broadside.PdfCollectionFieldType.Date = 1 -> Broadside.PdfCollectionFieldType +Broadside.PdfCollectionFieldType.Description = 4 -> Broadside.PdfCollectionFieldType +Broadside.PdfCollectionFieldType.FileName = 3 -> Broadside.PdfCollectionFieldType +Broadside.PdfCollectionFieldType.ModificationDate = 5 -> Broadside.PdfCollectionFieldType +Broadside.PdfCollectionFieldType.Number = 2 -> Broadside.PdfCollectionFieldType +Broadside.PdfCollectionFieldType.Size = 7 -> Broadside.PdfCollectionFieldType +Broadside.PdfCollectionFieldType.Text = 0 -> Broadside.PdfCollectionFieldType +Broadside.PdfCollectionFieldType.Unknown = 9 -> Broadside.PdfCollectionFieldType +Broadside.PdfCollectionFolder +Broadside.PdfCollectionFolder.Children.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfCollectionFolder.CollectionItem.get -> Broadside.PdfCollectionItem? +Broadside.PdfCollectionFolder.CreationDate.get -> Broadside.Objects.CosString? +Broadside.PdfCollectionFolder.Description.get -> string? +Broadside.PdfCollectionFolder.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfCollectionFolder.FreeIds.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfCollectionFolder.Id.get -> int +Broadside.PdfCollectionFolder.ModificationDate.get -> Broadside.Objects.CosString? +Broadside.PdfCollectionFolder.Name.get -> string! +Broadside.PdfCollectionFolder.Parent.get -> Broadside.PdfCollectionFolder? +Broadside.PdfCollectionFolder.Reference.get -> Broadside.Objects.CosReference? +Broadside.PdfCollectionFolder.Thumbnail.get -> Broadside.Objects.CosStream? +Broadside.PdfCollectionIdRange +Broadside.PdfCollectionIdRange.Equals(Broadside.PdfCollectionIdRange other) -> bool +Broadside.PdfCollectionIdRange.High.get -> int +Broadside.PdfCollectionIdRange.Low.get -> int +Broadside.PdfCollectionIdRange.PdfCollectionIdRange() -> void +Broadside.PdfCollectionIdRange.PdfCollectionIdRange(int low, int high) -> void Broadside.PdfCollectionItem Broadside.PdfCollectionItem.Dictionary.get -> Broadside.Objects.CosDictionary! Broadside.PdfCollectionItem.GetValue(string! fieldKey) -> Broadside.PdfCollectionItemValue? @@ -78,6 +144,23 @@ Broadside.PdfCollectionItemValue.Data.get -> Broadside.Objects.CosObject! Broadside.PdfCollectionItemValue.Number.get -> double? Broadside.PdfCollectionItemValue.Prefix.get -> string? Broadside.PdfCollectionItemValue.Text.get -> string? +Broadside.PdfCollectionSort +Broadside.PdfCollectionSort.Ascending.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfCollectionSort.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfCollectionSort.Keys.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfCollectionSplit +Broadside.PdfCollectionSplit.Direction.get -> Broadside.PdfCollectionSplitDirection +Broadside.PdfCollectionSplit.Position.get -> double? +Broadside.PdfCollectionSplitDirection +Broadside.PdfCollectionSplitDirection.Horizontal = 0 -> Broadside.PdfCollectionSplitDirection +Broadside.PdfCollectionSplitDirection.None = 2 -> Broadside.PdfCollectionSplitDirection +Broadside.PdfCollectionSplitDirection.Vertical = 1 -> Broadside.PdfCollectionSplitDirection +Broadside.PdfCollectionView +Broadside.PdfCollectionView.Details = 0 -> Broadside.PdfCollectionView +Broadside.PdfCollectionView.Hidden = 2 -> Broadside.PdfCollectionView +Broadside.PdfCollectionView.Navigator = 3 -> Broadside.PdfCollectionView +Broadside.PdfCollectionView.Tile = 1 -> Broadside.PdfCollectionView +Broadside.PdfDocument.Collection.get -> Broadside.PdfCollection? Broadside.PdfDocument.EmbeddedFiles.get -> System.Collections.Generic.IReadOnlyList! Broadside.PdfDocument.GetFileSpecification(Broadside.Objects.CosObject? value) -> Broadside.PdfFileSpecification? Broadside.PdfDocument.OptionalContent.get -> Broadside.PdfOptionalContentProperties? @@ -269,6 +352,14 @@ override Broadside.Objects.CosReference.GetHashCode() -> int override Broadside.Objects.CosStream.IsDirty.get -> bool override Broadside.Objects.CosString.Equals(object? obj) -> bool override Broadside.Objects.CosString.GetHashCode() -> int +override Broadside.PdfCollectionColor.Equals(object? obj) -> bool +override Broadside.PdfCollectionColor.GetHashCode() -> int +override Broadside.PdfCollectionColor.ToString() -> string! +override Broadside.PdfCollectionField.ToString() -> string! +override Broadside.PdfCollectionFolder.ToString() -> string! +override Broadside.PdfCollectionIdRange.Equals(object? obj) -> bool +override Broadside.PdfCollectionIdRange.GetHashCode() -> int +override Broadside.PdfCollectionIdRange.ToString() -> string! override Broadside.PdfEmbeddedFileEntry.ToString() -> string! override Broadside.PdfOptionalContentConfiguration.ToString() -> string! override Broadside.PdfOptionalContentGroup.ToString() -> string! @@ -280,6 +371,10 @@ static Broadside.Objects.CosNull.Instance.get -> Broadside.Objects.CosNull! static Broadside.Objects.CosObject.DeepEquals(Broadside.Objects.CosObject? left, Broadside.Objects.CosObject? right) -> bool static Broadside.Objects.CosObject.Parse(System.ReadOnlySpan bytes) -> Broadside.Objects.CosObject! static Broadside.Objects.CosObject.TryParse(System.ReadOnlySpan bytes, out Broadside.Objects.CosObject? result) -> bool +static Broadside.PdfCollectionColor.operator !=(Broadside.PdfCollectionColor left, Broadside.PdfCollectionColor right) -> bool +static Broadside.PdfCollectionColor.operator ==(Broadside.PdfCollectionColor left, Broadside.PdfCollectionColor right) -> bool +static Broadside.PdfCollectionIdRange.operator !=(Broadside.PdfCollectionIdRange left, Broadside.PdfCollectionIdRange right) -> bool +static Broadside.PdfCollectionIdRange.operator ==(Broadside.PdfCollectionIdRange left, Broadside.PdfCollectionIdRange right) -> bool virtual Broadside.Objects.CosObject.IsDirty.get -> bool Broadside.Diagnostics.Diagnostic Broadside.Diagnostics.Diagnostic.Code.get -> string! diff --git a/tests/Broadside.Tests/Files/CollectionTests.cs b/tests/Broadside.Tests/Files/CollectionTests.cs new file mode 100644 index 00000000..4f7e1e52 --- /dev/null +++ b/tests/Broadside.Tests/Files/CollectionTests.cs @@ -0,0 +1,145 @@ +using Broadside.Tests.Document; +using Broadside.TestSupport; + +namespace Broadside.Tests.Files; + +/// Portable collections (portfolios): schema, sort, colours, split, folders and collection items. ISO 32000-2 §12.3.5, §7.11.6. +public class CollectionTests +{ + private static PdfDocument OpenCorpus() => PdfDocument.Open(Corpus.Path("collection-portfolio.pdf")); + + [Fact] + public void The_collection_exposes_view_initial_document_and_schema_fields() + { + using PdfDocument document = OpenCorpus(); + + PdfCollection collection = document.Collection!; + + Assert.Equal(PdfCollectionView.Details, collection.View); + Assert.Equal("notes.txt", collection.InitialDocument); + Assert.Equal(["name", "date", "pages", "fname", "size"], collection.Schema.Select(field => field.Key)); + Assert.Equal( + [PdfCollectionFieldType.Text, PdfCollectionFieldType.Date, PdfCollectionFieldType.Number, PdfCollectionFieldType.FileName, PdfCollectionFieldType.Size], + collection.Schema.Select(field => field.Type)); + Assert.Equal(["Name", "Date", "Pages", "File", "Size"], collection.Schema.Select(field => field.Name)); + Assert.Equal([0, 1, 2, 3, 4], collection.Schema.Select(field => field.Order ?? -1)); + Assert.Equal([true, true, false, true, true], collection.Schema.Select(field => field.IsVisible)); + Assert.Equal([false, false, false, true, false], collection.Schema.Select(field => field.IsEditable)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Sort_pads_its_ascending_flags_with_true() + { + using PdfDocument document = OpenCorpus(); + + PdfCollectionSort sort = document.Collection!.Sort!; + + Assert.Equal(["date", "name"], sort.Keys); + Assert.Equal([false, true], sort.Ascending); + } + + [Fact] + public void Colors_and_split_are_typed() + { + using PdfDocument document = OpenCorpus(); + PdfCollection collection = document.Collection!; + + Assert.Equal(new PdfCollectionColor(1, 1, 1), collection.Colors!.Background); + Assert.Equal(new PdfCollectionColor(0.9, 0.9, 0.9), collection.Colors.CardBackground); + Assert.Equal(new PdfCollectionColor(0, 0, 0), collection.Colors.CardBorder); + Assert.Equal(new PdfCollectionColor(0.5, 0.5, 0.5), collection.Colors.SecondaryText); + Assert.Equal(PdfCollectionSplitDirection.Vertical, collection.Split.Direction); + Assert.Equal(30, collection.Split.Position); + } + + [Fact] + public void Folders_form_a_tree_and_files_are_placed_by_their_key_prefix() + { + using PdfDocument document = OpenCorpus(); + PdfCollection collection = document.Collection!; + + PdfCollectionFolder root = collection.RootFolder!; + + Assert.Equal(0, root.Id); + Assert.Equal("Portfolio", root.Name); + Assert.Null(root.Parent); + Assert.Equal([new PdfCollectionIdRange(2, 10)], root.FreeIds); + PdfCollectionFolder reports = Assert.Single(root.Children); + Assert.Equal((1, "Reports", "Quarterly reports"), (reports.Id, reports.Name, reports.Description)); + Assert.Same(root, reports.Parent); + Assert.Same(reports.Dictionary, collection.FindFolder(1)!.Dictionary); + IReadOnlyList files = document.EmbeddedFiles; + Assert.Same(reports.Dictionary, collection.GetFolder(files[0])!.Dictionary); + Assert.Same(root.Dictionary, collection.GetFolder(files[1])!.Dictionary); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Collection_items_give_each_files_values_with_subitem_prefixes() + { + using PdfDocument document = OpenCorpus(); + IReadOnlyList files = document.EmbeddedFiles; + + PdfCollectionItem report = files[0].File.CollectionItem!; + + Assert.Equal(["name", "date", "pages"], report.Keys); + Assert.Equal("Quarterly report", report.GetValue("name")!.Text); + Assert.Equal("Q1: ", report.GetValue("name")!.Prefix); + Assert.Equal("D:20240301000000Z", report.GetValue("date")!.Text); + Assert.Equal(3, report.GetValue("pages")!.Number); + Assert.Null(report.GetValue("size")); + Assert.Equal("Notes", files[1].File.CollectionItem!.GetValue("name")!.Text); + } + + [Fact] + public void A_document_without_a_collection_has_none() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("embedded-files.pdf")); + + Assert.Null(document.Collection); + } + + [Fact] + public void A_navigator_view_without_a_navigator_reads_as_details_with_a_diagnostic() + { + using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("", "/Collection << /Type /Collection /View /C >>")); + + PdfCollection collection = document.Collection!; + + Assert.Equal(PdfCollectionView.Details, collection.View); + Assert.Equal(PdfCollectionSplitDirection.Horizontal, collection.Split.Direction); + Assert.Null(collection.Split.Position); + Assert.Equal(["CollectionInvalid"], document.Diagnostics.Select(diagnostic => diagnostic.Code)); + } + + [Fact] + public void Split_defaults_follow_the_view() + { + using PdfDocument tile = PdfDocument.Open(TestPdf.OnePage("", "/Collection << /View /T >>")); + using PdfDocument hidden = PdfDocument.Open(TestPdf.OnePage("", "/Collection << /View /H >>")); + + Assert.Equal(PdfCollectionSplitDirection.Vertical, tile.Collection!.Split.Direction); + Assert.Equal(PdfCollectionSplitDirection.None, hidden.Collection!.Split.Direction); + } + + [Fact] + public void A_folder_cycle_and_a_duplicate_id_are_cut_with_diagnostics() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R /Collection << /Folders 4 0 R >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>", + "<< /Type /Folder /ID 0 /Name (Root) /Child 5 0 R >>", + "<< /Type /Folder /ID 1 /Name (A) /Parent 4 0 R /Next 6 0 R /Child 4 0 R >>", + "<< /Type /Folder /ID 1 /Name (B) /Parent 4 0 R /Next 5 0 R >>"); + using PdfDocument document = PdfDocument.Open(file); + + PdfCollectionFolder root = document.Collection!.RootFolder!; + + Assert.Equal(["A", "B"], root.Children.Select(folder => folder.Name)); + Assert.Empty(root.Children[0].Children); + Assert.Equal("A", document.Collection.FindFolder(1)!.Name); + Assert.Equal(["CollectionFolderCycle", "CollectionFolderIdDuplicate"], document.Diagnostics.Select(diagnostic => diagnostic.Code).Distinct().Order()); + } +} From b5434c7e48ef50acfa2308f6d13ae2ab52b920b9 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:24:07 -0500 Subject: [PATCH 024/152] feat(document): page labels, fuzz targets and conformance rows (#69) Page labels resolve per page through the #70 number tree floor lookup in every Table 161 style. Fuzz targets xmp and pdf-date; the document target and the real-world corpus walker read every document-level entry. Conformance rows for 7.7.2, 7.9.4, 7.12, 12.2, 12.4, 12.11, 14.3 and 14.4. The real-world corpus and veraPDF agreement snapshots take the new diagnostics (all reviewed: genuine deviations; four veraPDF rules now agree because IDs under 16 bytes violate Table 15). Co-Authored-By: Claude Opus 5.5 --- docs/conformance/iso-32000-2.md | 32 ++- src/Broadside/PdfDocument.Catalog.cs | 15 +- src/Broadside/PdfPageLabelRange.cs | 197 ++++++++++++++ src/Broadside/PdfPageLabelStyle.cs | 24 ++ src/Broadside/PdfPageLabels.cs | 126 +++++++++ src/Broadside/PublicAPI.Unshipped.txt | 19 ++ tests/Broadside.Fuzz/FuzzTargets.cs | 149 +++++++++++ tests/Broadside.Fuzz/README.md | 2 +- tests/Broadside.TestSupport/DocumentWalker.cs | 42 +++ .../Document/CatalogEntryTests.cs | 64 +++-- .../Document/DocumentInformationTests.cs | 11 +- .../Document/PageLabelTests.cs | 251 ++++++++++++++++++ ...histograms_match_the_snapshot.verified.txt | 36 ++- ..._triaged_rule_still_disagrees.verified.txt | 11 +- .../Document/VeraPdfAgreementTests.cs | 6 +- .../Document/WellFormedCorpusTests.cs | 2 +- .../Document/XmpPacketTests.cs | 27 +- 17 files changed, 944 insertions(+), 70 deletions(-) create mode 100644 src/Broadside/PdfPageLabelRange.cs create mode 100644 src/Broadside/PdfPageLabelStyle.cs create mode 100644 src/Broadside/PdfPageLabels.cs create mode 100644 tests/Broadside.Tests/Document/PageLabelTests.cs diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index f18429c5..183ac882 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -47,20 +47,25 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.6.6 | Crypt filters | done | `DocumentDecryptor`, `CryptFilter`, `CryptMethod` | `Broadside.Tests.Security.CryptFilterTests.An_embedded_file_is_decrypted_with_eff_which_defaults_to_stmf`, `Broadside.Tests.Security.CryptFilterTests.Each_content_stream_decrypts_with_the_crypt_filter_it_names_or_the_default_one`, `Broadside.Tests.Security.CryptFilterTests.Metadata_is_left_as_it_is_when_encrypt_metadata_is_false`, `Broadside.Tests.Security.CryptFilterTests.The_owner_password_opens_a_document_whose_metadata_is_not_encrypted`, `Broadside.Tests.Security.CryptFilterTests.A_stream_that_names_a_crypt_filter_the_document_does_not_define_is_left_encrypted_with_a_diagnostic`, `Broadside.Tests.Security.CryptFilterTests.Metadata_in_plaintext_although_encrypt_metadata_is_true_is_read_as_it_is_with_a_diagnostic`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.An_unknown_crypt_filter_method_is_an_unsupported_algorithm` | CF, StmF, StrF, EFF (default StmF), Identity, CFM V2/AESV2/AESV3 (and AESV4, ISO/TS 32003); CFM None leaves data as is with CryptFilterMethodInvalid; AESV2 under V 5 read as AESV3 with a diagnostic; unknown CFM for StmF/StrF/EFF throws `PdfEncryptionNotSupportedException`; EncryptMetadata false leaves /Type /Metadata streams alone (plaintext XMP under EncryptMetadata true read with MetadataNotEncrypted); crypt filter Length not used (keys come from the handler); encrypted-crypt-filters.pdf | | 7.6.7 | Unencrypted wrapper document | not started | | | Collections of encrypted payloads (PDF 2.0); a wrapper opens as an ordinary unencrypted document | | 7.7.1 | General | n/a | | | Introductory text | -| 7.7.2 | Document catalog dictionary | partial | `PdfDocument`, `PdfVersion` | `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_catalog_version_written_as_a_number_is_read_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.A_malformed_catalog_version_is_ignored_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_catalog_without_its_type_is_read_with_a_diagnostic` | Type, Version (effective version = later of header and catalog) and Pages; the other Table 29 entries arrive with their features (outlines, names, AcroForm, ...) | +| 7.7.2 | Document catalog dictionary | partial | `PdfDocument`, `PdfVersion`, `PdfPageLayout`, `PdfPageMode`, `DictionaryView` | `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_catalog_version_written_as_a_number_is_read_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.A_malformed_catalog_version_is_ignored_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_catalog_without_its_type_is_read_with_a_diagnostic`, `Broadside.Tests.Document.CatalogEntryTests.Empty_page_pdf_has_the_default_layout_and_mode_and_no_viewer_preferences`, `Broadside.Tests.Document.CatalogEntryTests.Catalog_version_extensions_pdf_exposes_its_version_extensions_and_requirements`, `Broadside.Tests.Document.CatalogEntryTests.Pdf20_header_pdf_is_version_2_0_from_the_header_and_the_catalog`, `Broadside.Tests.Document.CatalogEntryTests.The_language_is_a_text_string`, `Broadside.Tests.Document.CatalogEntryTests.An_unknown_layout_mode_or_preferences_entry_reads_as_the_default_with_a_warning`, `Broadside.Tests.Document.CatalogEntryTests.Outline_pdf_opens_with_the_outline_visible`, `Broadside.Tests.Document.CatalogEntryTests.Reading_every_catalog_entry_changes_nothing` | Type, Version (effective version = later of header and catalog; `HeaderVersion`, `CatalogVersion`), Pages, PageLabels (12.4.2), ViewerPreferences (12.2), PageLayout, PageMode, Metadata (14.3.2), Lang, Extensions (7.12), Requirements (12.11) (#69); the other Table 29 entries arrive with their features (outlines, names, AcroForm, ...) | | 7.7.3 | Page tree | done | `PdfPage`, `PdfPageCollection`, `PageTreeReader` | `Broadside.Tests.Document.OpenDocumentTests.Page_tree_inherited_pdf_pages_inherit_media_box_and_resources_from_the_intermediate_node`, `Broadside.Tests.Document.PageTreeTests.Pages_come_in_kids_order_depth_first_across_intermediate_nodes`, `Broadside.Tests.Document.PageTreeTests.The_nearest_ancestor_wins_and_values_are_inherited_as_is_without_merging`, `Broadside.Tests.Document.PageTreeTests.A_change_to_an_ancestor_node_shows_through_the_pages_that_inherit_from_it`, `Broadside.Tests.Document.PageTreeTests.Page_count_comes_from_the_kids_not_the_count_entry_which_is_checked`, `Broadside.Tests.Document.PageTreeTests.A_node_referenced_twice_is_read_once_with_a_diagnostic`, `Broadside.Tests.Document.PageAttributeTests.Crop_bleed_trim_and_art_boxes_default_to_the_media_box_through_the_crop_box`, `Broadside.Tests.Document.PageAttributeTests.Rotation_is_a_multiple_of_90_normalized_into_0_to_270` | 7.7.3.1 to 7.7.3.4: Kids walk with cycle guard, Count checked not trusted, Resources/MediaBox/CropBox/Rotate inherited as-is from the nearest node; page boxes, Rotate and UserUnit from Table 31; other Table 31 entries arrive with their features | | 7.7.4 | Name dictionary | partial | `PdfNameDictionary`, `PdfDocument` | `Broadside.Tests.Navigation.NameTreeTests.Name_tree_dests_pdf_maps_its_three_keys_to_their_destination_arrays_with_no_diagnostics`, `Broadside.Tests.Navigation.NameTreeTests.A_tree_root_that_is_not_a_dictionary_reads_as_absent_with_a_diagnostic` | `PdfDocument.Names`; every Table 32 entry is reachable as a name tree through `PdfNameDictionary.GetTree`, `Dests` by name; typed values arrive with their features (Dests destinations #70, EmbeddedFiles #76, JavaScript #73) | | 7.8 | Content streams and resources | not started | | | | | 7.9.1 | General | not started | | | | | 7.9.2 | String object types | partial | `CosString` | `Broadside.Tests.Objects.TextStringTests` | Text strings decode (PDFDocEncoding, UTF-16BE, UTF-8, language escapes removed); encoding text into a string pending | | 7.9.3 | Text streams | not started | | | | -| 7.9.4 | Dates | not started | | | | +| 7.9.4 | Dates | done | `PdfDate`, `PdfDatePrecision`, `XmpDate`, `PdfDocumentInformation` | `Broadside.Tests.Document.DateTests.A_date_reads_every_field_its_string_has_and_defaults_the_rest`, `Broadside.Tests.Document.DateTests.An_offset_beyond_what_DateTimeOffset_holds_keeps_the_instant_in_universal_time`, `Broadside.Tests.Document.DateTests.A_date_that_deviates_but_can_be_read_is_read_with_its_fields_clamped`, `Broadside.Tests.Document.DateTests.A_string_that_is_not_a_date_does_not_parse`, `Broadside.Tests.Document.DateTests.An_xmp_date_reads_the_iso_8601_subset_and_knows_whether_it_has_a_time_zone`, `Broadside.Tests.Document.DocumentInformationTests.A_date_that_deviates_is_read_with_a_warning_and_one_that_cannot_be_read_keeps_its_text`, `Broadside.Tests.Document.DocumentInformationTests.A_utf_16_date_string_is_decoded_before_it_is_parsed` | `PdfDate.TryParse` never throws; legacy trailing apostrophe (NOTE 2) and Z with offsets (NOTE 3) accepted silently; missing `D:`, `+0100`, out-of-range fields and trailing white-space repaired (`DateInvalid`); free text and over-long fields unreadable (`DateUnreadable`, raw text kept); offsets beyond ±14 h keep the instant in UTC with the written offset in `UtcOffsetMinutes`; fuzz target `pdf-date`. `XmpDate` reads the ISO 16684-1 §8.2.1.2 subset. | | 7.9.5 | Rectangles | done | `PdfRectangle` | `Broadside.Tests.Document.PageAttributeTests.Rectangles_given_by_any_two_opposite_corners_are_normalized`, `Broadside.Tests.Document.PageAttributeTests.A_box_and_its_numbers_may_be_indirect_objects`, `Broadside.Tests.Document.PageAttributeTests.A_malformed_box_reads_as_its_default_with_a_diagnostic` | Any two opposite corners, normalized | | 7.9.6 | Name trees | done | `PdfNameTree`, `NameTreeReader`, `TreeReader`, `PdfDocument` | `Broadside.Tests.Navigation.NameTreeTests.Name_tree_dests_pdf_maps_its_three_keys_to_their_destination_arrays_with_no_diagnostics`, `Broadside.Tests.Navigation.NameTreeTests.Every_key_of_a_four_level_tree_resolves_and_enumeration_returns_them_once_in_byte_order`, `Broadside.Tests.Navigation.NameTreeTests.Keys_are_compared_byte_by_byte_and_a_text_lookup_tries_pdf_doc_encoding_first`, `Broadside.Tests.Navigation.NameTreeTests.A_text_lookup_falls_back_to_utf_16_and_then_to_every_key_decoded`, `Broadside.Tests.Navigation.NameTreeTests.A_lookup_reads_one_path_from_the_root_and_not_the_whole_tree`, `Broadside.Tests.Navigation.NameTreeTests.A_damaged_tree_reports_each_defect_once_per_node_and_every_key_still_resolves`, `Broadside.Tests.Navigation.NameTreeTests.Lookups_of_a_damaged_tree_fall_back_to_the_whole_tree_and_agree_with_enumeration_on_duplicates`, `Broadside.Tests.Navigation.NameTreeTests.Strict_mode_throws_from_the_lookup_that_meets_the_damage_not_from_open`, `Broadside.Tests.Navigation.NameTreeTests.Reading_a_tree_writes_nothing_and_a_change_to_a_node_shows_in_the_next_lookup`, `Broadside.Tests.Navigation.NameTreeTests.Malformed_nodes_and_keys_are_repaired_or_skipped_with_a_diagnostic` | Read only (writing trees is Phase 4). Lookups descend by Limits (binary search over kids and leaf), keys compared byte by byte (Annex J.3.3); text lookups try PDFDocEncoding, UTF-16BE, then every key decoded. Damage (stale or missing Limits, unsorted or duplicate keys, cycles, depth over 64, odd Names, non-string keys) is reported once per node (`NameTree*` codes) and lookups fall back to an index of the whole tree, rebuilt when a node changes (internal container `Version`); first occurrence in tree order wins. `name-tree-dests.pdf`, `name-tree-deep.pdf`, `name-tree-broken.pdf`. qpdf compares decoded text, not bytes, and reports `name-tree-deep.pdf` as unsorted. | | 7.9.7 | Number trees | done | `PdfNumberTree`, `NumberTreeReader`, `TreeReader`, `PdfDocument` | `Broadside.Tests.Navigation.NumberTreeTests.A_three_level_page_labels_tree_enumerates_its_keys_in_order_with_no_diagnostics`, `Broadside.Tests.Navigation.NumberTreeTests.Exact_lookups_find_keys_through_the_limits_and_miss_keys_between_them`, `Broadside.Tests.Navigation.NumberTreeTests.A_floor_lookup_finds_the_greatest_key_not_greater_than_the_one_asked_for`, `Broadside.Tests.Navigation.NumberTreeTests.Keys_that_are_not_integers_are_repaired_or_skipped_with_a_diagnostic`, `Broadside.Tests.Navigation.NumberTreeTests.A_cycle_through_the_kids_ends_with_a_diagnostic`, `Broadside.Tests.Navigation.NumberTreeTests.A_chain_deeper_than_the_cap_ends_with_a_diagnostic` | Read only. Same walker as 7.9.6 with 32-bit integer keys; `TryGetFloor` for ranges keyed by their first number (page labels, 12.4.2); an integral real key is used with a diagnostic, other keys skipped (`NumberTree*` codes). `number-tree-deep.pdf`. | | 7.10 | Functions | not started | | | | | 7.11 | File specifications | not started | | | | -| 7.12 | Extensions dictionary | not started | | | | +| 7.12.1 | General | done | `PdfDeveloperExtension`, `PdfDocument` | `Broadside.Tests.Document.CatalogEntryTests.Catalog_version_extensions_pdf_exposes_its_version_extensions_and_requirements` | `PdfDocument.Extensions`; `catalog-version-extensions.pdf` | +| 7.12.2 | Extensions dictionary | done | `PdfDeveloperExtension`, `PdfDocument` | `Broadside.Tests.Document.CatalogEntryTests.Catalog_version_extensions_pdf_exposes_its_version_extensions_and_requirements`, `Broadside.Tests.Document.CatalogEntryTests.A_malformed_extensions_entry_is_reported`, `Broadside.Tests.Document.CatalogEntryTests.Extensions_given_through_indirect_references_are_read_with_a_warning` | Prefix values as a dictionary or (PDF 2.0) an array of them; indirect objects read with `ExtensionsNotDirect` | +| 7.12.3 | Developer extensions dictionary | done | `PdfDeveloperExtension` | `Broadside.Tests.Document.CatalogEntryTests.Catalog_version_extensions_pdf_exposes_its_version_extensions_and_requirements`, `Broadside.Tests.Document.CatalogEntryTests.A_malformed_extensions_entry_is_reported` | Missing BaseVersion or ExtensionLevel: `DeveloperExtensionInvalid`, value null | +| 7.12.4 | BaseVersion | partial | `PdfDeveloperExtension` | `Broadside.Tests.Document.CatalogEntryTests.Catalog_version_extensions_pdf_exposes_its_version_extensions_and_requirements`, `Broadside.Tests.Document.CatalogEntryTests.A_malformed_extensions_entry_is_reported` | Read as a version name; not yet checked to be at most the document version | +| 7.12.5 | ExtensionLevel | done | `PdfDeveloperExtension` | `Broadside.Tests.Document.CatalogEntryTests.Catalog_version_extensions_pdf_exposes_its_version_extensions_and_requirements`, `Broadside.Tests.Document.CatalogEntryTests.A_malformed_extensions_entry_is_reported` | | +| 7.12.6 | URL | done | `PdfDeveloperExtension` | `Broadside.Tests.Document.CatalogEntryTests.Catalog_version_extensions_pdf_exposes_its_version_extensions_and_requirements` | `Url` (absolute URI) and `ExtensionRevision` (PDF 2.0) | | 8.1 | Graphics: General | not started | | | | | 8.2 | Graphics objects | not started | | | | | 8.3 | Coordinate systems | not started | | | | @@ -98,16 +103,24 @@ Clause numbers at the second level; split rows to the third level as clauses are | 11.6 | Specifying transparency in PDF | not started | | | | | 11.7 | Colour space and rendering issues | not started | | | | | 12.1 | Interactive features: General | not started | | | | -| 12.2 | Viewer preferences | not started | | | | +| 12.2 | Viewer preferences | done | `PdfViewerPreferences`, `PdfPageMode`, `PdfReadingDirection`, `PdfPageBoundary`, `PdfPrintScaling`, `PdfDuplex`, `PdfPageRange` | `Broadside.Tests.Document.CatalogEntryTests.Viewer_preferences_pdf_types_every_table_147_entry`, `Broadside.Tests.Document.CatalogEntryTests.An_empty_viewer_preferences_dictionary_reads_every_default`, `Broadside.Tests.Document.CatalogEntryTests.A_malformed_viewer_preference_reads_as_its_default_with_a_warning`, `Broadside.Tests.Document.CatalogEntryTests.Unknown_viewer_preference_keys_are_ignored` | Tables 147 and 148 (Enforce, PDF 2.0); malformed entries read as their defaults with `ViewerPreferenceInvalid`; unknown keys ignored; `viewer-preferences.pdf` | | 12.3 | Document-level navigation | not started | | | | -| 12.4 | Page-level navigation | not started | | | | +| 12.4.1 | General | n/a | | | Introductory text | +| 12.4.2 | Page labels | done | `PdfPageLabels`, `PdfPageLabelRange`, `PdfPageLabelStyle` | `Broadside.Tests.Document.PageLabelTests.Page_labels_pdf_labels_every_page_in_every_style`, `Broadside.Tests.Document.PageLabelTests.Page_labels_pdf_lists_its_ranges_in_page_order`, `Broadside.Tests.Document.PageLabelTests.Number_tree_deep_pdf_finds_each_page_s_range_through_kids_and_limits`, `Broadside.Tests.Document.PageLabelTests.Letters_repeat_rather_than_carry`, `Broadside.Tests.Document.PageLabelTests.Roman_numerals_follow_the_subtractive_form_and_add_an_m_per_thousand_beyond_3999`, `Broadside.Tests.Document.PageLabelTests.Every_roman_numeral_from_1_to_3999_is_canonical_and_reads_back_as_its_number`, `Broadside.Tests.Document.PageLabelTests.A_malformed_page_label_is_repaired_with_a_warning`, `Broadside.Tests.Document.PageLabelTests.Pages_before_the_first_range_are_numbered_in_decimal_with_a_warning`, `Broadside.Tests.Document.PageLabelTests.A_range_whose_value_is_not_a_dictionary_is_skipped_and_the_previous_range_continues` | Floor lookup through #70's `NumberTreeReader`; no key 0 numbers earlier pages in decimal (PDFBox/Acrobat); unknown style decimal; letters and roman capped at 64 characters (decimal beyond); `page-labels.pdf`, `number-tree-deep.pdf` | +| 12.4.3 | Articles | not started | | | | +| 12.4.4 | Presentations | not started | | | | | 12.5 | Annotations | not started | | | | | 12.6 | Actions | not started | | | | | 12.7 | Forms | not started | | | | | 12.8 | Digital signatures | not started | | | | | 12.9 | Measurement properties | not started | | | | | 12.10 | Geospatial features | not started | | | | -| 12.11 | Document requirements | not started | | | | +| 12.11.1 | General | done | `PdfRequirement`, `PdfDocument` | `Broadside.Tests.Document.CatalogEntryTests.Catalog_version_extensions_pdf_exposes_its_version_extensions_and_requirements`, `Broadside.Tests.Document.CatalogEntryTests.A_malformed_requirement_is_reported` | `PdfDocument.Requirements`; exposed, never evaluated | +| 12.11.2 | Requirement types | done | `PdfRequirement` | `Broadside.Tests.Document.CatalogEntryTests.Catalog_version_extensions_pdf_exposes_its_version_extensions_and_requirements`, `Broadside.Tests.Document.CatalogEntryTests.A_malformed_requirement_is_reported` | S exposed as a name (Table 275 is open-ended; Table 273 cites Table 276 by erratum) | +| 12.11.3 | Requirement penalty values | done | `PdfRequirement` | `Broadside.Tests.Document.CatalogEntryTests.A_requirement_takes_the_default_penalty_and_handlers_given_as_an_array`, `Broadside.Tests.Document.CatalogEntryTests.A_malformed_requirement_is_reported` | Default 100; out of range clamped with `RequirementInvalid` | +| 12.11.4 | Requirement versions | done | `PdfRequirement` | `Broadside.Tests.Document.CatalogEntryTests.Catalog_version_extensions_pdf_exposes_its_version_extensions_and_requirements` | V exposed raw (name or extensions dictionary) | +| 12.11.5 | Requirement handlers | done | `PdfRequirementHandler` | `Broadside.Tests.Document.CatalogEntryTests.A_requirement_takes_the_default_penalty_and_handlers_given_as_an_array`, `Broadside.Tests.Document.CatalogEntryTests.Catalog_version_extensions_pdf_exposes_its_version_extensions_and_requirements` | RH as one dictionary or an array; JS handlers name their script, never run | +| 12.11.6 | Requirements processing | n/a | | | Evaluating requirements runs JavaScript handlers, which is out of scope (CLAUDE.md); requirements are exposed only | | 13.1 | Multimedia: General | not started | | | | | 13.2 | Multimedia | not started | | | | | 13.3 | Sounds | not started | | | | @@ -117,8 +130,11 @@ Clause numbers at the second level; split rows to the third level as clauses are | 13.7 | Rich media | not started | | | | | 14.1 | Document interchange: General | not started | | | | | 14.2 | Procedure sets | not started | | | | -| 14.3 | Metadata | not started | | | | -| 14.4 | File identifiers | partial | `FileWriter` | `Broadside.Tests.Writing.SaveTests.Saving_twice_writes_the_same_bytes_and_keeps_the_first_file_identifier`, `Broadside.Tests.Writing.SaveTests.A_file_without_identifiers_gets_two_equal_ones_when_saved`, `Broadside.Tests.Writing.CreateTests.A_saved_created_document_reopens_with_two_equal_file_identifiers` | written on save: the first identifier is kept, the second is the first 16 bytes of SHA-256 of the bytes before the cross-reference information (deterministic; MD5 is unavailable on browser-wasm); a file without identifiers gets two equal ones; incremental updates are Phase 4 | +| 14.3.1 | General | done | `PdfDocumentProperties`, `PdfDocument` | `Broadside.Tests.Document.DocumentInformationTests.The_properties_take_each_field_from_xmp_when_the_packet_has_it_and_from_info_otherwise`, `Broadside.Tests.Document.DocumentInformationTests.Metadata_xmp_pdf_yields_its_title_from_the_info_dictionary_and_from_xmp` | XMP preferred per field, Info otherwise | +| 14.3.2 | Metadata streams | partial | `PdfMetadata`, `XmpPacket`, `XmpProperty`, `XmpPropertyKind`, `XmpNamespaces`, `XmpDate` | `Broadside.Tests.Document.DocumentInformationTests.Metadata_xmp_pdf_yields_its_title_from_the_info_dictionary_and_from_xmp`, `Broadside.Tests.Document.DocumentInformationTests.Metadata_xmp_forms_pdf_types_the_common_properties_and_the_properties_prefer_xmp`, `Broadside.Tests.Document.DocumentInformationTests.A_malformed_packet_leaves_the_info_dictionary_readable_and_is_reported_once`, `Broadside.Tests.Document.DocumentInformationTests.A_packet_with_a_document_type_declaration_is_refused`, `Broadside.Tests.Document.DocumentInformationTests.A_metadata_stream_without_its_type_and_subtype_is_read_with_a_warning`, `Broadside.Tests.Document.DocumentInformationTests.The_parsed_packet_is_a_snapshot_until_the_stream_changes`, `Broadside.Tests.Document.XmpPacketTests.A_packet_reads_every_property_form_into_one_model`, `Broadside.Tests.Document.XmpPacketTests.A_document_type_declaration_is_refused_so_entities_never_expand`, `Broadside.Tests.Document.XmpPacketTests.A_packet_in_any_unicode_encoding_with_its_byte_order_mark_is_read` | Document-level metadata stream (catalog `Metadata`) with a managed ISO 16684-1 reader on the BCL `XmlReader` (DTD prohibited, no resolver); fuzz target `xmp`; object-level metadata (Table 348) is #76 | +| 14.3.3 | Document information dictionary | done | `PdfDocumentInformation`, `PdfTrapped`, `PdfDocument` | `Broadside.Tests.Document.DocumentInformationTests.Info_dictionary_pdf_types_every_table_349_entry`, `Broadside.Tests.Document.DocumentInformationTests.Hybrid_xref_pdf_reads_its_info_dictionary_from_an_object_stream`, `Broadside.Tests.Document.DocumentInformationTests.Info_values_that_are_not_text_strings_are_read_with_a_warning`, `Broadside.Tests.Document.DocumentInformationTests.Trapped_is_a_name_that_defaults_to_unknown`, `Broadside.Tests.Document.DocumentInformationTests.An_info_entry_that_is_not_a_dictionary_is_ignored_with_a_warning` | Every Table 349 key typed, custom keys through `GetText`/`GetDate`; `info-dictionary.pdf`; writing Info is Phase 4 | +| 14.3.4 | Reconciling two sources of document metadata | partial | `PdfDocumentProperties` | `Broadside.Tests.Document.DocumentInformationTests.The_properties_take_each_field_from_xmp_when_the_packet_has_it_and_from_info_otherwise` | Reader side (processor discretion: XMP first, no diagnostic for disagreement); the writer rules are Phase 4 | +| 14.4 | File identifiers | partial | `FileWriter`, `PdfFileIdentifier`, `PdfDocument` | `Broadside.Tests.Writing.SaveTests.Saving_twice_writes_the_same_bytes_and_keeps_the_first_file_identifier`, `Broadside.Tests.Writing.SaveTests.A_file_without_identifiers_gets_two_equal_ones_when_saved`, `Broadside.Tests.Writing.CreateTests.A_saved_created_document_reopens_with_two_equal_file_identifiers`, `Broadside.Tests.Document.DocumentInformationTests.Catalog_version_extensions_pdf_has_two_different_file_identifiers`, `Broadside.Tests.Document.DocumentInformationTests.An_encrypted_file_has_its_identifier_unencrypted`, `Broadside.Tests.Document.DocumentInformationTests.A_file_without_an_identifier_has_none`, `Broadside.Tests.Document.DocumentInformationTests.A_malformed_identifier_is_reported` | read: `PdfDocument.FileIdentifier` (IDs under 16 bytes kept with `FileIdentifierInvalid`, Table 15); written on save: the first identifier is kept, the second is the first 16 bytes of SHA-256 of the bytes before the cross-reference information (deterministic; MD5 is unavailable on browser-wasm); a file without identifiers gets two equal ones; incremental updates are Phase 4 | | 14.5 | Page-piece dictionaries | not started | | | | | 14.6 | Marked content | not started | | | | | 14.7 | Logical structure | not started | | | | diff --git a/src/Broadside/PdfDocument.Catalog.cs b/src/Broadside/PdfDocument.Catalog.cs index 989e0f00..3d7813fd 100644 --- a/src/Broadside/PdfDocument.Catalog.cs +++ b/src/Broadside/PdfDocument.Catalog.cs @@ -12,6 +12,7 @@ public sealed partial class PdfDocument private static readonly CosName PageModeKey = new("PageMode"); private static readonly CosName ViewerPreferencesKey = new("ViewerPreferences"); private static readonly CosName LangKey = new("Lang"); + private static readonly CosName PageLabelsKey = new("PageLabels"); private static readonly CosName MetadataKey = new("Metadata"); private static readonly CosName RequirementsKey = new("Requirements"); private static readonly CosName MetadataType = new("Metadata"); @@ -80,6 +81,14 @@ public PdfViewerPreferences? ViewerPreferences } } + /// Gets the page labels (PageLabels, PDF 1.3), or when the catalog has none: pages are then numbered from 1. + /// + /// ISO 32000-2 §7.7.2, Table 29, and §12.4.2. An entry that is not a number tree dictionary is ignored with a + /// NumberTreeNodeInvalid diagnostic. + /// + public PdfPageLabels? PageLabels => + GetNumberTreeReader(Catalog.GetValueOrDefault(PageLabelsKey)) is { } tree ? new PdfPageLabels(this, tree) : null; + /// Gets the natural language of the document's text (Lang), such as en-US, or when unknown. /// ISO 32000-2 §7.7.2, Table 29 (PDF 1.4), and §14.9.2. Not checked against BCP 47. public string? Language => CatalogView.ReadText(LangKey, DiagnosticCodes.CatalogEntryInvalid); @@ -184,10 +193,10 @@ public IReadOnlyList Requirements return []; } - const string Message = "The catalog's Requirements entry shall be an array of requirement dictionaries, each with a type and a penalty from 0 to 100 (Table 273)."; + const string message = "The catalog's Requirements entry shall be an array of requirement dictionaries, each with a type and a penalty from 0 to 100 (Table 273)."; if (value is not CosArray array) { - CatalogView.Report(DiagnosticCodes.RequirementInvalid, Message); + CatalogView.Report(DiagnosticCodes.RequirementInvalid, message); return []; } @@ -208,7 +217,7 @@ public IReadOnlyList Requirements if (invalid) { - CatalogView.Report(DiagnosticCodes.RequirementInvalid, Message); + CatalogView.Report(DiagnosticCodes.RequirementInvalid, message); } return requirements; diff --git a/src/Broadside/PdfPageLabelRange.cs b/src/Broadside/PdfPageLabelRange.cs new file mode 100644 index 00000000..9c6f1442 --- /dev/null +++ b/src/Broadside/PdfPageLabelRange.cs @@ -0,0 +1,197 @@ +using System.Globalization; +using System.Text; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// One page label range: the pages from to the next range, labelled by one page label dictionary. +/// +/// +/// ISO 32000-2 §12.4.2, Table 161. Page i of a range that starts at page index k is labelled +/// followed by the number + (i − k) written in . Letters repeat rather +/// than carry: A to Z, then AA to ZZ, then AAA. Roman numerals beyond 3999 have no standard form; like Acrobat, an M is written per +/// thousand. +/// +/// +/// A live view over the page label dictionary. Deviations are repaired and reported when read: an unknown style reads as decimal +/// (PageLabelStyleInvalid), a start that is not a positive integer as 1 (an integral real as its value; +/// PageLabelStartInvalid), a prefix that is not a text string as empty and one holding U+0000 up to it +/// (PageLabelPrefixInvalid), a Type other than PageLabel is ignored (PageLabelInvalid). +/// +/// +public sealed class PdfPageLabelRange +{ + /// The longest label written in letters or roman numerals; a longer one is written in decimal instead. + internal const int MaxNumeralLength = 64; + + private static readonly CosName SKey = new("S"); + private static readonly CosName PKey = new("P"); + private static readonly CosName StKey = new("St"); + private static readonly CosName PageLabelType = new("PageLabel"); + + private readonly DictionaryView _view; + + internal PdfPageLabelRange(PdfDocument document, int startPageIndex, CosDictionary dictionary, CosReference? reference) + { + _view = new DictionaryView(document, dictionary, reference); + StartPageIndex = startPageIndex; + } + + /// Gets the index of the first page of the range (the number tree key). + /// ISO 32000-2 §12.4.2. + public int StartPageIndex { get; } + + /// Gets the page label dictionary. + /// ISO 32000-2 §12.4.2, Table 161. + public CosDictionary Dictionary => _view.Dictionary; + + /// Gets the numbering style (S); when absent: the label is the prefix alone. + /// ISO 32000-2 §12.4.2, Table 161. + public PdfPageLabelStyle Style + { + get + { + CheckType(); + CosObject? value = _view.Get(SKey); + if (value is null) + { + return PdfPageLabelStyle.None; + } + + switch ((value as CosName)?.Value) + { + case "D": + return PdfPageLabelStyle.Arabic; + case "R": + return PdfPageLabelStyle.UppercaseRoman; + case "r": + return PdfPageLabelStyle.LowercaseRoman; + case "A": + return PdfPageLabelStyle.UppercaseLetters; + case "a": + return PdfPageLabelStyle.LowercaseLetters; + default: + _view.Report(DiagnosticCodes.PageLabelStyleInvalid, "A page label's S entry shall be D, R, r, A or a; the range is numbered in decimal."); + return PdfPageLabelStyle.Arabic; + } + } + } + + /// Gets the label prefix (P); empty when absent. + /// ISO 32000-2 §12.4.2, Table 161. + public string Prefix + { + get + { + switch (_view.Get(PKey)) + { + case null: + return string.Empty; + case CosString text: + string prefix = text.DecodeText(); + int nul = prefix.IndexOf('\0', StringComparison.Ordinal); + if (nul < 0) + { + return prefix; + } + + _view.Report(DiagnosticCodes.PageLabelPrefixInvalid, "A page label prefix holds U+0000; it is cut there."); + return prefix[..nul]; + default: + _view.Report(DiagnosticCodes.PageLabelPrefixInvalid, "A page label's P entry shall be a text string; it is ignored."); + return string.Empty; + } + } + } + + /// Gets the number of the range's first page (St), at least 1; 1 when absent. + /// ISO 32000-2 §12.4.2, Table 161. + public int FirstNumber + { + get + { + switch (_view.Get(StKey)) + { + case null: + return 1; + case CosInteger { Value: >= 1 and <= int.MaxValue } start: + return (int)start.Value; + case CosReal { Value: >= 1 and <= int.MaxValue } real when double.IsInteger(real.Value): + _view.Report(DiagnosticCodes.PageLabelStartInvalid, "A page label's St entry shall be an integer; it is a real holding an integral value, used as that integer."); + return (int)real.Value; + default: + _view.Report(DiagnosticCodes.PageLabelStartInvalid, "A page label's St entry shall be an integer of 1 or more; the range starts at 1."); + return 1; + } + } + } + + /// Returns the label of the page at from the range's first page. + internal string GetLabel(int offset) + { + PdfPageLabelStyle style = Style; + string prefix = Prefix; + if (style == PdfPageLabelStyle.None) + { + return prefix; + } + + long number = FirstNumber + (long)offset; + string? numeral = style switch + { + PdfPageLabelStyle.UppercaseRoman => Roman(number, upper: true), + PdfPageLabelStyle.LowercaseRoman => Roman(number, upper: false), + PdfPageLabelStyle.UppercaseLetters => Letters(number, 'A'), + PdfPageLabelStyle.LowercaseLetters => Letters(number, 'a'), + _ => Decimal(number), + }; + if (numeral is null) + { + _view.Report(DiagnosticCodes.PageLabelTooLong, "A page number is too large to write in letters or roman numerals; it is written in decimal."); + numeral = Decimal(number); + } + + return prefix + numeral; + } + + private static string Decimal(long number) => number.ToString(CultureInfo.InvariantCulture); + + /// A, ..., Z, AA, ..., ZZ, AAA: the letter for (n − 1) mod 26, repeated (n − 1) / 26 + 1 times. + private static string? Letters(long number, char a) + { + long count = ((number - 1) / 26) + 1; + return count > MaxNumeralLength ? null : new string((char)(a + ((number - 1) % 26)), (int)count); + } + + /// Subtractive roman numerals; one M per thousand, so 4000 is MMMM. + private static string? Roman(long number, bool upper) + { + ReadOnlySpan values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; + string[] symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]; + if (number / 1000 > MaxNumeralLength / 2) + { + return null; + } + + var text = new StringBuilder(); + for (int index = 0; index < values.Length; index++) + { + while (number >= values[index]) + { + text.Append(symbols[index]); + number -= values[index]; + } + } + + return upper ? text.ToString() : text.ToString().ToLowerInvariant(); + } + + private void CheckType() + { + if (_view.Get(KnownNames.Type) is { } type && !PageLabelType.Equals(type)) + { + _view.Report(DiagnosticCodes.PageLabelInvalid, "A page label dictionary's Type entry, if present, shall be PageLabel; it is ignored."); + } + } +} diff --git a/src/Broadside/PdfPageLabelStyle.cs b/src/Broadside/PdfPageLabelStyle.cs new file mode 100644 index 00000000..4d341d1b --- /dev/null +++ b/src/Broadside/PdfPageLabelStyle.cs @@ -0,0 +1,24 @@ +namespace Broadside; + +/// How the numeric portion of a page label is written: a page label dictionary's S entry. +/// ISO 32000-2 §12.4.2, Table 161. +public enum PdfPageLabelStyle +{ + /// No numeric portion: the label is the prefix alone (S absent). + None, + + /// Decimal arabic numerals (D). + Arabic, + + /// Uppercase roman numerals (R). + UppercaseRoman, + + /// Lowercase roman numerals (r). + LowercaseRoman, + + /// Uppercase letters, A to Z, then AA to ZZ, and so on (A). + UppercaseLetters, + + /// Lowercase letters, a to z, then aa to zz, and so on (a). + LowercaseLetters, +} diff --git a/src/Broadside/PdfPageLabels.cs b/src/Broadside/PdfPageLabels.cs new file mode 100644 index 00000000..e809e98e --- /dev/null +++ b/src/Broadside/PdfPageLabels.cs @@ -0,0 +1,126 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// The labels the document gives its pages, such as i, ii, 1, A-1: a live view over the catalog's PageLabels number tree. +/// +/// +/// ISO 32000-2 §12.4.2 and §7.9.7. The tree maps the index of each range's first page to a page label dictionary; a page takes the +/// range with the greatest key at or below its index. Labels are computed on every call from the tree, which is read through the +/// document's shared number tree reader (Limits-guided lookup, with a checked index of the whole tree as the fallback). +/// +/// +/// Repairs, each reported the first time it is met (in strict mode, the call throws): pages before the first range (the tree +/// "shall include a value for page index 0") are numbered in decimal from 1, as Acrobat and PDFBox do (PageLabelsMissingZeroKey); +/// a value that is not a dictionary, and a negative key, are skipped, so the range before continues (PageLabelInvalid). See +/// for the repairs inside a range. +/// +/// +public sealed class PdfPageLabels +{ + private readonly PdfDocument _document; + private readonly NumberTreeReader _tree; + + internal PdfPageLabels(PdfDocument document, NumberTreeReader tree) + { + _document = document; + _tree = tree; + } + + /// Gets the root of the number tree. + /// ISO 32000-2 §7.9.7, Table 37. + public CosDictionary Root => _tree.Root; + + /// Gets the ranges, in page order: the entries of the number tree whose key is a page index and whose value is a page label dictionary. + /// ISO 32000-2 §12.4.2. Read from the tree on every call. + public IReadOnlyList Ranges + { + get + { + var ranges = new List(); + foreach ((int key, CosObject value) in _tree.Enumerate()) + { + if (Range(key, value) is { } range) + { + ranges.Add(range); + } + } + + return ranges; + } + } + + /// Returns the label of the page at . + /// The page's index, from 0. + /// The label: the range's prefix followed by the page's number in the range's style. + /// is not the index of a page of the document. + /// In strict mode, the label needs a repair. + /// ISO 32000-2 §12.4.2, Table 161. + public string GetLabel(int pageIndex) + { + ArgumentOutOfRangeException.ThrowIfNegative(pageIndex); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(pageIndex, _document.Pages.Count); + return Label(pageIndex); + } + + /// Returns the label of every page, in page order. + /// One label per page. + /// In strict mode, a label needs a repair. + /// ISO 32000-2 §12.4.2, Table 161. + public IReadOnlyList GetLabels() + { + int count = _document.Pages.Count; + string[] labels = new string[count]; + for (int index = 0; index < count; index++) + { + labels[index] = Label(index); + } + + return labels; + } + + private string Label(int pageIndex) + { + int key = pageIndex; + while (_tree.TryGetFloor(key, out int start, out CosObject? value)) + { + if (Range(start, value) is { } range) + { + return range.GetLabel(pageIndex - start); + } + + if (start <= 0) + { + break; + } + + key = start - 1; + } + + Report(DiagnosticCodes.PageLabelsMissingZeroKey, "The page labels number tree shall have a range for page index 0; pages before its first range are numbered in decimal from 1."); + return (pageIndex + 1).ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + /// The range for a tree entry, or null (reported) when the key is negative or the value is not a dictionary. + private PdfPageLabelRange? Range(int key, CosObject value) + { + if (key < 0) + { + Report(DiagnosticCodes.PageLabelInvalid, "A page labels number tree key shall be a page index; a negative key is ignored."); + return null; + } + + if (value is not CosDictionary dictionary) + { + Report(DiagnosticCodes.PageLabelInvalid, "A page labels number tree value shall be a page label dictionary; the entry is ignored."); + return null; + } + + return new PdfPageLabelRange(_document, key, dictionary, _tree.RootReference ?? _document.CatalogReference); + } + + private void Report(string code, string message) => + _document.DiagnosticSink.Report(code, DiagnosticSeverity.Warning, message, objectReference: _tree.RootReference ?? _document.CatalogReference); +} diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index 6bde41b2..ba45c9b1 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -634,3 +634,22 @@ Broadside.PdfNumberTree.Root.get -> Broadside.Objects.CosDictionary! Broadside.PdfNumberTree.RootReference.get -> Broadside.Objects.CosReference? Broadside.PdfNumberTree.TryGetFloor(int key, out int floorKey, out Broadside.Objects.CosObject! value) -> bool Broadside.PdfNumberTree.TryGetValue(int key, out Broadside.Objects.CosObject! value) -> bool +Broadside.PdfDocument.PageLabels.get -> Broadside.PdfPageLabels? +Broadside.PdfPageLabelRange +Broadside.PdfPageLabelRange.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfPageLabelRange.FirstNumber.get -> int +Broadside.PdfPageLabelRange.Prefix.get -> string! +Broadside.PdfPageLabelRange.StartPageIndex.get -> int +Broadside.PdfPageLabelRange.Style.get -> Broadside.PdfPageLabelStyle +Broadside.PdfPageLabels +Broadside.PdfPageLabels.GetLabel(int pageIndex) -> string! +Broadside.PdfPageLabels.GetLabels() -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfPageLabels.Ranges.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfPageLabels.Root.get -> Broadside.Objects.CosDictionary! +Broadside.PdfPageLabelStyle +Broadside.PdfPageLabelStyle.Arabic = 1 -> Broadside.PdfPageLabelStyle +Broadside.PdfPageLabelStyle.LowercaseLetters = 5 -> Broadside.PdfPageLabelStyle +Broadside.PdfPageLabelStyle.LowercaseRoman = 3 -> Broadside.PdfPageLabelStyle +Broadside.PdfPageLabelStyle.None = 0 -> Broadside.PdfPageLabelStyle +Broadside.PdfPageLabelStyle.UppercaseLetters = 4 -> Broadside.PdfPageLabelStyle +Broadside.PdfPageLabelStyle.UppercaseRoman = 2 -> Broadside.PdfPageLabelStyle diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 4a3ab467..60ed8968 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -37,6 +37,8 @@ internal static class FuzzTargets ["decrypt"] = Decrypt, ["mac-token"] = MacToken, ["public-key"] = PublicKey.Target, + ["xmp"] = Xmp, + ["pdf-date"] = PdfDateTarget, }; private static readonly CosName ContentsKey = new("Contents"); @@ -76,6 +78,7 @@ private static void Document(ReadOnlySpan data) _ = linearization.Hints?.Pages.Count; } + ReadCatalogEssentials(document); foreach (PdfPage page in document.Pages) { foreach (PdfRectangle box in (ReadOnlySpan)[page.MediaBox, page.CropBox, page.BleedBox, page.TrimBox, page.ArtBox]) @@ -619,4 +622,150 @@ private static void CheckRoundTrip(CosObject parsed) throw new InvalidOperationException($"Writing and reparsing a {parsed.GetType().Name} changed it: {parsed} became {reparsed}."); } } + + /// + /// Reads every document-level entry of issue #69 (version, extensions, requirements, layout, mode, viewer preferences, language, + /// page labels of every page, Info, XMP packet, resolved properties, file identifier): none may throw in lenient mode. + /// + /// ISO 32000-2 §7.7.2, §7.12, §12.2, §12.4.2, §12.11, §14.3, §14.4. + private static void ReadCatalogEssentials(PdfDocument document) + { + _ = (document.HeaderVersion, document.CatalogVersion, document.PageLayout, document.PageMode, document.Language); + foreach (PdfDeveloperExtension extension in document.Extensions) + { + _ = (extension.BaseVersion, extension.ExtensionLevel, extension.Url, extension.ExtensionRevision); + } + + foreach (PdfRequirement requirement in document.Requirements) + { + _ = (requirement.RequirementType, requirement.Version, requirement.Penalty); + foreach (PdfRequirementHandler handler in requirement.Handlers) + { + _ = (handler.HandlerType, handler.Script); + } + } + + if (document.ViewerPreferences is { } preferences) + { + _ = (preferences.HideToolbar, preferences.HideMenubar, preferences.HideWindowUI, preferences.FitWindow, preferences.CenterWindow); + _ = (preferences.DisplayDocTitle, preferences.NonFullScreenPageMode, preferences.Direction, preferences.ViewArea, preferences.ViewClip); + _ = (preferences.PrintArea, preferences.PrintClip, preferences.PrintScaling, preferences.Duplex, preferences.PickTrayByPdfSize); + _ = (preferences.PrintPageRange, preferences.NumCopies, preferences.Enforce); + } + + if (document.PageLabels is { } labels) + { + IReadOnlyList all = labels.GetLabels(); + if (all.Count != document.Pages.Count || all.Any(label => label.Length > PdfPageLabelRange.MaxNumeralLength + 4096)) + { + throw new InvalidOperationException("Page labels must give one bounded label per page."); + } + + foreach (PdfPageLabelRange range in labels.Ranges) + { + _ = (range.Style, range.Prefix, range.FirstNumber); + } + } + + if (document.Information is { } info) + { + _ = (info.Title, info.Author, info.Subject, info.Keywords, info.Creator, info.Producer, info.CreationDate, info.ModificationDate, info.Trapped); + } + + if (document.Metadata?.Packet is { } packet) + { + WalkPacket(packet); + } + + PdfDocumentProperties properties = document.Properties; + _ = (properties.Title, properties.Author, properties.Subject, properties.Keywords, properties.Creator, properties.Producer); + _ = (properties.CreationDate, properties.ModificationDate, document.FileIdentifier); + } + + /// + /// Reads the input as an XMP packet (ISO 16684-1 §7) through the reader the document uses. The packet is null exactly when an + /// Error diagnostic says why; a readable packet's every property, item, field and qualifier, and every typed getter, must read. + /// The XML reader must refuse document type declarations, so no input can expand entities or fetch anything. + /// + private static void Xmp(ReadOnlySpan data) + { + // Whole corpus files are the smoke seeds: start at a packet when the input holds one, so mutations reach the XML. + int packet = data.IndexOf(" 0) + { + XmpSlice(data[packet..]); + } + } + + private static void XmpSlice(ReadOnlySpan data) + { + var errors = new List(); + XmpPacket? packet = XmpPacketReader.Read(data, (code, severity, _) => + { + if (severity == DiagnosticSeverity.Error) + { + errors.Add(code); + } + }); + if ((packet is null) != (errors.Count > 0)) + { + throw new InvalidOperationException($"An XMP packet must be null exactly when an error is reported; errors: {string.Join(", ", errors)}."); + } + + if (XmpPacket.TryParse(data, out XmpPacket? again) != packet is not null || (again?.Properties.Count ?? 0) != (packet?.Properties.Count ?? 0)) + { + throw new InvalidOperationException("TryParse must agree with the document's reader."); + } + + if (packet is not null) + { + WalkPacket(packet); + } + } + + private static void WalkPacket(XmpPacket packet) + { + _ = (packet.About, packet.Title, packet.Description, packet.Creators, packet.Subjects, packet.Format, packet.CreateDate, packet.ModifyDate); + _ = (packet.MetadataDate, packet.CreatorTool, packet.Producer, packet.Keywords, packet.PdfVersion, packet.Trapped, packet.PdfAPart); + _ = (packet.PdfAConformance, packet.PdfUAPart, packet.DocumentId, packet.InstanceId); + var pending = new Stack(packet.Properties); + while (pending.TryPop(out XmpProperty? property)) + { + if ((property.Kind == XmpPropertyKind.Simple) != (property.Value is not null)) + { + throw new InvalidOperationException($"Only a simple XMP property has a value: {property.Name} is {property.Kind}."); + } + + foreach (XmpProperty child in property.Items.Concat(property.Fields).Concat(property.Qualifiers)) + { + pending.Push(child); + } + } + } + + /// + /// Reads the input as a date (ISO 32000-2 §7.9.4 and ISO 16684-1 §8.2.1.2), as Latin-1 text; neither parser may throw, a parsed + /// date keeps the text it was read from, and an offset beyond what holds keeps the instant in UTC. + /// + private static void PdfDateTarget(ReadOnlySpan data) + { + string text = System.Text.Encoding.Latin1.GetString(data); + DateParseOutcome outcome = PdfDate.Parse(text, out PdfDate date); + if ((outcome != DateParseOutcome.Unreadable) != PdfDate.TryParse(text, out _)) + { + throw new InvalidOperationException("PdfDate.TryParse must agree with the outcome of parsing."); + } + + if (outcome != DateParseOutcome.Unreadable + && (date.Text != text || Math.Abs(date.Value.Offset.TotalHours) > 14 || date.UtcOffsetMinutes is < -(23 * 60) - 59 or > (23 * 60) + 59)) + { + throw new InvalidOperationException($"Date {text} parsed inconsistently: {date.Value:O}, offset {date.UtcOffsetMinutes}."); + } + + if (XmpDate.TryParse(text, out XmpDate xmp) && xmp.Text != text) + { + throw new InvalidOperationException("An XMP date must keep its text."); + } + } } diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index 1a3db895..214b3090 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. `xmp` reads the input as an XMP packet (ISO 16684-1) through the reader the document uses, and again from its first ` + /// Reads the document-level entries (issue #69): version, extensions, requirements, layout, mode, viewer preferences, language, + /// every page label, the Info dictionary, the XMP packet and every property in it, the resolved properties, the file identifier. + /// + private static void ReadCatalogEssentials(PdfDocument document) + { + _ = (document.HeaderVersion, document.CatalogVersion, document.PageLayout, document.PageMode, document.Language, document.FileIdentifier); + foreach (PdfDeveloperExtension extension in document.Extensions) + { + _ = (extension.BaseVersion, extension.ExtensionLevel, extension.Url, extension.ExtensionRevision); + } + + foreach (PdfRequirement requirement in document.Requirements) + { + _ = (requirement.RequirementType, requirement.Penalty, requirement.Handlers.Select(handler => handler.Script).ToList()); + } + + if (document.ViewerPreferences is { } preferences) + { + _ = (preferences.HideToolbar, preferences.HideMenubar, preferences.HideWindowUI, preferences.FitWindow, preferences.CenterWindow); + _ = (preferences.DisplayDocTitle, preferences.NonFullScreenPageMode, preferences.Direction, preferences.ViewArea, preferences.ViewClip); + _ = (preferences.PrintArea, preferences.PrintClip, preferences.PrintScaling, preferences.Duplex, preferences.PickTrayByPdfSize); + _ = (preferences.PrintPageRange, preferences.NumCopies, preferences.Enforce); + } + + _ = document.PageLabels?.GetLabels(); + if (document.Information is { } info) + { + _ = (info.Title, info.Author, info.Subject, info.Keywords, info.Creator, info.Producer, info.CreationDate, info.ModificationDate, info.Trapped); + } + + if (document.Metadata?.Packet is { } packet) + { + _ = (packet.Title, packet.Creators, packet.Subjects, packet.CreateDate, packet.ModifyDate, packet.PdfAPart, packet.PdfUAPart); + } + + PdfDocumentProperties properties = document.Properties; + _ = (properties.Title, properties.Author, properties.CreationDate, properties.ModificationDate); + } + /// An iterative depth-first walk (no recursion: real files nest deeply) over references, containers and streams. private sealed class GraphWalk(PdfDocument document) { diff --git a/tests/Broadside.Tests/Document/CatalogEntryTests.cs b/tests/Broadside.Tests/Document/CatalogEntryTests.cs index b520dbfe..b752700b 100644 --- a/tests/Broadside.Tests/Document/CatalogEntryTests.cs +++ b/tests/Broadside.Tests/Document/CatalogEntryTests.cs @@ -89,18 +89,23 @@ public void An_empty_viewer_preferences_dictionary_reads_every_default() Assert.Empty(document.Diagnostics); } + public static TheoryData MalformedViewerPreferences => new() + { + "/HideToolbar /true", + "/NonFullScreenPageMode /FullScreen", + "/Direction /TopToBottom", + "/ViewArea /PageBox", + "/PrintScaling /Fit", + "/Duplex /Triplex", + "/NumCopies 0", + "/PrintPageRange [1 2 3]", + "/PrintPageRange [3 2]", + "/Enforce [/HideToolbar]", + "/Enforce [/PrintScaling]", + }; + [Theory] - [InlineData("/HideToolbar /true")] - [InlineData("/NonFullScreenPageMode /FullScreen")] - [InlineData("/Direction /TopToBottom")] - [InlineData("/ViewArea /PageBox")] - [InlineData("/PrintScaling /Fit")] - [InlineData("/Duplex /Triplex")] - [InlineData("/NumCopies 0")] - [InlineData("/PrintPageRange [1 2 3]")] - [InlineData("/PrintPageRange [3 2]")] - [InlineData("/Enforce [/HideToolbar]")] - [InlineData("/Enforce [/PrintScaling]")] + [MemberData(nameof(MalformedViewerPreferences))] public void A_malformed_viewer_preference_reads_as_its_default_with_a_warning(string entry) { using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", $"/ViewerPreferences << {entry} >>")); @@ -129,10 +134,15 @@ public void Unknown_viewer_preference_keys_are_ignored() Assert.Empty(document.Diagnostics); } + public static TheoryData UnknownCatalogEntries => new() + { + { "/PageLayout /Spread", "PageLayoutInvalid" }, + { "/PageMode (UseOutlines)", "PageModeInvalid" }, + { "/ViewerPreferences [1]", "ViewerPreferencesInvalid" }, + }; + [Theory] - [InlineData("/PageLayout /Spread", "PageLayoutInvalid")] - [InlineData("/PageMode (UseOutlines)", "PageModeInvalid")] - [InlineData("/ViewerPreferences [1]", "ViewerPreferencesInvalid")] + [MemberData(nameof(UnknownCatalogEntries))] public void An_unknown_layout_mode_or_preferences_entry_reads_as_the_default_with_a_warning(string entry, string code) { using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", entry)); @@ -209,11 +219,16 @@ public void A_requirement_takes_the_default_penalty_and_handlers_given_as_an_arr Assert.Empty(document.Diagnostics); } + public static TheoryData MalformedRequirements => new() + { + "/Requirements << /S /Navigation >>", + "/Requirements [(x) << /S /Navigation >>]", + "/Requirements [<< /S /Navigation /Penalty 101 >>]", + "/Requirements [<< /Penalty 1 >>]", + }; + [Theory] - [InlineData("/Requirements << /S /Navigation >>")] - [InlineData("/Requirements [(x) << /S /Navigation >>]")] - [InlineData("/Requirements [<< /S /Navigation /Penalty 101 >>]")] - [InlineData("/Requirements [<< /Penalty 1 >>]")] + [MemberData(nameof(MalformedRequirements))] public void A_malformed_requirement_is_reported(string entry) { using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", entry)); @@ -222,11 +237,16 @@ public void A_malformed_requirement_is_reported(string entry) Assert.Equal("RequirementInvalid", Assert.Single(document.Diagnostics).Code); } + public static TheoryData MalformedExtensions => new() + { + { "/Extensions [1]", "ExtensionsInvalid", 0 }, + { "/Extensions << /ADBE 5 >>", "DeveloperExtensionInvalid", 0 }, + { "/Extensions << /ADBE << /ExtensionLevel 3 >> >>", "DeveloperExtensionInvalid", 1 }, + { "/Extensions << /ADBE << /BaseVersion /1.7 /ExtensionLevel 3.5 >> >>", "DeveloperExtensionInvalid", 1 }, + }; + [Theory] - [InlineData("/Extensions [1]", "ExtensionsInvalid", 0)] - [InlineData("/Extensions << /ADBE 5 >>", "DeveloperExtensionInvalid", 0)] - [InlineData("/Extensions << /ADBE << /ExtensionLevel 3 >> >>", "DeveloperExtensionInvalid", 1)] - [InlineData("/Extensions << /ADBE << /BaseVersion /1.7 /ExtensionLevel 3.5 >> >>", "DeveloperExtensionInvalid", 1)] + [MemberData(nameof(MalformedExtensions))] public void A_malformed_extensions_entry_is_reported(string entry, string code, int count) { using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792]", entry)); diff --git a/tests/Broadside.Tests/Document/DocumentInformationTests.cs b/tests/Broadside.Tests/Document/DocumentInformationTests.cs index bf6300a0..6e8c17ce 100644 --- a/tests/Broadside.Tests/Document/DocumentInformationTests.cs +++ b/tests/Broadside.Tests/Document/DocumentInformationTests.cs @@ -286,10 +286,15 @@ public void A_file_without_an_identifier_has_none() Assert.Empty(document.Diagnostics); } + public static TheoryData MalformedIdentifiers => new() + { + { "/ID [<0123> <0123>]", true }, + { "/ID [<00112233445566778899AABBCCDDEEFF>]", false }, + { "/ID (one)", false }, + }; + [Theory] - [InlineData("/ID [<0123> <0123>]", true)] - [InlineData("/ID [<00112233445566778899AABBCCDDEEFF>]", false)] - [InlineData("/ID (one)", false)] + [MemberData(nameof(MalformedIdentifiers))] public void A_malformed_identifier_is_reported(string entry, bool exposed) { byte[] file = new TestPdf { TrailerEntries = entry }.Build( diff --git a/tests/Broadside.Tests/Document/PageLabelTests.cs b/tests/Broadside.Tests/Document/PageLabelTests.cs new file mode 100644 index 00000000..320327bd --- /dev/null +++ b/tests/Broadside.Tests/Document/PageLabelTests.cs @@ -0,0 +1,251 @@ +using System.Text.RegularExpressions; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Document; + +/// Page labels: ranges in a number tree, numbered in a style with a prefix. ISO 32000-2 §12.4.2, Table 161; §7.9.7. +public partial class PageLabelTests +{ + private static readonly string[] PageLabelsPdfLabels = ["i", "ii", "iii", "1", "2", "IV", "V", "Z", "AA", "A-zz", "A-aaa", "Cover"]; + + [Fact] + public void Page_labels_pdf_labels_every_page_in_every_style() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("page-labels.pdf")); + PdfPageLabels labels = document.PageLabels!; + + Assert.Equal(PageLabelsPdfLabels, labels.GetLabels()); + Assert.Equal(PageLabelsPdfLabels, Enumerable.Range(0, 12).Select(labels.GetLabel)); + Assert.Empty(document.Diagnostics); + Assert.False(document.Catalog.IsDirty); + } + + [Fact] + public void Page_labels_pdf_lists_its_ranges_in_page_order() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("page-labels.pdf")); + IReadOnlyList ranges = document.PageLabels!.Ranges; + + Assert.Equal([0, 3, 5, 7, 9, 11], ranges.Select(range => range.StartPageIndex)); + Assert.Equal( + [PdfPageLabelStyle.LowercaseRoman, PdfPageLabelStyle.Arabic, PdfPageLabelStyle.UppercaseRoman, PdfPageLabelStyle.UppercaseLetters, PdfPageLabelStyle.LowercaseLetters, PdfPageLabelStyle.None], + ranges.Select(range => range.Style)); + Assert.Equal([1, 1, 4, 26, 52, 1], ranges.Select(range => range.FirstNumber)); + Assert.Equal(["", "", "", "", "A-", "Cover"], ranges.Select(range => range.Prefix)); + Assert.Equal(new CosName("PageLabel"), ranges[2].Dictionary[new CosName("Type")]); + } + + [Fact] + public void Number_tree_deep_pdf_finds_each_page_s_range_through_kids_and_limits() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("number-tree-deep.pdf")); + PdfPageLabels labels = document.PageLabels!; + PdfNumberTree tree = document.GetNumberTree(document.Catalog[new CosName("PageLabels")])!; + + // Each page's label comes from the range with the greatest key at or below its index (§12.4.2). + IReadOnlyList expected = [.. Enumerable.Range(0, document.Pages.Count).Select(index => + { + Assert.True(tree.TryGetFloor(index, out int start, out CosObject? value)); + return Expected((CosDictionary)value, index - start); + })]; + Assert.Equal(expected, labels.GetLabels()); + Assert.Equal(tree.Select(pair => pair.Key), labels.Ranges.Select(range => range.StartPageIndex)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_document_without_page_labels_has_none() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + + Assert.Null(document.PageLabels); + } + + [Theory] + [InlineData(1, "A")] + [InlineData(2, "B")] + [InlineData(26, "Z")] + [InlineData(27, "AA")] + [InlineData(28, "BB")] + [InlineData(52, "ZZ")] + [InlineData(53, "AAA")] + [InlineData(702, "ZZZZZZZZZZZZZZZZZZZZZZZZZZZ")] + [InlineData(703, "AAAAAAAAAAAAAAAAAAAAAAAAAAAA")] + public void Letters_repeat_rather_than_carry(int number, string expected) + { + using PdfDocument document = OnePageLabelled($"/S /A /St {number}"); + + Assert.Equal(expected, document.PageLabels!.GetLabel(0)); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [InlineData(1, "I")] + [InlineData(4, "IV")] + [InlineData(9, "IX")] + [InlineData(14, "XIV")] + [InlineData(40, "XL")] + [InlineData(90, "XC")] + [InlineData(400, "CD")] + [InlineData(1994, "MCMXCIV")] + [InlineData(3999, "MMMCMXCIX")] + [InlineData(4000, "MMMM")] + [InlineData(12345, "MMMMMMMMMMMMCCCXLV")] + public void Roman_numerals_follow_the_subtractive_form_and_add_an_m_per_thousand_beyond_3999(int number, string expected) + { + using PdfDocument document = OnePageLabelled($"/S /R /St {number}"); + + Assert.Equal(expected, document.PageLabels!.GetLabel(0)); + } + + [Fact] + public void Every_roman_numeral_from_1_to_3999_is_canonical_and_reads_back_as_its_number() + { + using PdfDocument document = OnePageLabelled("/S /r /St 1"); + CosDictionary range = (CosDictionary)((CosArray)((CosDictionary)document.Catalog[new CosName("PageLabels")])[new CosName("Nums")])[1]; + + for (int number = 1; number <= 3999; number++) + { + range[new CosName("St")] = new CosInteger(number); + string label = document.PageLabels!.GetLabel(0); + Assert.Matches(CanonicalRoman(), label.ToUpperInvariant()); + Assert.Equal(number, ParseRoman(label)); + Assert.Equal(label.ToLowerInvariant(), label); + } + } + + [Theory] + [InlineData("/S /d", "PageLabelStyleInvalid", "1")] + [InlineData("/S /D /St 0", "PageLabelStartInvalid", "1")] + [InlineData("/S /D /St -5", "PageLabelStartInvalid", "1")] + [InlineData("/S /D /St 3.0", "PageLabelStartInvalid", "3")] + [InlineData("/S /D /St (7)", "PageLabelStartInvalid", "1")] + [InlineData("/S /D /P 5", "PageLabelPrefixInvalid", "1")] + [InlineData("/S /D /P (ab\\000cd)", "PageLabelPrefixInvalid", "ab1")] + [InlineData("/Type /Label /S /D", "PageLabelInvalid", "1")] + [InlineData("/S /A /St 2147483647", "PageLabelTooLong", "2147483647")] + [InlineData("/S /R /St 2147483647", "PageLabelTooLong", "2147483647")] + public void A_malformed_page_label_is_repaired_with_a_warning(string entries, string code, string expected) + { + using PdfDocument document = OnePageLabelled(entries); + + Assert.Equal(expected, document.PageLabels!.GetLabel(0)); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal(code, diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); + } + + [Fact] + public void Pages_before_the_first_range_are_numbered_in_decimal_with_a_warning() + { + using PdfDocument document = Labelled(3, "2 << /S /r >>"); + PdfPageLabels labels = document.PageLabels!; + + Assert.Equal(["1", "2", "i"], labels.GetLabels()); + Assert.Equal("PageLabelsMissingZeroKey", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_range_whose_value_is_not_a_dictionary_is_skipped_and_the_previous_range_continues() + { + using PdfDocument document = Labelled(4, "0 << /S /D >> 2 /NotALabel"); + + Assert.Equal(["1", "2", "3", "4"], document.PageLabels!.GetLabels()); + Assert.Equal(["PageLabelInvalid"], document.Diagnostics.Select(d => d.Code).Distinct()); + Assert.Equal([0], document.PageLabels.Ranges.Select(range => range.StartPageIndex)); + } + + [Fact] + public void A_negative_key_is_ignored_with_a_warning() + { + using PdfDocument document = Labelled(2, "-1 << /S /R >> 1 << /S /a >>"); + + Assert.Equal(["1", "a"], document.PageLabels!.GetLabels()); + Assert.Contains("PageLabelInvalid", document.Diagnostics.Select(d => d.Code)); + Assert.Equal([1], document.PageLabels.Ranges.Select(range => range.StartPageIndex)); + } + + [Fact] + public void A_page_index_outside_the_document_is_refused() + { + using PdfDocument document = OnePageLabelled("/S /D"); + + Assert.Throws(() => document.PageLabels!.GetLabel(1)); + Assert.Throws(() => document.PageLabels!.GetLabel(-1)); + } + + [Fact] + public void Labels_are_read_live_from_the_number_tree() + { + using PdfDocument document = OnePageLabelled("/S /D"); + var range = (CosDictionary)((CosArray)((CosDictionary)document.Catalog[new CosName("PageLabels")])[new CosName("Nums")])[1]; + + range[new CosName("P")] = new CosString("p-"u8); + + Assert.Equal("p-1", document.PageLabels!.GetLabel(0)); + } + + [Fact] + public void Strict_mode_throws_from_the_label_that_needs_a_repair() + { + byte[] file = LabelledFile(1, "0 << /S /d >>"); + using PdfDocument document = PdfDocument.Open(file, new PdfOptions().UseStrict()); + + Assert.Equal("PageLabelStyleInvalid", Assert.Throws(() => document.PageLabels!.GetLabel(0)).Diagnostic.Code); + } + + /// An independent rendering of Table 161 for the deep-tree check: decimal, roman by table lookup, repeated letters. + private static string Expected(CosDictionary range, int offset) + { + int number = (range.TryGetValue(new CosName("St"), out CosObject? start) ? (int)((CosInteger)start).Value : 1) + offset; + string prefix = range.TryGetValue(new CosName("P"), out CosObject? p) ? ((CosString)p).DecodeText() : string.Empty; + string style = range.TryGetValue(new CosName("S"), out CosObject? s) ? ((CosName)s).Value : string.Empty; + string[] ones = ["", "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix"]; + string[] tens = ["", "x", "xx", "xxx", "xl", "l", "lx", "lxx", "lxxx", "xc"]; + string roman = new string('m', number / 1000) + new[] { "", "c", "cc", "ccc", "cd", "d", "dc", "dcc", "dccc", "cm" }[number / 100 % 10] + tens[number / 10 % 10] + ones[number % 10]; + string letters = new((char)('a' + ((number - 1) % 26)), ((number - 1) / 26) + 1); + return prefix + style switch + { + "D" => number.ToString(System.Globalization.CultureInfo.InvariantCulture), + "r" => roman, + "R" => roman.ToUpperInvariant(), + "a" => letters, + "A" => letters.ToUpperInvariant(), + _ => string.Empty, + }; + } + + private static int ParseRoman(string text) + { + var values = new Dictionary { ['i'] = 1, ['v'] = 5, ['x'] = 10, ['l'] = 50, ['c'] = 100, ['d'] = 500, ['m'] = 1000 }; + int total = 0; + for (int index = 0; index < text.Length; index++) + { + int value = values[text[index]]; + total += index + 1 < text.Length && values[text[index + 1]] > value ? -value : value; + } + + return total; + } + + [GeneratedRegex("^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$")] + private static partial Regex CanonicalRoman(); + + private static PdfDocument OnePageLabelled(string entries) => PdfDocument.Open(LabelledFile(1, $"0 << {entries} >>")); + + private static PdfDocument Labelled(int pages, string nums) => PdfDocument.Open(LabelledFile(pages, nums)); + + private static byte[] LabelledFile(int pages, string nums) + { + string kids = string.Join(' ', Enumerable.Range(3, pages).Select(n => $"{n} 0 R")); + string[] objects = + [ + $"<< /Type /Catalog /Pages 2 0 R /PageLabels << /Nums [{nums}] >> >>", + $"<< /Type /Pages /Kids [{kids}] /Count {pages} >>", + .. Enumerable.Repeat("<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>", pages), + ]; + return new TestPdf().Build(objects); + } +} diff --git a/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt b/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt index e91fe552..c312247b 100644 --- a/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt +++ b/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt @@ -1,6 +1,6 @@ pdfjs: 989 files - Clean: 689 - Diagnostics: 286 + Clean: 681 + Diagnostics: 294 PasswordRequired: 12 CertificateRequired: 0 EncryptionUnsupported: 0 @@ -28,20 +28,25 @@ CatalogTypeInvalid: 4 DictionaryDuplicateKey: 4 PageMediaBoxMissing: 4 + DateInvalid: 3 DictionaryUnterminated: 3 + FileIdentifierInvalid: 3 PageTreeNodeTypeInvalid: 3 PagesMissing: 3 ArrayUnterminated: 2 + DateUnreadable: 2 DecodeParmsInvalid: 2 EncryptionEntryLengthInvalid: 2 EndOfFileMarkerMissing: 2 FilterAbbreviationNotAllowed: 2 + InfoTrappedInvalid: 2 LinearizationHintsInvalid: 2 PageTreeKidsInvalid: 2 PageTreeParentMismatch: 2 StreamKeywordEndOfLine: 2 TrailerIdMissing: 2 TrailerMissing: 2 + XmpMalformed: 2 DictionaryValueMissing: 1 EncryptDictionaryInvalid: 1 EncryptedDataInvalid: 1 @@ -50,9 +55,14 @@ HeaderMissing: 1 HeaderVersionInvalid: 1 HexStringInvalidDigit: 1 + InfoDictionaryInvalid: 1 + InfoValueNotTextString: 1 + MetadataStreamInvalid: 1 NumberMalformed: 1 + NumberTreeDuplicateKey: 1 ObjectStreamIndexMismatch: 1 ObjectStreamInvalid: 1 + PageModeInvalid: 1 PageResourcesInvalid: 1 PageTreeCycle: 1 PageTreeKidInvalid: 1 @@ -81,6 +91,7 @@ pdfbox: 137 files XrefEntryOffsetInvalid: 3 RootMissing: 2 CatalogTypeInvalid: 1 + DateUnreadable: 1 DictionaryDuplicateKey: 1 EndOfFileMarkerNotLast: 1 FilterAbbreviationNotAllowed: 1 @@ -90,8 +101,8 @@ pdfbox: 137 files StartxrefInvalid: 1 StreamLengthInvalid: 1 qpdf: 639 files - Clean: 450 - Diagnostics: 152 + Clean: 441 + Diagnostics: 161 PasswordRequired: 23 CertificateRequired: 0 EncryptionUnsupported: 1 @@ -122,10 +133,12 @@ qpdf: 639 files PageTreeCycle: 5 PageTreeNodeTypeInvalid: 5 PageTreeParentMismatch: 5 + DeveloperExtensionInvalid: 4 PageMediaBoxMissing: 4 PredictorInvalid: 4 EndOfFileMarkerNotLast: 3 EndstreamMissing: 3 + FileIdentifierInvalid: 3 FilterDataTruncated: 3 NameInvalidEscape: 3 ObjectStreamNested: 3 @@ -134,10 +147,12 @@ qpdf: 639 files ArrayUnterminated: 2 DictionaryDuplicateKey: 2 EndOfFileMarkerMissing: 2 + ExtensionsNotDirect: 2 FilterAbbreviationNotAllowed: 2 FilterInvalid: 2 HexStringInvalidDigit: 2 NameContainsNull: 2 + PageLabelsMissingZeroKey: 2 RootNotIndirect: 2 StreamKeywordEndOfLine: 2 TrailerMissing: 2 @@ -148,10 +163,13 @@ qpdf: 639 files EncryptionKeyLengthInvalid: 1 HeaderInvalid: 1 NestingTooDeep: 1 + NumberTreeKeysUnsorted: 1 + NumberTreeNodeInvalid: 1 ObjectStreamHeaderInvalid: 1 ObjectStreamInvalid: 1 ObjectStreamTypeInvalid: 1 PageBoxInvalid: 1 + PageLabelInvalid: 1 PageTreeKidInvalid: 1 PageTreeKidNotIndirect: 1 ReferenceInvalid: 1 @@ -163,8 +181,8 @@ qpdf: 639 files XrefStreamWidthsInvalid: 1 XrefSubsectionHeaderInvalid: 1 pdfium-tests: 840 files - Clean: 384 - Diagnostics: 449 + Clean: 299 + Diagnostics: 534 PasswordRequired: 2 CertificateRequired: 4 EncryptionUnsupported: 0 @@ -179,6 +197,9 @@ pdfium-tests: 840 files StreamLengthInvalid: 92 XrefSectionInvalid: 84 PredictorInvalid: 72 + DateInvalid: 56 + XmpMalformed: 43 + XmpPropertyDuplicate: 37 HeaderInvalid: 29 FilterDataInvalid: 28 DecodeParmsInvalid: 24 @@ -187,6 +208,7 @@ pdfium-tests: 840 files UnexpectedToken: 10 CatalogTypeInvalid: 5 DictionaryDuplicateKey: 5 + FileIdentifierInvalid: 5 PageMediaBoxMissing: 5 PageResourcesMissing: 5 PageTreeNodeTypeInvalid: 5 @@ -201,6 +223,7 @@ pdfium-tests: 840 files EncryptionRevisionInvalid: 2 EndOfFileMarkerNotLast: 2 TrailerMissing: 2 + ViewerPreferenceInvalid: 2 XrefSubsectionHeaderInvalid: 2 DictionaryValueMissing: 1 EncryptDictionaryInvalid: 1 @@ -209,6 +232,7 @@ pdfium-tests: 840 files HeaderMissing: 1 HexStringInvalidDigit: 1 LinearizationHintsInvalid: 1 + NumberTreeLimitsInvalid: 1 PageTreeCountMismatch: 1 PageTreeKidInvalid: 1 PageTreeKidNotIndirect: 1 diff --git a/tests/Broadside.Tests/Document/Snapshots/VeraPdfAgreementTests.Every_disagreement_matches_the_snapshot_and_every_triaged_rule_still_disagrees.verified.txt b/tests/Broadside.Tests/Document/Snapshots/VeraPdfAgreementTests.Every_disagreement_matches_the_snapshot_and_every_triaged_rule_still_disagrees.verified.txt index 01ed8759..79028745 100644 --- a/tests/Broadside.Tests/Document/Snapshots/VeraPdfAgreementTests.Every_disagreement_matches_the_snapshot_and_every_triaged_rule_still_disagrees.verified.txt +++ b/tests/Broadside.Tests/Document/Snapshots/VeraPdfAgreementTests.Every_disagreement_matches_the_snapshot_and_every_triaged_rule_still_disagrees.verified.txt @@ -1,4 +1,4 @@ -171 files, 53 agree, 118 disagree +171 files, 62 agree, 109 disagree PdfAOnly | Isartor 6-1-12-t01 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.12 Implementation Limits/isartor-6-1-12-t01-fail-a.pdf PdfAOnly | Isartor 6-1-12-t01 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.12 Implementation Limits/isartor-6-1-12-t01-fail-b.pdf PdfAOnly | Isartor 6-1-12-t01 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.12 Implementation Limits/isartor-6-1-12-t01-fail-c.pdf @@ -20,12 +20,10 @@ PdfAOnly | Isartor 6-1-8-t03 | veraPDF fail, strict pass | verapdf-corpus/Isarto PdfAOnly | Isartor 6-1-8-t04 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.8 Indirect objects/isartor-6-1-8-t04-fail-a.pdf PdfAOnly | Isartor 6-1-8-t05 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.8 Indirect objects/isartor-6-1-8-t05-fail-a.pdf PdfAOnly | Isartor 6-1-8-t06 | veraPDF fail, strict pass | verapdf-corpus/Isartor test files/PDFA-1b/6.1 File structure/6.1.8 Indirect objects/isartor-6-1-8-t06-fail-a.pdf -PdfAOnly | PDF_A-1b 6-1-12-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t01-fail-a.pdf PdfAOnly | PDF_A-1b 6-1-12-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t02-fail-c.pdf PdfAOnly | PDF_A-1b 6-1-12-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t02-fail-d.pdf PdfAOnly | PDF_A-1b 6-1-12-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t02-fail-e.pdf PdfAOnly | PDF_A-1b 6-1-12-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t02-fail-f.pdf -PdfAOnly | PDF_A-1b 6-1-12-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t02-fail-l.pdf PdfAOnly | PDF_A-1b 6-1-12-t03 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t03-fail-a.pdf PdfAOnly | PDF_A-1b 6-1-12-t03 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t03-fail-b.pdf PdfAOnly | PDF_A-1b 6-1-12-t03 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t03-fail-c.pdf @@ -33,7 +31,6 @@ PdfAOnly | PDF_A-1b 6-1-12-t03 | veraPDF fail, strict pass | verapdf-corpus/PDF_ PdfAOnly | PDF_A-1b 6-1-12-t04 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t04-fail-a.pdf PdfAOnly | PDF_A-1b 6-1-12-t06 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t06-fail-a.pdf PdfAOnly | PDF_A-1b 6-1-12-t08 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t08-fail-a.pdf -PdfAOnly | PDF_A-1b 6-1-12-t09 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t09-fail-a.pdf PdfAOnly | PDF_A-1b 6-1-12-t10 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t10-fail-a.pdf PdfAOnly | PDF_A-1b 6-1-12-t10 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.12 Implementation limits/veraPDF test suite 6-1-12-t10-fail-b.pdf StrictTooLenient | PDF_A-1b 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t02-fail-a.pdf @@ -46,9 +43,6 @@ PdfAOnly | PDF_A-1b 6-1-4-t03 | veraPDF fail, strict pass | verapdf-corpus/PDF_A PdfAOnly | PDF_A-1b 6-1-6-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.6 String objects/veraPDF test suite 6-1-6-t01-fail-a.pdf PdfAOnly | PDF_A-1b 6-1-6-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.6 String objects/veraPDF test suite 6-1-6-t01-fail-b.pdf PdfAOnly | PDF_A-1b 6-1-8-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-1b/6.1 File structure/6.1.8 Indirect objects/veraPDF test suite 6-1-8-t01-fail-a.pdf -PdfAOnly | PDF_A-2b 6-1-13-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t01-fail-a.pdf -PdfAOnly | PDF_A-2b 6-1-13-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t01-fail-b.pdf -PdfAOnly | PDF_A-2b 6-1-13-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t01-fail-c.pdf PdfAOnly | PDF_A-2b 6-1-13-t03 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t03-fail-a.pdf PdfAOnly | PDF_A-2b 6-1-13-t03 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t03-fail-d.pdf PdfAOnly | PDF_A-2b 6-1-13-t04 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.13 Implementation limits/veraPDF test suite 6-1-13-t04-fail-a.pdf @@ -69,7 +63,6 @@ StrictTooLenient | PDF_A-2b 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corp StrictTooLenient | PDF_A-2b 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t02-fail-c.pdf StrictTooLenient | PDF_A-2b 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t02-fail-d.pdf PdfAOnly | PDF_A-2b 6-1-3-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.3 File trailer/veraPDF test suite 6-1-3-t01-fail-a.pdf -PdfAOnly | PDF_A-2b 6-1-3-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.3 File trailer/veraPDF test suite 6-1-3-t01-fail-b.pdf PdfAOnly | PDF_A-2b 6-1-3-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.3 File trailer/veraPDF test suite 6-1-3-t01-fail-c.pdf PdfAOnly | PDF_A-2b 6-1-3-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.3 File trailer/veraPDF test suite 6-1-3-t02-fail-a.pdf PdfAOnly | PDF_A-2b 6-1-4-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.4 Cross reference table/veraPDF test suite 6-1-4-t01-fail-a.pdf @@ -80,7 +73,6 @@ PdfAOnly | PDF_A-2b 6-1-7-1-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF PdfAOnly | PDF_A-2b 6-1-7-1-t04 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.7.1 General/veraPDF test suite 6-1-7-1-t04-fail-a.pdf PdfAOnly | PDF_A-2b 6-1-7-1-t04 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.7.1 General/veraPDF test suite 6-1-7-1-t04-fail-b.pdf PdfAOnly | PDF_A-2b 6-1-7-1-t04 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.7.1 General/veraPDF test suite 6-1-7-1-t04-fail-c.pdf -PdfAOnly | PDF_A-2b 6-1-8-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.8 Name objects/veraPDF test suite 6-1-8-t01-fail-a.pdf PdfAOnly | PDF_A-2b 6-1-8-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.8 Name objects/veraPDF test suite 6-1-8-t01-fail-b.pdf PdfAOnly | PDF_A-2b 6-1-9-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.9 Indirect objects/veraPDF test suite 6-1-9-t01-fail-a.pdf PdfAOnly | PDF_A-2b 6-1-9-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-2b/6.1 File structure/6.1.9 Indirect objects/veraPDF test suite 6-1-9-t02-fail-a.pdf @@ -95,7 +87,6 @@ StrictTooLenient | PDF_A-4 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpu StrictTooLenient | PDF_A-4 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t02-fail-b.pdf StrictTooLenient | PDF_A-4 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t02-fail-c.pdf StrictTooLenient | PDF_A-4 6-1-2-t02 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.2 File header/veraPDF test suite 6-1-2-t02-fail-d.pdf -PdfAOnly | PDF_A-4 6-1-3-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.3 File trailer/veraPDF test suite 6-1-3-t01-fail-b.pdf PdfAOnly | PDF_A-4 6-1-3-t04 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.3 File trailer/veraPDF test suite 6-1-3-t04-fail-a.pdf PdfAOnly | PDF_A-4 6-1-3-t05 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.3 File trailer/veraPDF test suite 6-1-3-t05-fail-a.pdf PdfAOnly | PDF_A-4 6-1-4-t01 | veraPDF fail, strict pass | verapdf-corpus/PDF_A-4/6.1 File structure/6.1.4 Cross reference table/veraPDF test suite 6-1-4-t01-fail-a.pdf diff --git a/tests/Broadside.Tests/Document/VeraPdfAgreementTests.cs b/tests/Broadside.Tests/Document/VeraPdfAgreementTests.cs index 74a71b19..c434cd10 100644 --- a/tests/Broadside.Tests/Document/VeraPdfAgreementTests.cs +++ b/tests/Broadside.Tests/Document/VeraPdfAgreementTests.cs @@ -52,8 +52,7 @@ public partial class VeraPdfAgreementTests(ITestOutputHelper output) // Trailer (§7.5.5, §14.4). ["Isartor 6-1-3-t01"] = (VeraPdfTriage.PdfAOnly, "No ID in a PDF 1.4 trailer: Table 15 requires ID only in PDF 2.0 or with Encrypt."), - ["PDF_A-2b 6-1-3-t01"] = (VeraPdfTriage.PdfAOnly, "PDF 1.7 trailer without ID, with empty ID strings, or a linearized first-page trailer without ID: ID is optional before 2.0 and §14.4 sets no length."), - ["PDF_A-4 6-1-3-t01"] = (VeraPdfTriage.PdfAOnly, "ID present with an empty string: Table 15 and §14.4 require two byte strings but no length. (The PDF 2.0 trailer without ID now fails: TrailerIdMissing.)"), + ["PDF_A-2b 6-1-3-t01"] = (VeraPdfTriage.PdfAOnly, "PDF 1.7 trailer without ID, or a linearized first-page trailer without ID: ID is optional before 2.0. (An ID shorter than 16 bytes now fails: FileIdentifierInvalid, Table 15.)"), ["Isartor 6-1-3-t02"] = (VeraPdfTriage.PdfAOnly, "Encrypt in the trailer: PDF/A forbids encryption; ISO 32000-2 §7.6 defines it."), ["PDF_A-1b 6-1-3-t02"] = (VeraPdfTriage.PdfAOnly, "Encrypt in the trailer: PDF/A forbids encryption."), ["PDF_A-2b 6-1-3-t02"] = (VeraPdfTriage.PdfAOnly, "Encrypt in the trailer: PDF/A forbids encryption."), @@ -103,15 +102,12 @@ public partial class VeraPdfAgreementTests(ITestOutputHelper output) // Implementation limits: ISO 32000-2 Annex C is informative advice, not requirements on a file. ["Isartor 6-1-12-t01"] = (VeraPdfTriage.PdfAOnly, "Array over 8191 elements, name over 127 bytes, integer over 2^31-1: PDF/A-1 limits (ISO 32000-2 Annex C is informative)."), - ["PDF_A-1b 6-1-12-t01"] = (VeraPdfTriage.PdfAOnly, "Integer outside 32 bits: a PDF/A-1 limit."), ["PDF_A-1b 6-1-12-t02"] = (VeraPdfTriage.PdfAOnly, "Real over 32767: a PDF/A-1 limit."), ["PDF_A-1b 6-1-12-t03"] = (VeraPdfTriage.PdfAOnly, "String over 65535 bytes: a PDF/A-1 limit."), ["PDF_A-1b 6-1-12-t04"] = (VeraPdfTriage.PdfAOnly, "Name over 127 bytes: a PDF/A-1 limit."), ["PDF_A-1b 6-1-12-t06"] = (VeraPdfTriage.PdfAOnly, "Dictionary over 4095 entries: a PDF/A-1 limit."), ["PDF_A-1b 6-1-12-t08"] = (VeraPdfTriage.PdfAOnly, "q/Q nesting over 28: a PDF/A-1 limit (and a content stream rule)."), - ["PDF_A-1b 6-1-12-t09"] = (VeraPdfTriage.PdfAOnly, "DeviceN over 8 components: a PDF/A-1 limit."), ["PDF_A-1b 6-1-12-t10"] = (VeraPdfTriage.PdfAOnly, "CID over 65535: a PDF/A-1 limit."), - ["PDF_A-2b 6-1-13-t01"] = (VeraPdfTriage.PdfAOnly, "Integer outside 32 bits: a PDF/A-2 limit."), ["PDF_A-2b 6-1-13-t03"] = (VeraPdfTriage.PdfAOnly, "String over 32767 bytes: a PDF/A-2 limit."), ["PDF_A-2b 6-1-13-t04"] = (VeraPdfTriage.PdfAOnly, "Name over 127 bytes: a PDF/A-2 limit."), ["PDF_A-2b 6-1-13-t08"] = (VeraPdfTriage.PdfAOnly, "q/Q nesting over 28: a PDF/A-2 limit."), diff --git a/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs b/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs index 82c81c59..b9750572 100644 --- a/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs +++ b/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs @@ -17,7 +17,7 @@ public void A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics(str int expectedPages = fileName switch { "page-tree-inherited.pdf" or "linearized.pdf" or "linearized-xref-stream.pdf" => 2, - "number-tree-deep.pdf" => 12, + "number-tree-deep.pdf" or "page-labels.pdf" => 12, _ => 1, }; Assert.Equal(expectedPages, document.Pages.Count); diff --git a/tests/Broadside.Tests/Document/XmpPacketTests.cs b/tests/Broadside.Tests/Document/XmpPacketTests.cs index eba1ce5b..cd1c3b1e 100644 --- a/tests/Broadside.Tests/Document/XmpPacketTests.cs +++ b/tests/Broadside.Tests/Document/XmpPacketTests.cs @@ -56,22 +56,22 @@ public void A_packet_reads_every_property_form_into_one_model() Assert.Equal(XmpPropertyKind.OrderedArray, packet.GetProperty(XmpNamespaces.DublinCore, "creator")!.Kind); Assert.Equal(XmpPropertyKind.UnorderedArray, packet.GetProperty(XmpNamespaces.DublinCore, "subject")!.Kind); - const string Ex = "http://example.com/ns/"; - XmpProperty resource = packet.GetProperty(Ex, "Resource")!; + const string ex = "http://example.com/ns/"; + XmpProperty resource = packet.GetProperty(ex, "Resource")!; Assert.Equal(XmpPropertyKind.Structure, resource.Kind); - Assert.Equal("Resource form", resource.GetField(Ex, "Name")!.Value); - Assert.Equal("2", resource.GetField(Ex, "Count")!.Value); - XmpProperty nested = packet.GetProperty(Ex, "Nested")!; + Assert.Equal("Resource form", resource.GetField(ex, "Name")!.Value); + Assert.Equal("2", resource.GetField(ex, "Count")!.Value); + XmpProperty nested = packet.GetProperty(ex, "Nested")!; Assert.Equal(XmpPropertyKind.Structure, nested.Kind); Assert.Equal(["Attribute field", "3"], nested.Fields.Select(field => field.Value)); - Assert.Equal("Shorthand", packet.GetProperty(Ex, "Short")!.GetField(Ex, "Name")!.Value); - Assert.Equal("http://example.com/", packet.GetProperty(Ex, "Link")!.Value); + Assert.Equal("Shorthand", packet.GetProperty(ex, "Short")!.GetField(ex, "Name")!.Value); + Assert.Equal("http://example.com/", packet.GetProperty(ex, "Link")!.Value); - XmpProperty qualified = packet.GetProperty(Ex, "WithQualifier")!; + XmpProperty qualified = packet.GetProperty(ex, "WithQualifier")!; Assert.Equal(XmpPropertyKind.Simple, qualified.Kind); Assert.Equal("42", qualified.Value); Assert.Equal("mm", Assert.Single(qualified.Qualifiers).Value); - Assert.Null(packet.GetProperty(Ex, "Missing")); + Assert.Null(packet.GetProperty(ex, "Missing")); Assert.Equal(17, packet.Properties.Count); } @@ -177,9 +177,14 @@ public void Predefined_and_character_references_are_text() Assert.Equal("A & B ☺ <", packet.Title); } + public static TheoryData DocumentTypeDeclarations => new() + { + "]>", + "", + }; + [Theory] - [InlineData("]>")] - [InlineData("")] + [MemberData(nameof(DocumentTypeDeclarations))] public void A_document_type_declaration_is_refused_so_entities_never_expand(string doctype) { byte[] bytes = Encoding.UTF8.GetBytes(doctype + Title("&lol2;")); From cc91850e37d79db240a92098cfbd179243a24883 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:27:01 -0500 Subject: [PATCH 025/152] feat(fonts): Standard 14 metrics and simple-font encodings (#49) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Start the Broadside.Fonts namespace with typed, live views over font dictionaries and font descriptors (ISO 32000-2 §9.5, §9.6, §9.8): PdfFont, PdfSimpleFont, PdfType1Font (Type1 and MMType1), PdfTrueTypeFont, PdfType3Font and PdfType0Font shells, PdfFontDescriptor with every Table 120 entry, PdfFontFlags, PdfFontStretch, PdfFontType and Standard14Font. PdfDocument.GetFont and PdfPage.GetFont return one view per font dictionary. For every code of a simple font, GetGlyphName applies the encoding (named encodings, encoding dictionaries with BaseEncoding and Differences, the built-in encoding by the Table 112 rule) and GetWidth applies FirstChar/LastChar/Widths/MissingWidth, falling back to the Standard 14 AFM metrics for non-embedded Standard 14 fonts (and the pdf.js/PDFBox aliases such as Arial,Bold). The 256 names and widths are cached per font and rebuilt when a contributing COS container changes, through a new internal Version counter on CosDictionary and CosArray; lookups allocate nothing. The metrics, the Annex D encodings (StandardEncoding, WinAnsiEncoding, MacRomanEncoding, MacExpertEncoding, Symbol, ZapfDingbats, plus the Mac OS Roman additions of Table 113 for TrueType) and the Adobe Glyph List are generated C# tables from checked-in sources (src/Broadside/Fonts/Data/generate.py). The AFM MustRead.html notice, the glyph list licence and THIRD-PARTY-NOTICES.txt ship in the package. Nine new corpus files, conformance rows 9.5, 9.6.x, 9.8.x and D.1-D.6, a FontMetricsBenchmarks benchmark, font reading in the document fuzz target, and a real-world corpus test over every page font. Co-Authored-By: Claude Opus 5.5 --- .../FontMetricsBenchmarks.cs | 100 + docs/conformance/iso-32000-2.md | 24 +- src/Broadside/Broadside.csproj | 6 + src/Broadside/Fonts/AdobeGlyphList.cs | 119 + src/Broadside/Fonts/AdobeGlyphList.g.cs | 1268 ++++ src/Broadside/Fonts/Data/Afm/Courier-Bold.afm | 684 ++ .../Fonts/Data/Afm/Courier-BoldOblique.afm | 684 ++ .../Fonts/Data/Afm/Courier-Oblique.afm | 684 ++ src/Broadside/Fonts/Data/Afm/Courier.afm | 684 ++ .../Fonts/Data/Afm/Helvetica-Bold.afm | 5654 +++++++++++++++ .../Fonts/Data/Afm/Helvetica-BoldOblique.afm | 5654 +++++++++++++++ .../Fonts/Data/Afm/Helvetica-Oblique.afm | 6102 +++++++++++++++++ src/Broadside/Fonts/Data/Afm/Helvetica.afm | 6102 +++++++++++++++++ src/Broadside/Fonts/Data/Afm/MustRead.html | 19 + src/Broadside/Fonts/Data/Afm/Symbol.afm | 426 ++ src/Broadside/Fonts/Data/Afm/Times-Bold.afm | 5176 ++++++++++++++ .../Fonts/Data/Afm/Times-BoldItalic.afm | 4768 +++++++++++++ src/Broadside/Fonts/Data/Afm/Times-Italic.afm | 5334 ++++++++++++++ src/Broadside/Fonts/Data/Afm/Times-Roman.afm | 4838 +++++++++++++ src/Broadside/Fonts/Data/Afm/ZapfDingbats.afm | 450 ++ src/Broadside/Fonts/Data/GlyphList/LICENSE.md | 26 + .../Fonts/Data/GlyphList/glyphlist.txt | 4325 ++++++++++++ .../Fonts/Data/GlyphList/zapfdingbats.txt | 245 + src/Broadside/Fonts/Data/encodings.txt | 774 +++ src/Broadside/Fonts/Data/generate.py | 380 + src/Broadside/Fonts/FontNames.cs | 127 + src/Broadside/Fonts/GlyphNameTable.cs | 60 + src/Broadside/Fonts/GlyphNameTable.g.cs | 224 + src/Broadside/Fonts/PdfFont.cs | 154 + src/Broadside/Fonts/PdfFontDescriptor.cs | 186 + src/Broadside/Fonts/PdfFontFlags.cs | 41 + src/Broadside/Fonts/PdfFontStretch.cs | 33 + src/Broadside/Fonts/PdfFontType.cs | 24 + src/Broadside/Fonts/PdfSimpleFont.cs | 85 + src/Broadside/Fonts/PdfTrueTypeFont.cs | 17 + src/Broadside/Fonts/PdfType0Font.cs | 13 + src/Broadside/Fonts/PdfType1Font.cs | 21 + src/Broadside/Fonts/PdfType3Font.cs | 20 + src/Broadside/Fonts/SimpleFontMetrics.cs | 582 ++ src/Broadside/Fonts/Standard14Data.cs | 304 + src/Broadside/Fonts/Standard14Data.g.cs | 674 ++ src/Broadside/Fonts/Standard14Font.cs | 51 + src/Broadside/Objects/CosArray.cs | 33 +- src/Broadside/Objects/CosDictionary.cs | 35 +- src/Broadside/Parsing/DiagnosticCodes.cs | 16 + src/Broadside/PdfDocument.cs | 31 + src/Broadside/PdfPage.cs | 18 + src/Broadside/PublicAPI.Unshipped.txt | 85 + src/Broadside/THIRD-PARTY-NOTICES.txt | 109 + tests/Broadside.Fuzz/FuzzTargets.cs | 35 +- tests/Broadside.Fuzz/README.md | 2 +- tests/Broadside.TestSupport/Corpus.cs | 9 + tests/Broadside.Tests/Fonts/EncodingTests.cs | 198 + tests/Broadside.Tests/Fonts/FontModelTests.cs | 199 + tests/Broadside.Tests/Fonts/FontPdf.cs | 36 + .../Fonts/RealWorldFontTests.cs | 107 + .../Fonts/SimpleFontCorpusTests.cs | 161 + .../Fonts/Standard14FontTests.cs | 32 + .../Fonts/Standard14MetricsTests.cs | 172 + tests/Broadside.Tests/Fonts/WidthTests.cs | 162 + ...pus_file_names_match_snapshot.verified.txt | 9 + tests/Corpus/README.md | 9 + tests/Corpus/generate.py | 99 + tests/Corpus/text-standard14-alias.pdf | Bin 0 -> 613 bytes tests/Corpus/text-standard14-differences.pdf | Bin 0 -> 682 bytes tests/Corpus/text-standard14-macroman.pdf | Bin 0 -> 616 bytes .../text-standard14-symbol-differences.pdf | Bin 0 -> 634 bytes tests/Corpus/text-standard14-symbol.pdf | Bin 0 -> 738 bytes tests/Corpus/text-standard14-widths.pdf | Bin 0 -> 902 bytes .../Corpus/text-standard14-winansi-quirks.pdf | Bin 0 -> 619 bytes tests/Corpus/text-standard14-zapfdingbats.pdf | Bin 0 -> 587 bytes .../Corpus/text-type1-symbolic-noencoding.pdf | Bin 0 -> 856 bytes 72 files changed, 58682 insertions(+), 17 deletions(-) create mode 100644 bench/Broadside.Benchmarks/FontMetricsBenchmarks.cs create mode 100644 src/Broadside/Fonts/AdobeGlyphList.cs create mode 100644 src/Broadside/Fonts/AdobeGlyphList.g.cs create mode 100644 src/Broadside/Fonts/Data/Afm/Courier-Bold.afm create mode 100644 src/Broadside/Fonts/Data/Afm/Courier-BoldOblique.afm create mode 100644 src/Broadside/Fonts/Data/Afm/Courier-Oblique.afm create mode 100644 src/Broadside/Fonts/Data/Afm/Courier.afm create mode 100644 src/Broadside/Fonts/Data/Afm/Helvetica-Bold.afm create mode 100644 src/Broadside/Fonts/Data/Afm/Helvetica-BoldOblique.afm create mode 100644 src/Broadside/Fonts/Data/Afm/Helvetica-Oblique.afm create mode 100644 src/Broadside/Fonts/Data/Afm/Helvetica.afm create mode 100644 src/Broadside/Fonts/Data/Afm/MustRead.html create mode 100644 src/Broadside/Fonts/Data/Afm/Symbol.afm create mode 100644 src/Broadside/Fonts/Data/Afm/Times-Bold.afm create mode 100644 src/Broadside/Fonts/Data/Afm/Times-BoldItalic.afm create mode 100644 src/Broadside/Fonts/Data/Afm/Times-Italic.afm create mode 100644 src/Broadside/Fonts/Data/Afm/Times-Roman.afm create mode 100644 src/Broadside/Fonts/Data/Afm/ZapfDingbats.afm create mode 100644 src/Broadside/Fonts/Data/GlyphList/LICENSE.md create mode 100644 src/Broadside/Fonts/Data/GlyphList/glyphlist.txt create mode 100644 src/Broadside/Fonts/Data/GlyphList/zapfdingbats.txt create mode 100644 src/Broadside/Fonts/Data/encodings.txt create mode 100644 src/Broadside/Fonts/Data/generate.py create mode 100644 src/Broadside/Fonts/FontNames.cs create mode 100644 src/Broadside/Fonts/GlyphNameTable.cs create mode 100644 src/Broadside/Fonts/GlyphNameTable.g.cs create mode 100644 src/Broadside/Fonts/PdfFont.cs create mode 100644 src/Broadside/Fonts/PdfFontDescriptor.cs create mode 100644 src/Broadside/Fonts/PdfFontFlags.cs create mode 100644 src/Broadside/Fonts/PdfFontStretch.cs create mode 100644 src/Broadside/Fonts/PdfFontType.cs create mode 100644 src/Broadside/Fonts/PdfSimpleFont.cs create mode 100644 src/Broadside/Fonts/PdfTrueTypeFont.cs create mode 100644 src/Broadside/Fonts/PdfType0Font.cs create mode 100644 src/Broadside/Fonts/PdfType1Font.cs create mode 100644 src/Broadside/Fonts/PdfType3Font.cs create mode 100644 src/Broadside/Fonts/SimpleFontMetrics.cs create mode 100644 src/Broadside/Fonts/Standard14Data.cs create mode 100644 src/Broadside/Fonts/Standard14Data.g.cs create mode 100644 src/Broadside/Fonts/Standard14Font.cs create mode 100644 src/Broadside/THIRD-PARTY-NOTICES.txt create mode 100644 tests/Broadside.Tests/Fonts/EncodingTests.cs create mode 100644 tests/Broadside.Tests/Fonts/FontModelTests.cs create mode 100644 tests/Broadside.Tests/Fonts/FontPdf.cs create mode 100644 tests/Broadside.Tests/Fonts/RealWorldFontTests.cs create mode 100644 tests/Broadside.Tests/Fonts/SimpleFontCorpusTests.cs create mode 100644 tests/Broadside.Tests/Fonts/Standard14FontTests.cs create mode 100644 tests/Broadside.Tests/Fonts/Standard14MetricsTests.cs create mode 100644 tests/Broadside.Tests/Fonts/WidthTests.cs create mode 100644 tests/Corpus/text-standard14-alias.pdf create mode 100644 tests/Corpus/text-standard14-differences.pdf create mode 100644 tests/Corpus/text-standard14-macroman.pdf create mode 100644 tests/Corpus/text-standard14-symbol-differences.pdf create mode 100644 tests/Corpus/text-standard14-symbol.pdf create mode 100644 tests/Corpus/text-standard14-widths.pdf create mode 100644 tests/Corpus/text-standard14-winansi-quirks.pdf create mode 100644 tests/Corpus/text-standard14-zapfdingbats.pdf create mode 100644 tests/Corpus/text-type1-symbolic-noencoding.pdf diff --git a/bench/Broadside.Benchmarks/FontMetricsBenchmarks.cs b/bench/Broadside.Benchmarks/FontMetricsBenchmarks.cs new file mode 100644 index 00000000..a367cd92 --- /dev/null +++ b/bench/Broadside.Benchmarks/FontMetricsBenchmarks.cs @@ -0,0 +1,100 @@ +using System.Globalization; +using System.Text; +using BenchmarkDotNet.Attributes; +using Broadside.Fonts; + +namespace Broadside.Benchmarks; + +/// +/// The per-glyph lookups of simple fonts (ISO 32000-2 §9.6.2, §9.6.5, issue #49): glyph name and width of every code of the +/// fourteen non-embedded Standard 14 fonts. The text interpreter asks for these once per shown glyph, so +/// must allocate nothing (Allocated = -); is the one-time cost per font. +/// +[MemoryDiagnoser] +public class FontMetricsBenchmarks +{ + private static readonly string[] Names = + [ + "Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique", "Helvetica", "Helvetica-Bold", "Helvetica-Oblique", + "Helvetica-BoldOblique", "Times-Roman", "Times-Bold", "Times-Italic", "Times-BoldItalic", "Symbol", "ZapfDingbats", + ]; + + private byte[] _bytes = []; + private PdfDocument? _document; + private PdfSimpleFont[] _fonts = []; + + [GlobalSetup] + public void Setup() + { + _bytes = FileWithFonts(); + _document = PdfDocument.Open(_bytes); + PdfPage page = _document.Pages[0]; + _fonts = [.. Enumerable.Range(1, Names.Length).Select(index => (PdfSimpleFont)page.GetFont("F" + index.ToString(CultureInfo.InvariantCulture))!)]; + _ = NameAndWidth(); + } + + [GlobalCleanup] + public void Cleanup() => _document?.Dispose(); + + /// Glyph name and width of the 256 codes of each of the 14 fonts: 3,584 lookups of each. + [Benchmark(OperationsPerInvoke = 256 * 14)] + public double NameAndWidth() + { + double total = 0; + foreach (PdfSimpleFont font in _fonts) + { + for (int code = 0; code < 256; code++) + { + total += font.GetWidth((byte)code) + font.GetGlyphName((byte)code).Length; + } + } + + return total; + } + + /// Opens the file and computes the 256 names and widths of each of the 14 fonts once. + [Benchmark] + public double BuildMetrics() + { + using PdfDocument document = PdfDocument.Open(_bytes); + PdfPage page = document.Pages[0]; + double total = 0; + for (int index = 1; index <= Names.Length; index++) + { + total += ((PdfSimpleFont)page.GetFont("F" + index.ToString(CultureInfo.InvariantCulture))!).GetWidth(65); + } + + return total; + } + + /// One page whose resources name the fourteen fonts F1 to F14, objects 4 to 17. + private static byte[] FileWithFonts() + { + var objects = new List + { + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << " + + string.Concat(Names.Select((_, index) => string.Create(CultureInfo.InvariantCulture, $"/F{index + 1} {index + 4} 0 R "))) + ">> >> >>", + }; + objects.AddRange(Names.Select(name => $"<< /Type /Font /Subtype /Type1 /BaseFont /{name} /Encoding << /Differences [ 128 /Euro /bullet ] >> >>")); + + var text = new StringBuilder("%PDF-1.7\n"); + var offsets = new List(); + for (int index = 0; index < objects.Count; index++) + { + offsets.Add(text.Length); + text.Append(CultureInfo.InvariantCulture, $"{index + 1} 0 obj\n{objects[index]}\nendobj\n"); + } + + int xref = text.Length; + text.Append(CultureInfo.InvariantCulture, $"xref\n0 {objects.Count + 1}\n0000000000 65535 f \n"); + foreach (int offset in offsets) + { + text.Append(CultureInfo.InvariantCulture, $"{offset:D10} 00000 n \n"); + } + + text.Append(CultureInfo.InvariantCulture, $"trailer\n<< /Size {objects.Count + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n"); + return Encoding.ASCII.GetBytes(text.ToString()); + } +} diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index 22181c28..68e1917d 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -76,10 +76,21 @@ Clause numbers at the second level; split rows to the third level as clauses are | 9.2 | Organisation and use of fonts | not started | | | | | 9.3 | Text state parameters and operators | not started | | | | | 9.4 | Text objects | not started | | | | -| 9.5 | Introduction to font data structures | not started | | | | -| 9.6 | Simple fonts | not started | | | | +| 9.5 | Introduction to font data structures | done | `PdfFont`, `PdfFontType`, `PdfType1Font`, `PdfTrueTypeFont`, `PdfType3Font`, `PdfType0Font` | `Broadside.Tests.Fonts.FontModelTests.The_subtype_selects_the_type_of_the_view`, `Broadside.Tests.Fonts.FontModelTests.A_dictionary_that_is_not_quite_a_font_is_read_as_a_type_1_font_with_a_diagnostic`, `Broadside.Tests.Fonts.FontModelTests.The_same_dictionary_gives_the_same_view_and_a_non_dictionary_none` | Table 108: one live view type per Subtype, reached through `PdfDocument.GetFont` and `PdfPage.GetFont`; a missing or unknown Subtype (including a CIDFont used directly) is read as Type 1 with FontSubtypeInvalid, a Type other than Font with FontTypeInvalid. Type 0 and CIDFonts are 9.7 | +| 9.6.1 | General | done | `PdfSimpleFont`, `SimpleFontMetrics` | `Broadside.Tests.Fonts.Standard14FontTests.Text_standard14_pdf_gives_each_code_its_glyph_name_and_its_Helvetica_width`, `Broadside.Tests.Fonts.FontModelTests.A_simple_font_that_is_not_a_standard_14_font_needs_a_descriptor_and_a_base_font`, `Broadside.Tests.Fonts.WidthTests.Looking_up_a_glyph_name_and_width_allocates_nothing`, `Broadside.Tests.Fonts.WidthTests.Concurrent_lookups_on_a_new_font_agree` | One byte per code, 256-entry encoding, one width per code; FontDescriptorMissing for a simple font that is neither Type 3 nor a standard 14 font. The 256 names and widths are cached per font and rebuilt when a contributing dictionary or array changes (internal `Version` on `CosDictionary`/`CosArray`); lookups allocate nothing (`bench/Broadside.Benchmarks/FontMetricsBenchmarks.cs`) | +| 9.6.2.1 | General | done | `PdfType1Font`, `PdfSimpleFont`, `SimpleFontMetrics` | `Broadside.Tests.Fonts.WidthTests.Codes_in_range_take_their_widths_and_the_others_take_MissingWidth`, `Broadside.Tests.Fonts.WidthTests.A_missing_FirstChar_is_read_as_0_and_a_missing_LastChar_from_the_number_of_widths`, `Broadside.Tests.Fonts.WidthTests.A_widths_array_shorter_than_its_range_or_with_a_non_number_falls_back_to_MissingWidth`, `Broadside.Tests.Fonts.WidthTests.A_font_without_widths_that_is_not_a_standard_14_font_has_zero_widths_and_a_diagnostic`, `Broadside.Tests.Fonts.WidthTests.A_standard_14_font_with_widths_but_no_descriptor_takes_its_metrics_outside_the_range_with_a_diagnostic`, `Broadside.Tests.Fonts.WidthTests.Widths_follow_changes_to_the_widths_array_and_the_font_dictionary`, `Broadside.Tests.Fonts.WidthTests.Strict_mode_throws_from_the_first_lookup_of_a_font_with_malformed_widths`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.Widths_override_the_standard_14_metrics_and_other_codes_take_MissingWidth` | Table 109: FirstChar/LastChar/Widths with MissingWidth outside the range; missing FirstChar reads as 0, missing LastChar from the count, non-number elements take MissingWidth (FontWidthsInvalid); no Widths and not standard 14: widths 0 (FontWidthsMissing); a standard 14 font with some but not all four entries: FontStandard14EntriesIncomplete. text-standard14-widths.pdf | +| 9.6.2.2 | Standard Type 1 fonts (standard 14 fonts) (PDF 1.0-1.7) | done | `Standard14Font`, `Standard14Data`, `PdfFontDescriptor`, `PdfSimpleFont` | `Broadside.Tests.Fonts.Standard14FontTests.Text_standard14_pdf_gives_each_code_its_glyph_name_and_its_Helvetica_width`, `Broadside.Tests.Fonts.Standard14MetricsTests.Every_glyph_of_every_font_has_its_AFM_width`, `Broadside.Tests.Fonts.Standard14MetricsTests.A_font_without_a_descriptor_gets_one_synthesized_from_its_AFM_file`, `Broadside.Tests.Fonts.Standard14MetricsTests.Synthesized_flags_follow_the_AFM_files`, `Broadside.Tests.Fonts.FontModelTests.A_non_embedded_font_named_after_a_standard_14_font_takes_its_metrics`, `Broadside.Tests.Fonts.FontModelTests.Fonts_whose_metrics_differ_from_the_standard_14_are_not_matched`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.A_non_embedded_Arial_bold_takes_the_Helvetica_bold_metrics_with_an_information_diagnostic`, `Broadside.Tests.Fonts.RealWorldFontTests.Every_font_of_a_real_world_corpus_reads_leniently_without_an_exception` | Metrics of the Adobe Core 14 AFM files generated into the core (`src/Broadside/Fonts/Data/generate.py`; MustRead.html and THIRD-PARTY-NOTICES ship in the package); widths only, no per-glyph boxes or kerning. A non-embedded Type 1 or TrueType font matches by name after pdf.js normalization, with the pdf.js and PDFBox aliases (Arial, TimesNewRoman, CourierNew families; not Arial Narrow/Black/Unicode) as FontStandard14Alias (Information). .notdef is 250 (Courier 600) as in Acrobat; a name the AFM lacks is measured through its AGL/uniXXXX Unicode value, else 0 (FontGlyphMissing, Information). Descriptor synthesized from the AFM when absent. Glyph programs: #59 | +| 9.6.2.3 | Multiple master fonts | partial | `PdfType1Font` | `Broadside.Tests.Fonts.FontModelTests.A_multiple_master_instance_is_a_type_1_font` | MMType1 dictionaries read as Type 1 (`IsMultipleMaster`); the snapshot program is read with Type 1 programs (#52) | +| 9.6.3 | TrueType fonts | partial | `PdfTrueTypeFont` | `Broadside.Tests.Fonts.FontModelTests.The_subtype_selects_the_type_of_the_view`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.A_non_embedded_Arial_bold_takes_the_Helvetica_bold_metrics_with_an_information_diagnostic` | Dictionary view, widths and encoding names; the program and glyph selection are #50 | +| 9.6.4 | Type 3 fonts | partial | `PdfType3Font` | `Broadside.Tests.Fonts.EncodingTests.A_type_3_font_has_only_the_glyph_names_its_encoding_dictionary_gives` | Dictionary view with Widths (glyph space) and the encoding; FontMatrix, CharProcs and Resources are #57 | +| 9.6.5.1 | General | done | `SimpleFontMetrics`, `GlyphNameTable`, `BuiltInEncoding` | `Broadside.Tests.Fonts.SimpleFontCorpusTests.Differences_without_a_base_encoding_change_StandardEncoding_for_a_nonsymbolic_font`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.Differences_on_the_Symbol_font_apply_to_its_built_in_encoding`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.The_Symbol_font_uses_its_built_in_encoding_and_ignores_a_named_encoding`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.A_symbolic_font_without_its_program_or_an_encoding_reads_names_from_StandardEncoding_with_a_diagnostic`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.Strict_mode_does_not_reject_the_compatibility_choices_on_legal_files`, `Broadside.Tests.Fonts.EncodingTests.Differences_take_codes_as_integers_or_whole_reals_and_later_runs_win`, `Broadside.Tests.Fonts.EncodingTests.Malformed_differences_are_skipped_with_a_diagnostic`, `Broadside.Tests.Fonts.EncodingTests.An_encoding_dictionary_with_a_base_encoding_applies_its_differences_to_it`, `Broadside.Tests.Fonts.EncodingTests.StandardEncoding_by_name_is_used_with_a_diagnostic_since_it_is_not_a_predefined_name`, `Broadside.Tests.Fonts.EncodingTests.An_unknown_or_malformed_encoding_falls_back_to_the_built_in_encoding_with_a_diagnostic`, `Broadside.Tests.Fonts.WidthTests.Glyph_names_follow_changes_to_the_differences_array` | Table 112: named encodings and encoding dictionaries; default base StandardEncoding for nonsymbolic, built-in for symbolic or embedded (Symbolic from the descriptor, or from the AFM for a standard 14 font without one); Differences runs in any order, later wins; /StandardEncoding accepted (FontEncodingInvalid), other names fall back to the built-in encoding; a named or base encoding on non-embedded Symbol/ZapfDingbats is ignored (FontEncodingIgnored, Information, as pdf.js); a non-embedded symbolic font that is not standard 14 uses StandardEncoding (FontBuiltInEncodingUnavailable, Information) | +| 9.6.5.2 | Encodings for Type 1 fonts | partial | `SimpleFontMetrics`, `Standard14Data` | `Broadside.Tests.Fonts.Standard14MetricsTests.Without_an_encoding_each_code_has_the_glyph_the_AFM_file_encodes_and_other_codes_are_notdef`, `Broadside.Tests.Fonts.EncodingTests.An_embedded_font_without_an_encoding_uses_StandardEncoding_until_its_program_is_read`, `Broadside.Tests.Fonts.EncodingTests.A_glyph_name_the_metrics_do_not_use_is_measured_through_its_Unicode_value` | Encoding overrides the built-in encoding; codes without a name are .notdef. The built-in encoding of an embedded program is not read yet: StandardEncoding stands in (FontBuiltInEncodingUnavailable, Information) until #51/#52 supply it through `PdfSimpleFont.GetProgramEncoding` | +| 9.6.5.3 | Encodings for Type 3 fonts | partial | `PdfType3Font`, `SimpleFontMetrics` | `Broadside.Tests.Fonts.EncodingTests.A_type_3_font_has_only_the_glyph_names_its_encoding_dictionary_gives`, `Broadside.Tests.Fonts.EncodingTests.A_type_3_font_without_an_encoding_dictionary_has_no_glyph_names_and_a_diagnostic` | Names from the encoding dictionary (Differences over a valid BaseEncoding); CharProcs lookup is #57 | +| 9.6.5.4 | Encodings for TrueType fonts | not started | | | #50. The Mac OS Roman table of Table 113 (`BuiltInEncoding.MacOSRoman`) and the Adobe Glyph List (`AdobeGlyphList`) it needs ship in the core with #49 | | 9.7 | Composite fonts | not started | | | | -| 9.8 | Font descriptors | not started | | | | +| 9.8.1 | General | done | `PdfFontDescriptor`, `SimpleFontMetrics` | `Broadside.Tests.Fonts.FontModelTests.The_descriptor_view_reads_every_entry_of_table_120`, `Broadside.Tests.Fonts.FontModelTests.Optional_descriptor_entries_default_and_the_view_follows_changes`, `Broadside.Tests.Fonts.FontModelTests.A_descriptor_missing_required_entries_or_with_two_programs_is_reported_once`, `Broadside.Tests.Fonts.Standard14MetricsTests.A_font_without_a_descriptor_gets_one_synthesized_from_its_AFM_file` | Every Table 120 entry as a live property with the table's defaults; FontDescriptorInvalid (once per descriptor, on the font) for a wrong Type, missing or malformed Flags/FontBBox/ItalicAngle/Ascent/Descent/StemV (ItalicAngle only for Type 3), or more than one FontFile*; `IsEmbedded` from FontFile/FontFile2/FontFile3 | +| 9.8.2 | Font descriptor flags | done | `PdfFontFlags`, `PdfFontDescriptor` | `Broadside.Tests.Fonts.FontModelTests.The_descriptor_view_reads_every_entry_of_table_120`, `Broadside.Tests.Fonts.Standard14MetricsTests.Synthesized_flags_follow_the_AFM_files`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.Differences_on_the_Symbol_font_apply_to_its_built_in_encoding` | Table 121 bits; the Symbolic flag decides the default base encoding (Symbolic wins when both are set); a non-integer Flags reads as none | +| 9.8.3 | Font descriptors for CIDFonts | not started | | | CIDFont ticket (#53) | | 9.9 | Embedded font programs | not started | | | | | 9.10 | Extraction of text content | not started | | | | | 10.1 | Rendering: General | not started | | | | @@ -137,7 +148,12 @@ Clause numbers at the second level; split rows to the third level as clauses are | Annex A | Operator summary | not started | | | | | Annex B | Operators in Type 4 functions | not started | | | | | Annex C | Advice on maximising portability | not started | | | | -| Annex D | Character sets and encodings | partial | `CosString` | `Broadside.Tests.Objects.TextStringTests.Decodes_pdfdocencoding_when_there_is_no_byte_order_marker` | D.3 PDFDocEncoding decodes text strings; the font encodings of D.2 and D.4 to D.6 pending | +| D.1 | General | done | `GlyphNameTable`, `BuiltInEncoding` | `Broadside.Tests.Fonts.EncodingTests.A_predefined_encoding_gives_the_name_annex_D_lists`, `Broadside.Tests.Fonts.EncodingTests.StandardEncoding_by_name_is_used_with_a_diagnostic_since_it_is_not_a_predefined_name` | Table D.1: MacRomanEncoding, WinAnsiEncoding and MacExpertEncoding are the predefined names; StandardEncoding is the default base, not a name | +| D.2 | Latin character set and encodings | done | `GlyphNameTable`, `Standard14Data` | `Broadside.Tests.Fonts.EncodingTests.A_predefined_encoding_gives_the_name_annex_D_lists`, `Broadside.Tests.Fonts.Standard14MetricsTests.Without_an_encoding_each_code_has_the_glyph_the_AFM_file_encodes_and_other_codes_are_notdef`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.WinAnsiEncoding_applies_the_notes_of_table_D2`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.MacRomanEncoding_is_table_D2_and_not_Mac_OS_Roman`, `Broadside.Tests.Fonts.EncodingTests.The_example_of_annex_D_maps_codes_to_the_no_break_space_and_soft_hyphen_names_whose_widths_are_the_space_and_hyphen` | STD/MAC/WIN columns with notes 1-6 (WinAnsi 224 codes incl. bullet at unused codes, MacRoman 208 incl. 0xCA space) in `src/Broadside/Fonts/Data/encodings.txt`; STD equals the AFM C codes; equal to pdf.js except MacRoman, where pdf.js mixes in Table 113. The PDF column is D.3 | +| D.3 | PDFDocEncoding character set | done | `CosString`, `TextStringDecoder` | `Broadside.Tests.Objects.TextStringTests.Decodes_pdfdocencoding_when_there_is_no_byte_order_marker` | Text strings only; never used for fonts | +| D.4 | Expert set and MacExpert encoding | done | `GlyphNameTable` | `Broadside.Tests.Fonts.EncodingTests.A_predefined_encoding_gives_the_name_annex_D_lists` | 165 codes; no standard 14 font has the expert set, so their widths are 0 there (FontGlyphMissing, Information) | +| D.5 | Symbol set and encoding | done | `GlyphNameTable`, `Standard14Data` | `Broadside.Tests.Fonts.Standard14MetricsTests.Without_an_encoding_each_code_has_the_glyph_the_AFM_file_encodes_and_other_codes_are_notdef`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.The_Symbol_font_uses_its_built_in_encoding_and_ignores_a_named_encoding` | 189 codes, generated from the Symbol AFM C codes (equal to Table D.5 and pdf.js) | +| D.6 | ZapfDingbats set and encoding | done | `GlyphNameTable`, `Standard14Data` | `Broadside.Tests.Fonts.Standard14MetricsTests.Without_an_encoding_each_code_has_the_glyph_the_AFM_file_encodes_and_other_codes_are_notdef`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.The_ZapfDingbats_font_encodes_the_codes_its_metrics_list_beyond_table_D6` | 202 codes from the ZapfDingbats AFM C codes: Table D.6 omits 0x80-0x8D (a89 a90 a93 a94 a91 a92 a205 a85 a206 a86 a87 a88 a95 a96), which the AFM, pdf.js and PDFBox encode; text-standard14-zapfdingbats.pdf | | Annex E | Extending PDF | not started | | | | | F.1 | General | n/a | | | Introductory text | | F.2 | Background and assumptions | n/a | | | Informative background | diff --git a/src/Broadside/Broadside.csproj b/src/Broadside/Broadside.csproj index a10d20e5..ebe14edc 100644 --- a/src/Broadside/Broadside.csproj +++ b/src/Broadside/Broadside.csproj @@ -9,6 +9,12 @@ true + + + + + + diff --git a/src/Broadside/Fonts/AdobeGlyphList.cs b/src/Broadside/Fonts/AdobeGlyphList.cs new file mode 100644 index 00000000..2bc76381 --- /dev/null +++ b/src/Broadside/Fonts/AdobeGlyphList.cs @@ -0,0 +1,119 @@ +using System.Buffers; +using System.Globalization; +using System.Text; + +namespace Broadside.Fonts; + +/// Glyph name to Unicode, through the Adobe Glyph List, the ITC Zapf Dingbats Glyph List and the uniXXXX/uXXXX forms. +/// +/// The data is in AdobeGlyphList.g.cs. The lookups allocate nothing. The full AGL specification algorithm (components joined by +/// underscores, suffixes after a period) is not applied here; a name either is in a list or has one of the two numeric forms. +/// +internal static partial class AdobeGlyphList +{ + /// Looks up a glyph name's Unicode value. + /// The glyph name. + /// Whether to look in the ITC Zapf Dingbats list (names a1 to a191) first. + /// The Unicode value: one or more UTF-16 code units. + /// when the name has a value. + public static bool TryGetUnicode(ReadOnlySpan name, bool zapfDingbats, out ReadOnlySpan value) + { + if (zapfDingbats && TryFind(name, ZapfNames, ZapfNameOffsets, ZapfValues, ZapfValueOffsets, ZapfCount, out value)) + { + return true; + } + + if (TryFind(name, AglNames, AglNameOffsets, AglValues, AglValueOffsets, AglCount, out value)) + { + return true; + } + + value = default; + return false; + } + + /// Looks up a glyph name's single Unicode scalar value: from a list, or from a uniXXXX or uXXXX–uXXXXXX name. + /// The glyph name. + /// Whether to look in the ITC Zapf Dingbats list first. + /// The scalar value. + /// when the name stands for exactly one scalar value. + public static bool TryGetScalar(ReadOnlySpan name, bool zapfDingbats, out int scalar) + { + scalar = 0; + if (TryGetUnicode(name, zapfDingbats, out ReadOnlySpan value)) + { + if (Rune.DecodeFromUtf16(value, out Rune rune, out int consumed) != OperationStatus.Done || consumed != value.Length) + { + return false; + } + + scalar = rune.Value; + return true; + } + + // "uni" followed by exactly four uppercase hexadecimal digits, not a surrogate; "u" followed by four to six. + if (name.Length == 7 && name.StartsWith("uni", StringComparison.Ordinal)) + { + return TryParseHex(name[3..], out scalar) && !IsSurrogate(scalar); + } + + if (name.Length is >= 5 and <= 7 && name[0] == 'u') + { + return TryParseHex(name[1..], out scalar) && !IsSurrogate(scalar) && scalar <= 0x10FFFF; + } + + return false; + } + + private static bool IsSurrogate(int value) => value is >= 0xD800 and <= 0xDFFF; + + private static bool TryParseHex(ReadOnlySpan digits, out int value) + { + foreach (char digit in digits) + { + if (!char.IsAsciiHexDigitUpper(digit) && !char.IsAsciiDigit(digit)) + { + value = 0; + return false; + } + } + + return int.TryParse(digits, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out value); + } + + private static bool TryFind( + ReadOnlySpan name, + string names, + ReadOnlySpan nameOffsets, + string values, + ReadOnlySpan valueOffsets, + int count, + out ReadOnlySpan value) + { + int low = 0; + int high = count - 1; + while (low <= high) + { + int middle = low + ((high - low) >> 1); + ReadOnlySpan candidate = names.AsSpan(nameOffsets[middle], nameOffsets[middle + 1] - nameOffsets[middle]); + int order = candidate.SequenceCompareTo(name); + if (order == 0) + { + value = values.AsSpan(valueOffsets[middle], valueOffsets[middle + 1] - valueOffsets[middle]); + return true; + } + + if (order < 0) + { + low = middle + 1; + } + else + { + high = middle - 1; + } + } + + value = default; + return false; + } +} diff --git a/src/Broadside/Fonts/AdobeGlyphList.g.cs b/src/Broadside/Fonts/AdobeGlyphList.g.cs new file mode 100644 index 00000000..cf20f7a6 --- /dev/null +++ b/src/Broadside/Fonts/AdobeGlyphList.g.cs @@ -0,0 +1,1268 @@ +// +// Generated by src/Broadside/Fonts/Data/generate.py. Do not edit; edit the generator or its inputs and re-run it. +// +// Derived from the Adobe Glyph List and the ITC Zapf Dingbats Glyph List (https://github.com/adobe-type-tools/agl-aglfn, +// commit 4036a9ca80a62f64f9de4f7321a9a045ad0ecfd6), converted to C# tables. +// +// Copyright 2002-2019 Adobe (http://www.adobe.com/). +// +// Redistribution and use in source and binary forms, with or without modification, are permitted provided that +// the following conditions are met: +// +// Redistributions of source code must retain the above copyright notice, this list of conditions and the +// following disclaimer. +// +// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the +// following disclaimer in the documentation and/or other materials provided with the distribution. +// +// Neither the name of Adobe nor the names of its contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED +// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY +// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// + +namespace Broadside.Fonts; + +/// The Adobe Glyph List and the ITC Zapf Dingbats Glyph List: glyph name to Unicode. +/// ISO 32000-2 §9.10.2 refers to the Adobe Glyph List for mapping glyph names to Unicode. +internal static partial class AdobeGlyphList +{ + private const int AglCount = 4281; + + /// The glyph names, ordinal order, concatenated. + private const string AglNames = + "AAEAEacuteAEmacronAEsmallAacuteAacutesmallAbreveAbreveacuteAbrevecyrillicAbreved" + + "otbelowAbrevegraveAbrevehookaboveAbrevetildeAcaronAcircleAcircumflexAcircumflexa" + + "cuteAcircumflexdotbelowAcircumflexgraveAcircumflexhookaboveAcircumflexsmallAcirc" + + "umflextildeAcuteAcutesmallAcyrillicAdblgraveAdieresisAdieresiscyrillicAdieresism" + + "acronAdieresissmallAdotbelowAdotmacronAgraveAgravesmallAhookaboveAiecyrillicAinv" + + "ertedbreveAlphaAlphatonosAmacronAmonospaceAogonekAringAringacuteAringbelowArings" + + "mallAsmallAtildeAtildesmallAybarmenianBBcircleBdotaccentBdotbelowBecyrillicBenar" + + "menianBetaBhookBlinebelowBmonospaceBrevesmallBsmallBtopbarCCaarmenianCacuteCaron" + + "CaronsmallCcaronCcedillaCcedillaacuteCcedillasmallCcircleCcircumflexCdotCdotacce" + + "ntCedillasmallChaarmenianCheabkhasiancyrillicChecyrillicChedescenderabkhasiancyr" + + "illicChedescendercyrillicChedieresiscyrillicCheharmenianChekhakassiancyrillicChe" + + "verticalstrokecyrillicChiChookCircumflexsmallCmonospaceCoarmenianCsmallDDZDZcaro" + + "nDaarmenianDafricanDcaronDcedillaDcircleDcircumflexbelowDcroatDdotaccentDdotbelo" + + "wDecyrillicDeicopticDeltaDeltagreekDhookDieresisDieresisAcuteDieresisGraveDieres" + + "issmallDigammagreekDjecyrillicDlinebelowDmonospaceDotaccentsmallDslashDsmallDtop" + + "barDzDzcaronDzeabkhasiancyrillicDzecyrillicDzhecyrillicEEacuteEacutesmallEbreveE" + + "caronEcedillabreveEcharmenianEcircleEcircumflexEcircumflexacuteEcircumflexbelowE" + + "circumflexdotbelowEcircumflexgraveEcircumflexhookaboveEcircumflexsmallEcircumfle" + + "xtildeEcyrillicEdblgraveEdieresisEdieresissmallEdotEdotaccentEdotbelowEfcyrillic" + + "EgraveEgravesmallEharmenianEhookaboveEightromanEinvertedbreveEiotifiedcyrillicEl" + + "cyrillicElevenromanEmacronEmacronacuteEmacrongraveEmcyrillicEmonospaceEncyrillic" + + "EndescendercyrillicEngEnghecyrillicEnhookcyrillicEogonekEopenEpsilonEpsilontonos" + + "ErcyrillicEreversedEreversedcyrillicEscyrillicEsdescendercyrillicEshEsmallEtaEta" + + "rmenianEtatonosEthEthsmallEtildeEtildebelowEuroEzhEzhcaronEzhreversedFFcircleFdo" + + "taccentFeharmenianFeicopticFhookFitacyrillicFiveromanFmonospaceFourromanFsmallGG" + + "BsquareGacuteGammaGammaafricanGangiacopticGbreveGcaronGcedillaGcircleGcircumflex" + + "GcommaaccentGdotGdotaccentGecyrillicGhadarmenianGhemiddlehookcyrillicGhestrokecy" + + "rillicGheupturncyrillicGhookGimarmenianGjecyrillicGmacronGmonospaceGraveGravesma" + + "llGsmallGsmallhookGstrokeHH18533H18543H18551H22073HPsquareHaabkhasiancyrillicHad" + + "escendercyrillicHardsigncyrillicHbarHbrevebelowHcedillaHcircleHcircumflexHdieres" + + "isHdotaccentHdotbelowHmonospaceHoarmenianHoricopticHsmallHungarumlautHungarumlau" + + "tsmallHzsquareIIAcyrillicIJIUcyrillicIacuteIacutesmallIbreveIcaronIcircleIcircum" + + "flexIcircumflexsmallIcyrillicIdblgraveIdieresisIdieresisacuteIdieresiscyrillicId" + + "ieresissmallIdotIdotaccentIdotbelowIebrevecyrillicIecyrillicIfrakturIgraveIgrave" + + "smallIhookaboveIicyrillicIinvertedbreveIishortcyrillicImacronImacroncyrillicImon" + + "ospaceIniarmenianIocyrillicIogonekIotaIotaafricanIotadieresisIotatonosIsmallIstr" + + "okeItildeItildebelowIzhitsacyrillicIzhitsadblgravecyrillicJJaarmenianJcircleJcir" + + "cumflexJecyrillicJheharmenianJmonospaceJsmallKKBsquareKKsquareKabashkircyrillicK" + + "acuteKacyrillicKadescendercyrillicKahookcyrillicKappaKastrokecyrillicKaverticals" + + "trokecyrillicKcaronKcedillaKcircleKcommaaccentKdotbelowKeharmenianKenarmenianKha" + + "cyrillicKheicopticKhookKjecyrillicKlinebelowKmonospaceKoppacyrillicKoppagreekKsi" + + "cyrillicKsmallLLJLLLacuteLambdaLcaronLcedillaLcircleLcircumflexbelowLcommaaccent" + + "LdotLdotaccentLdotbelowLdotbelowmacronLiwnarmenianLjLjecyrillicLlinebelowLmonosp" + + "aceLslashLslashsmallLsmallMMBsquareMacronMacronsmallMacuteMcircleMdotaccentMdotb" + + "elowMenarmenianMmonospaceMsmallMturnedMuNNJNacuteNcaronNcedillaNcircleNcircumfle" + + "xbelowNcommaaccentNdotaccentNdotbelowNhookleftNineromanNjNjecyrillicNlinebelowNm" + + "onospaceNowarmenianNsmallNtildeNtildesmallNuOOEOEsmallOacuteOacutesmallObarredcy" + + "rillicObarreddieresiscyrillicObreveOcaronOcenteredtildeOcircleOcircumflexOcircum" + + "flexacuteOcircumflexdotbelowOcircumflexgraveOcircumflexhookaboveOcircumflexsmall" + + "OcircumflextildeOcyrillicOdblacuteOdblgraveOdieresisOdieresiscyrillicOdieresissm" + + "allOdotbelowOgoneksmallOgraveOgravesmallOharmenianOhmOhookaboveOhornOhornacuteOh" + + "orndotbelowOhorngraveOhornhookaboveOhorntildeOhungarumlautOiOinvertedbreveOmacro" + + "nOmacronacuteOmacrongraveOmegaOmegacyrillicOmegagreekOmegaroundcyrillicOmegatitl" + + "ocyrillicOmegatonosOmicronOmicrontonosOmonospaceOneromanOogonekOogonekmacronOope" + + "nOslashOslashacuteOslashsmallOsmallOstrokeacuteOtcyrillicOtildeOtildeacuteOtilde" + + "dieresisOtildesmallPPacutePcirclePdotaccentPecyrillicPeharmenianPemiddlehookcyri" + + "llicPhiPhookPiPiwrarmenianPmonospacePsiPsicyrillicPsmallQQcircleQmonospaceQsmall" + + "RRaarmenianRacuteRcaronRcedillaRcircleRcommaaccentRdblgraveRdotaccentRdotbelowRd" + + "otbelowmacronReharmenianRfrakturRhoRingsmallRinvertedbreveRlinebelowRmonospaceRs" + + "mallRsmallinvertedRsmallinvertedsuperiorSSF010000SF020000SF030000SF040000SF05000" + + "0SF060000SF070000SF080000SF090000SF100000SF110000SF190000SF200000SF210000SF22000" + + "0SF230000SF240000SF250000SF260000SF270000SF280000SF360000SF370000SF380000SF39000" + + "0SF400000SF410000SF420000SF430000SF440000SF450000SF460000SF470000SF480000SF49000" + + "0SF500000SF510000SF520000SF530000SF540000SacuteSacutedotaccentSampigreekScaronSc" + + "arondotaccentScaronsmallScedillaSchwaSchwacyrillicSchwadieresiscyrillicScircleSc" + + "ircumflexScommaaccentSdotaccentSdotbelowSdotbelowdotaccentSeharmenianSevenromanS" + + "haarmenianShacyrillicShchacyrillicSheicopticShhacyrillicShimacopticSigmaSixroman" + + "SmonospaceSoftsigncyrillicSsmallStigmagreekTTauTbarTcaronTcedillaTcircleTcircumf" + + "lexbelowTcommaaccentTdotaccentTdotbelowTecyrillicTedescendercyrillicTenromanTets" + + "ecyrillicThetaThookThornThornsmallThreeromanTildesmallTiwnarmenianTlinebelowTmon" + + "ospaceToarmenianTonefiveTonesixTonetwoTretroflexhookTsecyrillicTshecyrillicTsmal" + + "lTwelveromanTworomanUUacuteUacutesmallUbreveUcaronUcircleUcircumflexUcircumflexb" + + "elowUcircumflexsmallUcyrillicUdblacuteUdblgraveUdieresisUdieresisacuteUdieresisb" + + "elowUdieresiscaronUdieresiscyrillicUdieresisgraveUdieresismacronUdieresissmallUd" + + "otbelowUgraveUgravesmallUhookaboveUhornUhornacuteUhorndotbelowUhorngraveUhornhoo" + + "kaboveUhorntildeUhungarumlautUhungarumlautcyrillicUinvertedbreveUkcyrillicUmacro" + + "nUmacroncyrillicUmacrondieresisUmonospaceUogonekUpsilonUpsilon1Upsilonacutehooks" + + "ymbolgreekUpsilonafricanUpsilondieresisUpsilondieresishooksymbolgreekUpsilonhook" + + "symbolUpsilontonosUringUshortcyrillicUsmallUstraightcyrillicUstraightstrokecyril" + + "licUtildeUtildeacuteUtildebelowVVcircleVdotbelowVecyrillicVewarmenianVhookVmonos" + + "paceVoarmenianVsmallVtildeWWacuteWcircleWcircumflexWdieresisWdotaccentWdotbelowW" + + "graveWmonospaceWsmallXXcircleXdieresisXdotaccentXeharmenianXiXmonospaceXsmallYYa" + + "cuteYacutesmallYatcyrillicYcircleYcircumflexYdieresisYdieresissmallYdotaccentYdo" + + "tbelowYericyrillicYerudieresiscyrillicYgraveYhookYhookaboveYiarmenianYicyrillicY" + + "iwnarmenianYmonospaceYsmallYtildeYusbigcyrillicYusbigiotifiedcyrillicYuslittlecy" + + "rillicYuslittleiotifiedcyrillicZZaarmenianZacuteZcaronZcaronsmallZcircleZcircumf" + + "lexZdotZdotaccentZdotbelowZecyrillicZedescendercyrillicZedieresiscyrillicZetaZhe" + + "armenianZhebrevecyrillicZhecyrillicZhedescendercyrillicZhedieresiscyrillicZlineb" + + "elowZmonospaceZsmallZstrokeaaabengaliaacuteaadevaaagujaratiaagurmukhiaamatragurm" + + "ukhiaarusquareaavowelsignbengaliaavowelsigndevaaavowelsigngujaratiabbreviationma" + + "rkarmenianabbreviationsigndevaabengaliabopomofoabreveabreveacuteabrevecyrillicab" + + "revedotbelowabrevegraveabrevehookaboveabrevetildeacaronacircleacircumflexacircum" + + "flexacuteacircumflexdotbelowacircumflexgraveacircumflexhookaboveacircumflextilde" + + "acuteacutebelowcmbacutecmbacutecombacutedevaacutelowmodacutetonecmbacyrillicadbl" + + "graveaddakgurmukhiadevaadieresisadieresiscyrillicadieresismacronadotbelowadotmac" + + "ronaeaeacuteaekoreanaemacronafii00208afii08941afii10017afii10018afii10019afii100" + + "20afii10021afii10022afii10023afii10024afii10025afii10026afii10027afii10028afii10" + + "029afii10030afii10031afii10032afii10033afii10034afii10035afii10036afii10037afii1" + + "0038afii10039afii10040afii10041afii10042afii10043afii10044afii10045afii10046afii" + + "10047afii10048afii10049afii10050afii10051afii10052afii10053afii10054afii10055afi" + + "i10056afii10057afii10058afii10059afii10060afii10061afii10062afii10063afii10064af" + + "ii10065afii10066afii10067afii10068afii10069afii10070afii10071afii10072afii10073a" + + "fii10074afii10075afii10076afii10077afii10078afii10079afii10080afii10081afii10082" + + "afii10083afii10084afii10085afii10086afii10087afii10088afii10089afii10090afii1009" + + "1afii10092afii10093afii10094afii10095afii10096afii10097afii10098afii10099afii101" + + "00afii10101afii10102afii10103afii10104afii10105afii10106afii10107afii10108afii10" + + "109afii10110afii10145afii10146afii10147afii10148afii10192afii10193afii10194afii1" + + "0195afii10196afii10831afii10832afii10846afii299afii300afii301afii57381afii57388a" + + "fii57392afii57393afii57394afii57395afii57396afii57397afii57398afii57399afii57400" + + "afii57401afii57403afii57407afii57409afii57410afii57411afii57412afii57413afii5741" + + "4afii57415afii57416afii57417afii57418afii57419afii57420afii57421afii57422afii574" + + "23afii57424afii57425afii57426afii57427afii57428afii57429afii57430afii57431afii57" + + "432afii57433afii57434afii57440afii57441afii57442afii57443afii57444afii57445afii5" + + "7446afii57448afii57449afii57450afii57451afii57452afii57453afii57454afii57455afii" + + "57456afii57457afii57458afii57470afii57505afii57506afii57507afii57508afii57509afi" + + "i57511afii57512afii57513afii57514afii57519afii57534afii57636afii57645afii57658af" + + "ii57664afii57665afii57666afii57667afii57668afii57669afii57670afii57671afii57672a" + + "fii57673afii57674afii57675afii57676afii57677afii57678afii57679afii57680afii57681" + + "afii57682afii57683afii57684afii57685afii57686afii57687afii57688afii57689afii5769" + + "0afii57694afii57695afii57700afii57705afii57716afii57717afii57718afii57723afii577" + + "93afii57794afii57795afii57796afii57797afii57798afii57799afii57800afii57801afii57" + + "802afii57803afii57804afii57806afii57807afii57839afii57841afii57842afii57929afii6" + + "1248afii61289afii61352afii61573afii61574afii61575afii61664afii63167afii64937agra" + + "veagujaratiagurmukhiahiraganaahookaboveaibengaliaibopomofoaidevaaiecyrillicaiguj" + + "aratiaigurmukhiaimatragurmukhiainarabicainfinalarabicaininitialarabicainmedialar" + + "abicainvertedbreveaivowelsignbengaliaivowelsigndevaaivowelsigngujaratiakatakanaa" + + "katakanahalfwidthakoreanalefalefarabicalefdageshhebrewaleffinalarabicalefhamzaab" + + "ovearabicalefhamzaabovefinalarabicalefhamzabelowarabicalefhamzabelowfinalarabica" + + "lefhebrewaleflamedhebrewalefmaddaabovearabicalefmaddaabovefinalarabicalefmaksura" + + "arabicalefmaksurafinalarabicalefmaksurainitialarabicalefmaksuramedialarabicalefp" + + "atahhebrewalefqamatshebrewalephallequalalphaalphatonosamacronamonospaceampersand" + + "ampersandmonospaceampersandsmallamsquareanbopomofoangbopomofoangkhankhuthaiangle" + + "anglebracketleftanglebracketleftverticalanglebracketrightanglebracketrightvertic" + + "alangleleftanglerightangstromanoteleiaanudattadevaanusvarabengalianusvaradevaanu" + + "svaragujaratiaogonekapaatosquareaparenapostrophearmenianapostrophemodappleapproa" + + "chesapproxequalapproxequalorimageapproximatelyequalaraeaekoreanaraeakoreanarcari" + + "ghthalfringaringaringacutearingbelowarrowbotharrowdashdownarrowdashleftarrowdash" + + "rightarrowdashuparrowdblbotharrowdbldownarrowdblleftarrowdblrightarrowdbluparrow" + + "downarrowdownleftarrowdownrightarrowdownwhitearrowheaddownmodarrowheadleftmodarr" + + "owheadrightmodarrowheadupmodarrowhorizexarrowleftarrowleftdblarrowleftdblstrokea" + + "rrowleftoverrightarrowleftwhitearrowrightarrowrightdblstrokearrowrightheavyarrow" + + "rightoverleftarrowrightwhitearrowtableftarrowtabrightarrowuparrowupdnarrowupdnbs" + + "earrowupdownbasearrowupleftarrowupleftofdownarrowuprightarrowupwhitearrowvertexa" + + "sciicircumasciicircummonospaceasciitildeasciitildemonospaceascriptascriptturneda" + + "smallhiraganaasmallkatakanaasmallkatakanahalfwidthasteriskasteriskaltonearabicas" + + "teriskarabicasteriskmathasteriskmonospaceasterisksmallasterismasuperiorasymptoti" + + "callyequalatatildeatmonospaceatsmallaturnedaubengaliaubopomofoaudevaaugujaratiau" + + "gurmukhiaulengthmarkbengaliaumatragurmukhiauvowelsignbengaliauvowelsigndevaauvow" + + "elsigngujaratiavagrahadevaaybarmenianayinayinaltonehebrewayinhebrewbbabengalibac" + + "kslashbackslashmonospacebadevabagujaratibagurmukhibahiraganabahtthaibakatakanaba" + + "rbarmonospacebbopomofobcirclebdotaccentbdotbelowbeamedsixteenthnotesbecausebecyr" + + "illicbeharabicbehfinalarabicbehinitialarabicbehiraganabehmedialarabicbehmeeminit" + + "ialarabicbehmeemisolatedarabicbehnoonfinalarabicbekatakanabenarmenianbetbetabeta" + + "symbolgreekbetdageshbetdageshhebrewbethebrewbetrafehebrewbhabengalibhadevabhaguj" + + "aratibhagurmukhibhookbihiraganabikatakanabilabialclickbindigurmukhibirusquarebla" + + "ckcircleblackdiamondblackdownpointingtriangleblackleftpointingpointerblackleftpo" + + "intingtriangleblacklenticularbracketleftblacklenticularbracketleftverticalblackl" + + "enticularbracketrightblacklenticularbracketrightverticalblacklowerlefttrianglebl" + + "acklowerrighttriangleblackrectangleblackrightpointingpointerblackrightpointingtr" + + "iangleblacksmallsquareblacksmilingfaceblacksquareblackstarblackupperlefttriangle" + + "blackupperrighttriangleblackuppointingsmalltriangleblackuppointingtriangleblankb" + + "linebelowblockbmonospacebobaimaithaibohiraganabokatakanabparenbqsquarebraceexbra" + + "celeftbraceleftbtbraceleftmidbraceleftmonospacebraceleftsmallbracelefttpbracelef" + + "tverticalbracerightbracerightbtbracerightmidbracerightmonospacebracerightsmallbr" + + "acerighttpbracerightverticalbracketleftbracketleftbtbracketleftexbracketleftmono" + + "spacebracketlefttpbracketrightbracketrightbtbracketrightexbracketrightmonospaceb" + + "racketrighttpbrevebrevebelowcmbbrevecmbbreveinvertedbelowcmbbreveinvertedcmbbrev" + + "einverteddoublecmbbridgebelowcmbbridgeinvertedbelowcmbbrokenbarbstrokebsuperiorb" + + "topbarbuhiraganabukatakanabulletbulletinversebulletoperatorbullseyeccaarmenianca" + + "bengalicacutecadevacagujaraticagurmukhicalsquarecandrabindubengalicandrabinducmb" + + "candrabindudevacandrabindugujaraticapslockcareofcaroncaronbelowcmbcaroncmbcarria" + + "gereturncbopomofoccaronccedillaccedillaacuteccircleccircumflexccurlcdotcdotaccen" + + "tcdsquarecedillacedillacmbcentcentigradecentinferiorcentmonospacecentoldstylecen" + + "tsuperiorchaarmenianchabengalichadevachagujaratichagurmukhichbopomofocheabkhasia" + + "ncyrilliccheckmarkchecyrillicchedescenderabkhasiancyrillicchedescendercyrillicch" + + "edieresiscyrilliccheharmenianchekhakassiancyrilliccheverticalstrokecyrillicchich" + + "ieuchacirclekoreanchieuchaparenkoreanchieuchcirclekoreanchieuchkoreanchieuchpare" + + "nkoreanchochangthaichochanthaichochingthaichochoethaichookcieucacirclekoreancieu" + + "caparenkoreancieuccirclekoreancieuckoreancieucparenkoreancieucuparenkoreancircle" + + "circlemultiplycircleotcirclepluscirclepostalmarkcirclewithlefthalfblackcirclewit" + + "hrighthalfblackcircumflexcircumflexbelowcmbcircumflexcmbclearclickalveolarclickd" + + "entalclicklateralclickretroflexclubclubsuitblackclubsuitwhitecmcubedsquarecmonos" + + "pacecmsquaredsquarecoarmeniancoloncolonmonetarycolonmonospacecolonsigncolonsmall" + + "colontriangularhalfmodcolontriangularmodcommacommaabovecmbcommaaboverightcmbcomm" + + "aaccentcommaarabiccommaarmeniancommainferiorcommamonospacecommareversedabovecmbc" + + "ommareversedmodcommasmallcommasuperiorcommaturnedabovecmbcommaturnedmodcompassco" + + "ngruentcontourintegralcontrolcontrolACKcontrolBELcontrolBScontrolCANcontrolCRcon" + + "trolDC1controlDC2controlDC3controlDC4controlDELcontrolDLEcontrolEMcontrolENQcont" + + "rolEOTcontrolESCcontrolETBcontrolETXcontrolFFcontrolFScontrolGScontrolHTcontrolL" + + "FcontrolNAKcontrolRScontrolSIcontrolSOcontrolSOTcontrolSTXcontrolSUBcontrolSYNco" + + "ntrolUScontrolVTcopyrightcopyrightsanscopyrightserifcornerbracketleftcornerbrack" + + "etlefthalfwidthcornerbracketleftverticalcornerbracketrightcornerbracketrighthalf" + + "widthcornerbracketrightverticalcorporationsquarecosquarecoverkgsquarecparencruze" + + "irocstretchedcurlyandcurlyorcurrencycyrBrevecyrFlexcyrbrevecyrflexddaarmeniandab" + + "engalidadarabicdadevadadfinalarabicdadinitialarabicdadmedialarabicdageshdageshhe" + + "brewdaggerdaggerdbldagujaratidagurmukhidahiraganadakatakanadalarabicdaletdaletda" + + "geshdaletdageshhebrewdalethatafpatahdalethatafpatahhebrewdalethatafsegoldalethat" + + "afsegolhebrewdalethebrewdalethiriqdalethiriqhebrewdaletholamdaletholamhebrewdale" + + "tpatahdaletpatahhebrewdaletqamatsdaletqamatshebrewdaletqubutsdaletqubutshebrewda" + + "letsegoldaletsegolhebrewdaletshevadaletshevahebrewdalettseredalettserehebrewdalf" + + "inalarabicdammaarabicdammalowarabicdammatanaltonearabicdammatanarabicdandadargah" + + "ebrewdargalefthebrewdasiapneumatacyrilliccmbdblGravedblanglebracketleftdblangleb" + + "racketleftverticaldblanglebracketrightdblanglebracketrightverticaldblarchinverte" + + "dbelowcmbdblarrowleftdblarrowrightdbldandadblgravedblgravecmbdblintegraldbllowli" + + "nedbllowlinecmbdbloverlinecmbdblprimemoddblverticalbardblverticallineabovecmbdbo" + + "pomofodbsquaredcarondcedilladcircledcircumflexbelowdcroatddabengaliddadevaddaguj" + + "aratiddagurmukhiddalarabicddalfinalarabicdddhadevaddhabengaliddhadevaddhagujarat" + + "iddhagurmukhiddotaccentddotbelowdecimalseparatorarabicdecimalseparatorpersiandec" + + "yrillicdegreedehihebrewdehiraganadeicopticdekatakanadeleteleftdeleterightdeltade" + + "ltaturneddenominatorminusonenumeratorbengalidezhdhabengalidhadevadhagujaratidhag" + + "urmukhidhookdialytikatonosdialytikatonoscmbdiamonddiamondsuitwhitedieresisdieres" + + "isacutedieresisbelowcmbdieresiscmbdieresisgravedieresistonosdihiraganadikatakana" + + "dittomarkdividedividesdivisionslashdjecyrillicdkshadedlinebelowdlsquaredmacrondm" + + "onospacednblockdochadathaidodekthaidohiraganadokatakanadollardollarinferiordolla" + + "rmonospacedollaroldstyledollarsmalldollarsuperiordongdorusquaredotaccentdotaccen" + + "tcmbdotbelowcmbdotbelowcombdotkatakanadotlessidotlessjdotlessjstrokehookdotmathd" + + "ottedcircledoubleyodpatahdoubleyodpatahhebrewdowntackbelowcmbdowntackmoddparends" + + "uperiordtaildtopbarduhiraganadukatakanadzdzaltonedzcarondzcurldzeabkhasiancyrill" + + "icdzecyrillicdzhecyrilliceeacuteearthebengaliebopomofoebreveecandradevaecandragu" + + "jaratiecandravowelsigndevaecandravowelsigngujaratiecaronecedillabreveecharmenian" + + "echyiwnarmenianecircleecircumflexecircumflexacuteecircumflexbelowecircumflexdotb" + + "elowecircumflexgraveecircumflexhookaboveecircumflextildeecyrillicedblgraveedevae" + + "dieresisedotedotaccentedotbeloweegurmukhieematragurmukhiefcyrillicegraveegujarat" + + "ieharmenianehbopomofoehiraganaehookaboveeibopomofoeighteightarabiceightbengaliei" + + "ghtcircleeightcircleinversesansserifeightdevaeighteencircleeighteenpareneighteen" + + "periodeightgujaratieightgurmukhieighthackarabiceighthangzhoueighthnotebeamedeigh" + + "tideographicpareneightinferioreightmonospaceeightoldstyleeightpareneightperiodei" + + "ghtpersianeightromaneightsuperioreightthaieinvertedbreveeiotifiedcyrillicekataka" + + "naekatakanahalfwidthekonkargurmukhiekoreanelcyrillicelementelevencircleelevenpar" + + "enelevenperiodelevenromanellipsisellipsisverticalemacronemacronacuteemacrongrave" + + "emcyrillicemdashemdashverticalemonospaceemphasismarkarmenianemptysetenbopomofoen" + + "cyrillicendashendashverticalendescendercyrillicengengbopomofoenghecyrillicenhook" + + "cyrillicenspaceeogonekeokoreaneopeneopenclosedeopenreversedeopenreversedclosedeo" + + "penreversedhookeparenepsilonepsilontonosequalequalmonospaceequalsmallequalsuperi" + + "orequivalenceerbopomofoercyrillicereversedereversedcyrillicescyrillicesdescender" + + "cyrillicesheshcurleshortdevaeshortvowelsigndevaeshreversedloopeshsquatreversedes" + + "mallhiraganaesmallkatakanaesmallkatakanahalfwidthestimatedesuperioretaetarmenian" + + "etatonosethetildeetildebelowetnahtafoukhhebrewetnahtafoukhlefthebrewetnahtahebre" + + "wetnahtalefthebreweturnedeukoreaneuroevowelsignbengalievowelsigndevaevowelsigngu" + + "jaratiexclamexclamarmenianexclamdblexclamdownexclamdownsmallexclammonospaceexcla" + + "msmallexistentialezhezhcaronezhcurlezhreversedezhtailffadevafagurmukhifahrenheit" + + "fathaarabicfathalowarabicfathatanarabicfbopomofofcirclefdotaccentfeharabicfeharm" + + "enianfehfinalarabicfehinitialarabicfehmedialarabicfeicopticfemaleffffifflfififte" + + "encirclefifteenparenfifteenperiodfiguredashfilledboxfilledrectfinalkaffinalkafda" + + "geshfinalkafdageshhebrewfinalkafhebrewfinalkafqamatsfinalkafqamatshebrewfinalkaf" + + "shevafinalkafshevahebrewfinalmemfinalmemhebrewfinalnunfinalnunhebrewfinalpefinal" + + "pehebrewfinaltsadifinaltsadihebrewfirsttonechinesefisheyefitacyrillicfivefiveara" + + "bicfivebengalifivecirclefivecircleinversesansseriffivedevafiveeighthsfivegujarat" + + "ifivegurmukhifivehackarabicfivehangzhoufiveideographicparenfiveinferiorfivemonos" + + "pacefiveoldstylefiveparenfiveperiodfivepersianfiveromanfivesuperiorfivethaiflflo" + + "rinfmonospacefmsquarefofanthaifofathaifongmanthaiforallfourfourarabicfourbengali" + + "fourcirclefourcircleinversesansseriffourdevafourgujaratifourgurmukhifourhackarab" + + "icfourhangzhoufourideographicparenfourinferiorfourmonospacefournumeratorbengalif" + + "ouroldstylefourparenfourperiodfourpersianfourromanfoursuperiorfourteencirclefour" + + "teenparenfourteenperiodfourthaifourthtonechinesefparenfractionfrancggabengaligac" + + "utegadevagafarabicgaffinalarabicgafinitialarabicgafmedialarabicgagujaratigagurmu" + + "khigahiraganagakatakanagammagammalatinsmallgammasuperiorgangiacopticgbopomofogbr" + + "evegcarongcedillagcirclegcircumflexgcommaaccentgdotgdotaccentgecyrillicgehiragan" + + "agekatakanageometricallyequalgereshaccenthebrewgereshhebrewgereshmuqdamhebrewger" + + "mandblsgershayimaccenthebrewgershayimhebrewgetamarkghabengalighadarmenianghadeva" + + "ghagujaratighagurmukhighainarabicghainfinalarabicghaininitialarabicghainmedialar" + + "abicghemiddlehookcyrillicghestrokecyrillicgheupturncyrillicghhadevaghhagurmukhig" + + "hookghzsquaregihiraganagikatakanagimarmeniangimelgimeldageshgimeldageshhebrewgim" + + "elhebrewgjecyrillicglottalinvertedstrokeglottalstopglottalstopinvertedglottalsto" + + "pmodglottalstopreversedglottalstopreversedmodglottalstopreversedsuperiorglottals" + + "topstrokeglottalstopstrokereversedgmacrongmonospacegohiraganagokatakanagparengpa" + + "squaregradientgravegravebelowcmbgravecmbgravecombgravedevagravelowmodgravemonosp" + + "acegravetonecmbgreatergreaterequalgreaterequalorlessgreatermonospacegreaterorequ" + + "ivalentgreaterorlessgreateroverequalgreatersmallgscriptgstrokeguhiraganaguillemo" + + "tleftguillemotrightguilsinglleftguilsinglrightgukatakanaguramusquaregysquarehhaa" + + "bkhasiancyrillichaaltonearabichabengalihadescendercyrillichadevahagujaratihagurm" + + "ukhihaharabichahfinalarabichahinitialarabichahiraganahahmedialarabichaitusquareh" + + "akatakanahakatakanahalfwidthhalantgurmukhihamzaarabichamzadammaarabichamzadammat" + + "anarabichamzafathaarabichamzafathatanarabichamzalowarabichamzalowkasraarabichamz" + + "alowkasratanarabichamzasukunarabichangulfillerhardsigncyrillicharpoonleftbarbuph" + + "arpoonrightbarbuphasquarehatafpatahhatafpatah16hatafpatah23hatafpatah2fhatafpata" + + "hhebrewhatafpatahnarrowhebrewhatafpatahquarterhebrewhatafpatahwidehebrewhatafqam" + + "atshatafqamats1bhatafqamats28hatafqamats34hatafqamatshebrewhatafqamatsnarrowhebr" + + "ewhatafqamatsquarterhebrewhatafqamatswidehebrewhatafsegolhatafsegol17hatafsegol2" + + "4hatafsegol30hatafsegolhebrewhatafsegolnarrowhebrewhatafsegolquarterhebrewhatafs" + + "egolwidehebrewhbarhbopomofohbrevebelowhcedillahcirclehcircumflexhdieresishdotacc" + + "enthdotbelowheheartheartsuitblackheartsuitwhitehedageshhedageshhebrewhehaltonear" + + "abicheharabichehebrewhehfinalaltonearabichehfinalalttwoarabichehfinalarabichehha" + + "mzaabovefinalarabichehhamzaaboveisolatedarabichehinitialaltonearabichehinitialar" + + "abichehiraganahehmedialaltonearabichehmedialarabicheiseierasquarehekatakanahekat" + + "akanahalfwidthhekutaarusquarehenghookherutusquarehethethebrewhhookhhooksuperiorh" + + "ieuhacirclekoreanhieuhaparenkoreanhieuhcirclekoreanhieuhkoreanhieuhparenkoreanhi" + + "hiraganahikatakanahikatakanahalfwidthhiriqhiriq14hiriq21hiriq2dhiriqhebrewhiriqn" + + "arrowhebrewhiriqquarterhebrewhiriqwidehebrewhlinebelowhmonospacehoarmenianhohipt" + + "haihohiraganahokatakanahokatakanahalfwidthholamholam19holam26holam32holamhebrewh" + + "olamnarrowhebrewholamquarterhebrewholamwidehebrewhonokhukthaihookabovecombhookcm" + + "bhookpalatalizedbelowcmbhookretroflexbelowcmbhoonsquarehoricoptichorizontalbarho" + + "rncmbhotspringshousehparenhsuperiorhturnedhuhiraganahuiitosquarehukatakanahukata" + + "kanahalfwidthhungarumlauthungarumlautcmbhvhyphenhypheninferiorhyphenmonospacehyp" + + "hensmallhyphensuperiorhyphentwoiiacuteiacyrillicibengaliibopomofoibreveicaronici" + + "rcleicircumflexicyrillicidblgraveideographearthcircleideographfirecircleideograp" + + "hicallianceparenideographiccallparenideographiccentrecircleideographiccloseideog" + + "raphiccommaideographiccommaleftideographiccongratulationparenideographiccorrectc" + + "ircleideographicearthparenideographicenterpriseparenideographicexcellentcircleid" + + "eographicfestivalparenideographicfinancialcircleideographicfinancialparenideogra" + + "phicfireparenideographichaveparenideographichighcircleideographiciterationmarkid" + + "eographiclaborcircleideographiclaborparenideographicleftcircleideographiclowcirc" + + "leideographicmedicinecircleideographicmetalparenideographicmoonparenideographicn" + + "ameparenideographicperiodideographicprintcircleideographicreachparenideographicr" + + "epresentparenideographicresourceparenideographicrightcircleideographicsecretcirc" + + "leideographicselfparenideographicsocietyparenideographicspaceideographicspecialp" + + "arenideographicstockparenideographicstudyparenideographicsunparenideographicsupe" + + "rviseparenideographicwaterparenideographicwoodparenideographiczeroideographmetal" + + "circleideographmooncircleideographnamecircleideographsuncircleideographwatercirc" + + "leideographwoodcircleidevaidieresisidieresisacuteidieresiscyrillicidotbelowiebre" + + "vecyrilliciecyrillicieungacirclekoreanieungaparenkoreanieungcirclekoreanieungkor" + + "eanieungparenkoreanigraveigujaratiigurmukhiihiraganaihookaboveiibengaliiicyrilli" + + "ciidevaiigujaratiiigurmukhiiimatragurmukhiiinvertedbreveiishortcyrilliciivowelsi" + + "gnbengaliiivowelsigndevaiivowelsigngujaratiijikatakanaikatakanahalfwidthikoreani" + + "ldeiluyhebrewimacronimacroncyrillicimageorapproximatelyequalimatragurmukhiimonos" + + "paceincrementinfinityiniarmenianintegralintegralbottomintegralbtintegralexintegr" + + "altopintegraltpintersectionintisquareinvbulletinvcircleinvsmilefaceiocyrilliciog" + + "onekiotaiotadieresisiotadieresistonosiotalatiniotatonosiparenirigurmukhiismallhi" + + "raganaismallkatakanaismallkatakanahalfwidthissharbengaliistrokeisuperioriteratio" + + "nhiraganaiterationkatakanaitildeitildebelowiubopomofoiucyrillicivowelsignbengali" + + "ivowelsigndevaivowelsigngujaratiizhitsacyrillicizhitsadblgravecyrillicjjaarmenia" + + "njabengalijadevajagujaratijagurmukhijbopomofojcaronjcirclejcircumflexjcrossedtai" + + "ljdotlessstrokejecyrillicjeemarabicjeemfinalarabicjeeminitialarabicjeemmedialara" + + "bicjeharabicjehfinalarabicjhabengalijhadevajhagujaratijhagurmukhijheharmenianjis" + + "jmonospacejparenjsuperiorkkabashkircyrillickabengalikacutekacyrillickadescenderc" + + "yrillickadevakafkafarabickafdageshkafdageshhebrewkaffinalarabickafhebrewkafiniti" + + "alarabickafmedialarabickafrafehebrewkagujaratikagurmukhikahiraganakahookcyrillic" + + "kakatakanakakatakanahalfwidthkappakappasymbolgreekkapyeounmieumkoreankapyeounphi" + + "euphkoreankapyeounpieupkoreankapyeounssangpieupkoreankaroriisquarekashidaautoara" + + "bickashidaautonosidebearingarabickasmallkatakanakasquarekasraarabickasratanarabi" + + "ckastrokecyrillickatahiraprolongmarkhalfwidthkaverticalstrokecyrillickbopomofokc" + + "alsquarekcaronkcedillakcirclekcommaaccentkdotbelowkeharmeniankehiraganakekatakan" + + "akekatakanahalfwidthkenarmeniankesmallkatakanakgreenlandickhabengalikhacyrillick" + + "hadevakhagujaratikhagurmukhikhaharabickhahfinalarabickhahinitialarabickhahmedial" + + "arabickheicoptickhhadevakhhagurmukhikhieukhacirclekoreankhieukhaparenkoreankhieu" + + "khcirclekoreankhieukhkoreankhieukhparenkoreankhokhaithaikhokhonthaikhokhuatthaik" + + "hokhwaithaikhomutthaikhookkhorakhangthaikhzsquarekihiraganakikatakanakikatakanah" + + "alfwidthkiroguramusquarekiromeetorusquarekirosquarekiyeokacirclekoreankiyeokapar" + + "enkoreankiyeokcirclekoreankiyeokkoreankiyeokparenkoreankiyeoksioskoreankjecyrill" + + "icklinebelowklsquarekmcubedsquarekmonospacekmsquaredsquarekohiraganakohmsquareko" + + "kaithaikokatakanakokatakanahalfwidthkooposquarekoppacyrillickoreanstandardsymbol" + + "koroniscmbkparenkpasquareksicyrillicktsquarekturnedkuhiraganakukatakanakukatakan" + + "ahalfwidthkvsquarekwsquarellabengalilacuteladevalagujaratilagurmukhilakkhangyaot" + + "hailamaleffinalarabiclamalefhamzaabovefinalarabiclamalefhamzaaboveisolatedarabic" + + "lamalefhamzabelowfinalarabiclamalefhamzabelowisolatedarabiclamalefisolatedarabic" + + "lamalefmaddaabovefinalarabiclamalefmaddaaboveisolatedarabiclamarabiclambdalambda" + + "strokelamedlameddageshlameddageshhebrewlamedhebrewlamedholamlamedholamdageshlame" + + "dholamdageshhebrewlamedholamhebrewlamfinalarabiclamhahinitialarabiclaminitialara" + + "biclamjeeminitialarabiclamkhahinitialarabiclamlamhehisolatedarabiclammedialarabi" + + "clammeemhahinitialarabiclammeeminitialarabiclammeemjeeminitialarabiclammeemkhahi" + + "nitialarabiclargecirclelbarlbeltlbopomofolcaronlcedillalcirclelcircumflexbelowlc" + + "ommaaccentldotldotaccentldotbelowldotbelowmacronleftangleabovecmblefttackbelowcm" + + "blesslessequallessequalorgreaterlessmonospacelessorequivalentlessorgreaterlessov" + + "erequallesssmalllezhlfblocklhookretroflexliraliwnarmenianljljecyrilliclllladeval" + + "lagujaratillinebelowllladevallvocalicbengalillvocalicdevallvocalicvowelsignbenga" + + "lillvocalicvowelsigndevalmiddletildelmonospacelmsquarelochulathailogicalandlogic" + + "alnotlogicalnotreversedlogicalorlolingthailongslowlinecenterlinelowlinecmblowlin" + + "edashedlozengelparenlslashlsquarelsuperiorltshadeluthailvocalicbengalilvocalicde" + + "valvocalicvowelsignbengalilvocalicvowelsigndevalxsquaremmabengalimacronmacronbel" + + "owcmbmacroncmbmacronlowmodmacronmonospacemacutemadevamagujaratimagurmukhimahapak" + + "hhebrewmahapakhlefthebrewmahiraganamaichattawalowleftthaimaichattawalowrightthai" + + "maichattawathaimaichattawaupperleftthaimaieklowleftthaimaieklowrightthaimaiektha" + + "imaiekupperleftthaimaihanakatleftthaimaihanakatthaimaitaikhuleftthaimaitaikhutha" + + "imaitholowleftthaimaitholowrightthaimaithothaimaithoupperleftthaimaitrilowleftth" + + "aimaitrilowrightthaimaitrithaimaitriupperleftthaimaiyamokthaimakatakanamakatakan" + + "ahalfwidthmalemansyonsquaremaqafhebrewmarsmasoracirclehebrewmasquarembopomofombs" + + "quaremcirclemcubedsquaremdotaccentmdotbelowmeemarabicmeemfinalarabicmeeminitiala" + + "rabicmeemmedialarabicmeemmeeminitialarabicmeemmeemisolatedarabicmeetorusquaremeh" + + "iraganameizierasquaremekatakanamekatakanahalfwidthmemmemdageshmemdageshhebrewmem" + + "hebrewmenarmenianmerkhahebrewmerkhakefulahebrewmerkhakefulalefthebrewmerkhalefth" + + "ebrewmhookmhzsquaremiddledotkatakanahalfwidthmiddotmieumacirclekoreanmieumaparen" + + "koreanmieumcirclekoreanmieumkoreanmieumpansioskoreanmieumparenkoreanmieumpieupko" + + "reanmieumsioskoreanmihiraganamikatakanamikatakanahalfwidthminusminusbelowcmbminu" + + "scircleminusmodminusplusminutemiribaarusquaremirisquaremlonglegturnedmlsquaremmc" + + "ubedsquaremmonospacemmsquaredsquaremohiraganamohmsquaremokatakanamokatakanahalfw" + + "idthmolsquaremomathaimoverssquaremoverssquaredsquaremparenmpasquaremssquaremsupe" + + "riormturnedmumu1muasquaremuchgreatermuchlessmufsquaremugreekmugsquaremuhiraganam" + + "ukatakanamukatakanahalfwidthmulsquaremultiplymumsquaremunahhebrewmunahlefthebrew" + + "musicalnotemusicalnotedblmusicflatsignmusicsharpsignmussquaremuvsquaremuwsquarem" + + "vmegasquaremvsquaremwmegasquaremwsquarennabengalinablanacutenadevanagujaratinagu" + + "rmukhinahiragananakatakananakatakanahalfwidthnapostrophenasquarenbopomofonbspace" + + "ncaronncedillancirclencircumflexbelowncommaaccentndotaccentndotbelownehiraganane" + + "katakananekatakanahalfwidthnewsheqelsignnfsquarengabengalingadevangagujaratingag" + + "urmukhingonguthainhiragananhookleftnhookretroflexnieunacirclekoreannieunaparenko" + + "reannieuncieuckoreannieuncirclekoreannieunhieuhkoreannieunkoreannieunpansioskore" + + "annieunparenkoreannieunsioskoreannieuntikeutkoreannihiragananikatakananikatakana" + + "halfwidthnikhahitleftthainikhahitthainineninearabicninebengalininecircleninecirc" + + "leinversesansserifninedevaninegujaratininegurmukhininehackarabicninehangzhounine" + + "ideographicparennineinferiorninemonospacenineoldstylenineparennineperiodninepers" + + "iannineromanninesuperiornineteencirclenineteenparennineteenperiodninethainjnjecy" + + "rillicnkatakanankatakanahalfwidthnlegrightlongnlinebelownmonospacenmsquarennaben" + + "galinnadevannagujaratinnagurmukhinnnadevanohiragananokatakananokatakanahalfwidth" + + "nonbreakingspacenonenthainonuthainoonarabicnoonfinalarabicnoonghunnaarabicnoongh" + + "unnafinalarabicnoonhehinitialarabicnooninitialarabicnoonjeeminitialarabicnoonjee" + + "misolatedarabicnoonmedialarabicnoonmeeminitialarabicnoonmeemisolatedarabicnoonno" + + "onfinalarabicnotcontainsnotelementnotelementofnotequalnotgreaternotgreaternorequ" + + "alnotgreaternorlessnotidenticalnotlessnotlessnorequalnotparallelnotprecedesnotsu" + + "bsetnotsucceedsnotsupersetnowarmeniannparennssquarensuperiorntildenunuhiragananu" + + "katakananukatakanahalfwidthnuktabengalinuktadevanuktagujaratinuktagurmukhinumber" + + "signnumbersignmonospacenumbersignsmallnumeralsigngreeknumeralsignlowergreeknumer" + + "onunnundageshnundageshhebrewnunhebrewnvsquarenwsquarenyabengalinyadevanyagujarat" + + "inyagurmukhiooacuteoangthaiobarredobarredcyrillicobarreddieresiscyrillicobengali" + + "obopomofoobreveocandradevaocandragujaratiocandravowelsigndevaocandravowelsignguj" + + "aratiocaronocircleocircumflexocircumflexacuteocircumflexdotbelowocircumflexgrave" + + "ocircumflexhookaboveocircumflextildeocyrillicodblacuteodblgraveodevaodieresisodi" + + "eresiscyrillicodotbelowoeoekoreanogonekogonekcmbograveogujaratioharmenianohiraga" + + "naohookaboveohornohornacuteohorndotbelowohorngraveohornhookaboveohorntildeohunga" + + "rumlautoioinvertedbreveokatakanaokatakanahalfwidthokoreanolehebrewomacronomacron" + + "acuteomacrongraveomdevaomegaomega1omegacyrillicomegalatinclosedomegaroundcyrilli" + + "comegatitlocyrillicomegatonosomgujaratiomicronomicrontonosomonospaceoneonearabic" + + "onebengalionecircleonecircleinversesansserifonedevaonedotenleaderoneeighthonefit" + + "tedonegujarationegurmukhionehackarabiconehalfonehangzhouoneideographicparenonein" + + "ferioronemonospaceonenumeratorbengalioneoldstyleoneparenoneperiodonepersianonequ" + + "arteroneromanonesuperioronethaionethirdoogonekoogonekmacronoogurmukhioomatragurm" + + "ukhioopenoparenopenbulletoptionordfeminineordmasculineorthogonaloshortdevaoshort" + + "vowelsigndevaoslashoslashacuteosmallhiraganaosmallkatakanaosmallkatakanahalfwidt" + + "hostrokeacuteosuperiorotcyrillicotildeotildeacuteotildedieresisoubopomofooverlin" + + "eoverlinecenterlineoverlinecmboverlinedashedoverlinedblwavyoverlinewavyoverscore" + + "ovowelsignbengaliovowelsigndevaovowelsigngujaratippaampssquarepaasentosquarepabe" + + "ngalipacutepadevapagedownpageuppagujaratipagurmukhipahiraganapaiyannoithaipakata" + + "kanapalatalizationcyrilliccmbpalochkacyrillicpansioskoreanparagraphparallelparen" + + "leftparenleftaltonearabicparenleftbtparenleftexparenleftinferiorparenleftmonospa" + + "ceparenleftsmallparenleftsuperiorparenlefttpparenleftverticalparenrightparenrigh" + + "taltonearabicparenrightbtparenrightexparenrightinferiorparenrightmonospaceparenr" + + "ightsmallparenrightsuperiorparenrighttpparenrightverticalpartialdiffpaseqhebrewp" + + "ashtahebrewpasquarepatahpatah11patah1dpatah2apatahhebrewpatahnarrowhebrewpatahqu" + + "arterhebrewpatahwidehebrewpazerhebrewpbopomofopcirclepdotaccentpepecyrillicpedag" + + "eshpedageshhebrewpeezisquarepefinaldageshhebrewpeharabicpeharmenianpehebrewpehfi" + + "nalarabicpehinitialarabicpehiraganapehmedialarabicpekatakanapemiddlehookcyrillic" + + "perafehebrewpercentpercentarabicpercentmonospacepercentsmallperiodperiodarmenian" + + "periodcenteredperiodhalfwidthperiodinferiorperiodmonospaceperiodsmallperiodsuper" + + "iorperispomenigreekcmbperpendicularperthousandpesetapfsquarephabengaliphadevapha" + + "gujaratiphagurmukhiphiphi1phieuphacirclekoreanphieuphaparenkoreanphieuphcircleko" + + "reanphieuphkoreanphieuphparenkoreanphilatinphinthuthaiphisymbolgreekphookphophan" + + "thaiphophungthaiphosamphaothaipipieupacirclekoreanpieupaparenkoreanpieupcieuckor" + + "eanpieupcirclekoreanpieupkiyeokkoreanpieupkoreanpieupparenkoreanpieupsioskiyeokk" + + "oreanpieupsioskoreanpieupsiostikeutkoreanpieupthieuthkoreanpieuptikeutkoreanpihi" + + "raganapikatakanapisymbolgreekpiwrarmenianplusplusbelowcmbpluscircleplusminusplus" + + "modplusmonospaceplussmallplussuperiorpmonospacepmsquarepohiraganapointingindexdo" + + "wnwhitepointingindexleftwhitepointingindexrightwhitepointingindexupwhitepokataka" + + "napoplathaipostalmarkpostalmarkfacepparenprecedesprescriptionprimemodprimerevers" + + "edproductprojectiveprolongedkanapropellorpropersubsetpropersupersetproportionpro" + + "portionalpsipsicyrillicpsilipneumatacyrilliccmbpssquarepuhiraganapukatakanapvsqu" + + "arepwsquareqqadevaqadmahebrewqafarabicqaffinalarabicqafinitialarabicqafmedialara" + + "bicqamatsqamats10qamats1aqamats1cqamats27qamats29qamats33qamatsdeqamatshebrewqam" + + "atsnarrowhebrewqamatsqatanhebrewqamatsqatannarrowhebrewqamatsqatanquarterhebrewq" + + "amatsqatanwidehebrewqamatsquarterhebrewqamatswidehebrewqarneyparahebrewqbopomofo" + + "qcircleqhookqmonospaceqofqofdageshqofdageshhebrewqofhatafpatahqofhatafpatahhebre" + + "wqofhatafsegolqofhatafsegolhebrewqofhebrewqofhiriqqofhiriqhebrewqofholamqofholam" + + "hebrewqofpatahqofpatahhebrewqofqamatsqofqamatshebrewqofqubutsqofqubutshebrewqofs" + + "egolqofsegolhebrewqofshevaqofshevahebrewqoftsereqoftserehebrewqparenquarternoteq" + + "ubutsqubuts18qubuts25qubuts31qubutshebrewqubutsnarrowhebrewqubutsquarterhebrewqu" + + "butswidehebrewquestionquestionarabicquestionarmenianquestiondownquestiondownsmal" + + "lquestiongreekquestionmonospacequestionsmallquotedblquotedblbasequotedblleftquot" + + "edblmonospacequotedblprimequotedblprimereversedquotedblrightquoteleftquoteleftre" + + "versedquotereversedquoterightquoterightnquotesinglbasequotesinglequotesinglemono" + + "spacerraarmenianrabengaliracuteradevaradicalradicalexradoverssquareradoverssquar" + + "edsquareradsquareraferafehebrewragujaratiragurmukhirahiraganarakatakanarakatakan" + + "ahalfwidthralowerdiagonalbengaliramiddlediagonalbengaliramshornratiorbopomoforca" + + "ronrcedillarcirclercommaaccentrdblgraverdotaccentrdotbelowrdotbelowmacronreferen" + + "cemarkreflexsubsetreflexsupersetregisteredregistersansregisterserifreharabicreha" + + "rmenianrehfinalarabicrehiraganarehyehaleflamarabicrekatakanarekatakanahalfwidthr" + + "eshreshdageshhebrewreshhatafpatahreshhatafpatahhebrewreshhatafsegolreshhatafsego" + + "lhebrewreshhebrewreshhiriqreshhiriqhebrewreshholamreshholamhebrewreshpatahreshpa" + + "tahhebrewreshqamatsreshqamatshebrewreshqubutsreshqubutshebrewreshsegolreshsegolh" + + "ebrewreshshevareshshevahebrewreshtserereshtserehebrewreversedtildereviahebrewrev" + + "iamugrashhebrewrevlogicalnotrfishhookrfishhookreversedrhabengalirhadevarhorhookr" + + "hookturnedrhookturnedsuperiorrhosymbolgreekrhotichookmodrieulacirclekoreanrieula" + + "parenkoreanrieulcirclekoreanrieulhieuhkoreanrieulkiyeokkoreanrieulkiyeoksioskore" + + "anrieulkoreanrieulmieumkoreanrieulpansioskoreanrieulparenkoreanrieulphieuphkorea" + + "nrieulpieupkoreanrieulpieupsioskoreanrieulsioskoreanrieulthieuthkoreanrieultikeu" + + "tkoreanrieulyeorinhieuhkoreanrightanglerighttackbelowcmbrighttrianglerihiraganar" + + "ikatakanarikatakanahalfwidthringringbelowcmbringcmbringhalfleftringhalfleftarmen" + + "ianringhalfleftbelowcmbringhalfleftcenteredringhalfrightringhalfrightbelowcmbrin" + + "ghalfrightcenteredrinvertedbreverittorusquarerlinebelowrlonglegrlonglegturnedrmo" + + "nospacerohiraganarokatakanarokatakanahalfwidthroruathairparenrrabengalirradevarr" + + "agurmukhirreharabicrrehfinalarabicrrvocalicbengalirrvocalicdevarrvocalicgujarati" + + "rrvocalicvowelsignbengalirrvocalicvowelsigndevarrvocalicvowelsigngujaratirsuperi" + + "orrtblockrturnedrturnedsuperiorruhiraganarukatakanarukatakanahalfwidthrupeemarkb" + + "engalirupeesignbengalirupiahruthairvocalicbengalirvocalicdevarvocalicgujaratirvo" + + "calicvowelsignbengalirvocalicvowelsigndevarvocalicvowelsigngujaratissabengalisac" + + "utesacutedotaccentsadarabicsadevasadfinalarabicsadinitialarabicsadmedialarabicsa" + + "gujaratisagurmukhisahiraganasakatakanasakatakanahalfwidthsallallahoualayhewasall" + + "amarabicsamekhsamekhdageshsamekhdageshhebrewsamekhhebrewsaraaathaisaraaethaisara" + + "aimaimalaithaisaraaimaimuanthaisaraamthaisaraathaisaraethaisaraiileftthaisaraiit" + + "haisaraileftthaisaraithaisaraothaisaraueeleftthaisaraueethaisaraueleftthaisaraue" + + "thaisarauthaisarauuthaisbopomofoscaronscarondotaccentscedillaschwaschwacyrillics" + + "chwadieresiscyrillicschwahookscirclescircumflexscommaaccentsdotaccentsdotbelowsd" + + "otbelowdotaccentseagullbelowcmbsecondsecondtonechinesesectionseenarabicseenfinal" + + "arabicseeninitialarabicseenmedialarabicsegolsegol13segol1fsegol2csegolhebrewsego" + + "lnarrowhebrewsegolquarterhebrewsegoltahebrewsegolwidehebrewseharmeniansehiragana" + + "sekatakanasekatakanahalfwidthsemicolonsemicolonarabicsemicolonmonospacesemicolon" + + "smallsemivoicedmarkkanasemivoicedmarkkanahalfwidthsentisquaresentosquaresevensev" + + "enarabicsevenbengalisevencirclesevencircleinversesansserifsevendevaseveneighthss" + + "evengujaratisevengurmukhisevenhackarabicsevenhangzhousevenideographicparenseveni" + + "nferiorsevenmonospacesevenoldstylesevenparensevenperiodsevenpersiansevenromansev" + + "ensuperiorseventeencircleseventeenparenseventeenperiodseventhaisfthyphenshaarmen" + + "ianshabengalishacyrillicshaddaarabicshaddadammaarabicshaddadammatanarabicshaddaf" + + "athaarabicshaddafathatanarabicshaddakasraarabicshaddakasratanarabicshadeshadedar" + + "kshadelightshademediumshadevashagujaratishagurmukhishalshelethebrewshbopomofoshc" + + "hacyrillicsheenarabicsheenfinalarabicsheeninitialarabicsheenmedialarabicsheicopt" + + "icsheqelsheqelhebrewshevasheva115sheva15sheva22sheva2eshevahebrewshevanarrowhebr" + + "ewshevaquarterhebrewshevawidehebrewshhacyrillicshimacopticshinshindageshshindage" + + "shhebrewshindageshshindotshindageshshindothebrewshindageshsindotshindageshsindot" + + "hebrewshindothebrewshinhebrewshinshindotshinshindothebrewshinsindotshinsindotheb" + + "rewshooksigmasigma1sigmafinalsigmalunatesymbolgreeksihiraganasikatakanasikatakan" + + "ahalfwidthsiluqhebrewsiluqlefthebrewsimilarsindothebrewsiosacirclekoreansiosapar" + + "enkoreansioscieuckoreansioscirclekoreansioskiyeokkoreansioskoreansiosnieunkorean" + + "siosparenkoreansiospieupkoreansiostikeutkoreansixsixarabicsixbengalisixcirclesix" + + "circleinversesansserifsixdevasixgujaratisixgurmukhisixhackarabicsixhangzhousixid" + + "eographicparensixinferiorsixmonospacesixoldstylesixparensixperiodsixpersiansixro" + + "mansixsuperiorsixteencirclesixteencurrencydenominatorbengalisixteenparensixteenp" + + "eriodsixthaislashslashmonospaceslongslongdotaccentsmilefacesmonospacesofpasuqheb" + + "rewsofthyphensoftsigncyrillicsohiraganasokatakanasokatakanahalfwidthsoliduslongo" + + "verlaycmbsolidusshortoverlaycmbsorusithaisosalathaisosothaisosuathaispacespaceha" + + "ckarabicspadespadesuitblackspadesuitwhitesparensquarebelowcmbsquareccsquarecmsqu" + + "arediagonalcrosshatchfillsquarehorizontalfillsquarekgsquarekmsquarekmcapitalsqua" + + "relnsquarelogsquaremgsquaremilsquaremmsquaremsquaredsquareorthogonalcrosshatchfi" + + "llsquareupperlefttolowerrightfillsquareupperrighttolowerleftfillsquareverticalfi" + + "llsquarewhitewithsmallblacksrsquaressabengalissadevassagujaratissangcieuckoreans" + + "sanghieuhkoreanssangieungkoreanssangkiyeokkoreanssangnieunkoreanssangpieupkorean" + + "ssangsioskoreanssangtikeutkoreanssuperiorsterlingsterlingmonospacestrokelongover" + + "laycmbstrokeshortoverlaycmbsubsetsubsetnotequalsubsetorequalsucceedssuchthatsuhi" + + "raganasukatakanasukatakanahalfwidthsukunarabicsummationsunsupersetsupersetnotequ" + + "alsupersetorequalsvsquaresyouwaerasquarettabengalitackdowntacklefttadevatagujara" + + "titagurmukhitaharabictahfinalarabictahinitialarabictahiraganatahmedialarabictais" + + "youerasquaretakatakanatakatakanahalfwidthtatweelarabictautavtavdagestavdageshtav" + + "dageshhebrewtavhebrewtbartbopomofotcarontccurltcedillatcheharabictchehfinalarabi" + + "ctchehinitialarabictchehmedialarabictchehmeeminitialarabictcircletcircumflexbelo" + + "wtcommaaccenttdieresistdotaccenttdotbelowtecyrillictedescendercyrillicteharabict" + + "ehfinalarabictehhahinitialarabictehhahisolatedarabictehinitialarabictehiraganate" + + "hjeeminitialarabictehjeemisolatedarabictehmarbutaarabictehmarbutafinalarabictehm" + + "edialarabictehmeeminitialarabictehmeemisolatedarabictehnoonfinalarabictekatakana" + + "tekatakanahalfwidthtelephonetelephoneblacktelishagedolahebrewtelishaqetanahebrew" + + "tencircletenideographicparentenparentenperiodtenromanteshtettetdageshtetdageshhe" + + "brewtethebrewtetsecyrillictevirhebrewtevirlefthebrewthabengalithadevathagujarati" + + "thagurmukhithalarabicthalfinalarabicthanthakhatlowleftthaithanthakhatlowrighttha" + + "ithanthakhatthaithanthakhatupperleftthaitheharabicthehfinalarabicthehinitialarab" + + "icthehmedialarabicthereexiststhereforethetatheta1thetasymbolgreekthieuthacirclek" + + "oreanthieuthaparenkoreanthieuthcirclekoreanthieuthkoreanthieuthparenkoreanthirte" + + "encirclethirteenparenthirteenperiodthonangmonthothaithookthophuthaothaithornthot" + + "hahanthaithothanthaithothongthaithothungthaithousandcyrillicthousandsseparatorar" + + "abicthousandsseparatorpersianthreethreearabicthreebengalithreecirclethreecirclei" + + "nversesansserifthreedevathreeeighthsthreegujaratithreegurmukhithreehackarabicthr" + + "eehangzhouthreeideographicparenthreeinferiorthreemonospacethreenumeratorbengalit" + + "hreeoldstylethreeparenthreeperiodthreepersianthreequartersthreequartersemdashthr" + + "eeromanthreesuperiorthreethaithzsquaretihiraganatikatakanatikatakanahalfwidthtik" + + "eutacirclekoreantikeutaparenkoreantikeutcirclekoreantikeutkoreantikeutparenkorea" + + "ntildetildebelowcmbtildecmbtildecombtildedoublecmbtildeoperatortildeoverlaycmbti" + + "ldeverticalcmbtimescircletipehahebrewtipehalefthebrewtippigurmukhititlocyrillicc" + + "mbtiwnarmeniantlinebelowtmonospacetoarmeniantohiraganatokatakanatokatakanahalfwi" + + "dthtonebarextrahighmodtonebarextralowmodtonebarhighmodtonebarlowmodtonebarmidmod" + + "tonefivetonesixtonetwotonostonsquaretopatakthaitortoiseshellbracketlefttortoises" + + "hellbracketleftsmalltortoiseshellbracketleftverticaltortoiseshellbracketrighttor" + + "toiseshellbracketrightsmalltortoiseshellbracketrightverticaltotaothaitpalatalhoo" + + "ktparentrademarktrademarksanstrademarkseriftretroflexhooktriagdntriaglftriagrttr" + + "iaguptstsaditsadidageshtsadidageshhebrewtsadihebrewtsecyrillictseretsere12tsere1" + + "etsere2btserehebrewtserenarrowhebrewtserequarterhebrewtserewidehebrewtshecyrilli" + + "ctsuperiorttabengalittadevattagujaratittagurmukhitteharabicttehfinalarabicttehin" + + "itialarabicttehmedialarabictthabengalitthadevatthagujaratitthagurmukhitturnedtuh" + + "iraganatukatakanatukatakanahalfwidthtusmallhiraganatusmallkatakanatusmallkatakan" + + "ahalfwidthtwelvecircletwelveparentwelveperiodtwelveromantwentycircletwentyhangzh" + + "outwentyparentwentyperiodtwotwoarabictwobengalitwocircletwocircleinversesansseri" + + "ftwodevatwodotenleadertwodotleadertwodotleaderverticaltwogujaratitwogurmukhitwoh" + + "ackarabictwohangzhoutwoideographicparentwoinferiortwomonospacetwonumeratorbengal" + + "itwooldstyletwoparentwoperiodtwopersiantworomantwostroketwosuperiortwothaitwothi" + + "rdsuuacuteubarubengaliubopomofoubreveucaronucircleucircumflexucircumflexbelowucy" + + "rillicudattadevaudblacuteudblgraveudevaudieresisudieresisacuteudieresisbelowudie" + + "resiscaronudieresiscyrillicudieresisgraveudieresismacronudotbelowugraveugujarati" + + "ugurmukhiuhiraganauhookaboveuhornuhornacuteuhorndotbelowuhorngraveuhornhookabove" + + "uhorntildeuhungarumlautuhungarumlautcyrillicuinvertedbreveukatakanaukatakanahalf" + + "widthukcyrillicukoreanumacronumacroncyrillicumacrondieresisumatragurmukhiumonosp" + + "aceunderscoreunderscoredblunderscoremonospaceunderscoreverticalunderscorewavyuni" + + "onuniversaluogonekuparenupblockupperdothebrewupsilonupsilondieresisupsilondieres" + + "istonosupsilonlatinupsilontonosuptackbelowcmbuptackmoduragurmukhiuringushortcyri" + + "llicusmallhiraganausmallkatakanausmallkatakanahalfwidthustraightcyrillicustraigh" + + "tstrokecyrillicutildeutildeacuteutildebelowuubengaliuudevauugujaratiuugurmukhiuu" + + "matragurmukhiuuvowelsignbengaliuuvowelsigndevauuvowelsigngujaratiuvowelsignbenga" + + "liuvowelsigndevauvowelsigngujarativvadevavagujarativagurmukhivakatakanavavvavdag" + + "eshvavdagesh65vavdageshhebrewvavhebrewvavholamvavholamhebrewvavvavhebrewvavyodhe" + + "brewvcirclevdotbelowvecyrillicveharabicvehfinalarabicvehinitialarabicvehmedialar" + + "abicvekatakanavenusverticalbarverticallineabovecmbverticallinebelowcmbverticalli" + + "nelowmodverticallinemodvewarmenianvhookvikatakanaviramabengaliviramadevaviramagu" + + "jarativisargabengalivisargadevavisargagujarativmonospacevoarmenianvoicediteratio" + + "nhiraganavoicediterationkatakanavoicedmarkkanavoicedmarkkanahalfwidthvokatakanav" + + "parenvtildevturnedvuhiraganavukatakanawwacutewaekoreanwahiraganawakatakanawakata" + + "kanahalfwidthwakoreanwasmallhiraganawasmallkatakanawattosquarewavedashwavyunders" + + "coreverticalwawarabicwawfinalarabicwawhamzaabovearabicwawhamzaabovefinalarabicwb" + + "squarewcirclewcircumflexwdieresiswdotaccentwdotbelowwehiraganaweierstrasswekatak" + + "anawekoreanweokoreanwgravewhitebulletwhitecirclewhitecircleinversewhitecornerbra" + + "cketleftwhitecornerbracketleftverticalwhitecornerbracketrightwhitecornerbracketr" + + "ightverticalwhitediamondwhitediamondcontainingblacksmalldiamondwhitedownpointing" + + "smalltrianglewhitedownpointingtrianglewhiteleftpointingsmalltrianglewhiteleftpoi" + + "ntingtrianglewhitelenticularbracketleftwhitelenticularbracketrightwhiterightpoin" + + "tingsmalltrianglewhiterightpointingtrianglewhitesmallsquarewhitesmilingfacewhite" + + "squarewhitestarwhitetelephonewhitetortoiseshellbracketleftwhitetortoiseshellbrac" + + "ketrightwhiteuppointingsmalltrianglewhiteuppointingtrianglewihiraganawikatakanaw" + + "ikoreanwmonospacewohiraganawokatakanawokatakanahalfwidthwonwonmonospacewowaentha" + + "iwparenwringwsuperiorwturnedwynnxxabovecmbxbopomofoxcirclexdieresisxdotaccentxeh" + + "armenianxixmonospacexparenxsuperioryyaadosquareyabengaliyacuteyadevayaekoreanyag" + + "ujaratiyagurmukhiyahiraganayakatakanayakatakanahalfwidthyakoreanyamakkanthaiyasm" + + "allhiraganayasmallkatakanayasmallkatakanahalfwidthyatcyrillicycircleycircumflexy" + + "dieresisydotaccentydotbelowyeharabicyehbarreearabicyehbarreefinalarabicyehfinala" + + "rabicyehhamzaabovearabicyehhamzaabovefinalarabicyehhamzaaboveinitialarabicyehham" + + "zaabovemedialarabicyehinitialarabicyehmedialarabicyehmeeminitialarabicyehmeemiso" + + "latedarabicyehnoonfinalarabicyehthreedotsbelowarabicyekoreanyenyenmonospaceyeoko" + + "reanyeorinhieuhkoreanyerahbenyomohebrewyerahbenyomolefthebrewyericyrillicyerudie" + + "resiscyrillicyesieungkoreanyesieungpansioskoreanyesieungsioskoreanyetivhebrewygr" + + "aveyhookyhookaboveyiarmenianyicyrillicyikoreanyinyangyiwnarmenianymonospaceyodyo" + + "ddageshyoddageshhebrewyodhebrewyodyodhebrewyodyodpatahhebrewyohiraganayoikoreany" + + "okatakanayokatakanahalfwidthyokoreanyosmallhiraganayosmallkatakanayosmallkatakan" + + "ahalfwidthyotgreekyoyaekoreanyoyakoreanyoyakthaiyoyingthaiyparenypogegrammeniypo" + + "gegrammenigreekcmbyryringysuperiorytildeyturnedyuhiraganayuikoreanyukatakanayuka" + + "takanahalfwidthyukoreanyusbigcyrillicyusbigiotifiedcyrillicyuslittlecyrillicyusl" + + "ittleiotifiedcyrillicyusmallhiraganayusmallkatakanayusmallkatakanahalfwidthyuyek" + + "oreanyuyeokoreanyyabengaliyyadevazzaarmenianzacutezadevazagurmukhizaharabiczahfi" + + "nalarabiczahinitialarabiczahiraganazahmedialarabiczainarabiczainfinalarabiczakat" + + "akanazaqefgadolhebrewzaqefqatanhebrewzarqahebrewzayinzayindageshzayindageshhebre" + + "wzayinhebrewzbopomofozcaronzcirclezcircumflexzcurlzdotzdotaccentzdotbelowzecyril" + + "liczedescendercyrilliczedieresiscyrilliczehiraganazekatakanazerozeroarabiczerobe" + + "ngalizerodevazerogujaratizerogurmukhizerohackarabiczeroinferiorzeromonospacezero" + + "oldstylezeropersianzerosuperiorzerothaizerowidthjoinerzerowidthnonjoinerzerowidt" + + "hspacezetazhbopomofozhearmenianzhebrevecyrilliczhecyrilliczhedescendercyrilliczh" + + "edieresiscyrilliczihiraganazikatakanazinorhebrewzlinebelowzmonospacezohiraganazo" + + "katakanazparenzretroflexhookzstrokezuhiraganazukatakana"; + + /// Where each name starts in the names; one more entry than there are names. + internal static ReadOnlySpan AglNameOffsets => + [ + 0, 1, 3, 10, 18, 25, 31, 42, 48, 59, 73, 87, 98, 113, 124, 130, 137, 148, 164, 183, 199, 219, 235, 251, 256, + 266, 275, 284, 293, 310, 325, 339, 348, 358, 364, 375, 385, 396, 410, 415, 425, 432, 442, 449, 454, 464, 474, + 484, 490, 496, 507, 518, 519, 526, 536, 545, 555, 566, 570, 575, 585, 595, 605, 611, 618, 619, 629, 635, 640, + 650, 656, 664, 677, 690, 697, 708, 712, 722, 734, 745, 765, 776, 805, 825, 844, 856, 877, 902, 905, 910, 925, + 935, 945, 951, 952, 954, 961, 971, 979, 985, 993, 1000, 1016, 1022, 1032, 1041, 1051, 1060, 1065, 1075, 1080, + 1088, 1101, 1114, 1127, 1139, 1150, 1160, 1170, 1184, 1190, 1196, 1203, 1205, 1212, 1232, 1243, 1255, 1256, + 1262, 1273, 1279, 1285, 1298, 1309, 1316, 1327, 1343, 1359, 1378, 1394, 1414, 1430, 1446, 1455, 1464, 1473, + 1487, 1491, 1501, 1510, 1520, 1526, 1537, 1547, 1557, 1567, 1581, 1598, 1608, 1619, 1626, 1638, 1650, 1660, + 1670, 1680, 1699, 1702, 1715, 1729, 1736, 1741, 1748, 1760, 1770, 1779, 1796, 1806, 1825, 1828, 1834, 1837, + 1847, 1855, 1858, 1866, 1872, 1883, 1887, 1890, 1898, 1909, 1910, 1917, 1927, 1938, 1947, 1952, 1964, 1973, + 1983, 1992, 1998, 1999, 2007, 2013, 2018, 2030, 2042, 2048, 2054, 2062, 2069, 2080, 2092, 2096, 2106, 2116, + 2128, 2149, 2166, 2183, 2188, 2199, 2210, 2217, 2227, 2232, 2242, 2248, 2258, 2265, 2266, 2272, 2278, 2284, + 2290, 2298, 2317, 2336, 2352, 2356, 2367, 2375, 2382, 2393, 2402, 2412, 2421, 2431, 2441, 2451, 2457, 2469, + 2486, 2494, 2495, 2505, 2507, 2517, 2523, 2534, 2540, 2546, 2553, 2564, 2580, 2589, 2598, 2607, 2621, 2638, + 2652, 2656, 2666, 2675, 2690, 2700, 2708, 2714, 2725, 2735, 2745, 2759, 2774, 2781, 2796, 2806, 2817, 2827, + 2834, 2838, 2849, 2861, 2870, 2876, 2883, 2889, 2900, 2915, 2938, 2939, 2949, 2956, 2967, 2977, 2989, 2999, + 3005, 3006, 3014, 3022, 3039, 3045, 3055, 3074, 3088, 3093, 3109, 3133, 3139, 3147, 3154, 3166, 3175, 3186, + 3197, 3208, 3218, 3223, 3234, 3244, 3254, 3267, 3277, 3288, 3294, 3295, 3297, 3299, 3305, 3311, 3317, 3325, + 3332, 3348, 3360, 3364, 3374, 3383, 3398, 3410, 3412, 3423, 3433, 3443, 3449, 3460, 3466, 3467, 3475, 3481, + 3492, 3498, 3505, 3515, 3524, 3535, 3545, 3551, 3558, 3560, 3561, 3563, 3569, 3575, 3583, 3590, 3606, 3618, + 3628, 3637, 3646, 3655, 3657, 3668, 3678, 3688, 3699, 3705, 3711, 3722, 3724, 3725, 3727, 3734, 3740, 3751, + 3766, 3789, 3795, 3801, 3815, 3822, 3833, 3849, 3868, 3884, 3904, 3920, 3936, 3945, 3954, 3963, 3972, 3989, + 4003, 4012, 4023, 4029, 4040, 4050, 4053, 4063, 4068, 4078, 4091, 4101, 4115, 4125, 4138, 4140, 4154, 4161, + 4173, 4185, 4190, 4203, 4213, 4231, 4249, 4259, 4266, 4278, 4288, 4296, 4303, 4316, 4321, 4327, 4338, 4349, + 4355, 4367, 4377, 4383, 4394, 4408, 4419, 4420, 4426, 4433, 4443, 4453, 4464, 4484, 4487, 4492, 4494, 4506, + 4516, 4519, 4530, 4536, 4537, 4544, 4554, 4560, 4561, 4571, 4577, 4583, 4591, 4598, 4610, 4619, 4629, 4638, + 4653, 4664, 4672, 4675, 4684, 4698, 4708, 4718, 4724, 4738, 4760, 4761, 4769, 4777, 4785, 4793, 4801, 4809, + 4817, 4825, 4833, 4841, 4849, 4857, 4865, 4873, 4881, 4889, 4897, 4905, 4913, 4921, 4929, 4937, 4945, 4953, + 4961, 4969, 4977, 4985, 4993, 5001, 5009, 5017, 5025, 5033, 5041, 5049, 5057, 5065, 5073, 5081, 5087, 5102, + 5112, 5118, 5133, 5144, 5152, 5157, 5170, 5191, 5198, 5209, 5221, 5231, 5240, 5258, 5269, 5279, 5290, 5301, + 5314, 5324, 5336, 5347, 5352, 5360, 5370, 5386, 5392, 5403, 5404, 5407, 5411, 5417, 5425, 5432, 5448, 5460, + 5470, 5479, 5489, 5508, 5516, 5529, 5534, 5539, 5544, 5554, 5564, 5574, 5586, 5596, 5606, 5616, 5624, 5631, + 5638, 5652, 5663, 5675, 5681, 5692, 5700, 5701, 5707, 5718, 5724, 5730, 5737, 5748, 5764, 5780, 5789, 5798, + 5807, 5816, 5830, 5844, 5858, 5875, 5889, 5904, 5918, 5927, 5933, 5944, 5954, 5959, 5969, 5982, 5992, 6006, + 6016, 6029, 6050, 6064, 6074, 6081, 6096, 6111, 6121, 6128, 6135, 6143, 6170, 6184, 6199, 6229, 6246, 6258, + 6263, 6277, 6283, 6300, 6323, 6329, 6340, 6351, 6352, 6359, 6368, 6378, 6389, 6394, 6404, 6414, 6420, 6426, + 6427, 6433, 6440, 6451, 6460, 6470, 6479, 6485, 6495, 6501, 6502, 6509, 6518, 6528, 6539, 6541, 6551, 6557, + 6558, 6564, 6575, 6586, 6593, 6604, 6613, 6627, 6637, 6646, 6658, 6678, 6684, 6689, 6699, 6709, 6719, 6731, + 6741, 6747, 6753, 6767, 6789, 6806, 6831, 6832, 6842, 6848, 6854, 6865, 6872, 6883, 6887, 6897, 6906, 6916, + 6935, 6953, 6957, 6968, 6984, 6995, 7015, 7034, 7044, 7054, 7060, 7067, 7068, 7077, 7083, 7089, 7099, 7109, + 7124, 7134, 7152, 7167, 7186, 7210, 7230, 7238, 7247, 7253, 7264, 7278, 7292, 7303, 7318, 7329, 7335, 7342, + 7353, 7369, 7388, 7404, 7424, 7440, 7445, 7458, 7466, 7475, 7484, 7495, 7507, 7516, 7525, 7538, 7543, 7552, + 7569, 7584, 7593, 7603, 7605, 7612, 7620, 7628, 7637, 7646, 7655, 7664, 7673, 7682, 7691, 7700, 7709, 7718, + 7727, 7736, 7745, 7754, 7763, 7772, 7781, 7790, 7799, 7808, 7817, 7826, 7835, 7844, 7853, 7862, 7871, 7880, + 7889, 7898, 7907, 7916, 7925, 7934, 7943, 7952, 7961, 7970, 7979, 7988, 7997, 8006, 8015, 8024, 8033, 8042, + 8051, 8060, 8069, 8078, 8087, 8096, 8105, 8114, 8123, 8132, 8141, 8150, 8159, 8168, 8177, 8186, 8195, 8204, + 8213, 8222, 8231, 8240, 8249, 8258, 8267, 8276, 8285, 8294, 8303, 8312, 8321, 8330, 8339, 8348, 8357, 8366, + 8375, 8384, 8393, 8402, 8411, 8420, 8429, 8438, 8447, 8456, 8465, 8474, 8483, 8492, 8501, 8510, 8519, 8528, + 8537, 8546, 8555, 8564, 8573, 8582, 8591, 8600, 8607, 8614, 8621, 8630, 8639, 8648, 8657, 8666, 8675, 8684, + 8693, 8702, 8711, 8720, 8729, 8738, 8747, 8756, 8765, 8774, 8783, 8792, 8801, 8810, 8819, 8828, 8837, 8846, + 8855, 8864, 8873, 8882, 8891, 8900, 8909, 8918, 8927, 8936, 8945, 8954, 8963, 8972, 8981, 8990, 8999, 9008, + 9017, 9026, 9035, 9044, 9053, 9062, 9071, 9080, 9089, 9098, 9107, 9116, 9125, 9134, 9143, 9152, 9161, 9170, + 9179, 9188, 9197, 9206, 9215, 9224, 9233, 9242, 9251, 9260, 9269, 9278, 9287, 9296, 9305, 9314, 9323, 9332, + 9341, 9350, 9359, 9368, 9377, 9386, 9395, 9404, 9413, 9422, 9431, 9440, 9449, 9458, 9467, 9476, 9485, 9494, + 9503, 9512, 9521, 9530, 9539, 9548, 9557, 9566, 9575, 9584, 9593, 9602, 9611, 9620, 9629, 9638, 9647, 9656, + 9665, 9674, 9683, 9692, 9701, 9710, 9719, 9728, 9737, 9746, 9755, 9764, 9773, 9782, 9791, 9800, 9809, 9818, + 9827, 9836, 9842, 9851, 9860, 9869, 9879, 9888, 9898, 9904, 9915, 9925, 9935, 9950, 9959, 9973, 9989, 10004, + 10018, 10036, 10051, 10070, 10079, 10097, 10104, 10108, 10118, 10134, 10149, 10169, 10194, 10214, 10239, 10249, + 10264, 10284, 10309, 10326, 10348, 10372, 10395, 10410, 10426, 10431, 10439, 10444, 10454, 10461, 10471, 10480, + 10498, 10512, 10520, 10530, 10541, 10555, 10560, 10576, 10600, 10617, 10642, 10651, 10661, 10669, 10678, 10690, + 10705, 10717, 10733, 10740, 10752, 10758, 10776, 10789, 10794, 10804, 10815, 10833, 10851, 10863, 10874, 10877, + 10891, 10896, 10906, 10916, 10925, 10938, 10951, 10965, 10976, 10988, 11000, 11012, 11025, 11035, 11044, 11057, + 11071, 11085, 11101, 11117, 11134, 11148, 11160, 11169, 11181, 11199, 11217, 11231, 11241, 11260, 11275, 11293, + 11308, 11320, 11333, 11340, 11349, 11361, 11376, 11387, 11404, 11416, 11428, 11439, 11450, 11470, 11480, 11499, + 11506, 11519, 11533, 11547, 11570, 11578, 11598, 11612, 11624, 11641, 11654, 11662, 11671, 11690, 11692, 11698, + 11709, 11716, 11723, 11732, 11742, 11748, 11758, 11768, 11787, 11802, 11820, 11835, 11854, 11866, 11877, 11881, + 11897, 11907, 11908, 11917, 11926, 11944, 11950, 11960, 11970, 11980, 11988, 11998, 12001, 12013, 12022, 12029, + 12039, 12048, 12068, 12075, 12085, 12094, 12108, 12124, 12134, 12149, 12169, 12190, 12208, 12218, 12229, 12232, + 12236, 12251, 12260, 12275, 12284, 12297, 12307, 12314, 12325, 12336, 12341, 12351, 12361, 12374, 12387, 12397, + 12408, 12420, 12445, 12469, 12494, 12520, 12554, 12581, 12616, 12638, 12661, 12675, 12700, 12726, 12742, 12758, + 12769, 12778, 12800, 12823, 12851, 12874, 12879, 12889, 12894, 12904, 12916, 12926, 12936, 12942, 12950, 12957, + 12966, 12977, 12989, 13007, 13021, 13032, 13049, 13059, 13071, 13084, 13103, 13118, 13130, 13148, 13159, 13172, + 13185, 13205, 13218, 13230, 13244, 13258, 13279, 13293, 13298, 13311, 13319, 13340, 13356, 13378, 13392, 13414, + 13423, 13430, 13439, 13446, 13456, 13466, 13472, 13485, 13499, 13507, 13508, 13518, 13527, 13533, 13539, 13549, + 13559, 13568, 13586, 13600, 13615, 13634, 13642, 13648, 13653, 13666, 13674, 13688, 13697, 13703, 13711, 13724, + 13731, 13742, 13747, 13751, 13761, 13769, 13776, 13786, 13790, 13800, 13812, 13825, 13837, 13849, 13860, 13870, + 13877, 13888, 13899, 13909, 13929, 13938, 13949, 13978, 13998, 14017, 14029, 14050, 14075, 14078, 14098, 14117, + 14136, 14149, 14167, 14179, 14190, 14202, 14213, 14218, 14236, 14253, 14270, 14281, 14297, 14314, 14320, 14334, + 14342, 14352, 14368, 14391, 14415, 14425, 14443, 14456, 14461, 14474, 14485, 14497, 14511, 14515, 14528, 14541, + 14554, 14564, 14579, 14589, 14594, 14607, 14621, 14630, 14640, 14662, 14680, 14685, 14698, 14716, 14727, 14738, + 14751, 14764, 14778, 14799, 14815, 14825, 14838, 14857, 14871, 14878, 14887, 14902, 14909, 14919, 14929, 14938, + 14948, 14957, 14967, 14977, 14987, 14997, 15007, 15017, 15026, 15036, 15046, 15056, 15066, 15076, 15085, 15094, + 15103, 15112, 15121, 15131, 15140, 15149, 15158, 15168, 15178, 15188, 15198, 15207, 15216, 15225, 15238, 15252, + 15269, 15295, 15320, 15338, 15365, 15391, 15408, 15416, 15429, 15435, 15443, 15453, 15461, 15468, 15476, 15484, + 15491, 15499, 15506, 15507, 15517, 15526, 15535, 15541, 15555, 15571, 15586, 15592, 15604, 15610, 15619, 15629, + 15639, 15649, 15659, 15668, 15673, 15684, 15701, 15716, 15737, 15752, 15773, 15784, 15794, 15810, 15820, 15836, + 15846, 15862, 15873, 15890, 15901, 15918, 15928, 15944, 15954, 15970, 15980, 15996, 16010, 16021, 16035, 16055, + 16069, 16074, 16085, 16100, 16124, 16132, 16151, 16178, 16198, 16226, 16249, 16261, 16274, 16282, 16290, 16301, + 16312, 16322, 16335, 16349, 16360, 16374, 16397, 16406, 16414, 16420, 16428, 16435, 16451, 16457, 16467, 16474, + 16485, 16496, 16506, 16521, 16530, 16541, 16549, 16561, 16573, 16583, 16592, 16614, 16637, 16647, 16653, 16663, + 16673, 16682, 16692, 16702, 16713, 16718, 16729, 16764, 16768, 16778, 16785, 16796, 16807, 16812, 16826, 16843, + 16850, 16866, 16874, 16887, 16903, 16914, 16927, 16940, 16950, 16960, 16969, 16975, 16982, 16995, 17006, 17013, + 17023, 17031, 17038, 17048, 17055, 17066, 17075, 17085, 17095, 17101, 17115, 17130, 17144, 17155, 17169, 17173, + 17183, 17192, 17204, 17215, 17227, 17238, 17246, 17254, 17272, 17279, 17291, 17305, 17325, 17341, 17352, 17358, + 17367, 17372, 17379, 17389, 17399, 17401, 17409, 17416, 17422, 17442, 17453, 17465, 17466, 17472, 17477, 17485, + 17494, 17500, 17511, 17526, 17546, 17570, 17576, 17589, 17600, 17615, 17622, 17633, 17649, 17665, 17684, 17700, + 17720, 17736, 17745, 17754, 17759, 17768, 17772, 17782, 17791, 17801, 17816, 17826, 17832, 17841, 17851, 17861, + 17870, 17880, 17890, 17895, 17906, 17918, 17929, 17956, 17965, 17979, 17992, 18006, 18019, 18032, 18047, 18060, + 18076, 18097, 18110, 18124, 18137, 18147, 18158, 18170, 18180, 18193, 18202, 18216, 18233, 18242, 18260, 18275, + 18282, 18292, 18299, 18311, 18322, 18334, 18345, 18353, 18369, 18376, 18388, 18400, 18410, 18416, 18430, 18440, + 18460, 18468, 18478, 18488, 18494, 18508, 18527, 18530, 18541, 18554, 18568, 18575, 18582, 18590, 18595, 18606, + 18619, 18638, 18655, 18661, 18668, 18680, 18685, 18699, 18709, 18722, 18733, 18743, 18753, 18762, 18779, 18789, + 18808, 18811, 18818, 18828, 18847, 18862, 18878, 18892, 18906, 18929, 18938, 18947, 18950, 18960, 18968, 18971, + 18977, 18988, 19006, 19028, 19041, 19058, 19065, 19073, 19077, 19094, 19108, 19126, 19132, 19146, 19155, 19165, + 19180, 19195, 19206, 19217, 19220, 19228, 19235, 19246, 19253, 19254, 19260, 19270, 19280, 19291, 19305, 19319, + 19328, 19335, 19345, 19354, 19365, 19379, 19395, 19410, 19419, 19425, 19427, 19430, 19433, 19435, 19448, 19460, + 19473, 19483, 19492, 19502, 19510, 19524, 19544, 19558, 19572, 19592, 19605, 19624, 19632, 19646, 19654, 19668, + 19675, 19688, 19698, 19714, 19730, 19737, 19749, 19753, 19763, 19774, 19784, 19810, 19818, 19829, 19841, 19853, + 19867, 19879, 19899, 19911, 19924, 19936, 19945, 19955, 19966, 19975, 19987, 19995, 19997, 20003, 20013, 20021, + 20030, 20038, 20049, 20055, 20059, 20069, 20080, 20090, 20116, 20124, 20136, 20148, 20162, 20174, 20194, 20206, + 20219, 20239, 20251, 20260, 20270, 20281, 20290, 20302, 20316, 20329, 20343, 20351, 20368, 20374, 20382, 20387, + 20388, 20397, 20403, 20409, 20418, 20432, 20448, 20463, 20473, 20483, 20493, 20503, 20508, 20523, 20536, 20548, + 20557, 20563, 20569, 20577, 20584, 20595, 20607, 20611, 20621, 20631, 20641, 20651, 20669, 20687, 20699, 20717, + 20727, 20748, 20763, 20771, 20781, 20793, 20800, 20811, 20822, 20833, 20849, 20867, 20884, 20905, 20922, 20939, + 20947, 20959, 20964, 20973, 20983, 20993, 21004, 21009, 21020, 21037, 21048, 21059, 21080, 21091, 21110, 21124, + 21143, 21165, 21192, 21209, 21234, 21241, 21251, 21261, 21271, 21277, 21286, 21294, 21299, 21312, 21320, 21329, + 21338, 21349, 21363, 21375, 21382, 21394, 21412, 21428, 21447, 21460, 21476, 21488, 21495, 21502, 21512, 21525, + 21539, 21552, 21566, 21576, 21588, 21596, 21597, 21616, 21630, 21639, 21658, 21664, 21674, 21684, 21693, 21707, + 21723, 21733, 21748, 21759, 21769, 21788, 21802, 21813, 21829, 21848, 21864, 21883, 21897, 21916, 21938, 21954, + 21966, 21982, 21999, 22017, 22025, 22035, 22047, 22059, 22071, 22087, 22109, 22132, 22152, 22163, 22176, 22189, + 22202, 22219, 22242, 22266, 22287, 22297, 22309, 22321, 22333, 22349, 22371, 22394, 22414, 22418, 22427, 22438, + 22446, 22453, 22464, 22473, 22483, 22492, 22494, 22499, 22513, 22527, 22535, 22549, 22564, 22573, 22581, 22601, + 22621, 22635, 22659, 22686, 22708, 22724, 22734, 22755, 22770, 22785, 22795, 22814, 22829, 22837, 22849, 22852, + 22861, 22866, 22879, 22897, 22914, 22931, 22942, 22958, 22968, 22978, 22997, 23002, 23009, 23016, 23023, 23034, + 23051, 23069, 23084, 23094, 23104, 23114, 23123, 23133, 23143, 23162, 23167, 23174, 23181, 23188, 23199, 23216, + 23234, 23249, 23261, 23274, 23281, 23304, 23325, 23335, 23345, 23358, 23365, 23375, 23380, 23386, 23395, 23402, + 23412, 23424, 23434, 23453, 23465, 23480, 23482, 23488, 23502, 23517, 23528, 23542, 23551, 23552, 23558, 23568, + 23576, 23585, 23591, 23597, 23604, 23615, 23624, 23633, 23653, 23672, 23696, 23716, 23739, 23755, 23771, 23791, + 23821, 23845, 23866, 23892, 23918, 23942, 23968, 23993, 24013, 24033, 24054, 24078, 24100, 24121, 24142, 24162, + 24187, 24208, 24228, 24248, 24265, 24287, 24308, 24333, 24357, 24379, 24402, 24422, 24445, 24461, 24484, 24505, + 24526, 24545, 24570, 24591, 24611, 24626, 24646, 24665, 24684, 24702, 24722, 24741, 24746, 24755, 24769, 24786, + 24795, 24810, 24820, 24838, 24855, 24872, 24883, 24899, 24905, 24914, 24923, 24932, 24942, 24951, 24961, 24967, + 24977, 24987, 25002, 25016, 25031, 25049, 25064, 25083, 25085, 25094, 25112, 25119, 25123, 25133, 25140, 25155, + 25180, 25194, 25204, 25213, 25221, 25232, 25240, 25254, 25264, 25274, 25285, 25295, 25307, 25317, 25326, 25335, + 25347, 25357, 25364, 25368, 25380, 25397, 25406, 25415, 25421, 25432, 25446, 25460, 25483, 25496, 25503, 25512, + 25529, 25546, 25552, 25563, 25573, 25583, 25600, 25614, 25632, 25647, 25670, 25671, 25681, 25690, 25696, 25706, + 25716, 25725, 25731, 25738, 25749, 25761, 25775, 25785, 25795, 25810, 25827, 25843, 25852, 25866, 25876, 25883, + 25894, 25905, 25917, 25920, 25930, 25936, 25945, 25946, 25963, 25972, 25978, 25988, 26007, 26013, 26016, 26025, + 26034, 26049, 26063, 26072, 26088, 26103, 26116, 26126, 26136, 26146, 26160, 26170, 26189, 26194, 26210, 26229, + 26250, 26269, 26293, 26306, 26323, 26353, 26368, 26376, 26387, 26401, 26417, 26445, 26469, 26478, 26488, 26494, + 26502, 26509, 26521, 26530, 26541, 26551, 26561, 26580, 26591, 26606, 26618, 26628, 26639, 26646, 26657, 26668, + 26678, 26693, 26710, 26726, 26736, 26744, 26756, 26776, 26795, 26814, 26827, 26845, 26856, 26867, 26879, 26891, + 26901, 26906, 26920, 26929, 26939, 26949, 26968, 26984, 27001, 27011, 27030, 27048, 27066, 27078, 27095, 27111, + 27122, 27132, 27140, 27153, 27163, 27178, 27188, 27198, 27207, 27217, 27236, 27247, 27260, 27280, 27290, 27296, + 27305, 27316, 27324, 27331, 27341, 27351, 27370, 27378, 27386, 27387, 27396, 27402, 27408, 27418, 27428, 27443, + 27461, 27489, 27520, 27548, 27579, 27600, 27628, 27659, 27668, 27674, 27686, 27691, 27702, 27719, 27730, 27740, + 27756, 27778, 27794, 27808, 27827, 27843, 27863, 27883, 27906, 27921, 27944, 27964, 27988, 28012, 28023, 28027, + 28032, 28041, 28047, 28055, 28062, 28078, 28090, 28094, 28104, 28113, 28128, 28145, 28161, 28165, 28174, 28192, + 28205, 28221, 28234, 28247, 28256, 28260, 28267, 28281, 28285, 28297, 28299, 28310, 28312, 28319, 28330, 28340, + 28348, 28364, 28377, 28402, 28424, 28436, 28446, 28454, 28465, 28475, 28485, 28503, 28512, 28522, 28527, 28544, + 28554, 28567, 28574, 28580, 28586, 28593, 28602, 28609, 28615, 28630, 28642, 28666, 28687, 28695, 28696, 28705, + 28711, 28725, 28734, 28746, 28761, 28767, 28773, 28783, 28793, 28807, 28825, 28835, 28857, 28880, 28895, 28919, + 28935, 28952, 28961, 28979, 28997, 29011, 29028, 29041, 29058, 29076, 29086, 29105, 29122, 29140, 29150, 29169, + 29181, 29191, 29210, 29214, 29227, 29238, 29242, 29260, 29268, 29277, 29285, 29292, 29304, 29314, 29323, 29333, + 29348, 29365, 29381, 29402, 29424, 29437, 29447, 29461, 29471, 29490, 29493, 29502, 29517, 29526, 29537, 29549, + 29567, 29589, 29605, 29610, 29619, 29645, 29651, 29669, 29686, 29703, 29714, 29732, 29748, 29764, 29779, 29789, + 29799, 29818, 29823, 29836, 29847, 29855, 29864, 29870, 29885, 29895, 29909, 29917, 29930, 29940, 29955, 29965, + 29975, 29985, 30004, 30013, 30021, 30033, 30052, 30058, 30067, 30075, 30084, 30091, 30093, 30096, 30105, 30116, + 30124, 30133, 30140, 30149, 30159, 30169, 30188, 30197, 30205, 30214, 30225, 30240, 30251, 30265, 30278, 30292, + 30301, 30310, 30319, 30331, 30339, 30351, 30359, 30360, 30369, 30374, 30380, 30386, 30396, 30406, 30416, 30426, + 30445, 30456, 30464, 30473, 30480, 30486, 30494, 30501, 30517, 30529, 30539, 30548, 30558, 30568, 30587, 30600, + 30608, 30618, 30625, 30636, 30647, 30657, 30666, 30675, 30689, 30707, 30724, 30740, 30757, 30773, 30784, 30802, + 30818, 30833, 30850, 30860, 30870, 30889, 30905, 30917, 30921, 30931, 30942, 30952, 30978, 30986, 30998, 31010, + 31024, 31036, 31056, 31068, 31081, 31093, 31102, 31112, 31123, 31132, 31144, 31158, 31171, 31185, 31193, 31195, + 31206, 31215, 31233, 31246, 31256, 31266, 31274, 31284, 31291, 31302, 31313, 31321, 31331, 31341, 31360, 31376, + 31385, 31393, 31403, 31418, 31434, 31455, 31475, 31492, 31513, 31535, 31551, 31572, 31594, 31613, 31624, 31634, + 31646, 31654, 31664, 31682, 31699, 31711, 31718, 31733, 31744, 31755, 31764, 31775, 31786, 31797, 31803, 31811, + 31820, 31826, 31828, 31838, 31848, 31867, 31879, 31888, 31901, 31914, 31924, 31943, 31958, 31974, 31995, 32001, + 32004, 32013, 32028, 32037, 32045, 32053, 32063, 32070, 32081, 32092, 32093, 32099, 32107, 32114, 32129, 32152, + 32160, 32169, 32175, 32186, 32201, 32221, 32245, 32251, 32258, 32269, 32285, 32304, 32320, 32340, 32356, 32365, + 32374, 32383, 32388, 32397, 32414, 32423, 32425, 32433, 32439, 32448, 32454, 32463, 32473, 32482, 32492, 32497, + 32507, 32520, 32530, 32544, 32554, 32567, 32569, 32583, 32592, 32610, 32617, 32626, 32633, 32645, 32657, 32663, + 32668, 32674, 32687, 32703, 32721, 32739, 32749, 32759, 32766, 32778, 32788, 32791, 32800, 32810, 32819, 32844, + 32851, 32865, 32874, 32883, 32894, 32905, 32918, 32925, 32936, 32955, 32966, 32978, 32997, 33008, 33016, 33025, + 33035, 33045, 33053, 33064, 33071, 33079, 33086, 33099, 33109, 33124, 33129, 33135, 33145, 33151, 33162, 33174, + 33184, 33194, 33213, 33219, 33230, 33244, 33258, 33281, 33293, 33302, 33312, 33318, 33329, 33343, 33353, 33361, + 33379, 33390, 33404, 33419, 33431, 33440, 33457, 33471, 33489, 33490, 33502, 33516, 33525, 33531, 33537, 33545, + 33551, 33561, 33571, 33581, 33594, 33604, 33629, 33645, 33658, 33667, 33675, 33684, 33705, 33716, 33727, 33744, + 33762, 33776, 33793, 33804, 33821, 33831, 33853, 33865, 33877, 33895, 33914, 33929, 33947, 33959, 33977, 33988, + 33999, 34011, 34019, 34024, 34031, 34038, 34045, 34056, 34073, 34091, 34106, 34117, 34126, 34133, 34143, 34145, + 34155, 34163, 34177, 34188, 34207, 34216, 34227, 34235, 34249, 34265, 34275, 34290, 34300, 34320, 34332, 34339, + 34352, 34368, 34380, 34386, 34400, 34414, 34429, 34443, 34458, 34469, 34483, 34502, 34515, 34526, 34532, 34540, + 34550, 34557, 34568, 34579, 34582, 34586, 34606, 34625, 34644, 34657, 34675, 34683, 34694, 34708, 34713, 34724, + 34736, 34750, 34752, 34770, 34787, 34803, 34820, 34837, 34848, 34864, 34885, 34900, 34921, 34939, 34956, 34966, + 34976, 34989, 35001, 35005, 35017, 35027, 35036, 35043, 35056, 35065, 35077, 35087, 35095, 35105, 35127, 35149, + 35172, 35192, 35202, 35211, 35221, 35235, 35241, 35249, 35261, 35269, 35282, 35289, 35299, 35312, 35321, 35333, + 35347, 35357, 35369, 35372, 35383, 35407, 35415, 35425, 35435, 35443, 35451, 35452, 35458, 35469, 35478, 35492, + 35508, 35523, 35529, 35537, 35545, 35553, 35561, 35569, 35577, 35585, 35597, 35615, 35632, 35655, 35679, 35700, + 35719, 35735, 35751, 35760, 35767, 35772, 35782, 35785, 35794, 35809, 35822, 35841, 35854, 35873, 35882, 35890, + 35904, 35912, 35926, 35934, 35948, 35957, 35972, 35981, 35996, 36004, 36018, 36026, 36040, 36048, 36062, 36068, + 36079, 36085, 36093, 36101, 36109, 36121, 36139, 36158, 36174, 36182, 36196, 36212, 36224, 36241, 36254, 36271, + 36284, 36292, 36304, 36316, 36333, 36346, 36367, 36380, 36389, 36406, 36419, 36429, 36440, 36454, 36465, 36485, + 36486, 36496, 36505, 36511, 36517, 36524, 36533, 36547, 36568, 36577, 36581, 36591, 36601, 36611, 36621, 36631, + 36650, 36672, 36695, 36703, 36708, 36717, 36723, 36731, 36738, 36750, 36759, 36769, 36778, 36793, 36806, 36818, + 36832, 36842, 36854, 36867, 36876, 36887, 36901, 36911, 36930, 36940, 36959, 36963, 36979, 36993, 37013, 37027, + 37047, 37057, 37066, 37081, 37090, 37105, 37114, 37129, 37139, 37155, 37165, 37181, 37190, 37205, 37214, 37229, + 37238, 37253, 37266, 37277, 37295, 37308, 37317, 37334, 37344, 37351, 37354, 37359, 37370, 37389, 37403, 37416, + 37434, 37451, 37468, 37484, 37501, 37522, 37533, 37549, 37567, 37583, 37601, 37617, 37637, 37652, 37670, 37687, + 37709, 37719, 37736, 37749, 37759, 37769, 37788, 37792, 37804, 37811, 37823, 37843, 37863, 37883, 37896, 37917, + 37938, 37952, 37965, 37975, 37983, 37997, 38007, 38017, 38027, 38046, 38055, 38061, 38071, 38078, 38089, 38099, + 38114, 38130, 38143, 38160, 38185, 38207, 38233, 38242, 38249, 38256, 38271, 38281, 38291, 38310, 38326, 38342, + 38348, 38354, 38369, 38381, 38397, 38421, 38442, 38467, 38468, 38477, 38483, 38498, 38507, 38513, 38527, 38543, + 38558, 38568, 38578, 38588, 38598, 38617, 38648, 38654, 38666, 38684, 38696, 38706, 38716, 38734, 38751, 38761, + 38770, 38779, 38793, 38803, 38816, 38825, 38834, 38849, 38860, 38874, 38884, 38893, 38903, 38912, 38918, 38933, + 38941, 38946, 38959, 38980, 38989, 38996, 39007, 39019, 39029, 39038, 39056, 39071, 39077, 39094, 39101, 39111, + 39126, 39143, 39159, 39164, 39171, 39178, 39185, 39196, 39213, 39231, 39244, 39259, 39270, 39280, 39290, 39309, + 39318, 39333, 39351, 39365, 39383, 39410, 39421, 39432, 39437, 39448, 39460, 39471, 39498, 39507, 39519, 39532, + 39545, 39560, 39573, 39594, 39607, 39621, 39634, 39644, 39655, 39667, 39677, 39690, 39705, 39719, 39734, 39743, + 39752, 39763, 39773, 39784, 39796, 39813, 39833, 39850, 39870, 39887, 39907, 39912, 39921, 39931, 39942, 39949, + 39960, 39971, 39987, 39997, 40010, 40021, 40037, 40055, 40072, 40082, 40088, 40100, 40105, 40113, 40120, 40127, + 40134, 40145, 40162, 40180, 40195, 40207, 40218, 40222, 40232, 40248, 40265, 40288, 40304, 40326, 40339, 40349, + 40360, 40377, 40387, 40403, 40408, 40413, 40419, 40429, 40451, 40461, 40471, 40490, 40501, 40516, 40523, 40535, + 40552, 40568, 40583, 40599, 40615, 40625, 40640, 40655, 40670, 40686, 40689, 40698, 40708, 40717, 40742, 40749, + 40760, 40771, 40784, 40795, 40814, 40825, 40837, 40848, 40856, 40865, 40875, 40883, 40894, 40907, 40940, 40952, + 40965, 40972, 40977, 40991, 40996, 41010, 41019, 41029, 41043, 41053, 41069, 41079, 41089, 41108, 41129, 41151, + 41161, 41171, 41179, 41188, 41193, 41208, 41213, 41227, 41241, 41247, 41261, 41269, 41277, 41305, 41325, 41333, + 41341, 41356, 41364, 41373, 41381, 41390, 41398, 41412, 41442, 41473, 41504, 41522, 41547, 41555, 41565, 41572, + 41583, 41599, 41615, 41631, 41648, 41664, 41680, 41695, 41712, 41721, 41729, 41746, 41766, 41787, 41793, 41807, + 41820, 41828, 41836, 41846, 41856, 41875, 41886, 41895, 41898, 41906, 41922, 41937, 41945, 41960, 41961, 41970, + 41978, 41986, 41992, 42002, 42012, 42021, 42035, 42051, 42061, 42076, 42092, 42102, 42121, 42134, 42137, 42140, + 42148, 42157, 42172, 42181, 42185, 42194, 42200, 42206, 42214, 42225, 42241, 42259, 42276, 42298, 42305, 42321, + 42333, 42342, 42352, 42361, 42371, 42390, 42399, 42413, 42432, 42452, 42468, 42478, 42498, 42519, 42535, 42556, + 42571, 42591, 42612, 42630, 42640, 42659, 42668, 42682, 42701, 42720, 42729, 42748, 42756, 42765, 42773, 42777, + 42780, 42789, 42804, 42813, 42826, 42837, 42852, 42862, 42869, 42880, 42891, 42901, 42916, 42938, 42961, 42976, + 43000, 43010, 43025, 43042, 43058, 43069, 43078, 43083, 43089, 43105, 43125, 43144, 43163, 43176, 43194, 43208, + 43221, 43235, 43252, 43257, 43271, 43276, 43289, 43300, 43312, 43324, 43340, 43364, 43389, 43394, 43405, 43417, + 43428, 43455, 43464, 43476, 43489, 43502, 43517, 43530, 43551, 43564, 43578, 43599, 43612, 43622, 43633, 43645, + 43658, 43677, 43687, 43700, 43709, 43718, 43728, 43738, 43757, 43776, 43794, 43812, 43824, 43841, 43846, 43859, + 43867, 43876, 43890, 43903, 43918, 43934, 43945, 43957, 43973, 43986, 44002, 44014, 44024, 44034, 44044, 44054, + 44064, 44083, 44102, 44120, 44134, 44147, 44160, 44168, 44175, 44182, 44187, 44196, 44207, 44231, 44260, 44292, + 44317, 44347, 44380, 44389, 44401, 44407, 44416, 44429, 44443, 44457, 44464, 44471, 44478, 44485, 44487, 44492, + 44503, 44520, 44531, 44542, 44547, 44554, 44561, 44568, 44579, 44596, 44614, 44629, 44641, 44650, 44660, 44667, + 44678, 44689, 44699, 44714, 44731, 44747, 44758, 44766, 44778, 44790, 44797, 44807, 44817, 44836, 44851, 44866, + 44890, 44902, 44913, 44925, 44936, 44948, 44962, 44973, 44985, 44988, 44997, 45007, 45016, 45041, 45048, 45062, + 45074, 45094, 45105, 45116, 45129, 45140, 45159, 45170, 45182, 45201, 45212, 45220, 45229, 45239, 45247, 45256, + 45267, 45274, 45283, 45284, 45290, 45294, 45302, 45311, 45317, 45323, 45330, 45341, 45357, 45366, 45376, 45385, + 45394, 45399, 45408, 45422, 45436, 45450, 45467, 45481, 45496, 45505, 45511, 45520, 45529, 45538, 45548, 45553, + 45563, 45576, 45586, 45600, 45610, 45623, 45644, 45658, 45667, 45685, 45695, 45702, 45709, 45724, 45739, 45753, + 45763, 45773, 45786, 45805, 45823, 45837, 45842, 45851, 45858, 45864, 45871, 45885, 45892, 45907, 45927, 45939, + 45951, 45965, 45974, 45985, 45990, 46004, 46018, 46032, 46055, 46072, 46095, 46101, 46112, 46123, 46132, 46138, + 46148, 46158, 46173, 46191, 46206, 46225, 46242, 46256, 46274, 46275, 46281, 46291, 46301, 46311, 46314, 46323, + 46334, 46349, 46358, 46366, 46380, 46392, 46404, 46411, 46420, 46430, 46439, 46453, 46469, 46484, 46494, 46499, + 46510, 46530, 46550, 46568, 46583, 46594, 46599, 46609, 46622, 46632, 46646, 46660, 46671, 46686, 46696, 46706, + 46729, 46752, 46766, 46789, 46799, 46805, 46811, 46818, 46828, 46838, 46839, 46845, 46854, 46864, 46874, 46893, + 46901, 46916, 46931, 46942, 46950, 46972, 46981, 46995, 47014, 47038, 47046, 47053, 47064, 47073, 47083, 47092, + 47102, 47113, 47123, 47131, 47140, 47146, 47157, 47168, 47186, 47208, 47238, 47261, 47292, 47304, 47343, 47373, + 47398, 47428, 47453, 47479, 47506, 47537, 47563, 47579, 47595, 47606, 47615, 47629, 47658, 47688, 47716, 47739, + 47749, 47759, 47767, 47777, 47787, 47797, 47816, 47819, 47831, 47841, 47847, 47852, 47861, 47868, 47872, 47873, + 47882, 47891, 47898, 47907, 47917, 47928, 47930, 47940, 47946, 47955, 47956, 47967, 47976, 47982, 47988, 47997, + 48007, 48017, 48027, 48037, 48056, 48064, 48076, 48091, 48106, 48130, 48141, 48148, 48159, 48168, 48178, 48187, + 48196, 48211, 48231, 48245, 48264, 48288, 48314, 48339, 48355, 48370, 48390, 48411, 48429, 48452, 48460, 48463, + 48475, 48484, 48501, 48519, 48541, 48553, 48573, 48587, 48608, 48626, 48637, 48643, 48648, 48658, 48668, 48678, + 48686, 48693, 48705, 48715, 48718, 48727, 48742, 48751, 48763, 48780, 48790, 48799, 48809, 48828, 48836, 48851, + 48866, 48890, 48898, 48909, 48919, 48928, 48938, 48944, 48957, 48978, 48980, 48985, 48994, 49000, 49007, 49017, + 49026, 49036, 49055, 49063, 49077, 49099, 49116, 49141, 49156, 49171, 49195, 49205, 49216, 49226, 49233, 49234, + 49244, 49250, 49256, 49266, 49275, 49289, 49305, 49315, 49330, 49340, 49355, 49365, 49381, 49397, 49408, 49413, + 49424, 49441, 49452, 49461, 49467, 49474, 49485, 49490, 49494, 49504, 49513, 49523, 49542, 49560, 49570, 49580, + 49584, 49594, 49605, 49613, 49625, 49637, 49651, 49663, 49676, 49688, 49699, 49711, 49719, 49734, 49752, 49766, + 49770, 49780, 49791, 49807, 49818, 49838, 49857, 49867, 49877, 49888, 49898, 49908, 49918, 49928, 49934, 49948, + 49955, 49965, 49975, + ]; + + /// The Unicode values of each name, concatenated. + private const string AglValues = + "A\u00C6\u01FC\u01E2\uF7E6\u00C1\uF7E1\u0102\u1EAE\u04D0\u1EB6\u1EB0\u1EB2\u1EB4\u01CD\u24B6\u00C2\u1EA4\u1EAC\u1EA6\u1EA8\uF7E2\u1EAA\uF6C9\uF7B4\u0410\u0200\u00C4\u04D2\u01DE\uF7E4\u1EA0\u01E0\u00C0\uF7E0\u1EA2\u04D4\u0202\u0391\u0386\u0100\uFF21\u0104\u00C5\u01FA\u1E00\uF7E5\uF761\u00C3\uF7E3\u0531B\u24B7\u1E02\u1E04\u0411\u0532\u0392\u0181\u1E06\uFF22\uF6F4\uF762\u0182C\u053E\u0106\uF6CA\uF6F5\u010C\u00C7\u1E08\uF7E7\u24B8\u0108\u010A\u010A\uF7B8\u0549\u04BC" + + "\u0427\u04BE\u04B6\u04F4\u0543\u04CB\u04B8\u03A7\u0187\uF6F6\uFF23\u0551\uF763D\u01F1\u01C4\u0534\u0189\u010E\u1E10\u24B9\u1E12\u0110\u1E0A\u1E0C\u0414\u03EE\u2206\u0394\u018A\uF6CB\uF6CC\uF6CD\uF7A8\u03DC\u0402\u1E0E\uFF24\uF6F7\u0110\uF764\u018B\u01F2\u01C5\u04E0\u0405\u040FE\u00C9\uF7E9\u0114\u011A\u1E1C\u0535\u24BA\u00CA\u1EBE\u1E18\u1EC6\u1EC0\u1EC2\uF7EA\u1EC4\u0404\u0204\u00CB\uF7EB\u0116\u0116\u1EB8\u0424\u00C8\uF7E8\u0537\u1EBA\u2167\u0206\u0464\u041B\u216A" + + "\u0112\u1E16\u1E14\u041C\uFF25\u041D\u04A2\u014A\u04A4\u04C7\u0118\u0190\u0395\u0388\u0420\u018E\u042D\u0421\u04AA\u01A9\uF765\u0397\u0538\u0389\u00D0\uF7F0\u1EBC\u1E1A\u20AC\u01B7\u01EE\u01B8F\u24BB\u1E1E\u0556\u03E4\u0191\u0472\u2164\uFF26\u2163\uF766G\u3387\u01F4\u0393\u0194\u03EA\u011E\u01E6\u0122\u24BC\u011C\u0122\u0120\u0120\u0413\u0542\u0494\u0492\u0490\u0193\u0533\u0403\u1E20\uFF27\uF6CE\uF760\uF767\u029B\u01E4H\u25CF\u25AA\u25AB\u25A1\u33CB\u04A8\u04B2" + + "\u042A\u0126\u1E2A\u1E28\u24BD\u0124\u1E26\u1E22\u1E24\uFF28\u0540\u03E8\uF768\uF6CF\uF6F8\u3390I\u042F\u0132\u042E\u00CD\uF7ED\u012C\u01CF\u24BE\u00CE\uF7EE\u0406\u0208\u00CF\u1E2E\u04E4\uF7EF\u0130\u0130\u1ECA\u04D6\u0415\u2111\u00CC\uF7EC\u1EC8\u0418\u020A\u0419\u012A\u04E2\uFF29\u053B\u0401\u012E\u0399\u0196\u03AA\u038A\uF769\u0197\u0128\u1E2C\u0474\u0476J\u0541\u24BF\u0134\u0408\u054B\uFF2A\uF76AK\u3385\u33CD\u04A0\u1E30\u041A\u049A\u04C3\u039A\u049E\u049C" + + "\u01E8\u0136\u24C0\u0136\u1E32\u0554\u053F\u0425\u03E6\u0198\u040C\u1E34\uFF2B\u0480\u03DE\u046E\uF76BL\u01C7\uF6BF\u0139\u039B\u013D\u013B\u24C1\u1E3C\u013B\u013F\u013F\u1E36\u1E38\u053C\u01C8\u0409\u1E3A\uFF2C\u0141\uF6F9\uF76CM\u3386\uF6D0\uF7AF\u1E3E\u24C2\u1E40\u1E42\u0544\uFF2D\uF76D\u019C\u039CN\u01CA\u0143\u0147\u0145\u24C3\u1E4A\u0145\u1E44\u1E46\u019D\u2168\u01CB\u040A\u1E48\uFF2E\u0546\uF76E\u00D1\uF7F1\u039DO\u0152\uF6FA\u00D3\uF7F3\u04E8\u04EA" + + "\u014E\u01D1\u019F\u24C4\u00D4\u1ED0\u1ED8\u1ED2\u1ED4\uF7F4\u1ED6\u041E\u0150\u020C\u00D6\u04E6\uF7F6\u1ECC\uF6FB\u00D2\uF7F2\u0555\u2126\u1ECE\u01A0\u1EDA\u1EE2\u1EDC\u1EDE\u1EE0\u0150\u01A2\u020E\u014C\u1E52\u1E50\u2126\u0460\u03A9\u047A\u047C\u038F\u039F\u038C\uFF2F\u2160\u01EA\u01EC\u0186\u00D8\u01FE\uF7F8\uF76F\u01FE\u047E\u00D5\u1E4C\u1E4E\uF7F5P\u1E54\u24C5\u1E56\u041F\u054A\u04A6\u03A6\u01A4\u03A0\u0553\uFF30\u03A8\u0470\uF770Q\u24C6\uFF31\uF771R\u054C" + + "\u0154\u0158\u0156\u24C7\u0156\u0210\u1E58\u1E5A\u1E5C\u0550\u211C\u03A1\uF6FC\u0212\u1E5E\uFF32\uF772\u0281\u02B6S\u250C\u2514\u2510\u2518\u253C\u252C\u2534\u251C\u2524\u2500\u2502\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u015A\u1E64\u03E0\u0160\u1E66\uF6FD\u015E\u018F\u04D8\u04DA\u24C8\u015C\u0218\u1E60\u1E62\u1E68\u054D\u2166\u0547\u0428" + + "\u0429\u03E2\u04BA\u03EC\u03A3\u2165\uFF33\u042C\uF773\u03DAT\u03A4\u0166\u0164\u0162\u24C9\u1E70\u0162\u1E6A\u1E6C\u0422\u04AC\u2169\u04B4\u0398\u01AC\u00DE\uF7FE\u2162\uF6FE\u054F\u1E6E\uFF34\u0539\u01BC\u0184\u01A7\u01AE\u0426\u040B\uF774\u216B\u2161U\u00DA\uF7FA\u016C\u01D3\u24CA\u00DB\u1E76\uF7FB\u0423\u0170\u0214\u00DC\u01D7\u1E72\u01D9\u04F0\u01DB\u01D5\uF7FC\u1EE4\u00D9\uF7F9\u1EE6\u01AF\u1EE8\u1EF0\u1EEA\u1EEC\u1EEE\u0170\u04F2\u0216\u0478\u016A\u04EE\u1E7A" + + "\uFF35\u0172\u03A5\u03D2\u03D3\u01B1\u03AB\u03D4\u03D2\u038E\u016E\u040E\uF775\u04AE\u04B0\u0168\u1E78\u1E74V\u24CB\u1E7E\u0412\u054E\u01B2\uFF36\u0548\uF776\u1E7CW\u1E82\u24CC\u0174\u1E84\u1E86\u1E88\u1E80\uFF37\uF777X\u24CD\u1E8C\u1E8A\u053D\u039E\uFF38\uF778Y\u00DD\uF7FD\u0462\u24CE\u0176\u0178\uF7FF\u1E8E\u1EF4\u042B\u04F8\u1EF2\u01B3\u1EF6\u0545\u0407\u0552\uFF39\uF779\u1EF8\u046A\u046C\u0466\u0468Z\u0536\u0179\u017D\uF6FF\u24CF\u1E90\u017B\u017B" + + "\u1E92\u0417\u0498\u04DE\u0396\u053A\u04C1\u0416\u0496\u04DC\u1E94\uFF3A\uF77A\u01B5a\u0986\u00E1\u0906\u0A86\u0A06\u0A3E\u3303\u09BE\u093E\u0ABE\u055F\u0970\u0985\u311A\u0103\u1EAF\u04D1\u1EB7\u1EB1\u1EB3\u1EB5\u01CE\u24D0\u00E2\u1EA5\u1EAD\u1EA7\u1EA9\u1EAB\u00B4\u0317\u0301\u0301\u0954\u02CF\u0341\u0430\u0201\u0A71\u0905\u00E4\u04D3\u01DF\u1EA1\u01E1\u00E6\u01FD\u3150\u01E3\u2015\u20A4\u0410\u0411\u0412\u0413\u0414\u0415\u0401\u0416\u0417\u0418\u0419\u041A\u041B\u041C" + + "\u041D\u041E\u041F\u0420\u0421\u0422\u0423\u0424\u0425\u0426\u0427\u0428\u0429\u042A\u042B\u042C\u042D\u042E\u042F\u0490\u0402\u0403\u0404\u0405\u0406\u0407\u0408\u0409\u040A\u040B\u040C\u040E\uF6C4\uF6C5\u0430\u0431\u0432\u0433\u0434\u0435\u0451\u0436\u0437\u0438\u0439\u043A\u043B\u043C\u043D\u043E\u043F\u0440\u0441\u0442\u0443\u0444\u0445\u0446\u0447\u0448\u0449\u044A\u044B\u044C\u044D\u044E\u044F\u0491\u0452\u0453\u0454\u0455\u0456\u0457\u0458\u0459\u045A\u045B\u045C\u045E" + + "\u040F\u0462\u0472\u0474\uF6C6\u045F\u0463\u0473\u0475\uF6C7\uF6C8\u04D9\u200E\u200F\u200D\u066A\u060C\u0660\u0661\u0662\u0663\u0664\u0665\u0666\u0667\u0668\u0669\u061B\u061F\u0621\u0622\u0623\u0624\u0625\u0626\u0627\u0628\u0629\u062A\u062B\u062C\u062D\u062E\u062F\u0630\u0631\u0632\u0633\u0634\u0635\u0636\u0637\u0638\u0639\u063A\u0640\u0641\u0642\u0643\u0644\u0645\u0646\u0648\u0649\u064A\u064B\u064C\u064D\u064E\u064F\u0650\u0651\u0652\u0647\u06A4\u067E\u0686\u0698\u06AF\u0679" + + "\u0688\u0691\u06BA\u06D2\u06D5\u20AA\u05BE\u05C3\u05D0\u05D1\u05D2\u05D3\u05D4\u05D5\u05D6\u05D7\u05D8\u05D9\u05DA\u05DB\u05DC\u05DD\u05DE\u05DF\u05E0\u05E1\u05E2\u05E3\u05E4\u05E5\u05E6\u05E7\u05E8\u05E9\u05EA\uFB2A\uFB2B\uFB4B\uFB1F\u05F0\u05F1\u05F2\uFB35\u05B4\u05B5\u05B6\u05BB\u05B8\u05B7\u05B0\u05B2\u05B1\u05B3\u05C2\u05C1\u05B9\u05BC\u05BD\u05BF\u05C0\u02BC\u2105\u2113\u2116\u202C\u202D\u202E\u200C\u066D\u02BD\u00E0\u0A85\u0A05\u3042\u1EA3\u0990\u311E\u0910\u04D5\u0A90" + + "\u0A10\u0A48\u0639\uFECA\uFECB\uFECC\u0203\u09C8\u0948\u0AC8\u30A2\uFF71\u314F\u05D0\u0627\uFB30\uFE8E\u0623\uFE84\u0625\uFE88\u05D0\uFB4F\u0622\uFE82\u0649\uFEF0\uFEF3\uFEF4\uFB2E\uFB2F\u2135\u224C\u03B1\u03AC\u0101\uFF41&\uFF06\uF726\u33C2\u3122\u3124\u0E5A\u2220\u3008\uFE3F\u3009\uFE40\u2329\u232A\u212B\u0387\u0952\u0982\u0902\u0A82\u0105\u3300\u249C\u055A\u02BC\uF8FF\u2250\u2248\u2252\u2245\u318E\u318D\u2312\u1E9A\u00E5\u01FB\u1E01\u2194\u21E3\u21E0\u21E2\u21E1\u21D4" + + "\u21D3\u21D0\u21D2\u21D1\u2193\u2199\u2198\u21E9\u02C5\u02C2\u02C3\u02C4\uF8E7\u2190\u21D0\u21CD\u21C6\u21E6\u2192\u21CF\u279E\u21C4\u21E8\u21E4\u21E5\u2191\u2195\u21A8\u21A8\u2196\u21C5\u2197\u21E7\uF8E6^\uFF3E~\uFF5E\u0251\u0252\u3041\u30A1\uFF67*\u066D\u066D\u2217\uFF0A\uFE61\u2042\uF6E9\u2243@\u00E3\uFF20\uFE6B\u0250\u0994\u3120\u0914\u0A94\u0A14\u09D7\u0A4C\u09CC\u094C\u0ACC\u093D\u0561\u05E2\uFB20\u05E2b\u09AC\u005C\uFF3C\u092C\u0AAC\u0A2C\u3070" + + "\u0E3F\u30D0|\uFF5C\u3105\u24D1\u1E03\u1E05\u266C\u2235\u0431\u0628\uFE90\uFE91\u3079\uFE92\uFC9F\uFC08\uFC6D\u30D9\u0562\u05D1\u03B2\u03D0\uFB31\uFB31\u05D1\uFB4C\u09AD\u092D\u0AAD\u0A2D\u0253\u3073\u30D3\u0298\u0A02\u3331\u25CF\u25C6\u25BC\u25C4\u25C0\u3010\uFE3B\u3011\uFE3C\u25E3\u25E2\u25AC\u25BA\u25B6\u25AA\u263B\u25A0\u2605\u25E4\u25E5\u25B4\u25B2\u2423\u1E07\u2588\uFF42\u0E1A\u307C\u30DC\u249D\u33C3\uF8F4{\uF8F3\uF8F2\uFF5B\uFE5B\uF8F1\uFE37}\uF8FE\uF8FD" + + "\uFF5D\uFE5C\uF8FC\uFE38[\uF8F0\uF8EF\uFF3B\uF8EE]\uF8FB\uF8FA\uFF3D\uF8F9\u02D8\u032E\u0306\u032F\u0311\u0361\u032A\u033A\u00A6\u0180\uF6EA\u0183\u3076\u30D6\u2022\u25D8\u2219\u25CEc\u056E\u099A\u0107\u091A\u0A9A\u0A1A\u3388\u0981\u0310\u0901\u0A81\u21EA\u2105\u02C7\u032C\u030C\u21B5\u3118\u010D\u00E7\u1E09\u24D2\u0109\u0255\u010B\u010B\u33C5\u00B8\u0327\u00A2\u2103\uF6DF\uFFE0\uF7A2\uF6E0\u0579\u099B\u091B\u0A9B\u0A1B\u3114\u04BD\u2713\u0447\u04BF\u04B7\u04F5" + + "\u0573\u04CC\u04B9\u03C7\u3277\u3217\u3269\u314A\u3209\u0E0A\u0E08\u0E09\u0E0C\u0188\u3276\u3216\u3268\u3148\u3208\u321C\u25CB\u2297\u2299\u2295\u3036\u25D0\u25D1\u02C6\u032D\u0302\u2327\u01C2\u01C0\u01C1\u01C3\u2663\u2663\u2667\u33A4\uFF43\u33A0\u0581:\u20A1\uFF1A\u20A1\uFE55\u02D1\u02D0,\u0313\u0315\uF6C3\u060C\u055D\uF6E1\uFF0C\u0314\u02BD\uFE50\uF6E2\u0312\u02BB\u263C\u2245\u222E\u2303\u0006\u0007\u0008\u0018\u000D\u0011\u0012\u0013\u0014\u007F\u0010\u0019\u0005" + + "\u0004\u001B\u0017\u0003\u000C\u001C\u001D\u0009\u000A\u0015\u001E\u000F\u000E\u0002\u0001\u001A\u0016\u001F\u000B\u00A9\uF8E9\uF6D9\u300C\uFF62\uFE41\u300D\uFF63\uFE42\u337F\u33C7\u33C6\u249E\u20A2\u0297\u22CF\u22CE\u00A4\uF6D1\uF6D2\uF6D4\uF6D5d\u0564\u09A6\u0636\u0926\uFEBE\uFEBF\uFEC0\u05BC\u05BC\u2020\u2021\u0AA6\u0A26\u3060\u30C0\u062F\u05D3\uFB33\uFB33\u05D3\u05B2\u05D3\u05B2\u05D3\u05B1\u05D3\u05B1\u05D3\u05D3\u05B4\u05D3\u05B4\u05D3\u05B9\u05D3\u05B9\u05D3\u05B7" + + "\u05D3\u05B7\u05D3\u05B8\u05D3\u05B8\u05D3\u05BB\u05D3\u05BB\u05D3\u05B6\u05D3\u05B6\u05D3\u05B0\u05D3\u05B0\u05D3\u05B5\u05D3\u05B5\uFEAA\u064F\u064F\u064C\u064C\u0964\u05A7\u05A7\u0485\uF6D3\u300A\uFE3D\u300B\uFE3E\u032B\u21D4\u21D2\u0965\uF6D6\u030F\u222C\u2017\u0333\u033F\u02BA\u2016\u030E\u3109\u33C8\u010F\u1E11\u24D3\u1E13\u0111\u09A1\u0921\u0AA1\u0A21\u0688\uFB89\u095C\u09A2\u0922\u0AA2\u0A22\u1E0B\u1E0D\u066B\u066B\u0434\u00B0\u05AD\u3067\u03EF\u30C7\u232B\u2326\u03B4" + + "\u018D\u09F8\u02A4\u09A7\u0927\u0AA7\u0A27\u0257\u0385\u0344\u2666\u2662\u00A8\uF6D7\u0324\u0308\uF6D8\u0385\u3062\u30C2\u3003\u00F7\u2223\u2215\u0452\u2593\u1E0F\u3397\u0111\uFF44\u2584\u0E0E\u0E14\u3069\u30C9$\uF6E3\uFF04\uF724\uFE69\uF6E4\u20AB\u3326\u02D9\u0307\u0323\u0323\u30FB\u0131\uF6BE\u0284\u22C5\u25CC\uFB1F\uFB1F\u031E\u02D5\u249F\uF6EB\u0256\u018C\u3065\u30C5\u01F3\u02A3\u01C6\u02A5\u04E1\u0455\u045Fe\u00E9\u2641\u098F\u311C\u0115\u090D\u0A8D\u0945\u0AC5" + + "\u011B\u1E1D\u0565\u0587\u24D4\u00EA\u1EBF\u1E19\u1EC7\u1EC1\u1EC3\u1EC5\u0454\u0205\u090F\u00EB\u0117\u0117\u1EB9\u0A0F\u0A47\u0444\u00E8\u0A8F\u0567\u311D\u3048\u1EBB\u311F8\u0668\u09EE\u2467\u2791\u096E\u2471\u2485\u2499\u0AEE\u0A6E\u0668\u3028\u266B\u3227\u2088\uFF18\uF738\u247B\u248F\u06F8\u2177\u2078\u0E58\u0207\u0465\u30A8\uFF74\u0A74\u3154\u043B\u2208\u246A\u247E\u2492\u217A\u2026\u22EE\u0113\u1E17\u1E15\u043C\u2014\uFE31\uFF45\u055B\u2205\u3123\u043D\u2013\uFE32" + + "\u04A3\u014B\u3125\u04A5\u04C8\u2002\u0119\u3153\u025B\u029A\u025C\u025E\u025D\u24A0\u03B5\u03AD=\uFF1D\uFE66\u207C\u2261\u3126\u0440\u0258\u044D\u0441\u04AB\u0283\u0286\u090E\u0946\u01AA\u0285\u3047\u30A7\uFF6A\u212E\uF6EC\u03B7\u0568\u03AE\u00F0\u1EBD\u1E1B\u0591\u0591\u0591\u0591\u01DD\u3161\u20AC\u09C7\u0947\u0AC7!\u055C\u203C\u00A1\uF7A1\uFF01\uF721\u2203\u0292\u01EF\u0293\u01B9\u01BAf\u095E\u0A5E\u2109\u064E\u064E\u064B\u3108\u24D5\u1E1F\u0641\u0586\uFED2" + + "\uFED3\uFED4\u03E5\u2640\uFB00\uFB03\uFB04\uFB01\u246E\u2482\u2496\u2012\u25A0\u25AC\u05DA\uFB3A\uFB3A\u05DA\u05DA\u05B8\u05DA\u05B8\u05DA\u05B0\u05DA\u05B0\u05DD\u05DD\u05DF\u05DF\u05E3\u05E3\u05E5\u05E5\u02C9\u25C9\u04735\u0665\u09EB\u2464\u278E\u096B\u215D\u0AEB\u0A6B\u0665\u3025\u3224\u2085\uFF15\uF735\u2478\u248C\u06F5\u2174\u2075\u0E55\uFB02\u0192\uFF46\u3399\u0E1F\u0E1D\u0E4F\u22004\u0664\u09EA\u2463\u278D\u096A\u0AEA\u0A6A\u0664\u3024\u3223\u2084\uFF14\u09F7" + + "\uF734\u2477\u248B\u06F4\u2173\u2074\u246D\u2481\u2495\u0E54\u02CB\u24A1\u2044\u20A3g\u0997\u01F5\u0917\u06AF\uFB93\uFB94\uFB95\u0A97\u0A17\u304C\u30AC\u03B3\u0263\u02E0\u03EB\u310D\u011F\u01E7\u0123\u24D6\u011D\u0123\u0121\u0121\u0433\u3052\u30B2\u2251\u059C\u05F3\u059D\u00DF\u059E\u05F4\u3013\u0998\u0572\u0918\u0A98\u0A18\u063A\uFECE\uFECF\uFED0\u0495\u0493\u0491\u095A\u0A5A\u0260\u3393\u304E\u30AE\u0563\u05D2\uFB32\uFB32\u05D2\u0453\u01BE\u0294\u0296\u02C0\u0295\u02C1" + + "\u02E4\u02A1\u02A2\u1E21\uFF47\u3054\u30B4\u24A2\u33AC\u2207`\u0316\u0300\u0300\u0953\u02CE\uFF40\u0340>\u2265\u22DB\uFF1E\u2273\u2277\u2267\uFE65\u0261\u01E5\u3050\u00AB\u00BB\u2039\u203A\u30B0\u3318\u33C9h\u04A9\u06C1\u09B9\u04B3\u0939\u0AB9\u0A39\u062D\uFEA2\uFEA3\u306F\uFEA4\u332A\u30CF\uFF8A\u0A4D\u0621\u0621\u064F\u0621\u064C\u0621\u064E\u0621\u064B\u0621\u0621\u0650\u0621\u064D\u0621\u0652\u3164\u044A\u21BC\u21C0\u33CA\u05B2\u05B2\u05B2\u05B2\u05B2\u05B2" + + "\u05B2\u05B2\u05B3\u05B3\u05B3\u05B3\u05B3\u05B3\u05B3\u05B3\u05B1\u05B1\u05B1\u05B1\u05B1\u05B1\u05B1\u05B1\u0127\u310F\u1E2B\u1E29\u24D7\u0125\u1E27\u1E23\u1E25\u05D4\u2665\u2665\u2661\uFB34\uFB34\u06C1\u0647\u05D4\uFBA7\uFEEA\uFEEA\uFBA5\uFBA4\uFBA8\uFEEB\u3078\uFBA9\uFEEC\u337B\u30D8\uFF8D\u3336\u0267\u3339\u05D7\u05D7\u0266\u02B1\u327B\u321B\u326D\u314E\u320D\u3072\u30D2\uFF8B\u05B4\u05B4\u05B4\u05B4\u05B4\u05B4\u05B4\u05B4\u1E96\uFF48\u0570\u0E2B\u307B\u30DB\uFF8E\u05B9" + + "\u05B9\u05B9\u05B9\u05B9\u05B9\u05B9\u05B9\u0E2E\u0309\u0309\u0321\u0322\u3342\u03E9\u2015\u031B\u2668\u2302\u24A3\u02B0\u0265\u3075\u3333\u30D5\uFF8C\u02DD\u030B\u0195-\uF6E5\uFF0D\uFE63\uF6E6\u2010i\u00ED\u044F\u0987\u3127\u012D\u01D0\u24D8\u00EE\u0456\u0209\u328F\u328B\u323F\u323A\u32A5\u3006\u3001\uFF64\u3237\u32A3\u322F\u323D\u329D\u3240\u3296\u3236\u322B\u3232\u32A4\u3005\u3298\u3238\u32A7\u32A6\u32A9\u322E\u322A\u3234\u3002\u329E\u3243\u3239\u323E\u32A8\u3299" + + "\u3242\u3233\u3000\u3235\u3231\u323B\u3230\u323C\u322C\u322D\u3007\u328E\u328A\u3294\u3290\u328C\u328D\u0907\u00EF\u1E2F\u04E5\u1ECB\u04D7\u0435\u3275\u3215\u3267\u3147\u3207\u00EC\u0A87\u0A07\u3044\u1EC9\u0988\u0438\u0908\u0A88\u0A08\u0A40\u020B\u0439\u09C0\u0940\u0AC0\u0133\u30A4\uFF72\u3163\u02DC\u05AC\u012B\u04E3\u2253\u0A3F\uFF49\u2206\u221E\u056B\u222B\u2321\u2321\uF8F5\u2320\u2320\u2229\u3305\u25D8\u25D9\u263B\u0451\u012F\u03B9\u03CA\u0390\u0269\u03AF\u24A4\u0A72\u3043" + + "\u30A3\uFF68\u09FA\u0268\uF6ED\u309D\u30FD\u0129\u1E2D\u3129\u044E\u09BF\u093F\u0ABF\u0475\u0477j\u0571\u099C\u091C\u0A9C\u0A1C\u3110\u01F0\u24D9\u0135\u029D\u025F\u0458\u062C\uFE9E\uFE9F\uFEA0\u0698\uFB8B\u099D\u091D\u0A9D\u0A1D\u057B\u3004\uFF4A\u24A5\u02B2k\u04A1\u0995\u1E31\u043A\u049B\u0915\u05DB\u0643\uFB3B\uFB3B\uFEDA\u05DB\uFEDB\uFEDC\uFB4D\u0A95\u0A15\u304B\u04C4\u30AB\uFF76\u03BA\u03F0\u3171\u3184\u3178\u3179\u330D\u0640\u0640\u30F5\u3384\u0650\u064D\u049F" + + "\uFF70\u049D\u310E\u3389\u01E9\u0137\u24DA\u0137\u1E33\u0584\u3051\u30B1\uFF79\u056F\u30F6\u0138\u0996\u0445\u0916\u0A96\u0A16\u062E\uFEA6\uFEA7\uFEA8\u03E7\u0959\u0A59\u3278\u3218\u326A\u314B\u320A\u0E02\u0E05\u0E03\u0E04\u0E5B\u0199\u0E06\u3391\u304D\u30AD\uFF77\u3315\u3316\u3314\u326E\u320E\u3260\u3131\u3200\u3133\u045C\u1E35\u3398\u33A6\uFF4B\u33A2\u3053\u33C0\u0E01\u30B3\uFF7A\u331E\u0481\u327F\u0343\u24A6\u33AA\u046F\u33CF\u029E\u304F\u30AF\uFF78\u33B8\u33BEl\u09B2" + + "\u013A\u0932\u0AB2\u0A32\u0E45\uFEFC\uFEF8\uFEF7\uFEFA\uFEF9\uFEFB\uFEF6\uFEF5\u0644\u03BB\u019B\u05DC\uFB3C\uFB3C\u05DC\u05DC\u05B9\u05DC\u05B9\u05BC\u05DC\u05B9\u05BC\u05DC\u05B9\uFEDE\uFCCA\uFEDF\uFCC9\uFCCB\uFDF2\uFEE0\uFD88\uFCCC\uFEDF\uFEE4\uFEA0\uFEDF\uFEE4\uFEA8\u25EF\u019A\u026C\u310C\u013E\u013C\u24DB\u1E3D\u013C\u0140\u0140\u1E37\u1E39\u031A\u0318<\u2264\u22DA\uFF1C\u2272\u2276\u2266\uFE64\u026E\u258C\u026D\u20A4\u056C\u01C9\u0459\uF6C0\u0933\u0AB3\u1E3B\u0934" + + "\u09E1\u0961\u09E3\u0963\u026B\uFF4C\u33D0\u0E2C\u2227\u00AC\u2310\u2228\u0E25\u017F\uFE4E\u0332\uFE4D\u25CA\u24A7\u0142\u2113\uF6EE\u2591\u0E26\u098C\u090C\u09E2\u0962\u33D3m\u09AE\u00AF\u0331\u0304\u02CD\uFFE3\u1E3F\u092E\u0AAE\u0A2E\u05A4\u05A4\u307E\uF895\uF894\u0E4B\uF893\uF88C\uF88B\u0E48\uF88A\uF884\u0E31\uF889\u0E47\uF88F\uF88E\u0E49\uF88D\uF892\uF891\u0E4A\uF890\u0E46\u30DE\uFF8F\u2642\u3347\u05BE\u2642\u05AF\u3383\u3107\u33D4\u24DC\u33A5\u1E41\u1E43\u0645\uFEE2" + + "\uFEE3\uFEE4\uFCD1\uFC48\u334D\u3081\u337E\u30E1\uFF92\u05DE\uFB3E\uFB3E\u05DE\u0574\u05A5\u05A6\u05A6\u05A5\u0271\u3392\uFF65\u00B7\u3272\u3212\u3264\u3141\u3170\u3204\u316E\u316F\u307F\u30DF\uFF90\u2212\u0320\u2296\u02D7\u2213\u2032\u334A\u3349\u0270\u3396\u33A3\uFF4D\u339F\u3082\u33C1\u30E2\uFF93\u33D6\u0E21\u33A7\u33A8\u24A8\u33AB\u33B3\uF6EF\u026F\u00B5\u00B5\u3382\u226B\u226A\u338C\u03BC\u338D\u3080\u30E0\uFF91\u3395\u00D7\u339B\u05A3\u05A3\u266A\u266B\u266D\u266F\u33B2" + + "\u33B6\u33BC\u33B9\u33B7\u33BF\u33BDn\u09A8\u2207\u0144\u0928\u0AA8\u0A28\u306A\u30CA\uFF85\u0149\u3381\u310B\u00A0\u0148\u0146\u24DD\u1E4B\u0146\u1E45\u1E47\u306D\u30CD\uFF88\u20AA\u338B\u0999\u0919\u0A99\u0A19\u0E07\u3093\u0272\u0273\u326F\u320F\u3135\u3261\u3136\u3134\u3168\u3201\u3167\u3166\u306B\u30CB\uFF86\uF899\u0E4D9\u0669\u09EF\u2468\u2792\u096F\u0AEF\u0A6F\u0669\u3029\u3228\u2089\uFF19\uF739\u247C\u2490\u06F9\u2178\u2079\u2472\u2486\u249A\u0E59\u01CC\u045A" + + "\u30F3\uFF9D\u019E\u1E49\uFF4E\u339A\u09A3\u0923\u0AA3\u0A23\u0929\u306E\u30CE\uFF89\u00A0\u0E13\u0E19\u0646\uFEE6\u06BA\uFB9F\uFEE7\uFEEC\uFEE7\uFCD2\uFC4B\uFEE8\uFCD5\uFC4E\uFC8D\u220C\u2209\u2209\u2260\u226F\u2271\u2279\u2262\u226E\u2270\u2226\u2280\u2284\u2281\u2285\u0576\u24A9\u33B1\u207F\u00F1\u03BD\u306C\u30CC\uFF87\u09BC\u093C\u0ABC\u0A3C#\uFF03\uFE5F\u0374\u0375\u2116\u05E0\uFB40\uFB40\u05E0\u33B5\u33BB\u099E\u091E\u0A9E\u0A1Eo\u00F3\u0E2D\u0275\u04E9\u04EB" + + "\u0993\u311B\u014F\u0911\u0A91\u0949\u0AC9\u01D2\u24DE\u00F4\u1ED1\u1ED9\u1ED3\u1ED5\u1ED7\u043E\u0151\u020D\u0913\u00F6\u04E7\u1ECD\u0153\u315A\u02DB\u0328\u00F2\u0A93\u0585\u304A\u1ECF\u01A1\u1EDB\u1EE3\u1EDD\u1EDF\u1EE1\u0151\u01A3\u020F\u30AA\uFF75\u3157\u05AB\u014D\u1E53\u1E51\u0950\u03C9\u03D6\u0461\u0277\u047B\u047D\u03CE\u0AD0\u03BF\u03CC\uFF4F1\u0661\u09E7\u2460\u278A\u0967\u2024\u215B\uF6DC\u0AE7\u0A67\u0661\u00BD\u3021\u3220\u2081\uFF11\u09F4\uF731\u2474\u2488" + + "\u06F1\u00BC\u2170\u00B9\u0E51\u2153\u01EB\u01ED\u0A13\u0A4B\u0254\u24AA\u25E6\u2325\u00AA\u00BA\u221F\u0912\u094A\u00F8\u01FF\u3049\u30A9\uFF6B\u01FF\uF6F0\u047F\u00F5\u1E4D\u1E4F\u3121\u203E\uFE4A\u0305\uFE49\uFE4C\uFE4B\u00AF\u09CB\u094B\u0ACBp\u3380\u332B\u09AA\u1E55\u092A\u21DF\u21DE\u0AAA\u0A2A\u3071\u0E2F\u30D1\u0484\u04C0\u317F\u00B6\u2225(\uFD3E\uF8ED\uF8EC\u208D\uFF08\uFE59\u207D\uF8EB\uFE35)\uFD3F\uF8F8\uF8F7\u208E\uFF09\uFE5A\u207E\uF8F6\uFE36\u2202" + + "\u05C0\u0599\u33A9\u05B7\u05B7\u05B7\u05B7\u05B7\u05B7\u05B7\u05B7\u05A1\u3106\u24DF\u1E57\u05E4\u043F\uFB44\uFB44\u333B\uFB43\u067E\u057A\u05E4\uFB57\uFB58\u307A\uFB59\u30DA\u04A7\uFB4E%\u066A\uFF05\uFE6A.\u0589\u00B7\uFF61\uF6E7\uFF0E\uFE52\uF6E8\u0342\u22A5\u2030\u20A7\u338A\u09AB\u092B\u0AAB\u0A2B\u03C6\u03D5\u327A\u321A\u326C\u314D\u320C\u0278\u0E3A\u03D5\u01A5\u0E1E\u0E1C\u0E20\u03C0\u3273\u3213\u3176\u3265\u3172\u3142\u3205\u3174\u3144\u3175\u3177\u3173\u3074" + + "\u30D4\u03D6\u0583+\u031F\u2295\u00B1\u02D6\uFF0B\uFE62\u207A\uFF50\u33D8\u307D\u261F\u261C\u261E\u261D\u30DD\u0E1B\u3012\u3020\u24AB\u227A\u211E\u02B9\u2035\u220F\u2305\u30FC\u2318\u2282\u2283\u2237\u221D\u03C8\u0471\u0486\u33B0\u3077\u30D7\u33B4\u33BAq\u0958\u05A8\u0642\uFED6\uFED7\uFED8\u05B8\u05B8\u05B8\u05B8\u05B8\u05B8\u05B8\u05B8\u05B8\u05B8\u05B8\u05B8\u05B8\u05B8\u05B8\u05B8\u059F\u3111\u24E0\u02A0\uFF51\u05E7\uFB47\uFB47\u05E7\u05B2\u05E7\u05B2\u05E7\u05B1" + + "\u05E7\u05B1\u05E7\u05E7\u05B4\u05E7\u05B4\u05E7\u05B9\u05E7\u05B9\u05E7\u05B7\u05E7\u05B7\u05E7\u05B8\u05E7\u05B8\u05E7\u05BB\u05E7\u05BB\u05E7\u05B6\u05E7\u05B6\u05E7\u05B0\u05E7\u05B0\u05E7\u05B5\u05E7\u05B5\u24AC\u2669\u05BB\u05BB\u05BB\u05BB\u05BB\u05BB\u05BB\u05BB?\u061F\u055E\u00BF\uF7BF\u037E\uFF1F\uF73F\u0022\u201E\u201C\uFF02\u301E\u301D\u201D\u2018\u201B\u201B\u2019\u0149\u201A'\uFF07r\u057C\u09B0\u0155\u0930\u221A\uF8E5\u33AE\u33AF\u33AD\u05BF\u05BF" + + "\u0AB0\u0A30\u3089\u30E9\uFF97\u09F1\u09F0\u0264\u2236\u3116\u0159\u0157\u24E1\u0157\u0211\u1E59\u1E5B\u1E5D\u203B\u2286\u2287\u00AE\uF8E8\uF6DA\u0631\u0580\uFEAE\u308C\u0631\uFEF3\uFE8E\u0644\u30EC\uFF9A\u05E8\uFB48\u05E8\u05B2\u05E8\u05B2\u05E8\u05B1\u05E8\u05B1\u05E8\u05E8\u05B4\u05E8\u05B4\u05E8\u05B9\u05E8\u05B9\u05E8\u05B7\u05E8\u05B7\u05E8\u05B8\u05E8\u05B8\u05E8\u05BB\u05E8\u05BB\u05E8\u05B6\u05E8\u05B6\u05E8\u05B0\u05E8\u05B0\u05E8\u05B5\u05E8\u05B5\u223D\u0597\u0597" + + "\u2310\u027E\u027F\u09DD\u095D\u03C1\u027D\u027B\u02B5\u03F1\u02DE\u3271\u3211\u3263\u3140\u313A\u3169\u3139\u313B\u316C\u3203\u313F\u313C\u316B\u313D\u313E\u316A\u316D\u221F\u0319\u22BF\u308A\u30EA\uFF98\u02DA\u0325\u030A\u02BF\u0559\u031C\u02D3\u02BE\u0339\u02D2\u0213\u3351\u1E5F\u027C\u027A\uFF52\u308D\u30ED\uFF9B\u0E23\u24AD\u09DC\u0931\u0A5C\u0691\uFB8D\u09E0\u0960\u0AE0\u09C4\u0944\u0AC4\uF6F1\u2590\u0279\u02B4\u308B\u30EB\uFF99\u09F2\u09F3\uF6DD\u0E24\u098B\u090B\u0A8B" + + "\u09C3\u0943\u0AC3s\u09B8\u015B\u1E65\u0635\u0938\uFEBA\uFEBB\uFEBC\u0AB8\u0A38\u3055\u30B5\uFF7B\uFDFA\u05E1\uFB41\uFB41\u05E1\u0E32\u0E41\u0E44\u0E43\u0E33\u0E30\u0E40\uF886\u0E35\uF885\u0E34\u0E42\uF888\u0E37\uF887\u0E36\u0E38\u0E39\u3119\u0161\u1E67\u015F\u0259\u04D9\u04DB\u025A\u24E2\u015D\u0219\u1E61\u1E63\u1E69\u033C\u2033\u02CA\u00A7\u0633\uFEB2\uFEB3\uFEB4\u05B6\u05B6\u05B6\u05B6\u05B6\u05B6\u05B6\u0592\u05B6\u057D\u305B\u30BB\uFF7E;\u061B\uFF1B\uFE54\u309C" + + "\uFF9F\u3322\u33237\u0667\u09ED\u2466\u2790\u096D\u215E\u0AED\u0A6D\u0667\u3027\u3226\u2087\uFF17\uF737\u247A\u248E\u06F7\u2176\u2077\u2470\u2484\u2498\u0E57\u00AD\u0577\u09B6\u0448\u0651\uFC61\uFC5E\uFC60\u0651\u064B\uFC62\uFC5F\u2592\u2593\u2591\u2592\u0936\u0AB6\u0A36\u0593\u3115\u0449\u0634\uFEB6\uFEB7\uFEB8\u03E3\u20AA\u20AA\u05B0\u05B0\u05B0\u05B0\u05B0\u05B0\u05B0\u05B0\u05B0\u04BB\u03ED\u05E9\uFB49\uFB49\uFB2C\uFB2C\uFB2D\uFB2D\u05C1\u05E9\uFB2A\uFB2A\uFB2B\uFB2B" + + "\u0282\u03C3\u03C2\u03C2\u03F2\u3057\u30B7\uFF7C\u05BD\u05BD\u223C\u05C2\u3274\u3214\u317E\u3266\u317A\u3145\u317B\u3206\u317D\u317C6\u0666\u09EC\u2465\u278F\u096C\u0AEC\u0A6C\u0666\u3026\u3225\u2086\uFF16\uF736\u2479\u248D\u06F6\u2175\u2076\u246F\u09F9\u2483\u2497\u0E56/\uFF0F\u017F\u1E9B\u263A\uFF53\u05C3\u00AD\u044C\u305D\u30BD\uFF7F\u0338\u0337\u0E29\u0E28\u0E0B\u0E2A \u2660\u2660\u2664\u24AE\u033B\u33C4\u339D\u25A9\u25A4\u338F\u339E\u33CE\u33D1\u33D2" + + "\u338E\u33D5\u339C\u33A1\u25A6\u25A7\u25A8\u25A5\u25A3\u33DB\u09B7\u0937\u0AB7\u3149\u3185\u3180\u3132\u3165\u3143\u3146\u3138\uF6F2\u00A3\uFFE1\u0336\u0335\u2282\u228A\u2286\u227B\u220B\u3059\u30B9\uFF7D\u0652\u2211\u263C\u2283\u228B\u2287\u33DC\u337Ct\u09A4\u22A4\u22A3\u0924\u0AA4\u0A24\u0637\uFEC2\uFEC3\u305F\uFEC4\u337D\u30BF\uFF80\u0640\u03C4\u05EA\uFB4A\uFB4A\uFB4A\u05EA\u0167\u310A\u0165\u02A8\u0163\u0686\uFB7B\uFB7C\uFB7D\uFB7C\uFEE4\u24E3\u1E71\u0163\u1E97\u1E6B" + + "\u1E6D\u0442\u04AD\u062A\uFE96\uFCA2\uFC0C\uFE97\u3066\uFCA1\uFC0B\u0629\uFE94\uFE98\uFCA4\uFC0E\uFC73\u30C6\uFF83\u2121\u260E\u05A0\u05A9\u2469\u3229\u247D\u2491\u2179\u02A7\u05D8\uFB38\uFB38\u05D8\u04B5\u059B\u059B\u09A5\u0925\u0AA5\u0A25\u0630\uFEAC\uF898\uF897\u0E4C\uF896\u062B\uFE9A\uFE9B\uFE9C\u2203\u2234\u03B8\u03D1\u03D1\u3279\u3219\u326B\u314C\u320B\u246C\u2480\u2494\u0E11\u01AD\u0E12\u00FE\u0E17\u0E10\u0E18\u0E16\u0482\u066C\u066C3\u0663\u09E9\u2462\u278C\u0969" + + "\u215C\u0AE9\u0A69\u0663\u3023\u3222\u2083\uFF13\u09F6\uF733\u2476\u248A\u06F3\u00BE\uF6DE\u2172\u00B3\u0E53\u3394\u3061\u30C1\uFF81\u3270\u3210\u3262\u3137\u3202\u02DC\u0330\u0303\u0303\u0360\u223C\u0334\u033E\u2297\u0596\u0596\u0A70\u0483\u057F\u1E6F\uFF54\u0569\u3068\u30C8\uFF84\u02E5\u02E9\u02E6\u02E8\u02E7\u01BD\u0185\u01A8\u0384\u3327\u0E0F\u3014\uFE5D\uFE39\u3015\uFE5E\uFE3A\u0E15\u01AB\u24AF\u2122\uF8EA\uF6DB\u0288\u25BC\u25C4\u25BA\u25B2\u02A6\u05E6\uFB46\uFB46\u05E6" + + "\u0446\u05B5\u05B5\u05B5\u05B5\u05B5\u05B5\u05B5\u05B5\u045B\uF6F3\u099F\u091F\u0A9F\u0A1F\u0679\uFB67\uFB68\uFB69\u09A0\u0920\u0AA0\u0A20\u0287\u3064\u30C4\uFF82\u3063\u30C3\uFF6F\u246B\u247F\u2493\u217B\u2473\u5344\u2487\u249B2\u0662\u09E8\u2461\u278B\u0968\u2025\u2025\uFE30\u0AE8\u0A68\u0662\u3022\u3221\u2082\uFF12\u09F5\uF732\u2475\u2489\u06F2\u2171\u01BB\u00B2\u0E52\u2154u\u00FA\u0289\u0989\u3128\u016D\u01D4\u24E4\u00FB\u1E77\u0443\u0951\u0171\u0215\u0909\u00FC" + + "\u01D8\u1E73\u01DA\u04F1\u01DC\u01D6\u1EE5\u00F9\u0A89\u0A09\u3046\u1EE7\u01B0\u1EE9\u1EF1\u1EEB\u1EED\u1EEF\u0171\u04F3\u0217\u30A6\uFF73\u0479\u315C\u016B\u04EF\u1E7B\u0A41\uFF55_\u2017\uFF3F\uFE33\uFE4F\u222A\u2200\u0173\u24B0\u2580\u05C4\u03C5\u03CB\u03B0\u028A\u03CD\u031D\u02D4\u0A73\u016F\u045E\u3045\u30A5\uFF69\u04AF\u04B1\u0169\u1E79\u1E75\u098A\u090A\u0A8A\u0A0A\u0A42\u09C2\u0942\u0AC2\u09C1\u0941\u0AC1v\u0935\u0AB5\u0A35\u30F7\u05D5\uFB35\uFB35\uFB35\u05D5" + + "\uFB4B\uFB4B\u05F0\u05F1\u24E5\u1E7F\u0432\u06A4\uFB6B\uFB6C\uFB6D\u30F9\u2640|\u030D\u0329\u02CC\u02C8\u057E\u028B\u30F8\u09CD\u094D\u0ACD\u0983\u0903\u0A83\uFF56\u0578\u309E\u30FE\u309B\uFF9E\u30FA\u24B1\u1E7D\u028C\u3094\u30F4w\u1E83\u3159\u308F\u30EF\uFF9C\u3158\u308E\u30EE\u3357\u301C\uFE34\u0648\uFEEE\u0624\uFE86\u33DD\u24E6\u0175\u1E85\u1E87\u1E89\u3091\u2118\u30F1\u315E\u315D\u1E81\u25E6\u25CB\u25D9\u300E\uFE43\u300F\uFE44\u25C7\u25C8\u25BF\u25BD\u25C3\u25C1" + + "\u3016\u3017\u25B9\u25B7\u25AB\u263A\u25A1\u2606\u260F\u3018\u3019\u25B5\u25B3\u3090\u30F0\u315F\uFF57\u3092\u30F2\uFF66\u20A9\uFFE6\u0E27\u24B2\u1E98\u02B7\u028D\u01BFx\u033D\u3112\u24E7\u1E8D\u1E8B\u056D\u03BE\uFF58\u24B3\u02E3y\u334E\u09AF\u00FD\u092F\u3152\u0AAF\u0A2F\u3084\u30E4\uFF94\u3151\u0E4E\u3083\u30E3\uFF6C\u0463\u24E8\u0177\u00FF\u1E8F\u1EF5\u064A\u06D2\uFBAF\uFEF2\u0626\uFE8A\uFE8B\uFE8C\uFEF3\uFEF4\uFCDD\uFC58\uFC94\u06D1\u3156\u00A5\uFFE5\u3155\u3186" + + "\u05AA\u05AA\u044B\u04F9\u3181\u3183\u3182\u059A\u1EF3\u01B4\u1EF7\u0575\u0457\u3162\u262F\u0582\uFF59\u05D9\uFB39\uFB39\u05D9\u05F2\uFB1F\u3088\u3189\u30E8\uFF96\u315B\u3087\u30E7\uFF6E\u03F3\u3188\u3187\u0E22\u0E0D\u24B4\u037A\u0345\u01A6\u1E99\u02B8\u1EF9\u028E\u3086\u318C\u30E6\uFF95\u3160\u046B\u046D\u0467\u0469\u3085\u30E5\uFF6D\u318B\u318A\u09DF\u095Fz\u0566\u017A\u095B\u0A5B\u0638\uFEC6\uFEC7\u3056\uFEC8\u0632\uFEB0\u30B6\u0595\u0594\u0598\u05D6\uFB36\uFB36\u05D6" + + "\u3117\u017E\u24E9\u1E91\u0291\u017C\u017C\u1E93\u0437\u0499\u04DF\u305C\u30BC0\u0660\u09E6\u0966\u0AE6\u0A66\u0660\u2080\uFF10\uF730\u06F0\u2070\u0E50\uFEFF\u200C\u200B\u03B6\u3113\u056A\u04C2\u0436\u0497\u04DD\u3058\u30B8\u05AE\u1E95\uFF5A\u305E\u30BE\u24B5\u0290\u01B6\u305A\u30BA"; + + /// Where each value starts in the values; one more entry than there are names. + internal static ReadOnlySpan AglValueOffsets => + [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, + 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, + 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, + 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, + 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, + 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, + 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, + 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, + 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, + 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, + 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, + 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, + 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, + 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, + 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, + 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, + 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, + 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, + 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, + 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, + 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, + 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, + 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, + 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, + 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, + 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, + 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, + 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, + 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, + 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, + 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, + 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, + 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, + 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, + 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, + 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, + 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, + 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 902, + 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, + 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, + 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, + 969, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, + 991, 992, 993, 994, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, + 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, + 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, + 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, + 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1073, 1074, 1075, 1076, 1077, 1078, 1079, 1080, 1081, 1082, + 1083, 1084, 1085, 1086, 1087, 1088, 1089, 1090, 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099, 1100, + 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1118, + 1119, 1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1130, 1131, 1132, 1133, 1134, 1135, 1136, + 1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1147, 1148, 1149, 1150, 1151, 1152, 1153, 1154, + 1155, 1156, 1157, 1158, 1159, 1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168, 1169, 1170, 1171, 1172, + 1173, 1174, 1175, 1176, 1177, 1178, 1179, 1180, 1181, 1182, 1183, 1184, 1185, 1186, 1187, 1188, 1189, 1190, + 1191, 1192, 1193, 1194, 1195, 1196, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1204, 1205, 1206, 1207, 1208, + 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1219, 1220, 1221, 1222, 1223, 1224, 1225, 1226, + 1227, 1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1238, 1239, 1240, 1241, 1242, 1243, 1244, + 1245, 1246, 1247, 1248, 1249, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 1259, 1260, 1261, 1262, + 1263, 1264, 1265, 1266, 1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1276, 1277, 1278, 1279, 1280, + 1281, 1282, 1283, 1284, 1285, 1286, 1287, 1288, 1289, 1290, 1291, 1292, 1293, 1294, 1295, 1296, 1297, 1298, + 1299, 1300, 1301, 1302, 1303, 1304, 1305, 1306, 1307, 1308, 1309, 1310, 1311, 1312, 1313, 1314, 1315, 1316, + 1317, 1318, 1319, 1320, 1321, 1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1331, 1332, 1333, 1334, + 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343, 1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, + 1353, 1354, 1355, 1356, 1357, 1358, 1359, 1360, 1361, 1362, 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1370, + 1371, 1372, 1373, 1374, 1375, 1376, 1377, 1378, 1379, 1380, 1381, 1382, 1383, 1384, 1385, 1386, 1387, 1388, + 1389, 1390, 1391, 1392, 1393, 1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 1404, 1405, 1406, + 1407, 1408, 1409, 1410, 1411, 1412, 1413, 1414, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, + 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434, 1435, 1436, 1437, 1438, 1439, 1440, 1441, 1442, + 1443, 1444, 1445, 1446, 1447, 1448, 1449, 1450, 1451, 1452, 1453, 1454, 1455, 1456, 1457, 1458, 1459, 1460, + 1461, 1462, 1463, 1464, 1465, 1466, 1467, 1468, 1469, 1470, 1471, 1472, 1473, 1474, 1475, 1476, 1477, 1478, + 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1489, 1490, 1491, 1492, 1493, 1494, 1495, 1496, + 1497, 1498, 1499, 1500, 1501, 1503, 1505, 1507, 1509, 1510, 1512, 1514, 1516, 1518, 1520, 1522, 1524, 1526, + 1528, 1530, 1532, 1534, 1536, 1538, 1540, 1542, 1543, 1544, 1545, 1546, 1547, 1548, 1549, 1550, 1551, 1552, + 1553, 1554, 1555, 1556, 1557, 1558, 1559, 1560, 1561, 1562, 1563, 1564, 1565, 1566, 1567, 1568, 1569, 1570, + 1571, 1572, 1573, 1574, 1575, 1576, 1577, 1578, 1579, 1580, 1581, 1582, 1583, 1584, 1585, 1586, 1587, 1588, + 1589, 1590, 1591, 1592, 1593, 1594, 1595, 1596, 1597, 1598, 1599, 1600, 1601, 1602, 1603, 1604, 1605, 1606, + 1607, 1608, 1609, 1610, 1611, 1612, 1613, 1614, 1615, 1616, 1617, 1618, 1619, 1620, 1621, 1622, 1623, 1624, + 1625, 1626, 1627, 1628, 1629, 1630, 1631, 1632, 1633, 1634, 1635, 1636, 1637, 1638, 1639, 1640, 1641, 1642, + 1643, 1644, 1645, 1646, 1647, 1648, 1649, 1650, 1651, 1652, 1653, 1654, 1655, 1656, 1657, 1658, 1659, 1660, + 1661, 1662, 1663, 1664, 1665, 1666, 1667, 1668, 1669, 1670, 1671, 1672, 1673, 1674, 1675, 1676, 1677, 1678, + 1679, 1680, 1681, 1682, 1683, 1684, 1685, 1686, 1687, 1688, 1689, 1690, 1691, 1692, 1693, 1694, 1695, 1696, + 1697, 1698, 1699, 1700, 1701, 1702, 1703, 1704, 1705, 1706, 1707, 1708, 1709, 1710, 1711, 1712, 1713, 1714, + 1715, 1716, 1717, 1718, 1719, 1720, 1721, 1722, 1723, 1724, 1725, 1726, 1727, 1728, 1729, 1730, 1731, 1732, + 1733, 1734, 1735, 1736, 1737, 1738, 1739, 1740, 1741, 1742, 1743, 1744, 1745, 1746, 1747, 1748, 1749, 1750, + 1751, 1752, 1753, 1754, 1755, 1756, 1757, 1758, 1759, 1760, 1761, 1762, 1763, 1764, 1765, 1766, 1767, 1768, + 1769, 1770, 1771, 1772, 1773, 1774, 1775, 1776, 1777, 1778, 1779, 1780, 1781, 1782, 1783, 1784, 1785, 1786, + 1787, 1788, 1789, 1790, 1791, 1792, 1793, 1794, 1795, 1796, 1797, 1798, 1799, 1800, 1801, 1802, 1803, 1804, + 1805, 1806, 1807, 1808, 1809, 1810, 1811, 1812, 1813, 1814, 1815, 1816, 1817, 1818, 1819, 1820, 1821, 1822, + 1823, 1824, 1825, 1826, 1827, 1828, 1829, 1830, 1831, 1832, 1833, 1834, 1835, 1836, 1837, 1838, 1839, 1840, + 1841, 1842, 1843, 1844, 1845, 1846, 1847, 1848, 1849, 1850, 1851, 1852, 1853, 1854, 1855, 1856, 1857, 1858, + 1860, 1862, 1864, 1866, 1867, 1868, 1869, 1870, 1871, 1872, 1873, 1874, 1875, 1876, 1877, 1878, 1879, 1880, + 1881, 1882, 1883, 1884, 1885, 1886, 1887, 1888, 1889, 1890, 1891, 1892, 1893, 1894, 1895, 1896, 1897, 1898, + 1899, 1900, 1901, 1902, 1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1914, 1915, 1916, + 1917, 1918, 1919, 1920, 1921, 1922, 1923, 1924, 1925, 1926, 1927, 1928, 1929, 1930, 1931, 1932, 1933, 1934, + 1935, 1936, 1937, 1938, 1939, 1940, 1941, 1942, 1943, 1944, 1945, 1946, 1947, 1948, 1949, 1950, 1951, 1952, + 1953, 1954, 1955, 1956, 1957, 1958, 1959, 1960, 1961, 1962, 1963, 1964, 1965, 1966, 1967, 1968, 1969, 1970, + 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, + 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, + 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, + 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037, 2038, 2039, 2040, 2041, 2042, + 2043, 2044, 2045, 2046, 2047, 2048, 2049, 2050, 2051, 2052, 2053, 2054, 2056, 2058, 2060, 2062, 2063, 2065, + 2067, 2069, 2070, 2071, 2072, 2073, 2074, 2075, 2076, 2077, 2078, 2079, 2080, 2081, 2082, 2083, 2084, 2085, + 2086, 2087, 2088, 2089, 2090, 2091, 2092, 2093, 2094, 2095, 2096, 2097, 2098, 2099, 2100, 2101, 2102, 2103, + 2104, 2105, 2106, 2107, 2108, 2109, 2110, 2111, 2112, 2113, 2114, 2115, 2116, 2117, 2118, 2119, 2120, 2121, + 2122, 2123, 2124, 2125, 2126, 2127, 2128, 2129, 2130, 2131, 2132, 2133, 2134, 2135, 2136, 2137, 2138, 2139, + 2140, 2141, 2142, 2143, 2144, 2145, 2146, 2147, 2148, 2149, 2150, 2151, 2152, 2153, 2154, 2155, 2156, 2157, + 2158, 2159, 2160, 2161, 2162, 2163, 2164, 2165, 2166, 2167, 2168, 2169, 2170, 2171, 2172, 2173, 2174, 2175, + 2176, 2177, 2178, 2179, 2180, 2181, 2182, 2183, 2184, 2185, 2186, 2187, 2188, 2189, 2190, 2191, 2192, 2193, + 2194, 2195, 2196, 2197, 2198, 2199, 2200, 2201, 2202, 2203, 2204, 2205, 2206, 2207, 2208, 2209, 2210, 2211, + 2212, 2213, 2214, 2215, 2216, 2217, 2218, 2219, 2220, 2221, 2222, 2223, 2224, 2225, 2226, 2227, 2228, 2229, + 2230, 2231, 2232, 2233, 2234, 2235, 2236, 2237, 2238, 2239, 2240, 2241, 2242, 2243, 2244, 2245, 2246, 2247, + 2248, 2249, 2250, 2251, 2252, 2253, 2254, 2255, 2256, 2257, 2258, 2259, 2260, 2261, 2262, 2263, 2264, 2265, + 2266, 2267, 2268, 2269, 2270, 2271, 2272, 2273, 2274, 2275, 2276, 2277, 2278, 2279, 2280, 2281, 2282, 2283, + 2284, 2285, 2286, 2287, 2288, 2289, 2290, 2291, 2292, 2293, 2294, 2295, 2296, 2297, 2298, 2299, 2300, 2301, + 2302, 2303, 2304, 2305, 2306, 2307, 2308, 2309, 2310, 2311, 2312, 2313, 2314, 2315, 2316, 2317, 2318, 2319, + 2320, 2321, 2322, 2323, 2324, 2325, 2326, 2327, 2328, 2329, 2330, 2331, 2332, 2333, 2334, 2335, 2336, 2337, + 2338, 2339, 2340, 2341, 2342, 2343, 2344, 2345, 2346, 2347, 2348, 2349, 2350, 2351, 2352, 2353, 2354, 2355, + 2356, 2357, 2358, 2359, 2360, 2361, 2362, 2363, 2364, 2365, 2366, 2367, 2368, 2369, 2370, 2371, 2372, 2373, + 2374, 2375, 2376, 2377, 2378, 2379, 2380, 2381, 2382, 2383, 2384, 2385, 2386, 2387, 2388, 2389, 2390, 2391, + 2392, 2393, 2394, 2395, 2396, 2397, 2398, 2399, 2400, 2401, 2402, 2403, 2404, 2405, 2406, 2407, 2408, 2409, + 2410, 2411, 2412, 2413, 2414, 2415, 2416, 2417, 2418, 2419, 2420, 2421, 2422, 2423, 2424, 2425, 2426, 2427, + 2428, 2429, 2430, 2431, 2432, 2433, 2434, 2435, 2436, 2437, 2438, 2439, 2440, 2441, 2442, 2443, 2444, 2445, + 2446, 2447, 2448, 2449, 2450, 2451, 2452, 2453, 2454, 2455, 2456, 2457, 2458, 2459, 2460, 2461, 2462, 2463, + 2464, 2465, 2466, 2467, 2468, 2469, 2470, 2471, 2472, 2473, 2474, 2475, 2476, 2477, 2478, 2479, 2480, 2481, + 2482, 2483, 2484, 2485, 2486, 2487, 2488, 2489, 2490, 2491, 2492, 2493, 2494, 2495, 2496, 2497, 2498, 2499, + 2500, 2502, 2505, 2508, 2510, 2511, 2512, 2513, 2514, 2515, 2516, 2517, 2518, 2519, 2522, 2525, 2526, 2527, + 2528, 2529, 2530, 2531, 2532, 2533, 2534, 2535, 2536, 2537, 2538, 2539, 2540, 2541, 2542, 2543, 2544, 2545, + 2546, 2547, 2548, 2549, 2550, 2551, 2552, 2553, 2554, 2555, 2556, 2557, 2558, 2559, 2560, 2561, 2562, 2563, + 2564, 2565, 2566, 2567, 2568, 2569, 2570, 2571, 2572, 2573, 2574, 2575, 2576, 2577, 2578, 2579, 2580, 2581, + 2582, 2583, 2584, 2585, 2586, 2587, 2588, 2589, 2590, 2591, 2592, 2593, 2594, 2595, 2596, 2597, 2598, 2599, + 2600, 2601, 2602, 2603, 2604, 2605, 2606, 2607, 2608, 2609, 2610, 2611, 2612, 2613, 2614, 2615, 2616, 2617, + 2618, 2619, 2620, 2621, 2622, 2623, 2624, 2625, 2626, 2627, 2628, 2629, 2630, 2631, 2632, 2633, 2634, 2635, + 2636, 2637, 2638, 2639, 2640, 2641, 2642, 2643, 2644, 2645, 2646, 2647, 2648, 2649, 2650, 2651, 2652, 2653, + 2654, 2655, 2656, 2657, 2658, 2659, 2660, 2661, 2662, 2663, 2664, 2665, 2666, 2667, 2668, 2669, 2670, 2671, + 2672, 2673, 2674, 2675, 2676, 2677, 2678, 2679, 2680, 2681, 2682, 2683, 2684, 2685, 2686, 2687, 2688, 2689, + 2690, 2691, 2692, 2693, 2694, 2695, 2696, 2697, 2698, 2699, 2700, 2701, 2702, 2703, 2704, 2705, 2706, 2707, + 2708, 2709, 2710, 2711, 2712, 2713, 2714, 2715, 2716, 2717, 2718, 2719, 2720, 2721, 2722, 2723, 2724, 2725, + 2726, 2727, 2728, 2729, 2730, 2731, 2732, 2733, 2734, 2735, 2736, 2737, 2738, 2739, 2740, 2741, 2742, 2743, + 2744, 2745, 2746, 2747, 2748, 2749, 2750, 2751, 2752, 2753, 2754, 2755, 2756, 2757, 2758, 2759, 2760, 2761, + 2762, 2763, 2764, 2765, 2766, 2767, 2768, 2769, 2770, 2771, 2772, 2773, 2774, 2775, 2776, 2777, 2778, 2779, + 2780, 2781, 2782, 2783, 2784, 2785, 2786, 2787, 2788, 2789, 2790, 2791, 2792, 2793, 2794, 2795, 2796, 2797, + 2798, 2799, 2800, 2801, 2802, 2803, 2804, 2805, 2806, 2807, 2808, 2809, 2810, 2811, 2812, 2813, 2814, 2815, + 2816, 2817, 2818, 2819, 2820, 2821, 2823, 2824, 2825, 2826, 2827, 2828, 2829, 2830, 2831, 2832, 2833, 2834, + 2835, 2836, 2837, 2838, 2839, 2840, 2841, 2842, 2843, 2844, 2845, 2846, 2847, 2848, 2849, 2850, 2851, 2852, + 2853, 2854, 2855, 2856, 2857, 2858, 2859, 2860, 2861, 2862, 2863, 2864, 2865, 2866, 2867, 2868, 2869, 2870, + 2871, 2872, 2873, 2874, 2875, 2876, 2877, 2878, 2879, 2880, 2881, 2882, 2883, 2884, 2885, 2886, 2887, 2888, + 2889, 2890, 2891, 2892, 2893, 2894, 2895, 2896, 2897, 2898, 2899, 2900, 2901, 2902, 2903, 2904, 2905, 2906, + 2907, 2908, 2909, 2910, 2911, 2912, 2913, 2914, 2915, 2916, 2917, 2918, 2919, 2920, 2921, 2922, 2923, 2924, + 2925, 2926, 2927, 2928, 2929, 2930, 2931, 2932, 2933, 2934, 2935, 2936, 2937, 2938, 2939, 2940, 2941, 2942, + 2943, 2944, 2945, 2946, 2947, 2948, 2949, 2950, 2951, 2952, 2953, 2954, 2955, 2956, 2957, 2958, 2959, 2960, + 2961, 2962, 2963, 2964, 2965, 2966, 2967, 2968, 2969, 2970, 2971, 2972, 2973, 2974, 2975, 2976, 2977, 2978, + 2979, 2980, 2981, 2982, 2983, 2984, 2985, 2986, 2987, 2988, 2989, 2990, 2991, 2992, 2993, 2994, 2995, 2996, + 2997, 2998, 2999, 3000, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, 3009, 3010, 3011, 3012, 3013, 3014, + 3015, 3016, 3017, 3018, 3019, 3020, 3021, 3022, 3023, 3024, 3025, 3026, 3027, 3028, 3029, 3030, 3031, 3032, + 3033, 3034, 3035, 3036, 3037, 3038, 3039, 3040, 3041, 3042, 3043, 3044, 3045, 3046, 3047, 3048, 3049, 3050, + 3051, 3052, 3053, 3054, 3055, 3056, 3057, 3058, 3059, 3060, 3061, 3062, 3063, 3064, 3065, 3066, 3067, 3068, + 3069, 3070, 3071, 3072, 3073, 3074, 3075, 3076, 3077, 3078, 3079, 3080, 3081, 3082, 3083, 3084, 3085, 3086, + 3087, 3088, 3089, 3090, 3091, 3092, 3093, 3094, 3095, 3096, 3097, 3098, 3099, 3100, 3101, 3102, 3103, 3104, + 3105, 3106, 3107, 3108, 3109, 3110, 3111, 3112, 3113, 3114, 3115, 3116, 3117, 3118, 3119, 3120, 3121, 3122, + 3123, 3124, 3125, 3126, 3127, 3128, 3129, 3130, 3131, 3132, 3133, 3134, 3135, 3136, 3137, 3138, 3139, 3140, + 3141, 3142, 3143, 3144, 3145, 3146, 3147, 3148, 3149, 3150, 3151, 3152, 3153, 3154, 3155, 3156, 3157, 3158, + 3159, 3160, 3161, 3162, 3163, 3164, 3165, 3166, 3167, 3168, 3169, 3170, 3171, 3172, 3173, 3174, 3175, 3176, + 3177, 3178, 3179, 3180, 3181, 3182, 3183, 3184, 3185, 3186, 3187, 3188, 3189, 3190, 3191, 3192, 3193, 3194, + 3196, 3198, 3200, 3202, 3203, 3205, 3207, 3209, 3211, 3213, 3215, 3217, 3219, 3221, 3223, 3225, 3227, 3229, + 3231, 3233, 3235, 3236, 3237, 3238, 3239, 3240, 3241, 3242, 3243, 3244, 3245, 3246, 3247, 3248, 3249, 3250, + 3251, 3252, 3253, 3254, 3255, 3256, 3257, 3258, 3259, 3260, 3261, 3262, 3263, 3264, 3265, 3266, 3267, 3268, + 3269, 3270, 3271, 3272, 3273, 3274, 3275, 3276, 3277, 3278, 3279, 3280, 3281, 3282, 3283, 3284, 3285, 3286, + 3287, 3288, 3289, 3290, 3291, 3292, 3293, 3294, 3295, 3296, 3297, 3298, 3299, 3300, 3301, 3302, 3303, 3304, + 3305, 3306, 3307, 3308, 3312, 3313, 3314, 3315, 3316, 3318, 3320, 3322, 3324, 3325, 3327, 3329, 3331, 3333, + 3335, 3337, 3339, 3341, 3343, 3345, 3347, 3349, 3351, 3353, 3355, 3357, 3358, 3359, 3360, 3361, 3362, 3363, + 3364, 3365, 3366, 3367, 3368, 3369, 3370, 3371, 3372, 3373, 3374, 3375, 3376, 3377, 3378, 3379, 3380, 3381, + 3382, 3383, 3384, 3385, 3386, 3387, 3388, 3389, 3390, 3391, 3392, 3393, 3394, 3395, 3396, 3397, 3398, 3399, + 3400, 3401, 3402, 3403, 3404, 3405, 3406, 3407, 3408, 3409, 3410, 3411, 3412, 3413, 3414, 3415, 3416, 3417, + 3418, 3419, 3420, 3421, 3422, 3423, 3424, 3425, 3426, 3427, 3428, 3429, 3430, 3431, 3432, 3433, 3434, 3435, + 3436, 3437, 3438, 3439, 3440, 3441, 3442, 3443, 3444, 3445, 3446, 3447, 3448, 3449, 3450, 3451, 3452, 3453, + 3454, 3455, 3456, 3457, 3458, 3459, 3460, 3461, 3462, 3463, 3464, 3465, 3466, 3467, 3468, 3469, 3470, 3471, + 3472, 3473, 3474, 3475, 3476, 3477, 3478, 3479, 3480, 3481, 3482, 3483, 3484, 3485, 3486, 3487, 3488, 3489, + 3490, 3491, 3492, 3493, 3494, 3495, 3496, 3497, 3498, 3499, 3500, 3501, 3502, 3503, 3504, 3505, 3506, 3507, + 3508, 3509, 3510, 3511, 3512, 3513, 3514, 3515, 3516, 3517, 3518, 3519, 3520, 3521, 3522, 3523, 3524, 3525, + 3526, 3527, 3528, 3529, 3530, 3531, 3532, 3533, 3534, 3535, 3536, 3537, 3538, 3539, 3540, 3541, 3542, 3543, + 3544, 3545, 3546, 3547, 3548, 3549, 3550, 3551, 3552, 3553, 3554, 3555, 3557, 3558, 3559, 3560, 3561, 3562, + 3563, 3564, 3565, 3566, 3567, 3568, 3569, 3570, 3571, 3572, 3573, 3574, 3575, 3576, 3577, 3578, 3579, 3580, + 3581, 3582, 3583, 3584, 3585, 3586, 3587, 3588, 3589, 3590, 3591, 3592, 3593, 3594, 3595, 3596, 3597, 3598, + 3599, 3600, 3601, 3602, 3603, 3604, 3605, 3606, 3607, 3608, 3609, 3610, 3611, 3612, 3613, 3614, 3615, 3616, + 3617, 3618, 3619, 3620, 3621, 3622, 3623, 3624, 3625, 3626, 3627, 3628, 3629, 3630, 3631, 3632, 3633, 3634, + 3635, 3636, 3637, 3638, 3639, 3640, 3641, 3642, 3643, 3644, 3645, 3646, 3647, 3648, 3649, 3650, 3651, 3652, + 3653, 3654, 3655, 3656, 3657, 3658, 3659, 3660, 3661, 3662, 3663, 3664, 3665, 3666, 3667, 3668, 3669, 3670, + 3671, 3672, 3673, 3674, 3675, 3676, 3677, 3678, 3679, 3680, 3681, 3682, 3683, 3684, 3685, 3686, 3687, 3688, + 3689, 3690, 3691, 3692, 3693, 3694, 3695, 3696, 3697, 3698, 3699, 3700, 3701, 3702, 3703, 3704, 3705, 3706, + 3707, 3708, 3709, 3710, 3711, 3712, 3713, 3714, 3715, 3716, 3717, 3718, 3719, 3720, 3721, 3722, 3723, 3724, + 3725, 3726, 3727, 3728, 3729, 3730, 3731, 3732, 3733, 3734, 3735, 3736, 3737, 3738, 3739, 3740, 3741, 3742, + 3743, 3744, 3745, 3746, 3747, 3748, 3749, 3750, 3751, 3752, 3753, 3755, 3756, 3757, 3758, 3759, 3760, 3761, + 3762, 3763, 3764, 3765, 3766, 3767, 3768, 3769, 3770, 3771, 3772, 3773, 3774, 3775, 3776, 3777, 3778, 3779, + 3780, 3781, 3782, 3783, 3784, 3785, 3786, 3787, 3788, 3789, 3790, 3791, 3792, 3793, 3794, 3795, 3796, 3797, + 3798, 3799, 3800, 3801, 3802, 3803, 3804, 3805, 3806, 3807, 3808, 3809, 3810, 3811, 3812, 3813, 3814, 3815, + 3816, 3817, 3818, 3819, 3820, 3821, 3822, 3823, 3824, 3825, 3826, 3827, 3828, 3829, 3830, 3831, 3832, 3833, + 3834, 3835, 3836, 3837, 3838, 3839, 3840, 3841, 3842, 3843, 3844, 3845, 3846, 3847, 3848, 3849, 3850, 3851, + 3852, 3853, 3854, 3855, 3856, 3857, 3858, 3859, 3860, 3861, 3862, 3863, 3864, 3865, 3866, 3867, 3868, 3869, + 3870, 3871, 3872, 3873, 3874, 3875, 3876, 3877, 3878, 3879, 3880, 3881, 3882, 3883, 3884, 3885, 3886, 3887, + 3888, 3889, 3890, 3891, 3892, 3893, 3894, 3895, 3896, 3897, 3898, 3899, 3900, 3901, 3902, 3903, 3904, 3905, + 3906, 3907, 3908, 3909, 3910, 3911, 3912, 3913, 3914, 3915, 3916, 3917, 3918, 3919, 3920, 3921, 3922, 3923, + 3924, 3925, 3926, 3927, 3928, 3929, 3930, 3931, 3932, 3933, 3934, 3935, 3936, 3937, 3938, 3939, 3940, 3941, + 3942, 3943, 3944, 3945, 3946, 3947, 3948, 3949, 3950, 3951, 3952, 3953, 3954, 3955, 3956, 3957, 3958, 3959, + 3960, 3961, 3962, 3963, 3964, 3965, 3966, 3967, 3968, 3969, 3970, 3971, 3972, 3973, 3974, 3975, 3976, 3977, + 3978, 3979, 3980, 3981, 3982, 3983, 3984, 3985, 3986, 3987, 3988, 3989, 3990, 3991, 3992, 3993, 3994, 3995, + 3996, 3997, 3998, 3999, 4000, 4001, 4002, 4003, 4004, 4005, 4006, 4007, 4008, 4009, 4010, 4011, 4012, 4013, + 4014, 4015, 4016, 4017, 4018, 4019, 4020, 4021, 4022, 4023, 4024, 4025, 4026, 4027, 4028, 4029, 4030, 4031, + 4032, 4033, 4034, 4035, 4036, 4037, 4038, 4039, 4040, 4041, 4042, 4043, 4044, 4045, 4046, 4047, 4048, 4049, + 4050, 4051, 4052, 4053, 4054, 4055, 4056, 4057, 4058, 4059, 4060, 4061, 4062, 4063, 4064, 4065, 4066, 4067, + 4068, 4069, 4070, 4071, 4072, 4073, 4074, 4075, 4076, 4077, 4078, 4079, 4080, 4081, 4082, 4083, 4084, 4085, + 4086, 4087, 4088, 4089, 4090, 4091, 4092, 4093, 4094, 4095, 4096, 4097, 4098, 4099, 4100, 4101, 4102, 4103, + 4104, 4105, 4106, 4107, 4108, 4109, 4110, 4111, 4112, 4113, 4114, 4115, 4116, 4117, 4118, 4119, 4120, 4121, + 4122, 4123, 4124, 4125, 4126, 4127, 4128, 4129, 4130, 4131, 4132, 4133, 4134, 4135, 4136, 4137, 4138, 4139, + 4140, 4141, 4142, 4143, 4144, 4145, 4146, 4147, 4148, 4149, 4150, 4151, 4152, 4153, 4154, 4155, 4156, 4157, + 4158, 4159, 4160, 4161, 4162, 4163, 4164, 4165, 4166, 4167, 4168, 4169, 4170, 4171, 4172, 4173, 4174, 4175, + 4176, 4177, 4178, 4179, 4180, 4181, 4182, 4183, 4184, 4185, 4186, 4187, 4188, 4189, 4190, 4191, 4192, 4193, + 4194, 4195, 4196, 4197, 4198, 4199, 4200, 4201, 4202, 4203, 4204, 4205, 4206, 4207, 4208, 4209, 4210, 4211, + 4212, 4213, 4214, 4215, 4216, 4217, 4218, 4219, 4220, 4221, 4222, 4223, 4224, 4225, 4226, 4227, 4228, 4229, + 4230, 4231, 4232, 4233, 4234, 4235, 4236, 4237, 4238, 4239, 4240, 4241, 4242, 4243, 4244, 4245, 4246, 4247, + 4248, 4249, 4250, 4251, 4252, 4253, 4254, 4255, 4256, 4257, 4258, 4259, 4260, 4261, 4262, 4263, 4264, 4265, + 4266, 4267, 4268, 4269, 4270, 4271, 4272, 4273, 4274, 4275, 4276, 4277, 4278, 4279, 4280, 4281, 4282, 4283, + 4284, 4285, 4286, 4287, 4288, 4289, 4290, 4291, 4292, 4293, 4294, 4295, 4296, 4297, 4298, 4299, 4300, 4301, + 4302, 4303, 4304, 4305, 4306, 4307, 4308, 4309, 4310, 4311, 4312, 4313, 4314, 4315, 4316, 4317, 4318, 4319, + 4320, 4321, 4322, 4323, 4324, 4325, 4326, 4327, 4328, 4329, 4330, 4331, 4332, 4333, 4334, 4335, 4336, 4337, + 4338, 4339, 4340, 4341, 4342, 4343, 4344, 4345, 4346, 4347, 4348, 4349, 4350, 4351, 4352, 4353, 4354, 4355, + 4356, 4357, 4358, 4359, 4360, 4361, 4362, 4363, 4364, 4365, 4366, 4367, 4368, + ]; + + private const int ZapfCount = 201; + + /// The glyph names, ordinal order, concatenated. + private const string ZapfNames = + "a1a10a100a101a102a103a104a105a106a107a108a109a11a110a111a112a117a118a119a12a120a" + + "121a122a123a124a125a126a127a128a129a13a130a131a132a133a134a135a136a137a138a139a1" + + "4a140a141a142a143a144a145a146a147a148a149a15a150a151a152a153a154a155a156a157a158" + + "a159a16a160a161a162a163a164a165a166a167a168a169a17a170a171a172a173a174a175a176a1" + + "77a178a179a18a180a181a182a183a184a185a186a187a188a189a19a190a191a192a193a194a195" + + "a196a197a198a199a2a20a200a201a202a203a204a205a206a21a22a23a24a25a26a27a28a29a3a3" + + "0a31a32a33a34a35a36a37a38a39a4a40a41a42a43a44a45a46a47a48a49a5a50a51a52a53a54a55" + + "a56a57a58a59a6a60a61a62a63a64a65a66a67a68a69a7a70a71a72a73a74a75a76a77a78a79a8a8" + + "1a82a83a84a85a86a87a88a89a9a90a91a92a93a94a95a96a97a98a99"; + + /// Where each name starts in the names; one more entry than there are names. + internal static ReadOnlySpan ZapfNameOffsets => + [ + 0, 2, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 48, 52, 56, 60, 64, 68, 72, 75, 79, 83, 87, 91, 95, 99, 103, + 107, 111, 115, 118, 122, 126, 130, 134, 138, 142, 146, 150, 154, 158, 161, 165, 169, 173, 177, 181, 185, 189, + 193, 197, 201, 204, 208, 212, 216, 220, 224, 228, 232, 236, 240, 244, 247, 251, 255, 259, 263, 267, 271, 275, + 279, 283, 287, 290, 294, 298, 302, 306, 310, 314, 318, 322, 326, 330, 333, 337, 341, 345, 349, 353, 357, 361, + 365, 369, 373, 376, 380, 384, 388, 392, 396, 400, 404, 408, 412, 416, 418, 421, 425, 429, 433, 437, 441, 445, + 449, 452, 455, 458, 461, 464, 467, 470, 473, 476, 478, 481, 484, 487, 490, 493, 496, 499, 502, 505, 508, 510, + 513, 516, 519, 522, 525, 528, 531, 534, 537, 540, 542, 545, 548, 551, 554, 557, 560, 563, 566, 569, 572, 574, + 577, 580, 583, 586, 589, 592, 595, 598, 601, 604, 606, 609, 612, 615, 618, 621, 624, 627, 630, 633, 636, 638, + 641, 644, 647, 650, 653, 656, 659, 662, 665, 667, 670, 673, 676, 679, 682, 685, 688, 691, 694, 697, + ]; + + /// The Unicode values of each name, concatenated. + private const string ZapfValues = + "\u2701\u2721\u275E\u2761\u2762\u2763\u2764\u2710\u2765\u2766\u2767\u2660\u261B\u2665\u2666\u2663\u2709\u2708\u2707\u261E\u2460\u2461\u2462\u2463\u2464\u2465\u2466\u2467\u2468\u2469\u270C\u2776\u2777\u2778\u2779\u277A\u277B\u277C\u277D\u277E\u277F\u270D\u2780\u2781\u2782\u2783\u2784\u2785\u2786\u2787\u2788\u2789\u270E\u278A\u278B\u278C\u278D\u278E\u278F\u2790\u2791\u2792\u2793\u270F\u2794\u2192\u27A3\u2194\u2195\u2799\u279B\u279C\u279D\u279E\u2711\u279F\u27A0\u27A1\u27A2\u27A4" + + "\u27A5\u27A6\u27A7\u27A8\u27A9\u2712\u27AB\u27AD\u27AF\u27B2\u27B3\u27B5\u27B8\u27BA\u27BB\u27BC\u2713\u27BD\u27BE\u279A\u27AA\u27B6\u27B9\u2798\u27B4\u27B7\u27AC\u2702\u2714\u27AE\u27B1\u2703\u2750\u2752\u276E\u2770\u2715\u2716\u2717\u2718\u2719\u271A\u271B\u271C\u2722\u2704\u2723\u2724\u2725\u2726\u2727\u2605\u2729\u272A\u272B\u272C\u260E\u272D\u272E\u272F\u2730\u2731\u2732\u2733\u2734\u2735\u2736\u2706\u2737\u2738\u2739\u273A\u273B\u273C\u273D\u273E\u273F\u2740\u271D\u2741" + + "\u2742\u2743\u2744\u2745\u2746\u2747\u2748\u2749\u274A\u271E\u274B\u25CF\u274D\u25A0\u274F\u2751\u25B2\u25BC\u25C6\u2756\u271F\u25D7\u2758\u2759\u275A\u276F\u2771\u2772\u2773\u2768\u2720\u2769\u276C\u276D\u276A\u276B\u2774\u2775\u275B\u275C\u275D"; + + /// Where each value starts in the values; one more entry than there are names. + internal static ReadOnlySpan ZapfValueOffsets => + [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, + 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, + 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, + 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, + 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, + 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, + 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, + 199, 200, 201, + ]; +} diff --git a/src/Broadside/Fonts/Data/Afm/Courier-Bold.afm b/src/Broadside/Fonts/Data/Afm/Courier-Bold.afm new file mode 100644 index 00000000..2011decb --- /dev/null +++ b/src/Broadside/Fonts/Data/Afm/Courier-Bold.afm @@ -0,0 +1,684 @@ +StartFontMetrics 4.1 + +Comment Copyright (c) 1989, 1990, 1991, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. + +Comment Creation Date: Mon Jun 23 16:28:00 1997 + +Comment UniqueID 43048 + +Comment VMusage 41139 52164 + +FontName Courier-Bold + +FullName Courier Bold + +FamilyName Courier + +Weight Bold + +ItalicAngle 0 + +IsFixedPitch true + +CharacterSet ExtendedRoman + +FontBBox -113 -250 749 801 + +UnderlinePosition -100 + +UnderlineThickness 50 + +Version 003.000 + +Notice Copyright (c) 1989, 1990, 1991, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. + +EncodingScheme AdobeStandardEncoding + +CapHeight 562 + +XHeight 439 + +Ascender 629 + +Descender -157 + +StdHW 84 + +StdVW 106 + +StartCharMetrics 315 + +C 32 ; WX 600 ; N space ; B 0 0 0 0 ; + +C 33 ; WX 600 ; N exclam ; B 202 -15 398 572 ; + +C 34 ; WX 600 ; N quotedbl ; B 135 277 465 562 ; + +C 35 ; WX 600 ; N numbersign ; B 56 -45 544 651 ; + +C 36 ; WX 600 ; N dollar ; B 82 -126 519 666 ; + +C 37 ; WX 600 ; N percent ; B 5 -15 595 616 ; + +C 38 ; WX 600 ; N ampersand ; B 36 -15 546 543 ; + +C 39 ; WX 600 ; N quoteright ; B 171 277 423 562 ; + +C 40 ; WX 600 ; N parenleft ; B 219 -102 461 616 ; + +C 41 ; WX 600 ; N parenright ; B 139 -102 381 616 ; + +C 42 ; WX 600 ; N asterisk ; B 91 219 509 601 ; + +C 43 ; WX 600 ; N plus ; B 71 39 529 478 ; + +C 44 ; WX 600 ; N comma ; B 123 -111 393 174 ; + +C 45 ; WX 600 ; N hyphen ; B 100 203 500 313 ; + +C 46 ; WX 600 ; N period ; B 192 -15 408 171 ; + +C 47 ; WX 600 ; N slash ; B 98 -77 502 626 ; + +C 48 ; WX 600 ; N zero ; B 87 -15 513 616 ; + +C 49 ; WX 600 ; N one ; B 81 0 539 616 ; + +C 50 ; WX 600 ; N two ; B 61 0 499 616 ; + +C 51 ; WX 600 ; N three ; B 63 -15 501 616 ; + +C 52 ; WX 600 ; N four ; B 53 0 507 616 ; + +C 53 ; WX 600 ; N five ; B 70 -15 521 601 ; + +C 54 ; WX 600 ; N six ; B 90 -15 521 616 ; + +C 55 ; WX 600 ; N seven ; B 55 0 494 601 ; + +C 56 ; WX 600 ; N eight ; B 83 -15 517 616 ; + +C 57 ; WX 600 ; N nine ; B 79 -15 510 616 ; + +C 58 ; WX 600 ; N colon ; B 191 -15 407 425 ; + +C 59 ; WX 600 ; N semicolon ; B 123 -111 408 425 ; + +C 60 ; WX 600 ; N less ; B 66 15 523 501 ; + +C 61 ; WX 600 ; N equal ; B 71 118 529 398 ; + +C 62 ; WX 600 ; N greater ; B 77 15 534 501 ; + +C 63 ; WX 600 ; N question ; B 98 -14 501 580 ; + +C 64 ; WX 600 ; N at ; B 16 -15 584 616 ; + +C 65 ; WX 600 ; N A ; B -9 0 609 562 ; + +C 66 ; WX 600 ; N B ; B 30 0 573 562 ; + +C 67 ; WX 600 ; N C ; B 22 -18 560 580 ; + +C 68 ; WX 600 ; N D ; B 30 0 594 562 ; + +C 69 ; WX 600 ; N E ; B 25 0 560 562 ; + +C 70 ; WX 600 ; N F ; B 39 0 570 562 ; + +C 71 ; WX 600 ; N G ; B 22 -18 594 580 ; + +C 72 ; WX 600 ; N H ; B 20 0 580 562 ; + +C 73 ; WX 600 ; N I ; B 77 0 523 562 ; + +C 74 ; WX 600 ; N J ; B 37 -18 601 562 ; + +C 75 ; WX 600 ; N K ; B 21 0 599 562 ; + +C 76 ; WX 600 ; N L ; B 39 0 578 562 ; + +C 77 ; WX 600 ; N M ; B -2 0 602 562 ; + +C 78 ; WX 600 ; N N ; B 8 -12 610 562 ; + +C 79 ; WX 600 ; N O ; B 22 -18 578 580 ; + +C 80 ; WX 600 ; N P ; B 48 0 559 562 ; + +C 81 ; WX 600 ; N Q ; B 32 -138 578 580 ; + +C 82 ; WX 600 ; N R ; B 24 0 599 562 ; + +C 83 ; WX 600 ; N S ; B 47 -22 553 582 ; + +C 84 ; WX 600 ; N T ; B 21 0 579 562 ; + +C 85 ; WX 600 ; N U ; B 4 -18 596 562 ; + +C 86 ; WX 600 ; N V ; B -13 0 613 562 ; + +C 87 ; WX 600 ; N W ; B -18 0 618 562 ; + +C 88 ; WX 600 ; N X ; B 12 0 588 562 ; + +C 89 ; WX 600 ; N Y ; B 12 0 589 562 ; + +C 90 ; WX 600 ; N Z ; B 62 0 539 562 ; + +C 91 ; WX 600 ; N bracketleft ; B 245 -102 475 616 ; + +C 92 ; WX 600 ; N backslash ; B 99 -77 503 626 ; + +C 93 ; WX 600 ; N bracketright ; B 125 -102 355 616 ; + +C 94 ; WX 600 ; N asciicircum ; B 108 250 492 616 ; + +C 95 ; WX 600 ; N underscore ; B 0 -125 600 -75 ; + +C 96 ; WX 600 ; N quoteleft ; B 178 277 428 562 ; + +C 97 ; WX 600 ; N a ; B 35 -15 570 454 ; + +C 98 ; WX 600 ; N b ; B 0 -15 584 626 ; + +C 99 ; WX 600 ; N c ; B 40 -15 545 459 ; + +C 100 ; WX 600 ; N d ; B 20 -15 591 626 ; + +C 101 ; WX 600 ; N e ; B 40 -15 563 454 ; + +C 102 ; WX 600 ; N f ; B 83 0 547 626 ; L i fi ; L l fl ; + +C 103 ; WX 600 ; N g ; B 30 -146 580 454 ; + +C 104 ; WX 600 ; N h ; B 5 0 592 626 ; + +C 105 ; WX 600 ; N i ; B 77 0 523 658 ; + +C 106 ; WX 600 ; N j ; B 63 -146 440 658 ; + +C 107 ; WX 600 ; N k ; B 20 0 585 626 ; + +C 108 ; WX 600 ; N l ; B 77 0 523 626 ; + +C 109 ; WX 600 ; N m ; B -22 0 626 454 ; + +C 110 ; WX 600 ; N n ; B 18 0 592 454 ; + +C 111 ; WX 600 ; N o ; B 30 -15 570 454 ; + +C 112 ; WX 600 ; N p ; B -1 -142 570 454 ; + +C 113 ; WX 600 ; N q ; B 20 -142 591 454 ; + +C 114 ; WX 600 ; N r ; B 47 0 580 454 ; + +C 115 ; WX 600 ; N s ; B 68 -17 535 459 ; + +C 116 ; WX 600 ; N t ; B 47 -15 532 562 ; + +C 117 ; WX 600 ; N u ; B -1 -15 569 439 ; + +C 118 ; WX 600 ; N v ; B -1 0 601 439 ; + +C 119 ; WX 600 ; N w ; B -18 0 618 439 ; + +C 120 ; WX 600 ; N x ; B 6 0 594 439 ; + +C 121 ; WX 600 ; N y ; B -4 -142 601 439 ; + +C 122 ; WX 600 ; N z ; B 81 0 520 439 ; + +C 123 ; WX 600 ; N braceleft ; B 160 -102 464 616 ; + +C 124 ; WX 600 ; N bar ; B 255 -250 345 750 ; + +C 125 ; WX 600 ; N braceright ; B 136 -102 440 616 ; + +C 126 ; WX 600 ; N asciitilde ; B 71 153 530 356 ; + +C 161 ; WX 600 ; N exclamdown ; B 202 -146 398 449 ; + +C 162 ; WX 600 ; N cent ; B 66 -49 518 614 ; + +C 163 ; WX 600 ; N sterling ; B 72 -28 558 611 ; + +C 164 ; WX 600 ; N fraction ; B 25 -60 576 661 ; + +C 165 ; WX 600 ; N yen ; B 10 0 590 562 ; + +C 166 ; WX 600 ; N florin ; B -30 -131 572 616 ; + +C 167 ; WX 600 ; N section ; B 83 -70 517 580 ; + +C 168 ; WX 600 ; N currency ; B 54 49 546 517 ; + +C 169 ; WX 600 ; N quotesingle ; B 227 277 373 562 ; + +C 170 ; WX 600 ; N quotedblleft ; B 71 277 535 562 ; + +C 171 ; WX 600 ; N guillemotleft ; B 8 70 553 446 ; + +C 172 ; WX 600 ; N guilsinglleft ; B 141 70 459 446 ; + +C 173 ; WX 600 ; N guilsinglright ; B 141 70 459 446 ; + +C 174 ; WX 600 ; N fi ; B 12 0 593 626 ; + +C 175 ; WX 600 ; N fl ; B 12 0 593 626 ; + +C 177 ; WX 600 ; N endash ; B 65 203 535 313 ; + +C 178 ; WX 600 ; N dagger ; B 106 -70 494 580 ; + +C 179 ; WX 600 ; N daggerdbl ; B 106 -70 494 580 ; + +C 180 ; WX 600 ; N periodcentered ; B 196 165 404 351 ; + +C 182 ; WX 600 ; N paragraph ; B 6 -70 576 580 ; + +C 183 ; WX 600 ; N bullet ; B 140 132 460 430 ; + +C 184 ; WX 600 ; N quotesinglbase ; B 175 -142 427 143 ; + +C 185 ; WX 600 ; N quotedblbase ; B 65 -142 529 143 ; + +C 186 ; WX 600 ; N quotedblright ; B 61 277 525 562 ; + +C 187 ; WX 600 ; N guillemotright ; B 47 70 592 446 ; + +C 188 ; WX 600 ; N ellipsis ; B 26 -15 574 116 ; + +C 189 ; WX 600 ; N perthousand ; B -113 -15 713 616 ; + +C 191 ; WX 600 ; N questiondown ; B 99 -146 502 449 ; + +C 193 ; WX 600 ; N grave ; B 132 508 395 661 ; + +C 194 ; WX 600 ; N acute ; B 205 508 468 661 ; + +C 195 ; WX 600 ; N circumflex ; B 103 483 497 657 ; + +C 196 ; WX 600 ; N tilde ; B 89 493 512 636 ; + +C 197 ; WX 600 ; N macron ; B 88 505 512 585 ; + +C 198 ; WX 600 ; N breve ; B 83 468 517 631 ; + +C 199 ; WX 600 ; N dotaccent ; B 230 498 370 638 ; + +C 200 ; WX 600 ; N dieresis ; B 128 498 472 638 ; + +C 202 ; WX 600 ; N ring ; B 198 481 402 678 ; + +C 203 ; WX 600 ; N cedilla ; B 205 -206 387 0 ; + +C 205 ; WX 600 ; N hungarumlaut ; B 68 488 588 661 ; + +C 206 ; WX 600 ; N ogonek ; B 169 -199 400 0 ; + +C 207 ; WX 600 ; N caron ; B 103 493 497 667 ; + +C 208 ; WX 600 ; N emdash ; B -10 203 610 313 ; + +C 225 ; WX 600 ; N AE ; B -29 0 602 562 ; + +C 227 ; WX 600 ; N ordfeminine ; B 147 196 453 580 ; + +C 232 ; WX 600 ; N Lslash ; B 39 0 578 562 ; + +C 233 ; WX 600 ; N Oslash ; B 22 -22 578 584 ; + +C 234 ; WX 600 ; N OE ; B -25 0 595 562 ; + +C 235 ; WX 600 ; N ordmasculine ; B 147 196 453 580 ; + +C 241 ; WX 600 ; N ae ; B -4 -15 601 454 ; + +C 245 ; WX 600 ; N dotlessi ; B 77 0 523 439 ; + +C 248 ; WX 600 ; N lslash ; B 77 0 523 626 ; + +C 249 ; WX 600 ; N oslash ; B 30 -24 570 463 ; + +C 250 ; WX 600 ; N oe ; B -18 -15 611 454 ; + +C 251 ; WX 600 ; N germandbls ; B 22 -15 596 626 ; + +C -1 ; WX 600 ; N Idieresis ; B 77 0 523 761 ; + +C -1 ; WX 600 ; N eacute ; B 40 -15 563 661 ; + +C -1 ; WX 600 ; N abreve ; B 35 -15 570 661 ; + +C -1 ; WX 600 ; N uhungarumlaut ; B -1 -15 628 661 ; + +C -1 ; WX 600 ; N ecaron ; B 40 -15 563 667 ; + +C -1 ; WX 600 ; N Ydieresis ; B 12 0 589 761 ; + +C -1 ; WX 600 ; N divide ; B 71 16 529 500 ; + +C -1 ; WX 600 ; N Yacute ; B 12 0 589 784 ; + +C -1 ; WX 600 ; N Acircumflex ; B -9 0 609 780 ; + +C -1 ; WX 600 ; N aacute ; B 35 -15 570 661 ; + +C -1 ; WX 600 ; N Ucircumflex ; B 4 -18 596 780 ; + +C -1 ; WX 600 ; N yacute ; B -4 -142 601 661 ; + +C -1 ; WX 600 ; N scommaaccent ; B 68 -250 535 459 ; + +C -1 ; WX 600 ; N ecircumflex ; B 40 -15 563 657 ; + +C -1 ; WX 600 ; N Uring ; B 4 -18 596 801 ; + +C -1 ; WX 600 ; N Udieresis ; B 4 -18 596 761 ; + +C -1 ; WX 600 ; N aogonek ; B 35 -199 586 454 ; + +C -1 ; WX 600 ; N Uacute ; B 4 -18 596 784 ; + +C -1 ; WX 600 ; N uogonek ; B -1 -199 585 439 ; + +C -1 ; WX 600 ; N Edieresis ; B 25 0 560 761 ; + +C -1 ; WX 600 ; N Dcroat ; B 30 0 594 562 ; + +C -1 ; WX 600 ; N commaaccent ; B 205 -250 397 -57 ; + +C -1 ; WX 600 ; N copyright ; B 0 -18 600 580 ; + +C -1 ; WX 600 ; N Emacron ; B 25 0 560 708 ; + +C -1 ; WX 600 ; N ccaron ; B 40 -15 545 667 ; + +C -1 ; WX 600 ; N aring ; B 35 -15 570 678 ; + +C -1 ; WX 600 ; N Ncommaaccent ; B 8 -250 610 562 ; + +C -1 ; WX 600 ; N lacute ; B 77 0 523 801 ; + +C -1 ; WX 600 ; N agrave ; B 35 -15 570 661 ; + +C -1 ; WX 600 ; N Tcommaaccent ; B 21 -250 579 562 ; + +C -1 ; WX 600 ; N Cacute ; B 22 -18 560 784 ; + +C -1 ; WX 600 ; N atilde ; B 35 -15 570 636 ; + +C -1 ; WX 600 ; N Edotaccent ; B 25 0 560 761 ; + +C -1 ; WX 600 ; N scaron ; B 68 -17 535 667 ; + +C -1 ; WX 600 ; N scedilla ; B 68 -206 535 459 ; + +C -1 ; WX 600 ; N iacute ; B 77 0 523 661 ; + +C -1 ; WX 600 ; N lozenge ; B 66 0 534 740 ; + +C -1 ; WX 600 ; N Rcaron ; B 24 0 599 790 ; + +C -1 ; WX 600 ; N Gcommaaccent ; B 22 -250 594 580 ; + +C -1 ; WX 600 ; N ucircumflex ; B -1 -15 569 657 ; + +C -1 ; WX 600 ; N acircumflex ; B 35 -15 570 657 ; + +C -1 ; WX 600 ; N Amacron ; B -9 0 609 708 ; + +C -1 ; WX 600 ; N rcaron ; B 47 0 580 667 ; + +C -1 ; WX 600 ; N ccedilla ; B 40 -206 545 459 ; + +C -1 ; WX 600 ; N Zdotaccent ; B 62 0 539 761 ; + +C -1 ; WX 600 ; N Thorn ; B 48 0 557 562 ; + +C -1 ; WX 600 ; N Omacron ; B 22 -18 578 708 ; + +C -1 ; WX 600 ; N Racute ; B 24 0 599 784 ; + +C -1 ; WX 600 ; N Sacute ; B 47 -22 553 784 ; + +C -1 ; WX 600 ; N dcaron ; B 20 -15 727 626 ; + +C -1 ; WX 600 ; N Umacron ; B 4 -18 596 708 ; + +C -1 ; WX 600 ; N uring ; B -1 -15 569 678 ; + +C -1 ; WX 600 ; N threesuperior ; B 138 222 433 616 ; + +C -1 ; WX 600 ; N Ograve ; B 22 -18 578 784 ; + +C -1 ; WX 600 ; N Agrave ; B -9 0 609 784 ; + +C -1 ; WX 600 ; N Abreve ; B -9 0 609 784 ; + +C -1 ; WX 600 ; N multiply ; B 81 39 520 478 ; + +C -1 ; WX 600 ; N uacute ; B -1 -15 569 661 ; + +C -1 ; WX 600 ; N Tcaron ; B 21 0 579 790 ; + +C -1 ; WX 600 ; N partialdiff ; B 63 -38 537 728 ; + +C -1 ; WX 600 ; N ydieresis ; B -4 -142 601 638 ; + +C -1 ; WX 600 ; N Nacute ; B 8 -12 610 784 ; + +C -1 ; WX 600 ; N icircumflex ; B 73 0 523 657 ; + +C -1 ; WX 600 ; N Ecircumflex ; B 25 0 560 780 ; + +C -1 ; WX 600 ; N adieresis ; B 35 -15 570 638 ; + +C -1 ; WX 600 ; N edieresis ; B 40 -15 563 638 ; + +C -1 ; WX 600 ; N cacute ; B 40 -15 545 661 ; + +C -1 ; WX 600 ; N nacute ; B 18 0 592 661 ; + +C -1 ; WX 600 ; N umacron ; B -1 -15 569 585 ; + +C -1 ; WX 600 ; N Ncaron ; B 8 -12 610 790 ; + +C -1 ; WX 600 ; N Iacute ; B 77 0 523 784 ; + +C -1 ; WX 600 ; N plusminus ; B 71 24 529 515 ; + +C -1 ; WX 600 ; N brokenbar ; B 255 -175 345 675 ; + +C -1 ; WX 600 ; N registered ; B 0 -18 600 580 ; + +C -1 ; WX 600 ; N Gbreve ; B 22 -18 594 784 ; + +C -1 ; WX 600 ; N Idotaccent ; B 77 0 523 761 ; + +C -1 ; WX 600 ; N summation ; B 15 -10 586 706 ; + +C -1 ; WX 600 ; N Egrave ; B 25 0 560 784 ; + +C -1 ; WX 600 ; N racute ; B 47 0 580 661 ; + +C -1 ; WX 600 ; N omacron ; B 30 -15 570 585 ; + +C -1 ; WX 600 ; N Zacute ; B 62 0 539 784 ; + +C -1 ; WX 600 ; N Zcaron ; B 62 0 539 790 ; + +C -1 ; WX 600 ; N greaterequal ; B 26 0 523 696 ; + +C -1 ; WX 600 ; N Eth ; B 30 0 594 562 ; + +C -1 ; WX 600 ; N Ccedilla ; B 22 -206 560 580 ; + +C -1 ; WX 600 ; N lcommaaccent ; B 77 -250 523 626 ; + +C -1 ; WX 600 ; N tcaron ; B 47 -15 532 703 ; + +C -1 ; WX 600 ; N eogonek ; B 40 -199 563 454 ; + +C -1 ; WX 600 ; N Uogonek ; B 4 -199 596 562 ; + +C -1 ; WX 600 ; N Aacute ; B -9 0 609 784 ; + +C -1 ; WX 600 ; N Adieresis ; B -9 0 609 761 ; + +C -1 ; WX 600 ; N egrave ; B 40 -15 563 661 ; + +C -1 ; WX 600 ; N zacute ; B 81 0 520 661 ; + +C -1 ; WX 600 ; N iogonek ; B 77 -199 523 658 ; + +C -1 ; WX 600 ; N Oacute ; B 22 -18 578 784 ; + +C -1 ; WX 600 ; N oacute ; B 30 -15 570 661 ; + +C -1 ; WX 600 ; N amacron ; B 35 -15 570 585 ; + +C -1 ; WX 600 ; N sacute ; B 68 -17 535 661 ; + +C -1 ; WX 600 ; N idieresis ; B 77 0 523 618 ; + +C -1 ; WX 600 ; N Ocircumflex ; B 22 -18 578 780 ; + +C -1 ; WX 600 ; N Ugrave ; B 4 -18 596 784 ; + +C -1 ; WX 600 ; N Delta ; B 6 0 594 688 ; + +C -1 ; WX 600 ; N thorn ; B -14 -142 570 626 ; + +C -1 ; WX 600 ; N twosuperior ; B 143 230 436 616 ; + +C -1 ; WX 600 ; N Odieresis ; B 22 -18 578 761 ; + +C -1 ; WX 600 ; N mu ; B -1 -142 569 439 ; + +C -1 ; WX 600 ; N igrave ; B 77 0 523 661 ; + +C -1 ; WX 600 ; N ohungarumlaut ; B 30 -15 668 661 ; + +C -1 ; WX 600 ; N Eogonek ; B 25 -199 576 562 ; + +C -1 ; WX 600 ; N dcroat ; B 20 -15 591 626 ; + +C -1 ; WX 600 ; N threequarters ; B -47 -60 648 661 ; + +C -1 ; WX 600 ; N Scedilla ; B 47 -206 553 582 ; + +C -1 ; WX 600 ; N lcaron ; B 77 0 597 626 ; + +C -1 ; WX 600 ; N Kcommaaccent ; B 21 -250 599 562 ; + +C -1 ; WX 600 ; N Lacute ; B 39 0 578 784 ; + +C -1 ; WX 600 ; N trademark ; B -9 230 749 562 ; + +C -1 ; WX 600 ; N edotaccent ; B 40 -15 563 638 ; + +C -1 ; WX 600 ; N Igrave ; B 77 0 523 784 ; + +C -1 ; WX 600 ; N Imacron ; B 77 0 523 708 ; + +C -1 ; WX 600 ; N Lcaron ; B 39 0 637 562 ; + +C -1 ; WX 600 ; N onehalf ; B -47 -60 648 661 ; + +C -1 ; WX 600 ; N lessequal ; B 26 0 523 696 ; + +C -1 ; WX 600 ; N ocircumflex ; B 30 -15 570 657 ; + +C -1 ; WX 600 ; N ntilde ; B 18 0 592 636 ; + +C -1 ; WX 600 ; N Uhungarumlaut ; B 4 -18 638 784 ; + +C -1 ; WX 600 ; N Eacute ; B 25 0 560 784 ; + +C -1 ; WX 600 ; N emacron ; B 40 -15 563 585 ; + +C -1 ; WX 600 ; N gbreve ; B 30 -146 580 661 ; + +C -1 ; WX 600 ; N onequarter ; B -56 -60 656 661 ; + +C -1 ; WX 600 ; N Scaron ; B 47 -22 553 790 ; + +C -1 ; WX 600 ; N Scommaaccent ; B 47 -250 553 582 ; + +C -1 ; WX 600 ; N Ohungarumlaut ; B 22 -18 628 784 ; + +C -1 ; WX 600 ; N degree ; B 86 243 474 616 ; + +C -1 ; WX 600 ; N ograve ; B 30 -15 570 661 ; + +C -1 ; WX 600 ; N Ccaron ; B 22 -18 560 790 ; + +C -1 ; WX 600 ; N ugrave ; B -1 -15 569 661 ; + +C -1 ; WX 600 ; N radical ; B -19 -104 473 778 ; + +C -1 ; WX 600 ; N Dcaron ; B 30 0 594 790 ; + +C -1 ; WX 600 ; N rcommaaccent ; B 47 -250 580 454 ; + +C -1 ; WX 600 ; N Ntilde ; B 8 -12 610 759 ; + +C -1 ; WX 600 ; N otilde ; B 30 -15 570 636 ; + +C -1 ; WX 600 ; N Rcommaaccent ; B 24 -250 599 562 ; + +C -1 ; WX 600 ; N Lcommaaccent ; B 39 -250 578 562 ; + +C -1 ; WX 600 ; N Atilde ; B -9 0 609 759 ; + +C -1 ; WX 600 ; N Aogonek ; B -9 -199 625 562 ; + +C -1 ; WX 600 ; N Aring ; B -9 0 609 801 ; + +C -1 ; WX 600 ; N Otilde ; B 22 -18 578 759 ; + +C -1 ; WX 600 ; N zdotaccent ; B 81 0 520 638 ; + +C -1 ; WX 600 ; N Ecaron ; B 25 0 560 790 ; + +C -1 ; WX 600 ; N Iogonek ; B 77 -199 523 562 ; + +C -1 ; WX 600 ; N kcommaaccent ; B 20 -250 585 626 ; + +C -1 ; WX 600 ; N minus ; B 71 203 529 313 ; + +C -1 ; WX 600 ; N Icircumflex ; B 77 0 523 780 ; + +C -1 ; WX 600 ; N ncaron ; B 18 0 592 667 ; + +C -1 ; WX 600 ; N tcommaaccent ; B 47 -250 532 562 ; + +C -1 ; WX 600 ; N logicalnot ; B 71 103 529 413 ; + +C -1 ; WX 600 ; N odieresis ; B 30 -15 570 638 ; + +C -1 ; WX 600 ; N udieresis ; B -1 -15 569 638 ; + +C -1 ; WX 600 ; N notequal ; B 12 -47 537 563 ; + +C -1 ; WX 600 ; N gcommaaccent ; B 30 -146 580 714 ; + +C -1 ; WX 600 ; N eth ; B 58 -27 543 626 ; + +C -1 ; WX 600 ; N zcaron ; B 81 0 520 667 ; + +C -1 ; WX 600 ; N ncommaaccent ; B 18 -250 592 454 ; + +C -1 ; WX 600 ; N onesuperior ; B 153 230 447 616 ; + +C -1 ; WX 600 ; N imacron ; B 77 0 523 585 ; + +C -1 ; WX 600 ; N Euro ; B 0 0 0 0 ; + +EndCharMetrics + +EndFontMetrics + diff --git a/src/Broadside/Fonts/Data/Afm/Courier-BoldOblique.afm b/src/Broadside/Fonts/Data/Afm/Courier-BoldOblique.afm new file mode 100644 index 00000000..5e18f852 --- /dev/null +++ b/src/Broadside/Fonts/Data/Afm/Courier-BoldOblique.afm @@ -0,0 +1,684 @@ +StartFontMetrics 4.1 + +Comment Copyright (c) 1989, 1990, 1991, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. + +Comment Creation Date: Mon Jun 23 16:28:46 1997 + +Comment UniqueID 43049 + +Comment VMusage 17529 79244 + +FontName Courier-BoldOblique + +FullName Courier Bold Oblique + +FamilyName Courier + +Weight Bold + +ItalicAngle -12 + +IsFixedPitch true + +CharacterSet ExtendedRoman + +FontBBox -57 -250 869 801 + +UnderlinePosition -100 + +UnderlineThickness 50 + +Version 003.000 + +Notice Copyright (c) 1989, 1990, 1991, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. + +EncodingScheme AdobeStandardEncoding + +CapHeight 562 + +XHeight 439 + +Ascender 629 + +Descender -157 + +StdHW 84 + +StdVW 106 + +StartCharMetrics 315 + +C 32 ; WX 600 ; N space ; B 0 0 0 0 ; + +C 33 ; WX 600 ; N exclam ; B 215 -15 495 572 ; + +C 34 ; WX 600 ; N quotedbl ; B 211 277 585 562 ; + +C 35 ; WX 600 ; N numbersign ; B 88 -45 641 651 ; + +C 36 ; WX 600 ; N dollar ; B 87 -126 630 666 ; + +C 37 ; WX 600 ; N percent ; B 101 -15 625 616 ; + +C 38 ; WX 600 ; N ampersand ; B 61 -15 595 543 ; + +C 39 ; WX 600 ; N quoteright ; B 229 277 543 562 ; + +C 40 ; WX 600 ; N parenleft ; B 265 -102 592 616 ; + +C 41 ; WX 600 ; N parenright ; B 117 -102 444 616 ; + +C 42 ; WX 600 ; N asterisk ; B 179 219 598 601 ; + +C 43 ; WX 600 ; N plus ; B 114 39 596 478 ; + +C 44 ; WX 600 ; N comma ; B 99 -111 430 174 ; + +C 45 ; WX 600 ; N hyphen ; B 143 203 567 313 ; + +C 46 ; WX 600 ; N period ; B 206 -15 427 171 ; + +C 47 ; WX 600 ; N slash ; B 90 -77 626 626 ; + +C 48 ; WX 600 ; N zero ; B 135 -15 593 616 ; + +C 49 ; WX 600 ; N one ; B 93 0 562 616 ; + +C 50 ; WX 600 ; N two ; B 61 0 594 616 ; + +C 51 ; WX 600 ; N three ; B 71 -15 571 616 ; + +C 52 ; WX 600 ; N four ; B 81 0 559 616 ; + +C 53 ; WX 600 ; N five ; B 77 -15 621 601 ; + +C 54 ; WX 600 ; N six ; B 135 -15 652 616 ; + +C 55 ; WX 600 ; N seven ; B 147 0 622 601 ; + +C 56 ; WX 600 ; N eight ; B 115 -15 604 616 ; + +C 57 ; WX 600 ; N nine ; B 75 -15 592 616 ; + +C 58 ; WX 600 ; N colon ; B 205 -15 480 425 ; + +C 59 ; WX 600 ; N semicolon ; B 99 -111 481 425 ; + +C 60 ; WX 600 ; N less ; B 120 15 613 501 ; + +C 61 ; WX 600 ; N equal ; B 96 118 614 398 ; + +C 62 ; WX 600 ; N greater ; B 97 15 589 501 ; + +C 63 ; WX 600 ; N question ; B 183 -14 592 580 ; + +C 64 ; WX 600 ; N at ; B 65 -15 642 616 ; + +C 65 ; WX 600 ; N A ; B -9 0 632 562 ; + +C 66 ; WX 600 ; N B ; B 30 0 630 562 ; + +C 67 ; WX 600 ; N C ; B 74 -18 675 580 ; + +C 68 ; WX 600 ; N D ; B 30 0 664 562 ; + +C 69 ; WX 600 ; N E ; B 25 0 670 562 ; + +C 70 ; WX 600 ; N F ; B 39 0 684 562 ; + +C 71 ; WX 600 ; N G ; B 74 -18 675 580 ; + +C 72 ; WX 600 ; N H ; B 20 0 700 562 ; + +C 73 ; WX 600 ; N I ; B 77 0 643 562 ; + +C 74 ; WX 600 ; N J ; B 58 -18 721 562 ; + +C 75 ; WX 600 ; N K ; B 21 0 692 562 ; + +C 76 ; WX 600 ; N L ; B 39 0 636 562 ; + +C 77 ; WX 600 ; N M ; B -2 0 722 562 ; + +C 78 ; WX 600 ; N N ; B 8 -12 730 562 ; + +C 79 ; WX 600 ; N O ; B 74 -18 645 580 ; + +C 80 ; WX 600 ; N P ; B 48 0 643 562 ; + +C 81 ; WX 600 ; N Q ; B 83 -138 636 580 ; + +C 82 ; WX 600 ; N R ; B 24 0 617 562 ; + +C 83 ; WX 600 ; N S ; B 54 -22 673 582 ; + +C 84 ; WX 600 ; N T ; B 86 0 679 562 ; + +C 85 ; WX 600 ; N U ; B 101 -18 716 562 ; + +C 86 ; WX 600 ; N V ; B 84 0 733 562 ; + +C 87 ; WX 600 ; N W ; B 79 0 738 562 ; + +C 88 ; WX 600 ; N X ; B 12 0 690 562 ; + +C 89 ; WX 600 ; N Y ; B 109 0 709 562 ; + +C 90 ; WX 600 ; N Z ; B 62 0 637 562 ; + +C 91 ; WX 600 ; N bracketleft ; B 223 -102 606 616 ; + +C 92 ; WX 600 ; N backslash ; B 222 -77 496 626 ; + +C 93 ; WX 600 ; N bracketright ; B 103 -102 486 616 ; + +C 94 ; WX 600 ; N asciicircum ; B 171 250 556 616 ; + +C 95 ; WX 600 ; N underscore ; B -27 -125 585 -75 ; + +C 96 ; WX 600 ; N quoteleft ; B 297 277 487 562 ; + +C 97 ; WX 600 ; N a ; B 61 -15 593 454 ; + +C 98 ; WX 600 ; N b ; B 13 -15 636 626 ; + +C 99 ; WX 600 ; N c ; B 81 -15 631 459 ; + +C 100 ; WX 600 ; N d ; B 60 -15 645 626 ; + +C 101 ; WX 600 ; N e ; B 81 -15 605 454 ; + +C 102 ; WX 600 ; N f ; B 83 0 677 626 ; L i fi ; L l fl ; + +C 103 ; WX 600 ; N g ; B 40 -146 674 454 ; + +C 104 ; WX 600 ; N h ; B 18 0 615 626 ; + +C 105 ; WX 600 ; N i ; B 77 0 546 658 ; + +C 106 ; WX 600 ; N j ; B 36 -146 580 658 ; + +C 107 ; WX 600 ; N k ; B 33 0 643 626 ; + +C 108 ; WX 600 ; N l ; B 77 0 546 626 ; + +C 109 ; WX 600 ; N m ; B -22 0 649 454 ; + +C 110 ; WX 600 ; N n ; B 18 0 615 454 ; + +C 111 ; WX 600 ; N o ; B 71 -15 622 454 ; + +C 112 ; WX 600 ; N p ; B -32 -142 622 454 ; + +C 113 ; WX 600 ; N q ; B 60 -142 685 454 ; + +C 114 ; WX 600 ; N r ; B 47 0 655 454 ; + +C 115 ; WX 600 ; N s ; B 66 -17 608 459 ; + +C 116 ; WX 600 ; N t ; B 118 -15 567 562 ; + +C 117 ; WX 600 ; N u ; B 70 -15 592 439 ; + +C 118 ; WX 600 ; N v ; B 70 0 695 439 ; + +C 119 ; WX 600 ; N w ; B 53 0 712 439 ; + +C 120 ; WX 600 ; N x ; B 6 0 671 439 ; + +C 121 ; WX 600 ; N y ; B -21 -142 695 439 ; + +C 122 ; WX 600 ; N z ; B 81 0 614 439 ; + +C 123 ; WX 600 ; N braceleft ; B 203 -102 595 616 ; + +C 124 ; WX 600 ; N bar ; B 201 -250 505 750 ; + +C 125 ; WX 600 ; N braceright ; B 114 -102 506 616 ; + +C 126 ; WX 600 ; N asciitilde ; B 120 153 590 356 ; + +C 161 ; WX 600 ; N exclamdown ; B 196 -146 477 449 ; + +C 162 ; WX 600 ; N cent ; B 121 -49 605 614 ; + +C 163 ; WX 600 ; N sterling ; B 106 -28 650 611 ; + +C 164 ; WX 600 ; N fraction ; B 22 -60 708 661 ; + +C 165 ; WX 600 ; N yen ; B 98 0 710 562 ; + +C 166 ; WX 600 ; N florin ; B -57 -131 702 616 ; + +C 167 ; WX 600 ; N section ; B 74 -70 620 580 ; + +C 168 ; WX 600 ; N currency ; B 77 49 644 517 ; + +C 169 ; WX 600 ; N quotesingle ; B 303 277 493 562 ; + +C 170 ; WX 600 ; N quotedblleft ; B 190 277 594 562 ; + +C 171 ; WX 600 ; N guillemotleft ; B 62 70 639 446 ; + +C 172 ; WX 600 ; N guilsinglleft ; B 195 70 545 446 ; + +C 173 ; WX 600 ; N guilsinglright ; B 165 70 514 446 ; + +C 174 ; WX 600 ; N fi ; B 12 0 644 626 ; + +C 175 ; WX 600 ; N fl ; B 12 0 644 626 ; + +C 177 ; WX 600 ; N endash ; B 108 203 602 313 ; + +C 178 ; WX 600 ; N dagger ; B 175 -70 586 580 ; + +C 179 ; WX 600 ; N daggerdbl ; B 121 -70 587 580 ; + +C 180 ; WX 600 ; N periodcentered ; B 248 165 461 351 ; + +C 182 ; WX 600 ; N paragraph ; B 61 -70 700 580 ; + +C 183 ; WX 600 ; N bullet ; B 196 132 523 430 ; + +C 184 ; WX 600 ; N quotesinglbase ; B 144 -142 458 143 ; + +C 185 ; WX 600 ; N quotedblbase ; B 34 -142 560 143 ; + +C 186 ; WX 600 ; N quotedblright ; B 119 277 645 562 ; + +C 187 ; WX 600 ; N guillemotright ; B 71 70 647 446 ; + +C 188 ; WX 600 ; N ellipsis ; B 35 -15 587 116 ; + +C 189 ; WX 600 ; N perthousand ; B -45 -15 743 616 ; + +C 191 ; WX 600 ; N questiondown ; B 100 -146 509 449 ; + +C 193 ; WX 600 ; N grave ; B 272 508 503 661 ; + +C 194 ; WX 600 ; N acute ; B 312 508 609 661 ; + +C 195 ; WX 600 ; N circumflex ; B 212 483 607 657 ; + +C 196 ; WX 600 ; N tilde ; B 199 493 643 636 ; + +C 197 ; WX 600 ; N macron ; B 195 505 637 585 ; + +C 198 ; WX 600 ; N breve ; B 217 468 652 631 ; + +C 199 ; WX 600 ; N dotaccent ; B 348 498 493 638 ; + +C 200 ; WX 600 ; N dieresis ; B 246 498 595 638 ; + +C 202 ; WX 600 ; N ring ; B 319 481 528 678 ; + +C 203 ; WX 600 ; N cedilla ; B 168 -206 368 0 ; + +C 205 ; WX 600 ; N hungarumlaut ; B 171 488 729 661 ; + +C 206 ; WX 600 ; N ogonek ; B 143 -199 367 0 ; + +C 207 ; WX 600 ; N caron ; B 238 493 633 667 ; + +C 208 ; WX 600 ; N emdash ; B 33 203 677 313 ; + +C 225 ; WX 600 ; N AE ; B -29 0 708 562 ; + +C 227 ; WX 600 ; N ordfeminine ; B 188 196 526 580 ; + +C 232 ; WX 600 ; N Lslash ; B 39 0 636 562 ; + +C 233 ; WX 600 ; N Oslash ; B 48 -22 673 584 ; + +C 234 ; WX 600 ; N OE ; B 26 0 701 562 ; + +C 235 ; WX 600 ; N ordmasculine ; B 188 196 543 580 ; + +C 241 ; WX 600 ; N ae ; B 21 -15 652 454 ; + +C 245 ; WX 600 ; N dotlessi ; B 77 0 546 439 ; + +C 248 ; WX 600 ; N lslash ; B 77 0 587 626 ; + +C 249 ; WX 600 ; N oslash ; B 54 -24 638 463 ; + +C 250 ; WX 600 ; N oe ; B 18 -15 662 454 ; + +C 251 ; WX 600 ; N germandbls ; B 22 -15 629 626 ; + +C -1 ; WX 600 ; N Idieresis ; B 77 0 643 761 ; + +C -1 ; WX 600 ; N eacute ; B 81 -15 609 661 ; + +C -1 ; WX 600 ; N abreve ; B 61 -15 658 661 ; + +C -1 ; WX 600 ; N uhungarumlaut ; B 70 -15 769 661 ; + +C -1 ; WX 600 ; N ecaron ; B 81 -15 633 667 ; + +C -1 ; WX 600 ; N Ydieresis ; B 109 0 709 761 ; + +C -1 ; WX 600 ; N divide ; B 114 16 596 500 ; + +C -1 ; WX 600 ; N Yacute ; B 109 0 709 784 ; + +C -1 ; WX 600 ; N Acircumflex ; B -9 0 632 780 ; + +C -1 ; WX 600 ; N aacute ; B 61 -15 609 661 ; + +C -1 ; WX 600 ; N Ucircumflex ; B 101 -18 716 780 ; + +C -1 ; WX 600 ; N yacute ; B -21 -142 695 661 ; + +C -1 ; WX 600 ; N scommaaccent ; B 66 -250 608 459 ; + +C -1 ; WX 600 ; N ecircumflex ; B 81 -15 607 657 ; + +C -1 ; WX 600 ; N Uring ; B 101 -18 716 801 ; + +C -1 ; WX 600 ; N Udieresis ; B 101 -18 716 761 ; + +C -1 ; WX 600 ; N aogonek ; B 61 -199 593 454 ; + +C -1 ; WX 600 ; N Uacute ; B 101 -18 716 784 ; + +C -1 ; WX 600 ; N uogonek ; B 70 -199 592 439 ; + +C -1 ; WX 600 ; N Edieresis ; B 25 0 670 761 ; + +C -1 ; WX 600 ; N Dcroat ; B 30 0 664 562 ; + +C -1 ; WX 600 ; N commaaccent ; B 151 -250 385 -57 ; + +C -1 ; WX 600 ; N copyright ; B 53 -18 667 580 ; + +C -1 ; WX 600 ; N Emacron ; B 25 0 670 708 ; + +C -1 ; WX 600 ; N ccaron ; B 81 -15 633 667 ; + +C -1 ; WX 600 ; N aring ; B 61 -15 593 678 ; + +C -1 ; WX 600 ; N Ncommaaccent ; B 8 -250 730 562 ; + +C -1 ; WX 600 ; N lacute ; B 77 0 639 801 ; + +C -1 ; WX 600 ; N agrave ; B 61 -15 593 661 ; + +C -1 ; WX 600 ; N Tcommaaccent ; B 86 -250 679 562 ; + +C -1 ; WX 600 ; N Cacute ; B 74 -18 675 784 ; + +C -1 ; WX 600 ; N atilde ; B 61 -15 643 636 ; + +C -1 ; WX 600 ; N Edotaccent ; B 25 0 670 761 ; + +C -1 ; WX 600 ; N scaron ; B 66 -17 633 667 ; + +C -1 ; WX 600 ; N scedilla ; B 66 -206 608 459 ; + +C -1 ; WX 600 ; N iacute ; B 77 0 609 661 ; + +C -1 ; WX 600 ; N lozenge ; B 145 0 614 740 ; + +C -1 ; WX 600 ; N Rcaron ; B 24 0 659 790 ; + +C -1 ; WX 600 ; N Gcommaaccent ; B 74 -250 675 580 ; + +C -1 ; WX 600 ; N ucircumflex ; B 70 -15 597 657 ; + +C -1 ; WX 600 ; N acircumflex ; B 61 -15 607 657 ; + +C -1 ; WX 600 ; N Amacron ; B -9 0 633 708 ; + +C -1 ; WX 600 ; N rcaron ; B 47 0 655 667 ; + +C -1 ; WX 600 ; N ccedilla ; B 81 -206 631 459 ; + +C -1 ; WX 600 ; N Zdotaccent ; B 62 0 637 761 ; + +C -1 ; WX 600 ; N Thorn ; B 48 0 620 562 ; + +C -1 ; WX 600 ; N Omacron ; B 74 -18 663 708 ; + +C -1 ; WX 600 ; N Racute ; B 24 0 665 784 ; + +C -1 ; WX 600 ; N Sacute ; B 54 -22 673 784 ; + +C -1 ; WX 600 ; N dcaron ; B 60 -15 861 626 ; + +C -1 ; WX 600 ; N Umacron ; B 101 -18 716 708 ; + +C -1 ; WX 600 ; N uring ; B 70 -15 592 678 ; + +C -1 ; WX 600 ; N threesuperior ; B 193 222 526 616 ; + +C -1 ; WX 600 ; N Ograve ; B 74 -18 645 784 ; + +C -1 ; WX 600 ; N Agrave ; B -9 0 632 784 ; + +C -1 ; WX 600 ; N Abreve ; B -9 0 684 784 ; + +C -1 ; WX 600 ; N multiply ; B 104 39 606 478 ; + +C -1 ; WX 600 ; N uacute ; B 70 -15 599 661 ; + +C -1 ; WX 600 ; N Tcaron ; B 86 0 679 790 ; + +C -1 ; WX 600 ; N partialdiff ; B 91 -38 627 728 ; + +C -1 ; WX 600 ; N ydieresis ; B -21 -142 695 638 ; + +C -1 ; WX 600 ; N Nacute ; B 8 -12 730 784 ; + +C -1 ; WX 600 ; N icircumflex ; B 77 0 577 657 ; + +C -1 ; WX 600 ; N Ecircumflex ; B 25 0 670 780 ; + +C -1 ; WX 600 ; N adieresis ; B 61 -15 595 638 ; + +C -1 ; WX 600 ; N edieresis ; B 81 -15 605 638 ; + +C -1 ; WX 600 ; N cacute ; B 81 -15 649 661 ; + +C -1 ; WX 600 ; N nacute ; B 18 0 639 661 ; + +C -1 ; WX 600 ; N umacron ; B 70 -15 637 585 ; + +C -1 ; WX 600 ; N Ncaron ; B 8 -12 730 790 ; + +C -1 ; WX 600 ; N Iacute ; B 77 0 643 784 ; + +C -1 ; WX 600 ; N plusminus ; B 76 24 614 515 ; + +C -1 ; WX 600 ; N brokenbar ; B 217 -175 489 675 ; + +C -1 ; WX 600 ; N registered ; B 53 -18 667 580 ; + +C -1 ; WX 600 ; N Gbreve ; B 74 -18 684 784 ; + +C -1 ; WX 600 ; N Idotaccent ; B 77 0 643 761 ; + +C -1 ; WX 600 ; N summation ; B 15 -10 672 706 ; + +C -1 ; WX 600 ; N Egrave ; B 25 0 670 784 ; + +C -1 ; WX 600 ; N racute ; B 47 0 655 661 ; + +C -1 ; WX 600 ; N omacron ; B 71 -15 637 585 ; + +C -1 ; WX 600 ; N Zacute ; B 62 0 665 784 ; + +C -1 ; WX 600 ; N Zcaron ; B 62 0 659 790 ; + +C -1 ; WX 600 ; N greaterequal ; B 26 0 627 696 ; + +C -1 ; WX 600 ; N Eth ; B 30 0 664 562 ; + +C -1 ; WX 600 ; N Ccedilla ; B 74 -206 675 580 ; + +C -1 ; WX 600 ; N lcommaaccent ; B 77 -250 546 626 ; + +C -1 ; WX 600 ; N tcaron ; B 118 -15 627 703 ; + +C -1 ; WX 600 ; N eogonek ; B 81 -199 605 454 ; + +C -1 ; WX 600 ; N Uogonek ; B 101 -199 716 562 ; + +C -1 ; WX 600 ; N Aacute ; B -9 0 655 784 ; + +C -1 ; WX 600 ; N Adieresis ; B -9 0 632 761 ; + +C -1 ; WX 600 ; N egrave ; B 81 -15 605 661 ; + +C -1 ; WX 600 ; N zacute ; B 81 0 614 661 ; + +C -1 ; WX 600 ; N iogonek ; B 77 -199 546 658 ; + +C -1 ; WX 600 ; N Oacute ; B 74 -18 645 784 ; + +C -1 ; WX 600 ; N oacute ; B 71 -15 649 661 ; + +C -1 ; WX 600 ; N amacron ; B 61 -15 637 585 ; + +C -1 ; WX 600 ; N sacute ; B 66 -17 609 661 ; + +C -1 ; WX 600 ; N idieresis ; B 77 0 561 618 ; + +C -1 ; WX 600 ; N Ocircumflex ; B 74 -18 645 780 ; + +C -1 ; WX 600 ; N Ugrave ; B 101 -18 716 784 ; + +C -1 ; WX 600 ; N Delta ; B 6 0 594 688 ; + +C -1 ; WX 600 ; N thorn ; B -32 -142 622 626 ; + +C -1 ; WX 600 ; N twosuperior ; B 191 230 542 616 ; + +C -1 ; WX 600 ; N Odieresis ; B 74 -18 645 761 ; + +C -1 ; WX 600 ; N mu ; B 49 -142 592 439 ; + +C -1 ; WX 600 ; N igrave ; B 77 0 546 661 ; + +C -1 ; WX 600 ; N ohungarumlaut ; B 71 -15 809 661 ; + +C -1 ; WX 600 ; N Eogonek ; B 25 -199 670 562 ; + +C -1 ; WX 600 ; N dcroat ; B 60 -15 712 626 ; + +C -1 ; WX 600 ; N threequarters ; B 8 -60 699 661 ; + +C -1 ; WX 600 ; N Scedilla ; B 54 -206 673 582 ; + +C -1 ; WX 600 ; N lcaron ; B 77 0 731 626 ; + +C -1 ; WX 600 ; N Kcommaaccent ; B 21 -250 692 562 ; + +C -1 ; WX 600 ; N Lacute ; B 39 0 636 784 ; + +C -1 ; WX 600 ; N trademark ; B 86 230 869 562 ; + +C -1 ; WX 600 ; N edotaccent ; B 81 -15 605 638 ; + +C -1 ; WX 600 ; N Igrave ; B 77 0 643 784 ; + +C -1 ; WX 600 ; N Imacron ; B 77 0 663 708 ; + +C -1 ; WX 600 ; N Lcaron ; B 39 0 757 562 ; + +C -1 ; WX 600 ; N onehalf ; B 22 -60 716 661 ; + +C -1 ; WX 600 ; N lessequal ; B 26 0 671 696 ; + +C -1 ; WX 600 ; N ocircumflex ; B 71 -15 622 657 ; + +C -1 ; WX 600 ; N ntilde ; B 18 0 643 636 ; + +C -1 ; WX 600 ; N Uhungarumlaut ; B 101 -18 805 784 ; + +C -1 ; WX 600 ; N Eacute ; B 25 0 670 784 ; + +C -1 ; WX 600 ; N emacron ; B 81 -15 637 585 ; + +C -1 ; WX 600 ; N gbreve ; B 40 -146 674 661 ; + +C -1 ; WX 600 ; N onequarter ; B 13 -60 707 661 ; + +C -1 ; WX 600 ; N Scaron ; B 54 -22 689 790 ; + +C -1 ; WX 600 ; N Scommaaccent ; B 54 -250 673 582 ; + +C -1 ; WX 600 ; N Ohungarumlaut ; B 74 -18 795 784 ; + +C -1 ; WX 600 ; N degree ; B 173 243 570 616 ; + +C -1 ; WX 600 ; N ograve ; B 71 -15 622 661 ; + +C -1 ; WX 600 ; N Ccaron ; B 74 -18 689 790 ; + +C -1 ; WX 600 ; N ugrave ; B 70 -15 592 661 ; + +C -1 ; WX 600 ; N radical ; B 67 -104 635 778 ; + +C -1 ; WX 600 ; N Dcaron ; B 30 0 664 790 ; + +C -1 ; WX 600 ; N rcommaaccent ; B 47 -250 655 454 ; + +C -1 ; WX 600 ; N Ntilde ; B 8 -12 730 759 ; + +C -1 ; WX 600 ; N otilde ; B 71 -15 643 636 ; + +C -1 ; WX 600 ; N Rcommaaccent ; B 24 -250 617 562 ; + +C -1 ; WX 600 ; N Lcommaaccent ; B 39 -250 636 562 ; + +C -1 ; WX 600 ; N Atilde ; B -9 0 669 759 ; + +C -1 ; WX 600 ; N Aogonek ; B -9 -199 632 562 ; + +C -1 ; WX 600 ; N Aring ; B -9 0 632 801 ; + +C -1 ; WX 600 ; N Otilde ; B 74 -18 669 759 ; + +C -1 ; WX 600 ; N zdotaccent ; B 81 0 614 638 ; + +C -1 ; WX 600 ; N Ecaron ; B 25 0 670 790 ; + +C -1 ; WX 600 ; N Iogonek ; B 77 -199 643 562 ; + +C -1 ; WX 600 ; N kcommaaccent ; B 33 -250 643 626 ; + +C -1 ; WX 600 ; N minus ; B 114 203 596 313 ; + +C -1 ; WX 600 ; N Icircumflex ; B 77 0 643 780 ; + +C -1 ; WX 600 ; N ncaron ; B 18 0 633 667 ; + +C -1 ; WX 600 ; N tcommaaccent ; B 118 -250 567 562 ; + +C -1 ; WX 600 ; N logicalnot ; B 135 103 617 413 ; + +C -1 ; WX 600 ; N odieresis ; B 71 -15 622 638 ; + +C -1 ; WX 600 ; N udieresis ; B 70 -15 595 638 ; + +C -1 ; WX 600 ; N notequal ; B 30 -47 626 563 ; + +C -1 ; WX 600 ; N gcommaaccent ; B 40 -146 674 714 ; + +C -1 ; WX 600 ; N eth ; B 93 -27 661 626 ; + +C -1 ; WX 600 ; N zcaron ; B 81 0 643 667 ; + +C -1 ; WX 600 ; N ncommaaccent ; B 18 -250 615 454 ; + +C -1 ; WX 600 ; N onesuperior ; B 212 230 514 616 ; + +C -1 ; WX 600 ; N imacron ; B 77 0 575 585 ; + +C -1 ; WX 600 ; N Euro ; B 0 0 0 0 ; + +EndCharMetrics + +EndFontMetrics + diff --git a/src/Broadside/Fonts/Data/Afm/Courier-Oblique.afm b/src/Broadside/Fonts/Data/Afm/Courier-Oblique.afm new file mode 100644 index 00000000..52a2eddd --- /dev/null +++ b/src/Broadside/Fonts/Data/Afm/Courier-Oblique.afm @@ -0,0 +1,684 @@ +StartFontMetrics 4.1 + +Comment Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. + +Comment Creation Date: Thu May 1 17:37:52 1997 + +Comment UniqueID 43051 + +Comment VMusage 16248 75829 + +FontName Courier-Oblique + +FullName Courier Oblique + +FamilyName Courier + +Weight Medium + +ItalicAngle -12 + +IsFixedPitch true + +CharacterSet ExtendedRoman + +FontBBox -27 -250 849 805 + +UnderlinePosition -100 + +UnderlineThickness 50 + +Version 003.000 + +Notice Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. + +EncodingScheme AdobeStandardEncoding + +CapHeight 562 + +XHeight 426 + +Ascender 629 + +Descender -157 + +StdHW 51 + +StdVW 51 + +StartCharMetrics 315 + +C 32 ; WX 600 ; N space ; B 0 0 0 0 ; + +C 33 ; WX 600 ; N exclam ; B 243 -15 464 572 ; + +C 34 ; WX 600 ; N quotedbl ; B 273 328 532 562 ; + +C 35 ; WX 600 ; N numbersign ; B 133 -32 596 639 ; + +C 36 ; WX 600 ; N dollar ; B 108 -126 596 662 ; + +C 37 ; WX 600 ; N percent ; B 134 -15 599 622 ; + +C 38 ; WX 600 ; N ampersand ; B 87 -15 580 543 ; + +C 39 ; WX 600 ; N quoteright ; B 283 328 495 562 ; + +C 40 ; WX 600 ; N parenleft ; B 313 -108 572 622 ; + +C 41 ; WX 600 ; N parenright ; B 137 -108 396 622 ; + +C 42 ; WX 600 ; N asterisk ; B 212 257 580 607 ; + +C 43 ; WX 600 ; N plus ; B 129 44 580 470 ; + +C 44 ; WX 600 ; N comma ; B 157 -112 370 122 ; + +C 45 ; WX 600 ; N hyphen ; B 152 231 558 285 ; + +C 46 ; WX 600 ; N period ; B 238 -15 382 109 ; + +C 47 ; WX 600 ; N slash ; B 112 -80 604 629 ; + +C 48 ; WX 600 ; N zero ; B 154 -15 575 622 ; + +C 49 ; WX 600 ; N one ; B 98 0 515 622 ; + +C 50 ; WX 600 ; N two ; B 70 0 568 622 ; + +C 51 ; WX 600 ; N three ; B 82 -15 538 622 ; + +C 52 ; WX 600 ; N four ; B 108 0 541 622 ; + +C 53 ; WX 600 ; N five ; B 99 -15 589 607 ; + +C 54 ; WX 600 ; N six ; B 155 -15 629 622 ; + +C 55 ; WX 600 ; N seven ; B 182 0 612 607 ; + +C 56 ; WX 600 ; N eight ; B 132 -15 588 622 ; + +C 57 ; WX 600 ; N nine ; B 93 -15 574 622 ; + +C 58 ; WX 600 ; N colon ; B 238 -15 441 385 ; + +C 59 ; WX 600 ; N semicolon ; B 157 -112 441 385 ; + +C 60 ; WX 600 ; N less ; B 96 42 610 472 ; + +C 61 ; WX 600 ; N equal ; B 109 138 600 376 ; + +C 62 ; WX 600 ; N greater ; B 85 42 599 472 ; + +C 63 ; WX 600 ; N question ; B 222 -15 583 572 ; + +C 64 ; WX 600 ; N at ; B 127 -15 582 622 ; + +C 65 ; WX 600 ; N A ; B 3 0 607 562 ; + +C 66 ; WX 600 ; N B ; B 43 0 616 562 ; + +C 67 ; WX 600 ; N C ; B 93 -18 655 580 ; + +C 68 ; WX 600 ; N D ; B 43 0 645 562 ; + +C 69 ; WX 600 ; N E ; B 53 0 660 562 ; + +C 70 ; WX 600 ; N F ; B 53 0 660 562 ; + +C 71 ; WX 600 ; N G ; B 83 -18 645 580 ; + +C 72 ; WX 600 ; N H ; B 32 0 687 562 ; + +C 73 ; WX 600 ; N I ; B 96 0 623 562 ; + +C 74 ; WX 600 ; N J ; B 52 -18 685 562 ; + +C 75 ; WX 600 ; N K ; B 38 0 671 562 ; + +C 76 ; WX 600 ; N L ; B 47 0 607 562 ; + +C 77 ; WX 600 ; N M ; B 4 0 715 562 ; + +C 78 ; WX 600 ; N N ; B 7 -13 712 562 ; + +C 79 ; WX 600 ; N O ; B 94 -18 625 580 ; + +C 80 ; WX 600 ; N P ; B 79 0 644 562 ; + +C 81 ; WX 600 ; N Q ; B 95 -138 625 580 ; + +C 82 ; WX 600 ; N R ; B 38 0 598 562 ; + +C 83 ; WX 600 ; N S ; B 76 -20 650 580 ; + +C 84 ; WX 600 ; N T ; B 108 0 665 562 ; + +C 85 ; WX 600 ; N U ; B 125 -18 702 562 ; + +C 86 ; WX 600 ; N V ; B 105 -13 723 562 ; + +C 87 ; WX 600 ; N W ; B 106 -13 722 562 ; + +C 88 ; WX 600 ; N X ; B 23 0 675 562 ; + +C 89 ; WX 600 ; N Y ; B 133 0 695 562 ; + +C 90 ; WX 600 ; N Z ; B 86 0 610 562 ; + +C 91 ; WX 600 ; N bracketleft ; B 246 -108 574 622 ; + +C 92 ; WX 600 ; N backslash ; B 249 -80 468 629 ; + +C 93 ; WX 600 ; N bracketright ; B 135 -108 463 622 ; + +C 94 ; WX 600 ; N asciicircum ; B 175 354 587 622 ; + +C 95 ; WX 600 ; N underscore ; B -27 -125 584 -75 ; + +C 96 ; WX 600 ; N quoteleft ; B 343 328 457 562 ; + +C 97 ; WX 600 ; N a ; B 76 -15 569 441 ; + +C 98 ; WX 600 ; N b ; B 29 -15 625 629 ; + +C 99 ; WX 600 ; N c ; B 106 -15 608 441 ; + +C 100 ; WX 600 ; N d ; B 85 -15 640 629 ; + +C 101 ; WX 600 ; N e ; B 106 -15 598 441 ; + +C 102 ; WX 600 ; N f ; B 114 0 662 629 ; L i fi ; L l fl ; + +C 103 ; WX 600 ; N g ; B 61 -157 657 441 ; + +C 104 ; WX 600 ; N h ; B 33 0 592 629 ; + +C 105 ; WX 600 ; N i ; B 95 0 515 657 ; + +C 106 ; WX 600 ; N j ; B 52 -157 550 657 ; + +C 107 ; WX 600 ; N k ; B 58 0 633 629 ; + +C 108 ; WX 600 ; N l ; B 95 0 515 629 ; + +C 109 ; WX 600 ; N m ; B -5 0 615 441 ; + +C 110 ; WX 600 ; N n ; B 26 0 585 441 ; + +C 111 ; WX 600 ; N o ; B 102 -15 588 441 ; + +C 112 ; WX 600 ; N p ; B -24 -157 605 441 ; + +C 113 ; WX 600 ; N q ; B 85 -157 682 441 ; + +C 114 ; WX 600 ; N r ; B 60 0 636 441 ; + +C 115 ; WX 600 ; N s ; B 78 -15 584 441 ; + +C 116 ; WX 600 ; N t ; B 167 -15 561 561 ; + +C 117 ; WX 600 ; N u ; B 101 -15 572 426 ; + +C 118 ; WX 600 ; N v ; B 90 -10 681 426 ; + +C 119 ; WX 600 ; N w ; B 76 -10 695 426 ; + +C 120 ; WX 600 ; N x ; B 20 0 655 426 ; + +C 121 ; WX 600 ; N y ; B -4 -157 683 426 ; + +C 122 ; WX 600 ; N z ; B 99 0 593 426 ; + +C 123 ; WX 600 ; N braceleft ; B 233 -108 569 622 ; + +C 124 ; WX 600 ; N bar ; B 222 -250 485 750 ; + +C 125 ; WX 600 ; N braceright ; B 140 -108 477 622 ; + +C 126 ; WX 600 ; N asciitilde ; B 116 197 600 320 ; + +C 161 ; WX 600 ; N exclamdown ; B 225 -157 445 430 ; + +C 162 ; WX 600 ; N cent ; B 151 -49 588 614 ; + +C 163 ; WX 600 ; N sterling ; B 124 -21 621 611 ; + +C 164 ; WX 600 ; N fraction ; B 84 -57 646 665 ; + +C 165 ; WX 600 ; N yen ; B 120 0 693 562 ; + +C 166 ; WX 600 ; N florin ; B -26 -143 671 622 ; + +C 167 ; WX 600 ; N section ; B 104 -78 590 580 ; + +C 168 ; WX 600 ; N currency ; B 94 58 628 506 ; + +C 169 ; WX 600 ; N quotesingle ; B 345 328 460 562 ; + +C 170 ; WX 600 ; N quotedblleft ; B 262 328 541 562 ; + +C 171 ; WX 600 ; N guillemotleft ; B 92 70 652 446 ; + +C 172 ; WX 600 ; N guilsinglleft ; B 204 70 540 446 ; + +C 173 ; WX 600 ; N guilsinglright ; B 170 70 506 446 ; + +C 174 ; WX 600 ; N fi ; B 3 0 619 629 ; + +C 175 ; WX 600 ; N fl ; B 3 0 619 629 ; + +C 177 ; WX 600 ; N endash ; B 124 231 586 285 ; + +C 178 ; WX 600 ; N dagger ; B 217 -78 546 580 ; + +C 179 ; WX 600 ; N daggerdbl ; B 163 -78 546 580 ; + +C 180 ; WX 600 ; N periodcentered ; B 275 189 434 327 ; + +C 182 ; WX 600 ; N paragraph ; B 100 -78 630 562 ; + +C 183 ; WX 600 ; N bullet ; B 224 130 485 383 ; + +C 184 ; WX 600 ; N quotesinglbase ; B 185 -134 397 100 ; + +C 185 ; WX 600 ; N quotedblbase ; B 115 -134 478 100 ; + +C 186 ; WX 600 ; N quotedblright ; B 213 328 576 562 ; + +C 187 ; WX 600 ; N guillemotright ; B 58 70 618 446 ; + +C 188 ; WX 600 ; N ellipsis ; B 46 -15 575 111 ; + +C 189 ; WX 600 ; N perthousand ; B 59 -15 627 622 ; + +C 191 ; WX 600 ; N questiondown ; B 105 -157 466 430 ; + +C 193 ; WX 600 ; N grave ; B 294 497 484 672 ; + +C 194 ; WX 600 ; N acute ; B 348 497 612 672 ; + +C 195 ; WX 600 ; N circumflex ; B 229 477 581 654 ; + +C 196 ; WX 600 ; N tilde ; B 212 489 629 606 ; + +C 197 ; WX 600 ; N macron ; B 232 525 600 565 ; + +C 198 ; WX 600 ; N breve ; B 279 501 576 609 ; + +C 199 ; WX 600 ; N dotaccent ; B 373 537 478 640 ; + +C 200 ; WX 600 ; N dieresis ; B 272 537 579 640 ; + +C 202 ; WX 600 ; N ring ; B 332 463 500 627 ; + +C 203 ; WX 600 ; N cedilla ; B 197 -151 344 10 ; + +C 205 ; WX 600 ; N hungarumlaut ; B 239 497 683 672 ; + +C 206 ; WX 600 ; N ogonek ; B 189 -172 377 4 ; + +C 207 ; WX 600 ; N caron ; B 262 492 614 669 ; + +C 208 ; WX 600 ; N emdash ; B 49 231 661 285 ; + +C 225 ; WX 600 ; N AE ; B 3 0 655 562 ; + +C 227 ; WX 600 ; N ordfeminine ; B 209 249 512 580 ; + +C 232 ; WX 600 ; N Lslash ; B 47 0 607 562 ; + +C 233 ; WX 600 ; N Oslash ; B 94 -80 625 629 ; + +C 234 ; WX 600 ; N OE ; B 59 0 672 562 ; + +C 235 ; WX 600 ; N ordmasculine ; B 210 249 535 580 ; + +C 241 ; WX 600 ; N ae ; B 41 -15 626 441 ; + +C 245 ; WX 600 ; N dotlessi ; B 95 0 515 426 ; + +C 248 ; WX 600 ; N lslash ; B 95 0 587 629 ; + +C 249 ; WX 600 ; N oslash ; B 102 -80 588 506 ; + +C 250 ; WX 600 ; N oe ; B 54 -15 615 441 ; + +C 251 ; WX 600 ; N germandbls ; B 48 -15 617 629 ; + +C -1 ; WX 600 ; N Idieresis ; B 96 0 623 753 ; + +C -1 ; WX 600 ; N eacute ; B 106 -15 612 672 ; + +C -1 ; WX 600 ; N abreve ; B 76 -15 576 609 ; + +C -1 ; WX 600 ; N uhungarumlaut ; B 101 -15 723 672 ; + +C -1 ; WX 600 ; N ecaron ; B 106 -15 614 669 ; + +C -1 ; WX 600 ; N Ydieresis ; B 133 0 695 753 ; + +C -1 ; WX 600 ; N divide ; B 136 48 573 467 ; + +C -1 ; WX 600 ; N Yacute ; B 133 0 695 805 ; + +C -1 ; WX 600 ; N Acircumflex ; B 3 0 607 787 ; + +C -1 ; WX 600 ; N aacute ; B 76 -15 612 672 ; + +C -1 ; WX 600 ; N Ucircumflex ; B 125 -18 702 787 ; + +C -1 ; WX 600 ; N yacute ; B -4 -157 683 672 ; + +C -1 ; WX 600 ; N scommaaccent ; B 78 -250 584 441 ; + +C -1 ; WX 600 ; N ecircumflex ; B 106 -15 598 654 ; + +C -1 ; WX 600 ; N Uring ; B 125 -18 702 760 ; + +C -1 ; WX 600 ; N Udieresis ; B 125 -18 702 753 ; + +C -1 ; WX 600 ; N aogonek ; B 76 -172 569 441 ; + +C -1 ; WX 600 ; N Uacute ; B 125 -18 702 805 ; + +C -1 ; WX 600 ; N uogonek ; B 101 -172 572 426 ; + +C -1 ; WX 600 ; N Edieresis ; B 53 0 660 753 ; + +C -1 ; WX 600 ; N Dcroat ; B 43 0 645 562 ; + +C -1 ; WX 600 ; N commaaccent ; B 145 -250 323 -58 ; + +C -1 ; WX 600 ; N copyright ; B 53 -18 667 580 ; + +C -1 ; WX 600 ; N Emacron ; B 53 0 660 698 ; + +C -1 ; WX 600 ; N ccaron ; B 106 -15 614 669 ; + +C -1 ; WX 600 ; N aring ; B 76 -15 569 627 ; + +C -1 ; WX 600 ; N Ncommaaccent ; B 7 -250 712 562 ; + +C -1 ; WX 600 ; N lacute ; B 95 0 640 805 ; + +C -1 ; WX 600 ; N agrave ; B 76 -15 569 672 ; + +C -1 ; WX 600 ; N Tcommaaccent ; B 108 -250 665 562 ; + +C -1 ; WX 600 ; N Cacute ; B 93 -18 655 805 ; + +C -1 ; WX 600 ; N atilde ; B 76 -15 629 606 ; + +C -1 ; WX 600 ; N Edotaccent ; B 53 0 660 753 ; + +C -1 ; WX 600 ; N scaron ; B 78 -15 614 669 ; + +C -1 ; WX 600 ; N scedilla ; B 78 -151 584 441 ; + +C -1 ; WX 600 ; N iacute ; B 95 0 612 672 ; + +C -1 ; WX 600 ; N lozenge ; B 94 0 519 706 ; + +C -1 ; WX 600 ; N Rcaron ; B 38 0 642 802 ; + +C -1 ; WX 600 ; N Gcommaaccent ; B 83 -250 645 580 ; + +C -1 ; WX 600 ; N ucircumflex ; B 101 -15 572 654 ; + +C -1 ; WX 600 ; N acircumflex ; B 76 -15 581 654 ; + +C -1 ; WX 600 ; N Amacron ; B 3 0 607 698 ; + +C -1 ; WX 600 ; N rcaron ; B 60 0 636 669 ; + +C -1 ; WX 600 ; N ccedilla ; B 106 -151 614 441 ; + +C -1 ; WX 600 ; N Zdotaccent ; B 86 0 610 753 ; + +C -1 ; WX 600 ; N Thorn ; B 79 0 606 562 ; + +C -1 ; WX 600 ; N Omacron ; B 94 -18 628 698 ; + +C -1 ; WX 600 ; N Racute ; B 38 0 670 805 ; + +C -1 ; WX 600 ; N Sacute ; B 76 -20 650 805 ; + +C -1 ; WX 600 ; N dcaron ; B 85 -15 849 629 ; + +C -1 ; WX 600 ; N Umacron ; B 125 -18 702 698 ; + +C -1 ; WX 600 ; N uring ; B 101 -15 572 627 ; + +C -1 ; WX 600 ; N threesuperior ; B 213 240 501 622 ; + +C -1 ; WX 600 ; N Ograve ; B 94 -18 625 805 ; + +C -1 ; WX 600 ; N Agrave ; B 3 0 607 805 ; + +C -1 ; WX 600 ; N Abreve ; B 3 0 607 732 ; + +C -1 ; WX 600 ; N multiply ; B 103 43 607 470 ; + +C -1 ; WX 600 ; N uacute ; B 101 -15 602 672 ; + +C -1 ; WX 600 ; N Tcaron ; B 108 0 665 802 ; + +C -1 ; WX 600 ; N partialdiff ; B 45 -38 546 710 ; + +C -1 ; WX 600 ; N ydieresis ; B -4 -157 683 620 ; + +C -1 ; WX 600 ; N Nacute ; B 7 -13 712 805 ; + +C -1 ; WX 600 ; N icircumflex ; B 95 0 551 654 ; + +C -1 ; WX 600 ; N Ecircumflex ; B 53 0 660 787 ; + +C -1 ; WX 600 ; N adieresis ; B 76 -15 575 620 ; + +C -1 ; WX 600 ; N edieresis ; B 106 -15 598 620 ; + +C -1 ; WX 600 ; N cacute ; B 106 -15 612 672 ; + +C -1 ; WX 600 ; N nacute ; B 26 0 602 672 ; + +C -1 ; WX 600 ; N umacron ; B 101 -15 600 565 ; + +C -1 ; WX 600 ; N Ncaron ; B 7 -13 712 802 ; + +C -1 ; WX 600 ; N Iacute ; B 96 0 640 805 ; + +C -1 ; WX 600 ; N plusminus ; B 96 44 594 558 ; + +C -1 ; WX 600 ; N brokenbar ; B 238 -175 469 675 ; + +C -1 ; WX 600 ; N registered ; B 53 -18 667 580 ; + +C -1 ; WX 600 ; N Gbreve ; B 83 -18 645 732 ; + +C -1 ; WX 600 ; N Idotaccent ; B 96 0 623 753 ; + +C -1 ; WX 600 ; N summation ; B 15 -10 670 706 ; + +C -1 ; WX 600 ; N Egrave ; B 53 0 660 805 ; + +C -1 ; WX 600 ; N racute ; B 60 0 636 672 ; + +C -1 ; WX 600 ; N omacron ; B 102 -15 600 565 ; + +C -1 ; WX 600 ; N Zacute ; B 86 0 670 805 ; + +C -1 ; WX 600 ; N Zcaron ; B 86 0 642 802 ; + +C -1 ; WX 600 ; N greaterequal ; B 98 0 594 710 ; + +C -1 ; WX 600 ; N Eth ; B 43 0 645 562 ; + +C -1 ; WX 600 ; N Ccedilla ; B 93 -151 658 580 ; + +C -1 ; WX 600 ; N lcommaaccent ; B 95 -250 515 629 ; + +C -1 ; WX 600 ; N tcaron ; B 167 -15 587 717 ; + +C -1 ; WX 600 ; N eogonek ; B 106 -172 598 441 ; + +C -1 ; WX 600 ; N Uogonek ; B 124 -172 702 562 ; + +C -1 ; WX 600 ; N Aacute ; B 3 0 660 805 ; + +C -1 ; WX 600 ; N Adieresis ; B 3 0 607 753 ; + +C -1 ; WX 600 ; N egrave ; B 106 -15 598 672 ; + +C -1 ; WX 600 ; N zacute ; B 99 0 612 672 ; + +C -1 ; WX 600 ; N iogonek ; B 95 -172 515 657 ; + +C -1 ; WX 600 ; N Oacute ; B 94 -18 640 805 ; + +C -1 ; WX 600 ; N oacute ; B 102 -15 612 672 ; + +C -1 ; WX 600 ; N amacron ; B 76 -15 600 565 ; + +C -1 ; WX 600 ; N sacute ; B 78 -15 612 672 ; + +C -1 ; WX 600 ; N idieresis ; B 95 0 545 620 ; + +C -1 ; WX 600 ; N Ocircumflex ; B 94 -18 625 787 ; + +C -1 ; WX 600 ; N Ugrave ; B 125 -18 702 805 ; + +C -1 ; WX 600 ; N Delta ; B 6 0 598 688 ; + +C -1 ; WX 600 ; N thorn ; B -24 -157 605 629 ; + +C -1 ; WX 600 ; N twosuperior ; B 230 249 535 622 ; + +C -1 ; WX 600 ; N Odieresis ; B 94 -18 625 753 ; + +C -1 ; WX 600 ; N mu ; B 72 -157 572 426 ; + +C -1 ; WX 600 ; N igrave ; B 95 0 515 672 ; + +C -1 ; WX 600 ; N ohungarumlaut ; B 102 -15 723 672 ; + +C -1 ; WX 600 ; N Eogonek ; B 53 -172 660 562 ; + +C -1 ; WX 600 ; N dcroat ; B 85 -15 704 629 ; + +C -1 ; WX 600 ; N threequarters ; B 73 -56 659 666 ; + +C -1 ; WX 600 ; N Scedilla ; B 76 -151 650 580 ; + +C -1 ; WX 600 ; N lcaron ; B 95 0 667 629 ; + +C -1 ; WX 600 ; N Kcommaaccent ; B 38 -250 671 562 ; + +C -1 ; WX 600 ; N Lacute ; B 47 0 607 805 ; + +C -1 ; WX 600 ; N trademark ; B 75 263 742 562 ; + +C -1 ; WX 600 ; N edotaccent ; B 106 -15 598 620 ; + +C -1 ; WX 600 ; N Igrave ; B 96 0 623 805 ; + +C -1 ; WX 600 ; N Imacron ; B 96 0 628 698 ; + +C -1 ; WX 600 ; N Lcaron ; B 47 0 632 562 ; + +C -1 ; WX 600 ; N onehalf ; B 65 -57 669 665 ; + +C -1 ; WX 600 ; N lessequal ; B 98 0 645 710 ; + +C -1 ; WX 600 ; N ocircumflex ; B 102 -15 588 654 ; + +C -1 ; WX 600 ; N ntilde ; B 26 0 629 606 ; + +C -1 ; WX 600 ; N Uhungarumlaut ; B 125 -18 761 805 ; + +C -1 ; WX 600 ; N Eacute ; B 53 0 670 805 ; + +C -1 ; WX 600 ; N emacron ; B 106 -15 600 565 ; + +C -1 ; WX 600 ; N gbreve ; B 61 -157 657 609 ; + +C -1 ; WX 600 ; N onequarter ; B 65 -57 674 665 ; + +C -1 ; WX 600 ; N Scaron ; B 76 -20 672 802 ; + +C -1 ; WX 600 ; N Scommaaccent ; B 76 -250 650 580 ; + +C -1 ; WX 600 ; N Ohungarumlaut ; B 94 -18 751 805 ; + +C -1 ; WX 600 ; N degree ; B 214 269 576 622 ; + +C -1 ; WX 600 ; N ograve ; B 102 -15 588 672 ; + +C -1 ; WX 600 ; N Ccaron ; B 93 -18 672 802 ; + +C -1 ; WX 600 ; N ugrave ; B 101 -15 572 672 ; + +C -1 ; WX 600 ; N radical ; B 85 -15 765 792 ; + +C -1 ; WX 600 ; N Dcaron ; B 43 0 645 802 ; + +C -1 ; WX 600 ; N rcommaaccent ; B 60 -250 636 441 ; + +C -1 ; WX 600 ; N Ntilde ; B 7 -13 712 729 ; + +C -1 ; WX 600 ; N otilde ; B 102 -15 629 606 ; + +C -1 ; WX 600 ; N Rcommaaccent ; B 38 -250 598 562 ; + +C -1 ; WX 600 ; N Lcommaaccent ; B 47 -250 607 562 ; + +C -1 ; WX 600 ; N Atilde ; B 3 0 655 729 ; + +C -1 ; WX 600 ; N Aogonek ; B 3 -172 607 562 ; + +C -1 ; WX 600 ; N Aring ; B 3 0 607 750 ; + +C -1 ; WX 600 ; N Otilde ; B 94 -18 655 729 ; + +C -1 ; WX 600 ; N zdotaccent ; B 99 0 593 620 ; + +C -1 ; WX 600 ; N Ecaron ; B 53 0 660 802 ; + +C -1 ; WX 600 ; N Iogonek ; B 96 -172 623 562 ; + +C -1 ; WX 600 ; N kcommaaccent ; B 58 -250 633 629 ; + +C -1 ; WX 600 ; N minus ; B 129 232 580 283 ; + +C -1 ; WX 600 ; N Icircumflex ; B 96 0 623 787 ; + +C -1 ; WX 600 ; N ncaron ; B 26 0 614 669 ; + +C -1 ; WX 600 ; N tcommaaccent ; B 165 -250 561 561 ; + +C -1 ; WX 600 ; N logicalnot ; B 155 108 591 369 ; + +C -1 ; WX 600 ; N odieresis ; B 102 -15 588 620 ; + +C -1 ; WX 600 ; N udieresis ; B 101 -15 575 620 ; + +C -1 ; WX 600 ; N notequal ; B 43 -16 621 529 ; + +C -1 ; WX 600 ; N gcommaaccent ; B 61 -157 657 708 ; + +C -1 ; WX 600 ; N eth ; B 102 -15 639 629 ; + +C -1 ; WX 600 ; N zcaron ; B 99 0 624 669 ; + +C -1 ; WX 600 ; N ncommaaccent ; B 26 -250 585 441 ; + +C -1 ; WX 600 ; N onesuperior ; B 231 249 491 622 ; + +C -1 ; WX 600 ; N imacron ; B 95 0 543 565 ; + +C -1 ; WX 600 ; N Euro ; B 0 0 0 0 ; + +EndCharMetrics + +EndFontMetrics + diff --git a/src/Broadside/Fonts/Data/Afm/Courier.afm b/src/Broadside/Fonts/Data/Afm/Courier.afm new file mode 100644 index 00000000..5d5399bc --- /dev/null +++ b/src/Broadside/Fonts/Data/Afm/Courier.afm @@ -0,0 +1,684 @@ +StartFontMetrics 4.1 + +Comment Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. + +Comment Creation Date: Thu May 1 17:27:09 1997 + +Comment UniqueID 43050 + +Comment VMusage 39754 50779 + +FontName Courier + +FullName Courier + +FamilyName Courier + +Weight Medium + +ItalicAngle 0 + +IsFixedPitch true + +CharacterSet ExtendedRoman + +FontBBox -23 -250 715 805 + +UnderlinePosition -100 + +UnderlineThickness 50 + +Version 003.000 + +Notice Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. + +EncodingScheme AdobeStandardEncoding + +CapHeight 562 + +XHeight 426 + +Ascender 629 + +Descender -157 + +StdHW 51 + +StdVW 51 + +StartCharMetrics 315 + +C 32 ; WX 600 ; N space ; B 0 0 0 0 ; + +C 33 ; WX 600 ; N exclam ; B 236 -15 364 572 ; + +C 34 ; WX 600 ; N quotedbl ; B 187 328 413 562 ; + +C 35 ; WX 600 ; N numbersign ; B 93 -32 507 639 ; + +C 36 ; WX 600 ; N dollar ; B 105 -126 496 662 ; + +C 37 ; WX 600 ; N percent ; B 81 -15 518 622 ; + +C 38 ; WX 600 ; N ampersand ; B 63 -15 538 543 ; + +C 39 ; WX 600 ; N quoteright ; B 213 328 376 562 ; + +C 40 ; WX 600 ; N parenleft ; B 269 -108 440 622 ; + +C 41 ; WX 600 ; N parenright ; B 160 -108 331 622 ; + +C 42 ; WX 600 ; N asterisk ; B 116 257 484 607 ; + +C 43 ; WX 600 ; N plus ; B 80 44 520 470 ; + +C 44 ; WX 600 ; N comma ; B 181 -112 344 122 ; + +C 45 ; WX 600 ; N hyphen ; B 103 231 497 285 ; + +C 46 ; WX 600 ; N period ; B 229 -15 371 109 ; + +C 47 ; WX 600 ; N slash ; B 125 -80 475 629 ; + +C 48 ; WX 600 ; N zero ; B 106 -15 494 622 ; + +C 49 ; WX 600 ; N one ; B 96 0 505 622 ; + +C 50 ; WX 600 ; N two ; B 70 0 471 622 ; + +C 51 ; WX 600 ; N three ; B 75 -15 466 622 ; + +C 52 ; WX 600 ; N four ; B 78 0 500 622 ; + +C 53 ; WX 600 ; N five ; B 92 -15 497 607 ; + +C 54 ; WX 600 ; N six ; B 111 -15 497 622 ; + +C 55 ; WX 600 ; N seven ; B 82 0 483 607 ; + +C 56 ; WX 600 ; N eight ; B 102 -15 498 622 ; + +C 57 ; WX 600 ; N nine ; B 96 -15 489 622 ; + +C 58 ; WX 600 ; N colon ; B 229 -15 371 385 ; + +C 59 ; WX 600 ; N semicolon ; B 181 -112 371 385 ; + +C 60 ; WX 600 ; N less ; B 41 42 519 472 ; + +C 61 ; WX 600 ; N equal ; B 80 138 520 376 ; + +C 62 ; WX 600 ; N greater ; B 66 42 544 472 ; + +C 63 ; WX 600 ; N question ; B 129 -15 492 572 ; + +C 64 ; WX 600 ; N at ; B 77 -15 533 622 ; + +C 65 ; WX 600 ; N A ; B 3 0 597 562 ; + +C 66 ; WX 600 ; N B ; B 43 0 559 562 ; + +C 67 ; WX 600 ; N C ; B 41 -18 540 580 ; + +C 68 ; WX 600 ; N D ; B 43 0 574 562 ; + +C 69 ; WX 600 ; N E ; B 53 0 550 562 ; + +C 70 ; WX 600 ; N F ; B 53 0 545 562 ; + +C 71 ; WX 600 ; N G ; B 31 -18 575 580 ; + +C 72 ; WX 600 ; N H ; B 32 0 568 562 ; + +C 73 ; WX 600 ; N I ; B 96 0 504 562 ; + +C 74 ; WX 600 ; N J ; B 34 -18 566 562 ; + +C 75 ; WX 600 ; N K ; B 38 0 582 562 ; + +C 76 ; WX 600 ; N L ; B 47 0 554 562 ; + +C 77 ; WX 600 ; N M ; B 4 0 596 562 ; + +C 78 ; WX 600 ; N N ; B 7 -13 593 562 ; + +C 79 ; WX 600 ; N O ; B 43 -18 557 580 ; + +C 80 ; WX 600 ; N P ; B 79 0 558 562 ; + +C 81 ; WX 600 ; N Q ; B 43 -138 557 580 ; + +C 82 ; WX 600 ; N R ; B 38 0 588 562 ; + +C 83 ; WX 600 ; N S ; B 72 -20 529 580 ; + +C 84 ; WX 600 ; N T ; B 38 0 563 562 ; + +C 85 ; WX 600 ; N U ; B 17 -18 583 562 ; + +C 86 ; WX 600 ; N V ; B -4 -13 604 562 ; + +C 87 ; WX 600 ; N W ; B -3 -13 603 562 ; + +C 88 ; WX 600 ; N X ; B 23 0 577 562 ; + +C 89 ; WX 600 ; N Y ; B 24 0 576 562 ; + +C 90 ; WX 600 ; N Z ; B 86 0 514 562 ; + +C 91 ; WX 600 ; N bracketleft ; B 269 -108 442 622 ; + +C 92 ; WX 600 ; N backslash ; B 118 -80 482 629 ; + +C 93 ; WX 600 ; N bracketright ; B 158 -108 331 622 ; + +C 94 ; WX 600 ; N asciicircum ; B 94 354 506 622 ; + +C 95 ; WX 600 ; N underscore ; B 0 -125 600 -75 ; + +C 96 ; WX 600 ; N quoteleft ; B 224 328 387 562 ; + +C 97 ; WX 600 ; N a ; B 53 -15 559 441 ; + +C 98 ; WX 600 ; N b ; B 14 -15 575 629 ; + +C 99 ; WX 600 ; N c ; B 66 -15 529 441 ; + +C 100 ; WX 600 ; N d ; B 45 -15 591 629 ; + +C 101 ; WX 600 ; N e ; B 66 -15 548 441 ; + +C 102 ; WX 600 ; N f ; B 114 0 531 629 ; L i fi ; L l fl ; + +C 103 ; WX 600 ; N g ; B 45 -157 566 441 ; + +C 104 ; WX 600 ; N h ; B 18 0 582 629 ; + +C 105 ; WX 600 ; N i ; B 95 0 505 657 ; + +C 106 ; WX 600 ; N j ; B 82 -157 410 657 ; + +C 107 ; WX 600 ; N k ; B 43 0 580 629 ; + +C 108 ; WX 600 ; N l ; B 95 0 505 629 ; + +C 109 ; WX 600 ; N m ; B -5 0 605 441 ; + +C 110 ; WX 600 ; N n ; B 26 0 575 441 ; + +C 111 ; WX 600 ; N o ; B 62 -15 538 441 ; + +C 112 ; WX 600 ; N p ; B 9 -157 555 441 ; + +C 113 ; WX 600 ; N q ; B 45 -157 591 441 ; + +C 114 ; WX 600 ; N r ; B 60 0 559 441 ; + +C 115 ; WX 600 ; N s ; B 80 -15 513 441 ; + +C 116 ; WX 600 ; N t ; B 87 -15 530 561 ; + +C 117 ; WX 600 ; N u ; B 21 -15 562 426 ; + +C 118 ; WX 600 ; N v ; B 10 -10 590 426 ; + +C 119 ; WX 600 ; N w ; B -4 -10 604 426 ; + +C 120 ; WX 600 ; N x ; B 20 0 580 426 ; + +C 121 ; WX 600 ; N y ; B 7 -157 592 426 ; + +C 122 ; WX 600 ; N z ; B 99 0 502 426 ; + +C 123 ; WX 600 ; N braceleft ; B 182 -108 437 622 ; + +C 124 ; WX 600 ; N bar ; B 275 -250 326 750 ; + +C 125 ; WX 600 ; N braceright ; B 163 -108 418 622 ; + +C 126 ; WX 600 ; N asciitilde ; B 63 197 540 320 ; + +C 161 ; WX 600 ; N exclamdown ; B 236 -157 364 430 ; + +C 162 ; WX 600 ; N cent ; B 96 -49 500 614 ; + +C 163 ; WX 600 ; N sterling ; B 84 -21 521 611 ; + +C 164 ; WX 600 ; N fraction ; B 92 -57 509 665 ; + +C 165 ; WX 600 ; N yen ; B 26 0 574 562 ; + +C 166 ; WX 600 ; N florin ; B 4 -143 539 622 ; + +C 167 ; WX 600 ; N section ; B 113 -78 488 580 ; + +C 168 ; WX 600 ; N currency ; B 73 58 527 506 ; + +C 169 ; WX 600 ; N quotesingle ; B 259 328 341 562 ; + +C 170 ; WX 600 ; N quotedblleft ; B 143 328 471 562 ; + +C 171 ; WX 600 ; N guillemotleft ; B 37 70 563 446 ; + +C 172 ; WX 600 ; N guilsinglleft ; B 149 70 451 446 ; + +C 173 ; WX 600 ; N guilsinglright ; B 149 70 451 446 ; + +C 174 ; WX 600 ; N fi ; B 3 0 597 629 ; + +C 175 ; WX 600 ; N fl ; B 3 0 597 629 ; + +C 177 ; WX 600 ; N endash ; B 75 231 525 285 ; + +C 178 ; WX 600 ; N dagger ; B 141 -78 459 580 ; + +C 179 ; WX 600 ; N daggerdbl ; B 141 -78 459 580 ; + +C 180 ; WX 600 ; N periodcentered ; B 222 189 378 327 ; + +C 182 ; WX 600 ; N paragraph ; B 50 -78 511 562 ; + +C 183 ; WX 600 ; N bullet ; B 172 130 428 383 ; + +C 184 ; WX 600 ; N quotesinglbase ; B 213 -134 376 100 ; + +C 185 ; WX 600 ; N quotedblbase ; B 143 -134 457 100 ; + +C 186 ; WX 600 ; N quotedblright ; B 143 328 457 562 ; + +C 187 ; WX 600 ; N guillemotright ; B 37 70 563 446 ; + +C 188 ; WX 600 ; N ellipsis ; B 37 -15 563 111 ; + +C 189 ; WX 600 ; N perthousand ; B 3 -15 600 622 ; + +C 191 ; WX 600 ; N questiondown ; B 108 -157 471 430 ; + +C 193 ; WX 600 ; N grave ; B 151 497 378 672 ; + +C 194 ; WX 600 ; N acute ; B 242 497 469 672 ; + +C 195 ; WX 600 ; N circumflex ; B 124 477 476 654 ; + +C 196 ; WX 600 ; N tilde ; B 105 489 503 606 ; + +C 197 ; WX 600 ; N macron ; B 120 525 480 565 ; + +C 198 ; WX 600 ; N breve ; B 153 501 447 609 ; + +C 199 ; WX 600 ; N dotaccent ; B 249 537 352 640 ; + +C 200 ; WX 600 ; N dieresis ; B 148 537 453 640 ; + +C 202 ; WX 600 ; N ring ; B 218 463 382 627 ; + +C 203 ; WX 600 ; N cedilla ; B 224 -151 362 10 ; + +C 205 ; WX 600 ; N hungarumlaut ; B 133 497 540 672 ; + +C 206 ; WX 600 ; N ogonek ; B 211 -172 407 4 ; + +C 207 ; WX 600 ; N caron ; B 124 492 476 669 ; + +C 208 ; WX 600 ; N emdash ; B 0 231 600 285 ; + +C 225 ; WX 600 ; N AE ; B 3 0 550 562 ; + +C 227 ; WX 600 ; N ordfeminine ; B 156 249 442 580 ; + +C 232 ; WX 600 ; N Lslash ; B 47 0 554 562 ; + +C 233 ; WX 600 ; N Oslash ; B 43 -80 557 629 ; + +C 234 ; WX 600 ; N OE ; B 7 0 567 562 ; + +C 235 ; WX 600 ; N ordmasculine ; B 157 249 443 580 ; + +C 241 ; WX 600 ; N ae ; B 19 -15 570 441 ; + +C 245 ; WX 600 ; N dotlessi ; B 95 0 505 426 ; + +C 248 ; WX 600 ; N lslash ; B 95 0 505 629 ; + +C 249 ; WX 600 ; N oslash ; B 62 -80 538 506 ; + +C 250 ; WX 600 ; N oe ; B 19 -15 559 441 ; + +C 251 ; WX 600 ; N germandbls ; B 48 -15 588 629 ; + +C -1 ; WX 600 ; N Idieresis ; B 96 0 504 753 ; + +C -1 ; WX 600 ; N eacute ; B 66 -15 548 672 ; + +C -1 ; WX 600 ; N abreve ; B 53 -15 559 609 ; + +C -1 ; WX 600 ; N uhungarumlaut ; B 21 -15 580 672 ; + +C -1 ; WX 600 ; N ecaron ; B 66 -15 548 669 ; + +C -1 ; WX 600 ; N Ydieresis ; B 24 0 576 753 ; + +C -1 ; WX 600 ; N divide ; B 87 48 513 467 ; + +C -1 ; WX 600 ; N Yacute ; B 24 0 576 805 ; + +C -1 ; WX 600 ; N Acircumflex ; B 3 0 597 787 ; + +C -1 ; WX 600 ; N aacute ; B 53 -15 559 672 ; + +C -1 ; WX 600 ; N Ucircumflex ; B 17 -18 583 787 ; + +C -1 ; WX 600 ; N yacute ; B 7 -157 592 672 ; + +C -1 ; WX 600 ; N scommaaccent ; B 80 -250 513 441 ; + +C -1 ; WX 600 ; N ecircumflex ; B 66 -15 548 654 ; + +C -1 ; WX 600 ; N Uring ; B 17 -18 583 760 ; + +C -1 ; WX 600 ; N Udieresis ; B 17 -18 583 753 ; + +C -1 ; WX 600 ; N aogonek ; B 53 -172 587 441 ; + +C -1 ; WX 600 ; N Uacute ; B 17 -18 583 805 ; + +C -1 ; WX 600 ; N uogonek ; B 21 -172 590 426 ; + +C -1 ; WX 600 ; N Edieresis ; B 53 0 550 753 ; + +C -1 ; WX 600 ; N Dcroat ; B 30 0 574 562 ; + +C -1 ; WX 600 ; N commaaccent ; B 198 -250 335 -58 ; + +C -1 ; WX 600 ; N copyright ; B 0 -18 600 580 ; + +C -1 ; WX 600 ; N Emacron ; B 53 0 550 698 ; + +C -1 ; WX 600 ; N ccaron ; B 66 -15 529 669 ; + +C -1 ; WX 600 ; N aring ; B 53 -15 559 627 ; + +C -1 ; WX 600 ; N Ncommaaccent ; B 7 -250 593 562 ; + +C -1 ; WX 600 ; N lacute ; B 95 0 505 805 ; + +C -1 ; WX 600 ; N agrave ; B 53 -15 559 672 ; + +C -1 ; WX 600 ; N Tcommaaccent ; B 38 -250 563 562 ; + +C -1 ; WX 600 ; N Cacute ; B 41 -18 540 805 ; + +C -1 ; WX 600 ; N atilde ; B 53 -15 559 606 ; + +C -1 ; WX 600 ; N Edotaccent ; B 53 0 550 753 ; + +C -1 ; WX 600 ; N scaron ; B 80 -15 513 669 ; + +C -1 ; WX 600 ; N scedilla ; B 80 -151 513 441 ; + +C -1 ; WX 600 ; N iacute ; B 95 0 505 672 ; + +C -1 ; WX 600 ; N lozenge ; B 18 0 443 706 ; + +C -1 ; WX 600 ; N Rcaron ; B 38 0 588 802 ; + +C -1 ; WX 600 ; N Gcommaaccent ; B 31 -250 575 580 ; + +C -1 ; WX 600 ; N ucircumflex ; B 21 -15 562 654 ; + +C -1 ; WX 600 ; N acircumflex ; B 53 -15 559 654 ; + +C -1 ; WX 600 ; N Amacron ; B 3 0 597 698 ; + +C -1 ; WX 600 ; N rcaron ; B 60 0 559 669 ; + +C -1 ; WX 600 ; N ccedilla ; B 66 -151 529 441 ; + +C -1 ; WX 600 ; N Zdotaccent ; B 86 0 514 753 ; + +C -1 ; WX 600 ; N Thorn ; B 79 0 538 562 ; + +C -1 ; WX 600 ; N Omacron ; B 43 -18 557 698 ; + +C -1 ; WX 600 ; N Racute ; B 38 0 588 805 ; + +C -1 ; WX 600 ; N Sacute ; B 72 -20 529 805 ; + +C -1 ; WX 600 ; N dcaron ; B 45 -15 715 629 ; + +C -1 ; WX 600 ; N Umacron ; B 17 -18 583 698 ; + +C -1 ; WX 600 ; N uring ; B 21 -15 562 627 ; + +C -1 ; WX 600 ; N threesuperior ; B 155 240 406 622 ; + +C -1 ; WX 600 ; N Ograve ; B 43 -18 557 805 ; + +C -1 ; WX 600 ; N Agrave ; B 3 0 597 805 ; + +C -1 ; WX 600 ; N Abreve ; B 3 0 597 732 ; + +C -1 ; WX 600 ; N multiply ; B 87 43 515 470 ; + +C -1 ; WX 600 ; N uacute ; B 21 -15 562 672 ; + +C -1 ; WX 600 ; N Tcaron ; B 38 0 563 802 ; + +C -1 ; WX 600 ; N partialdiff ; B 17 -38 459 710 ; + +C -1 ; WX 600 ; N ydieresis ; B 7 -157 592 620 ; + +C -1 ; WX 600 ; N Nacute ; B 7 -13 593 805 ; + +C -1 ; WX 600 ; N icircumflex ; B 94 0 505 654 ; + +C -1 ; WX 600 ; N Ecircumflex ; B 53 0 550 787 ; + +C -1 ; WX 600 ; N adieresis ; B 53 -15 559 620 ; + +C -1 ; WX 600 ; N edieresis ; B 66 -15 548 620 ; + +C -1 ; WX 600 ; N cacute ; B 66 -15 529 672 ; + +C -1 ; WX 600 ; N nacute ; B 26 0 575 672 ; + +C -1 ; WX 600 ; N umacron ; B 21 -15 562 565 ; + +C -1 ; WX 600 ; N Ncaron ; B 7 -13 593 802 ; + +C -1 ; WX 600 ; N Iacute ; B 96 0 504 805 ; + +C -1 ; WX 600 ; N plusminus ; B 87 44 513 558 ; + +C -1 ; WX 600 ; N brokenbar ; B 275 -175 326 675 ; + +C -1 ; WX 600 ; N registered ; B 0 -18 600 580 ; + +C -1 ; WX 600 ; N Gbreve ; B 31 -18 575 732 ; + +C -1 ; WX 600 ; N Idotaccent ; B 96 0 504 753 ; + +C -1 ; WX 600 ; N summation ; B 15 -10 585 706 ; + +C -1 ; WX 600 ; N Egrave ; B 53 0 550 805 ; + +C -1 ; WX 600 ; N racute ; B 60 0 559 672 ; + +C -1 ; WX 600 ; N omacron ; B 62 -15 538 565 ; + +C -1 ; WX 600 ; N Zacute ; B 86 0 514 805 ; + +C -1 ; WX 600 ; N Zcaron ; B 86 0 514 802 ; + +C -1 ; WX 600 ; N greaterequal ; B 98 0 502 710 ; + +C -1 ; WX 600 ; N Eth ; B 30 0 574 562 ; + +C -1 ; WX 600 ; N Ccedilla ; B 41 -151 540 580 ; + +C -1 ; WX 600 ; N lcommaaccent ; B 95 -250 505 629 ; + +C -1 ; WX 600 ; N tcaron ; B 87 -15 530 717 ; + +C -1 ; WX 600 ; N eogonek ; B 66 -172 548 441 ; + +C -1 ; WX 600 ; N Uogonek ; B 17 -172 583 562 ; + +C -1 ; WX 600 ; N Aacute ; B 3 0 597 805 ; + +C -1 ; WX 600 ; N Adieresis ; B 3 0 597 753 ; + +C -1 ; WX 600 ; N egrave ; B 66 -15 548 672 ; + +C -1 ; WX 600 ; N zacute ; B 99 0 502 672 ; + +C -1 ; WX 600 ; N iogonek ; B 95 -172 505 657 ; + +C -1 ; WX 600 ; N Oacute ; B 43 -18 557 805 ; + +C -1 ; WX 600 ; N oacute ; B 62 -15 538 672 ; + +C -1 ; WX 600 ; N amacron ; B 53 -15 559 565 ; + +C -1 ; WX 600 ; N sacute ; B 80 -15 513 672 ; + +C -1 ; WX 600 ; N idieresis ; B 95 0 505 620 ; + +C -1 ; WX 600 ; N Ocircumflex ; B 43 -18 557 787 ; + +C -1 ; WX 600 ; N Ugrave ; B 17 -18 583 805 ; + +C -1 ; WX 600 ; N Delta ; B 6 0 598 688 ; + +C -1 ; WX 600 ; N thorn ; B -6 -157 555 629 ; + +C -1 ; WX 600 ; N twosuperior ; B 177 249 424 622 ; + +C -1 ; WX 600 ; N Odieresis ; B 43 -18 557 753 ; + +C -1 ; WX 600 ; N mu ; B 21 -157 562 426 ; + +C -1 ; WX 600 ; N igrave ; B 95 0 505 672 ; + +C -1 ; WX 600 ; N ohungarumlaut ; B 62 -15 580 672 ; + +C -1 ; WX 600 ; N Eogonek ; B 53 -172 561 562 ; + +C -1 ; WX 600 ; N dcroat ; B 45 -15 591 629 ; + +C -1 ; WX 600 ; N threequarters ; B 8 -56 593 666 ; + +C -1 ; WX 600 ; N Scedilla ; B 72 -151 529 580 ; + +C -1 ; WX 600 ; N lcaron ; B 95 0 533 629 ; + +C -1 ; WX 600 ; N Kcommaaccent ; B 38 -250 582 562 ; + +C -1 ; WX 600 ; N Lacute ; B 47 0 554 805 ; + +C -1 ; WX 600 ; N trademark ; B -23 263 623 562 ; + +C -1 ; WX 600 ; N edotaccent ; B 66 -15 548 620 ; + +C -1 ; WX 600 ; N Igrave ; B 96 0 504 805 ; + +C -1 ; WX 600 ; N Imacron ; B 96 0 504 698 ; + +C -1 ; WX 600 ; N Lcaron ; B 47 0 554 562 ; + +C -1 ; WX 600 ; N onehalf ; B 0 -57 611 665 ; + +C -1 ; WX 600 ; N lessequal ; B 98 0 502 710 ; + +C -1 ; WX 600 ; N ocircumflex ; B 62 -15 538 654 ; + +C -1 ; WX 600 ; N ntilde ; B 26 0 575 606 ; + +C -1 ; WX 600 ; N Uhungarumlaut ; B 17 -18 590 805 ; + +C -1 ; WX 600 ; N Eacute ; B 53 0 550 805 ; + +C -1 ; WX 600 ; N emacron ; B 66 -15 548 565 ; + +C -1 ; WX 600 ; N gbreve ; B 45 -157 566 609 ; + +C -1 ; WX 600 ; N onequarter ; B 0 -57 600 665 ; + +C -1 ; WX 600 ; N Scaron ; B 72 -20 529 802 ; + +C -1 ; WX 600 ; N Scommaaccent ; B 72 -250 529 580 ; + +C -1 ; WX 600 ; N Ohungarumlaut ; B 43 -18 580 805 ; + +C -1 ; WX 600 ; N degree ; B 123 269 477 622 ; + +C -1 ; WX 600 ; N ograve ; B 62 -15 538 672 ; + +C -1 ; WX 600 ; N Ccaron ; B 41 -18 540 802 ; + +C -1 ; WX 600 ; N ugrave ; B 21 -15 562 672 ; + +C -1 ; WX 600 ; N radical ; B 3 -15 597 792 ; + +C -1 ; WX 600 ; N Dcaron ; B 43 0 574 802 ; + +C -1 ; WX 600 ; N rcommaaccent ; B 60 -250 559 441 ; + +C -1 ; WX 600 ; N Ntilde ; B 7 -13 593 729 ; + +C -1 ; WX 600 ; N otilde ; B 62 -15 538 606 ; + +C -1 ; WX 600 ; N Rcommaaccent ; B 38 -250 588 562 ; + +C -1 ; WX 600 ; N Lcommaaccent ; B 47 -250 554 562 ; + +C -1 ; WX 600 ; N Atilde ; B 3 0 597 729 ; + +C -1 ; WX 600 ; N Aogonek ; B 3 -172 608 562 ; + +C -1 ; WX 600 ; N Aring ; B 3 0 597 750 ; + +C -1 ; WX 600 ; N Otilde ; B 43 -18 557 729 ; + +C -1 ; WX 600 ; N zdotaccent ; B 99 0 502 620 ; + +C -1 ; WX 600 ; N Ecaron ; B 53 0 550 802 ; + +C -1 ; WX 600 ; N Iogonek ; B 96 -172 504 562 ; + +C -1 ; WX 600 ; N kcommaaccent ; B 43 -250 580 629 ; + +C -1 ; WX 600 ; N minus ; B 80 232 520 283 ; + +C -1 ; WX 600 ; N Icircumflex ; B 96 0 504 787 ; + +C -1 ; WX 600 ; N ncaron ; B 26 0 575 669 ; + +C -1 ; WX 600 ; N tcommaaccent ; B 87 -250 530 561 ; + +C -1 ; WX 600 ; N logicalnot ; B 87 108 513 369 ; + +C -1 ; WX 600 ; N odieresis ; B 62 -15 538 620 ; + +C -1 ; WX 600 ; N udieresis ; B 21 -15 562 620 ; + +C -1 ; WX 600 ; N notequal ; B 15 -16 540 529 ; + +C -1 ; WX 600 ; N gcommaaccent ; B 45 -157 566 708 ; + +C -1 ; WX 600 ; N eth ; B 62 -15 538 629 ; + +C -1 ; WX 600 ; N zcaron ; B 99 0 502 669 ; + +C -1 ; WX 600 ; N ncommaaccent ; B 26 -250 575 441 ; + +C -1 ; WX 600 ; N onesuperior ; B 172 249 428 622 ; + +C -1 ; WX 600 ; N imacron ; B 95 0 505 565 ; + +C -1 ; WX 600 ; N Euro ; B 0 0 0 0 ; + +EndCharMetrics + +EndFontMetrics + diff --git a/src/Broadside/Fonts/Data/Afm/Helvetica-Bold.afm b/src/Broadside/Fonts/Data/Afm/Helvetica-Bold.afm new file mode 100644 index 00000000..150c198b --- /dev/null +++ b/src/Broadside/Fonts/Data/Afm/Helvetica-Bold.afm @@ -0,0 +1,5654 @@ +StartFontMetrics 4.1 + +Comment Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved. + +Comment Creation Date: Thu May 1 12:43:52 1997 + +Comment UniqueID 43052 + +Comment VMusage 37169 48194 + +FontName Helvetica-Bold + +FullName Helvetica Bold + +FamilyName Helvetica + +Weight Bold + +ItalicAngle 0 + +IsFixedPitch false + +CharacterSet ExtendedRoman + +FontBBox -170 -228 1003 962 + +UnderlinePosition -100 + +UnderlineThickness 50 + +Version 002.000 + +Notice Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.Helvetica is a trademark of Linotype-Hell AG and/or its subsidiaries. + +EncodingScheme AdobeStandardEncoding + +CapHeight 718 + +XHeight 532 + +Ascender 718 + +Descender -207 + +StdHW 118 + +StdVW 140 + +StartCharMetrics 315 + +C 32 ; WX 278 ; N space ; B 0 0 0 0 ; + +C 33 ; WX 333 ; N exclam ; B 90 0 244 718 ; + +C 34 ; WX 474 ; N quotedbl ; B 98 447 376 718 ; + +C 35 ; WX 556 ; N numbersign ; B 18 0 538 698 ; + +C 36 ; WX 556 ; N dollar ; B 30 -115 523 775 ; + +C 37 ; WX 889 ; N percent ; B 28 -19 861 710 ; + +C 38 ; WX 722 ; N ampersand ; B 54 -19 701 718 ; + +C 39 ; WX 278 ; N quoteright ; B 69 445 209 718 ; + +C 40 ; WX 333 ; N parenleft ; B 35 -208 314 734 ; + +C 41 ; WX 333 ; N parenright ; B 19 -208 298 734 ; + +C 42 ; WX 389 ; N asterisk ; B 27 387 362 718 ; + +C 43 ; WX 584 ; N plus ; B 40 0 544 506 ; + +C 44 ; WX 278 ; N comma ; B 64 -168 214 146 ; + +C 45 ; WX 333 ; N hyphen ; B 27 215 306 345 ; + +C 46 ; WX 278 ; N period ; B 64 0 214 146 ; + +C 47 ; WX 278 ; N slash ; B -33 -19 311 737 ; + +C 48 ; WX 556 ; N zero ; B 32 -19 524 710 ; + +C 49 ; WX 556 ; N one ; B 69 0 378 710 ; + +C 50 ; WX 556 ; N two ; B 26 0 511 710 ; + +C 51 ; WX 556 ; N three ; B 27 -19 516 710 ; + +C 52 ; WX 556 ; N four ; B 27 0 526 710 ; + +C 53 ; WX 556 ; N five ; B 27 -19 516 698 ; + +C 54 ; WX 556 ; N six ; B 31 -19 520 710 ; + +C 55 ; WX 556 ; N seven ; B 25 0 528 698 ; + +C 56 ; WX 556 ; N eight ; B 32 -19 524 710 ; + +C 57 ; WX 556 ; N nine ; B 30 -19 522 710 ; + +C 58 ; WX 333 ; N colon ; B 92 0 242 512 ; + +C 59 ; WX 333 ; N semicolon ; B 92 -168 242 512 ; + +C 60 ; WX 584 ; N less ; B 38 -8 546 514 ; + +C 61 ; WX 584 ; N equal ; B 40 87 544 419 ; + +C 62 ; WX 584 ; N greater ; B 38 -8 546 514 ; + +C 63 ; WX 611 ; N question ; B 60 0 556 727 ; + +C 64 ; WX 975 ; N at ; B 118 -19 856 737 ; + +C 65 ; WX 722 ; N A ; B 20 0 702 718 ; + +C 66 ; WX 722 ; N B ; B 76 0 669 718 ; + +C 67 ; WX 722 ; N C ; B 44 -19 684 737 ; + +C 68 ; WX 722 ; N D ; B 76 0 685 718 ; + +C 69 ; WX 667 ; N E ; B 76 0 621 718 ; + +C 70 ; WX 611 ; N F ; B 76 0 587 718 ; + +C 71 ; WX 778 ; N G ; B 44 -19 713 737 ; + +C 72 ; WX 722 ; N H ; B 71 0 651 718 ; + +C 73 ; WX 278 ; N I ; B 64 0 214 718 ; + +C 74 ; WX 556 ; N J ; B 22 -18 484 718 ; + +C 75 ; WX 722 ; N K ; B 87 0 722 718 ; + +C 76 ; WX 611 ; N L ; B 76 0 583 718 ; + +C 77 ; WX 833 ; N M ; B 69 0 765 718 ; + +C 78 ; WX 722 ; N N ; B 69 0 654 718 ; + +C 79 ; WX 778 ; N O ; B 44 -19 734 737 ; + +C 80 ; WX 667 ; N P ; B 76 0 627 718 ; + +C 81 ; WX 778 ; N Q ; B 44 -52 737 737 ; + +C 82 ; WX 722 ; N R ; B 76 0 677 718 ; + +C 83 ; WX 667 ; N S ; B 39 -19 629 737 ; + +C 84 ; WX 611 ; N T ; B 14 0 598 718 ; + +C 85 ; WX 722 ; N U ; B 72 -19 651 718 ; + +C 86 ; WX 667 ; N V ; B 19 0 648 718 ; + +C 87 ; WX 944 ; N W ; B 16 0 929 718 ; + +C 88 ; WX 667 ; N X ; B 14 0 653 718 ; + +C 89 ; WX 667 ; N Y ; B 15 0 653 718 ; + +C 90 ; WX 611 ; N Z ; B 25 0 586 718 ; + +C 91 ; WX 333 ; N bracketleft ; B 63 -196 309 722 ; + +C 92 ; WX 278 ; N backslash ; B -33 -19 311 737 ; + +C 93 ; WX 333 ; N bracketright ; B 24 -196 270 722 ; + +C 94 ; WX 584 ; N asciicircum ; B 62 323 522 698 ; + +C 95 ; WX 556 ; N underscore ; B 0 -125 556 -75 ; + +C 96 ; WX 278 ; N quoteleft ; B 69 454 209 727 ; + +C 97 ; WX 556 ; N a ; B 29 -14 527 546 ; + +C 98 ; WX 611 ; N b ; B 61 -14 578 718 ; + +C 99 ; WX 556 ; N c ; B 34 -14 524 546 ; + +C 100 ; WX 611 ; N d ; B 34 -14 551 718 ; + +C 101 ; WX 556 ; N e ; B 23 -14 528 546 ; + +C 102 ; WX 333 ; N f ; B 10 0 318 727 ; L i fi ; L l fl ; + +C 103 ; WX 611 ; N g ; B 40 -217 553 546 ; + +C 104 ; WX 611 ; N h ; B 65 0 546 718 ; + +C 105 ; WX 278 ; N i ; B 69 0 209 725 ; + +C 106 ; WX 278 ; N j ; B 3 -214 209 725 ; + +C 107 ; WX 556 ; N k ; B 69 0 562 718 ; + +C 108 ; WX 278 ; N l ; B 69 0 209 718 ; + +C 109 ; WX 889 ; N m ; B 64 0 826 546 ; + +C 110 ; WX 611 ; N n ; B 65 0 546 546 ; + +C 111 ; WX 611 ; N o ; B 34 -14 578 546 ; + +C 112 ; WX 611 ; N p ; B 62 -207 578 546 ; + +C 113 ; WX 611 ; N q ; B 34 -207 552 546 ; + +C 114 ; WX 389 ; N r ; B 64 0 373 546 ; + +C 115 ; WX 556 ; N s ; B 30 -14 519 546 ; + +C 116 ; WX 333 ; N t ; B 10 -6 309 676 ; + +C 117 ; WX 611 ; N u ; B 66 -14 545 532 ; + +C 118 ; WX 556 ; N v ; B 13 0 543 532 ; + +C 119 ; WX 778 ; N w ; B 10 0 769 532 ; + +C 120 ; WX 556 ; N x ; B 15 0 541 532 ; + +C 121 ; WX 556 ; N y ; B 10 -214 539 532 ; + +C 122 ; WX 500 ; N z ; B 20 0 480 532 ; + +C 123 ; WX 389 ; N braceleft ; B 48 -196 365 722 ; + +C 124 ; WX 280 ; N bar ; B 84 -225 196 775 ; + +C 125 ; WX 389 ; N braceright ; B 24 -196 341 722 ; + +C 126 ; WX 584 ; N asciitilde ; B 61 163 523 343 ; + +C 161 ; WX 333 ; N exclamdown ; B 90 -186 244 532 ; + +C 162 ; WX 556 ; N cent ; B 34 -118 524 628 ; + +C 163 ; WX 556 ; N sterling ; B 28 -16 541 718 ; + +C 164 ; WX 167 ; N fraction ; B -170 -19 336 710 ; + +C 165 ; WX 556 ; N yen ; B -9 0 565 698 ; + +C 166 ; WX 556 ; N florin ; B -10 -210 516 737 ; + +C 167 ; WX 556 ; N section ; B 34 -184 522 727 ; + +C 168 ; WX 556 ; N currency ; B -3 76 559 636 ; + +C 169 ; WX 238 ; N quotesingle ; B 70 447 168 718 ; + +C 170 ; WX 500 ; N quotedblleft ; B 64 454 436 727 ; + +C 171 ; WX 556 ; N guillemotleft ; B 88 76 468 484 ; + +C 172 ; WX 333 ; N guilsinglleft ; B 83 76 250 484 ; + +C 173 ; WX 333 ; N guilsinglright ; B 83 76 250 484 ; + +C 174 ; WX 611 ; N fi ; B 10 0 542 727 ; + +C 175 ; WX 611 ; N fl ; B 10 0 542 727 ; + +C 177 ; WX 556 ; N endash ; B 0 227 556 333 ; + +C 178 ; WX 556 ; N dagger ; B 36 -171 520 718 ; + +C 179 ; WX 556 ; N daggerdbl ; B 36 -171 520 718 ; + +C 180 ; WX 278 ; N periodcentered ; B 58 172 220 334 ; + +C 182 ; WX 556 ; N paragraph ; B -8 -191 539 700 ; + +C 183 ; WX 350 ; N bullet ; B 10 194 340 524 ; + +C 184 ; WX 278 ; N quotesinglbase ; B 69 -146 209 127 ; + +C 185 ; WX 500 ; N quotedblbase ; B 64 -146 436 127 ; + +C 186 ; WX 500 ; N quotedblright ; B 64 445 436 718 ; + +C 187 ; WX 556 ; N guillemotright ; B 88 76 468 484 ; + +C 188 ; WX 1000 ; N ellipsis ; B 92 0 908 146 ; + +C 189 ; WX 1000 ; N perthousand ; B -3 -19 1003 710 ; + +C 191 ; WX 611 ; N questiondown ; B 55 -195 551 532 ; + +C 193 ; WX 333 ; N grave ; B -23 604 225 750 ; + +C 194 ; WX 333 ; N acute ; B 108 604 356 750 ; + +C 195 ; WX 333 ; N circumflex ; B -10 604 343 750 ; + +C 196 ; WX 333 ; N tilde ; B -17 610 350 737 ; + +C 197 ; WX 333 ; N macron ; B -6 604 339 678 ; + +C 198 ; WX 333 ; N breve ; B -2 604 335 750 ; + +C 199 ; WX 333 ; N dotaccent ; B 104 614 230 729 ; + +C 200 ; WX 333 ; N dieresis ; B 6 614 327 729 ; + +C 202 ; WX 333 ; N ring ; B 59 568 275 776 ; + +C 203 ; WX 333 ; N cedilla ; B 6 -228 245 0 ; + +C 205 ; WX 333 ; N hungarumlaut ; B 9 604 486 750 ; + +C 206 ; WX 333 ; N ogonek ; B 71 -228 304 0 ; + +C 207 ; WX 333 ; N caron ; B -10 604 343 750 ; + +C 208 ; WX 1000 ; N emdash ; B 0 227 1000 333 ; + +C 225 ; WX 1000 ; N AE ; B 5 0 954 718 ; + +C 227 ; WX 370 ; N ordfeminine ; B 22 401 347 737 ; + +C 232 ; WX 611 ; N Lslash ; B -20 0 583 718 ; + +C 233 ; WX 778 ; N Oslash ; B 33 -27 744 745 ; + +C 234 ; WX 1000 ; N OE ; B 37 -19 961 737 ; + +C 235 ; WX 365 ; N ordmasculine ; B 6 401 360 737 ; + +C 241 ; WX 889 ; N ae ; B 29 -14 858 546 ; + +C 245 ; WX 278 ; N dotlessi ; B 69 0 209 532 ; + +C 248 ; WX 278 ; N lslash ; B -18 0 296 718 ; + +C 249 ; WX 611 ; N oslash ; B 22 -29 589 560 ; + +C 250 ; WX 944 ; N oe ; B 34 -14 912 546 ; + +C 251 ; WX 611 ; N germandbls ; B 69 -14 579 731 ; + +C -1 ; WX 278 ; N Idieresis ; B -21 0 300 915 ; + +C -1 ; WX 556 ; N eacute ; B 23 -14 528 750 ; + +C -1 ; WX 556 ; N abreve ; B 29 -14 527 750 ; + +C -1 ; WX 611 ; N uhungarumlaut ; B 66 -14 625 750 ; + +C -1 ; WX 556 ; N ecaron ; B 23 -14 528 750 ; + +C -1 ; WX 667 ; N Ydieresis ; B 15 0 653 915 ; + +C -1 ; WX 584 ; N divide ; B 40 -42 544 548 ; + +C -1 ; WX 667 ; N Yacute ; B 15 0 653 936 ; + +C -1 ; WX 722 ; N Acircumflex ; B 20 0 702 936 ; + +C -1 ; WX 556 ; N aacute ; B 29 -14 527 750 ; + +C -1 ; WX 722 ; N Ucircumflex ; B 72 -19 651 936 ; + +C -1 ; WX 556 ; N yacute ; B 10 -214 539 750 ; + +C -1 ; WX 556 ; N scommaaccent ; B 30 -228 519 546 ; + +C -1 ; WX 556 ; N ecircumflex ; B 23 -14 528 750 ; + +C -1 ; WX 722 ; N Uring ; B 72 -19 651 962 ; + +C -1 ; WX 722 ; N Udieresis ; B 72 -19 651 915 ; + +C -1 ; WX 556 ; N aogonek ; B 29 -224 545 546 ; + +C -1 ; WX 722 ; N Uacute ; B 72 -19 651 936 ; + +C -1 ; WX 611 ; N uogonek ; B 66 -228 545 532 ; + +C -1 ; WX 667 ; N Edieresis ; B 76 0 621 915 ; + +C -1 ; WX 722 ; N Dcroat ; B -5 0 685 718 ; + +C -1 ; WX 250 ; N commaaccent ; B 64 -228 199 -50 ; + +C -1 ; WX 737 ; N copyright ; B -11 -19 749 737 ; + +C -1 ; WX 667 ; N Emacron ; B 76 0 621 864 ; + +C -1 ; WX 556 ; N ccaron ; B 34 -14 524 750 ; + +C -1 ; WX 556 ; N aring ; B 29 -14 527 776 ; + +C -1 ; WX 722 ; N Ncommaaccent ; B 69 -228 654 718 ; + +C -1 ; WX 278 ; N lacute ; B 69 0 329 936 ; + +C -1 ; WX 556 ; N agrave ; B 29 -14 527 750 ; + +C -1 ; WX 611 ; N Tcommaaccent ; B 14 -228 598 718 ; + +C -1 ; WX 722 ; N Cacute ; B 44 -19 684 936 ; + +C -1 ; WX 556 ; N atilde ; B 29 -14 527 737 ; + +C -1 ; WX 667 ; N Edotaccent ; B 76 0 621 915 ; + +C -1 ; WX 556 ; N scaron ; B 30 -14 519 750 ; + +C -1 ; WX 556 ; N scedilla ; B 30 -228 519 546 ; + +C -1 ; WX 278 ; N iacute ; B 69 0 329 750 ; + +C -1 ; WX 494 ; N lozenge ; B 10 0 484 745 ; + +C -1 ; WX 722 ; N Rcaron ; B 76 0 677 936 ; + +C -1 ; WX 778 ; N Gcommaaccent ; B 44 -228 713 737 ; + +C -1 ; WX 611 ; N ucircumflex ; B 66 -14 545 750 ; + +C -1 ; WX 556 ; N acircumflex ; B 29 -14 527 750 ; + +C -1 ; WX 722 ; N Amacron ; B 20 0 702 864 ; + +C -1 ; WX 389 ; N rcaron ; B 18 0 373 750 ; + +C -1 ; WX 556 ; N ccedilla ; B 34 -228 524 546 ; + +C -1 ; WX 611 ; N Zdotaccent ; B 25 0 586 915 ; + +C -1 ; WX 667 ; N Thorn ; B 76 0 627 718 ; + +C -1 ; WX 778 ; N Omacron ; B 44 -19 734 864 ; + +C -1 ; WX 722 ; N Racute ; B 76 0 677 936 ; + +C -1 ; WX 667 ; N Sacute ; B 39 -19 629 936 ; + +C -1 ; WX 743 ; N dcaron ; B 34 -14 750 718 ; + +C -1 ; WX 722 ; N Umacron ; B 72 -19 651 864 ; + +C -1 ; WX 611 ; N uring ; B 66 -14 545 776 ; + +C -1 ; WX 333 ; N threesuperior ; B 8 271 326 710 ; + +C -1 ; WX 778 ; N Ograve ; B 44 -19 734 936 ; + +C -1 ; WX 722 ; N Agrave ; B 20 0 702 936 ; + +C -1 ; WX 722 ; N Abreve ; B 20 0 702 936 ; + +C -1 ; WX 584 ; N multiply ; B 40 1 545 505 ; + +C -1 ; WX 611 ; N uacute ; B 66 -14 545 750 ; + +C -1 ; WX 611 ; N Tcaron ; B 14 0 598 936 ; + +C -1 ; WX 494 ; N partialdiff ; B 11 -21 494 750 ; + +C -1 ; WX 556 ; N ydieresis ; B 10 -214 539 729 ; + +C -1 ; WX 722 ; N Nacute ; B 69 0 654 936 ; + +C -1 ; WX 278 ; N icircumflex ; B -37 0 316 750 ; + +C -1 ; WX 667 ; N Ecircumflex ; B 76 0 621 936 ; + +C -1 ; WX 556 ; N adieresis ; B 29 -14 527 729 ; + +C -1 ; WX 556 ; N edieresis ; B 23 -14 528 729 ; + +C -1 ; WX 556 ; N cacute ; B 34 -14 524 750 ; + +C -1 ; WX 611 ; N nacute ; B 65 0 546 750 ; + +C -1 ; WX 611 ; N umacron ; B 66 -14 545 678 ; + +C -1 ; WX 722 ; N Ncaron ; B 69 0 654 936 ; + +C -1 ; WX 278 ; N Iacute ; B 64 0 329 936 ; + +C -1 ; WX 584 ; N plusminus ; B 40 0 544 506 ; + +C -1 ; WX 280 ; N brokenbar ; B 84 -150 196 700 ; + +C -1 ; WX 737 ; N registered ; B -11 -19 748 737 ; + +C -1 ; WX 778 ; N Gbreve ; B 44 -19 713 936 ; + +C -1 ; WX 278 ; N Idotaccent ; B 64 0 214 915 ; + +C -1 ; WX 600 ; N summation ; B 14 -10 585 706 ; + +C -1 ; WX 667 ; N Egrave ; B 76 0 621 936 ; + +C -1 ; WX 389 ; N racute ; B 64 0 384 750 ; + +C -1 ; WX 611 ; N omacron ; B 34 -14 578 678 ; + +C -1 ; WX 611 ; N Zacute ; B 25 0 586 936 ; + +C -1 ; WX 611 ; N Zcaron ; B 25 0 586 936 ; + +C -1 ; WX 549 ; N greaterequal ; B 26 0 523 704 ; + +C -1 ; WX 722 ; N Eth ; B -5 0 685 718 ; + +C -1 ; WX 722 ; N Ccedilla ; B 44 -228 684 737 ; + +C -1 ; WX 278 ; N lcommaaccent ; B 69 -228 213 718 ; + +C -1 ; WX 389 ; N tcaron ; B 10 -6 421 878 ; + +C -1 ; WX 556 ; N eogonek ; B 23 -228 528 546 ; + +C -1 ; WX 722 ; N Uogonek ; B 72 -228 651 718 ; + +C -1 ; WX 722 ; N Aacute ; B 20 0 702 936 ; + +C -1 ; WX 722 ; N Adieresis ; B 20 0 702 915 ; + +C -1 ; WX 556 ; N egrave ; B 23 -14 528 750 ; + +C -1 ; WX 500 ; N zacute ; B 20 0 480 750 ; + +C -1 ; WX 278 ; N iogonek ; B 16 -224 249 725 ; + +C -1 ; WX 778 ; N Oacute ; B 44 -19 734 936 ; + +C -1 ; WX 611 ; N oacute ; B 34 -14 578 750 ; + +C -1 ; WX 556 ; N amacron ; B 29 -14 527 678 ; + +C -1 ; WX 556 ; N sacute ; B 30 -14 519 750 ; + +C -1 ; WX 278 ; N idieresis ; B -21 0 300 729 ; + +C -1 ; WX 778 ; N Ocircumflex ; B 44 -19 734 936 ; + +C -1 ; WX 722 ; N Ugrave ; B 72 -19 651 936 ; + +C -1 ; WX 612 ; N Delta ; B 6 0 608 688 ; + +C -1 ; WX 611 ; N thorn ; B 62 -208 578 718 ; + +C -1 ; WX 333 ; N twosuperior ; B 9 283 324 710 ; + +C -1 ; WX 778 ; N Odieresis ; B 44 -19 734 915 ; + +C -1 ; WX 611 ; N mu ; B 66 -207 545 532 ; + +C -1 ; WX 278 ; N igrave ; B -50 0 209 750 ; + +C -1 ; WX 611 ; N ohungarumlaut ; B 34 -14 625 750 ; + +C -1 ; WX 667 ; N Eogonek ; B 76 -224 639 718 ; + +C -1 ; WX 611 ; N dcroat ; B 34 -14 650 718 ; + +C -1 ; WX 834 ; N threequarters ; B 16 -19 799 710 ; + +C -1 ; WX 667 ; N Scedilla ; B 39 -228 629 737 ; + +C -1 ; WX 400 ; N lcaron ; B 69 0 408 718 ; + +C -1 ; WX 722 ; N Kcommaaccent ; B 87 -228 722 718 ; + +C -1 ; WX 611 ; N Lacute ; B 76 0 583 936 ; + +C -1 ; WX 1000 ; N trademark ; B 44 306 956 718 ; + +C -1 ; WX 556 ; N edotaccent ; B 23 -14 528 729 ; + +C -1 ; WX 278 ; N Igrave ; B -50 0 214 936 ; + +C -1 ; WX 278 ; N Imacron ; B -33 0 312 864 ; + +C -1 ; WX 611 ; N Lcaron ; B 76 0 583 718 ; + +C -1 ; WX 834 ; N onehalf ; B 26 -19 794 710 ; + +C -1 ; WX 549 ; N lessequal ; B 29 0 526 704 ; + +C -1 ; WX 611 ; N ocircumflex ; B 34 -14 578 750 ; + +C -1 ; WX 611 ; N ntilde ; B 65 0 546 737 ; + +C -1 ; WX 722 ; N Uhungarumlaut ; B 72 -19 681 936 ; + +C -1 ; WX 667 ; N Eacute ; B 76 0 621 936 ; + +C -1 ; WX 556 ; N emacron ; B 23 -14 528 678 ; + +C -1 ; WX 611 ; N gbreve ; B 40 -217 553 750 ; + +C -1 ; WX 834 ; N onequarter ; B 26 -19 766 710 ; + +C -1 ; WX 667 ; N Scaron ; B 39 -19 629 936 ; + +C -1 ; WX 667 ; N Scommaaccent ; B 39 -228 629 737 ; + +C -1 ; WX 778 ; N Ohungarumlaut ; B 44 -19 734 936 ; + +C -1 ; WX 400 ; N degree ; B 57 426 343 712 ; + +C -1 ; WX 611 ; N ograve ; B 34 -14 578 750 ; + +C -1 ; WX 722 ; N Ccaron ; B 44 -19 684 936 ; + +C -1 ; WX 611 ; N ugrave ; B 66 -14 545 750 ; + +C -1 ; WX 549 ; N radical ; B 10 -46 512 850 ; + +C -1 ; WX 722 ; N Dcaron ; B 76 0 685 936 ; + +C -1 ; WX 389 ; N rcommaaccent ; B 64 -228 373 546 ; + +C -1 ; WX 722 ; N Ntilde ; B 69 0 654 923 ; + +C -1 ; WX 611 ; N otilde ; B 34 -14 578 737 ; + +C -1 ; WX 722 ; N Rcommaaccent ; B 76 -228 677 718 ; + +C -1 ; WX 611 ; N Lcommaaccent ; B 76 -228 583 718 ; + +C -1 ; WX 722 ; N Atilde ; B 20 0 702 923 ; + +C -1 ; WX 722 ; N Aogonek ; B 20 -224 742 718 ; + +C -1 ; WX 722 ; N Aring ; B 20 0 702 962 ; + +C -1 ; WX 778 ; N Otilde ; B 44 -19 734 923 ; + +C -1 ; WX 500 ; N zdotaccent ; B 20 0 480 729 ; + +C -1 ; WX 667 ; N Ecaron ; B 76 0 621 936 ; + +C -1 ; WX 278 ; N Iogonek ; B -11 -228 222 718 ; + +C -1 ; WX 556 ; N kcommaaccent ; B 69 -228 562 718 ; + +C -1 ; WX 584 ; N minus ; B 40 197 544 309 ; + +C -1 ; WX 278 ; N Icircumflex ; B -37 0 316 936 ; + +C -1 ; WX 611 ; N ncaron ; B 65 0 546 750 ; + +C -1 ; WX 333 ; N tcommaaccent ; B 10 -228 309 676 ; + +C -1 ; WX 584 ; N logicalnot ; B 40 108 544 419 ; + +C -1 ; WX 611 ; N odieresis ; B 34 -14 578 729 ; + +C -1 ; WX 611 ; N udieresis ; B 66 -14 545 729 ; + +C -1 ; WX 549 ; N notequal ; B 15 -49 540 570 ; + +C -1 ; WX 611 ; N gcommaaccent ; B 40 -217 553 850 ; + +C -1 ; WX 611 ; N eth ; B 34 -14 578 737 ; + +C -1 ; WX 500 ; N zcaron ; B 20 0 480 750 ; + +C -1 ; WX 611 ; N ncommaaccent ; B 65 -228 546 546 ; + +C -1 ; WX 333 ; N onesuperior ; B 26 283 237 710 ; + +C -1 ; WX 278 ; N imacron ; B -8 0 285 678 ; + +C -1 ; WX 556 ; N Euro ; B 0 0 0 0 ; + +EndCharMetrics + +StartKernData + +StartKernPairs 2481 + +KPX A C -40 + +KPX A Cacute -40 + +KPX A Ccaron -40 + +KPX A Ccedilla -40 + +KPX A G -50 + +KPX A Gbreve -50 + +KPX A Gcommaaccent -50 + +KPX A O -40 + +KPX A Oacute -40 + +KPX A Ocircumflex -40 + +KPX A Odieresis -40 + +KPX A Ograve -40 + +KPX A Ohungarumlaut -40 + +KPX A Omacron -40 + +KPX A Oslash -40 + +KPX A Otilde -40 + +KPX A Q -40 + +KPX A T -90 + +KPX A Tcaron -90 + +KPX A Tcommaaccent -90 + +KPX A U -50 + +KPX A Uacute -50 + +KPX A Ucircumflex -50 + +KPX A Udieresis -50 + +KPX A Ugrave -50 + +KPX A Uhungarumlaut -50 + +KPX A Umacron -50 + +KPX A Uogonek -50 + +KPX A Uring -50 + +KPX A V -80 + +KPX A W -60 + +KPX A Y -110 + +KPX A Yacute -110 + +KPX A Ydieresis -110 + +KPX A u -30 + +KPX A uacute -30 + +KPX A ucircumflex -30 + +KPX A udieresis -30 + +KPX A ugrave -30 + +KPX A uhungarumlaut -30 + +KPX A umacron -30 + +KPX A uogonek -30 + +KPX A uring -30 + +KPX A v -40 + +KPX A w -30 + +KPX A y -30 + +KPX A yacute -30 + +KPX A ydieresis -30 + +KPX Aacute C -40 + +KPX Aacute Cacute -40 + +KPX Aacute Ccaron -40 + +KPX Aacute Ccedilla -40 + +KPX Aacute G -50 + +KPX Aacute Gbreve -50 + +KPX Aacute Gcommaaccent -50 + +KPX Aacute O -40 + +KPX Aacute Oacute -40 + +KPX Aacute Ocircumflex -40 + +KPX Aacute Odieresis -40 + +KPX Aacute Ograve -40 + +KPX Aacute Ohungarumlaut -40 + +KPX Aacute Omacron -40 + +KPX Aacute Oslash -40 + +KPX Aacute Otilde -40 + +KPX Aacute Q -40 + +KPX Aacute T -90 + +KPX Aacute Tcaron -90 + +KPX Aacute Tcommaaccent -90 + +KPX Aacute U -50 + +KPX Aacute Uacute -50 + +KPX Aacute Ucircumflex -50 + +KPX Aacute Udieresis -50 + +KPX Aacute Ugrave -50 + +KPX Aacute Uhungarumlaut -50 + +KPX Aacute Umacron -50 + +KPX Aacute Uogonek -50 + +KPX Aacute Uring -50 + +KPX Aacute V -80 + +KPX Aacute W -60 + +KPX Aacute Y -110 + +KPX Aacute Yacute -110 + +KPX Aacute Ydieresis -110 + +KPX Aacute u -30 + +KPX Aacute uacute -30 + +KPX Aacute ucircumflex -30 + +KPX Aacute udieresis -30 + +KPX Aacute ugrave -30 + +KPX Aacute uhungarumlaut -30 + +KPX Aacute umacron -30 + +KPX Aacute uogonek -30 + +KPX Aacute uring -30 + +KPX Aacute v -40 + +KPX Aacute w -30 + +KPX Aacute y -30 + +KPX Aacute yacute -30 + +KPX Aacute ydieresis -30 + +KPX Abreve C -40 + +KPX Abreve Cacute -40 + +KPX Abreve Ccaron -40 + +KPX Abreve Ccedilla -40 + +KPX Abreve G -50 + +KPX Abreve Gbreve -50 + +KPX Abreve Gcommaaccent -50 + +KPX Abreve O -40 + +KPX Abreve Oacute -40 + +KPX Abreve Ocircumflex -40 + +KPX Abreve Odieresis -40 + +KPX Abreve Ograve -40 + +KPX Abreve Ohungarumlaut -40 + +KPX Abreve Omacron -40 + +KPX Abreve Oslash -40 + +KPX Abreve Otilde -40 + +KPX Abreve Q -40 + +KPX Abreve T -90 + +KPX Abreve Tcaron -90 + +KPX Abreve Tcommaaccent -90 + +KPX Abreve U -50 + +KPX Abreve Uacute -50 + +KPX Abreve Ucircumflex -50 + +KPX Abreve Udieresis -50 + +KPX Abreve Ugrave -50 + +KPX Abreve Uhungarumlaut -50 + +KPX Abreve Umacron -50 + +KPX Abreve Uogonek -50 + +KPX Abreve Uring -50 + +KPX Abreve V -80 + +KPX Abreve W -60 + +KPX Abreve Y -110 + +KPX Abreve Yacute -110 + +KPX Abreve Ydieresis -110 + +KPX Abreve u -30 + +KPX Abreve uacute -30 + +KPX Abreve ucircumflex -30 + +KPX Abreve udieresis -30 + +KPX Abreve ugrave -30 + +KPX Abreve uhungarumlaut -30 + +KPX Abreve umacron -30 + +KPX Abreve uogonek -30 + +KPX Abreve uring -30 + +KPX Abreve v -40 + +KPX Abreve w -30 + +KPX Abreve y -30 + +KPX Abreve yacute -30 + +KPX Abreve ydieresis -30 + +KPX Acircumflex C -40 + +KPX Acircumflex Cacute -40 + +KPX Acircumflex Ccaron -40 + +KPX Acircumflex Ccedilla -40 + +KPX Acircumflex G -50 + +KPX Acircumflex Gbreve -50 + +KPX Acircumflex Gcommaaccent -50 + +KPX Acircumflex O -40 + +KPX Acircumflex Oacute -40 + +KPX Acircumflex Ocircumflex -40 + +KPX Acircumflex Odieresis -40 + +KPX Acircumflex Ograve -40 + +KPX Acircumflex Ohungarumlaut -40 + +KPX Acircumflex Omacron -40 + +KPX Acircumflex Oslash -40 + +KPX Acircumflex Otilde -40 + +KPX Acircumflex Q -40 + +KPX Acircumflex T -90 + +KPX Acircumflex Tcaron -90 + +KPX Acircumflex Tcommaaccent -90 + +KPX Acircumflex U -50 + +KPX Acircumflex Uacute -50 + +KPX Acircumflex Ucircumflex -50 + +KPX Acircumflex Udieresis -50 + +KPX Acircumflex Ugrave -50 + +KPX Acircumflex Uhungarumlaut -50 + +KPX Acircumflex Umacron -50 + +KPX Acircumflex Uogonek -50 + +KPX Acircumflex Uring -50 + +KPX Acircumflex V -80 + +KPX Acircumflex W -60 + +KPX Acircumflex Y -110 + +KPX Acircumflex Yacute -110 + +KPX Acircumflex Ydieresis -110 + +KPX Acircumflex u -30 + +KPX Acircumflex uacute -30 + +KPX Acircumflex ucircumflex -30 + +KPX Acircumflex udieresis -30 + +KPX Acircumflex ugrave -30 + +KPX Acircumflex uhungarumlaut -30 + +KPX Acircumflex umacron -30 + +KPX Acircumflex uogonek -30 + +KPX Acircumflex uring -30 + +KPX Acircumflex v -40 + +KPX Acircumflex w -30 + +KPX Acircumflex y -30 + +KPX Acircumflex yacute -30 + +KPX Acircumflex ydieresis -30 + +KPX Adieresis C -40 + +KPX Adieresis Cacute -40 + +KPX Adieresis Ccaron -40 + +KPX Adieresis Ccedilla -40 + +KPX Adieresis G -50 + +KPX Adieresis Gbreve -50 + +KPX Adieresis Gcommaaccent -50 + +KPX Adieresis O -40 + +KPX Adieresis Oacute -40 + +KPX Adieresis Ocircumflex -40 + +KPX Adieresis Odieresis -40 + +KPX Adieresis Ograve -40 + +KPX Adieresis Ohungarumlaut -40 + +KPX Adieresis Omacron -40 + +KPX Adieresis Oslash -40 + +KPX Adieresis Otilde -40 + +KPX Adieresis Q -40 + +KPX Adieresis T -90 + +KPX Adieresis Tcaron -90 + +KPX Adieresis Tcommaaccent -90 + +KPX Adieresis U -50 + +KPX Adieresis Uacute -50 + +KPX Adieresis Ucircumflex -50 + +KPX Adieresis Udieresis -50 + +KPX Adieresis Ugrave -50 + +KPX Adieresis Uhungarumlaut -50 + +KPX Adieresis Umacron -50 + +KPX Adieresis Uogonek -50 + +KPX Adieresis Uring -50 + +KPX Adieresis V -80 + +KPX Adieresis W -60 + +KPX Adieresis Y -110 + +KPX Adieresis Yacute -110 + +KPX Adieresis Ydieresis -110 + +KPX Adieresis u -30 + +KPX Adieresis uacute -30 + +KPX Adieresis ucircumflex -30 + +KPX Adieresis udieresis -30 + +KPX Adieresis ugrave -30 + +KPX Adieresis uhungarumlaut -30 + +KPX Adieresis umacron -30 + +KPX Adieresis uogonek -30 + +KPX Adieresis uring -30 + +KPX Adieresis v -40 + +KPX Adieresis w -30 + +KPX Adieresis y -30 + +KPX Adieresis yacute -30 + +KPX Adieresis ydieresis -30 + +KPX Agrave C -40 + +KPX Agrave Cacute -40 + +KPX Agrave Ccaron -40 + +KPX Agrave Ccedilla -40 + +KPX Agrave G -50 + +KPX Agrave Gbreve -50 + +KPX Agrave Gcommaaccent -50 + +KPX Agrave O -40 + +KPX Agrave Oacute -40 + +KPX Agrave Ocircumflex -40 + +KPX Agrave Odieresis -40 + +KPX Agrave Ograve -40 + +KPX Agrave Ohungarumlaut -40 + +KPX Agrave Omacron -40 + +KPX Agrave Oslash -40 + +KPX Agrave Otilde -40 + +KPX Agrave Q -40 + +KPX Agrave T -90 + +KPX Agrave Tcaron -90 + +KPX Agrave Tcommaaccent -90 + +KPX Agrave U -50 + +KPX Agrave Uacute -50 + +KPX Agrave Ucircumflex -50 + +KPX Agrave Udieresis -50 + +KPX Agrave Ugrave -50 + +KPX Agrave Uhungarumlaut -50 + +KPX Agrave Umacron -50 + +KPX Agrave Uogonek -50 + +KPX Agrave Uring -50 + +KPX Agrave V -80 + +KPX Agrave W -60 + +KPX Agrave Y -110 + +KPX Agrave Yacute -110 + +KPX Agrave Ydieresis -110 + +KPX Agrave u -30 + +KPX Agrave uacute -30 + +KPX Agrave ucircumflex -30 + +KPX Agrave udieresis -30 + +KPX Agrave ugrave -30 + +KPX Agrave uhungarumlaut -30 + +KPX Agrave umacron -30 + +KPX Agrave uogonek -30 + +KPX Agrave uring -30 + +KPX Agrave v -40 + +KPX Agrave w -30 + +KPX Agrave y -30 + +KPX Agrave yacute -30 + +KPX Agrave ydieresis -30 + +KPX Amacron C -40 + +KPX Amacron Cacute -40 + +KPX Amacron Ccaron -40 + +KPX Amacron Ccedilla -40 + +KPX Amacron G -50 + +KPX Amacron Gbreve -50 + +KPX Amacron Gcommaaccent -50 + +KPX Amacron O -40 + +KPX Amacron Oacute -40 + +KPX Amacron Ocircumflex -40 + +KPX Amacron Odieresis -40 + +KPX Amacron Ograve -40 + +KPX Amacron Ohungarumlaut -40 + +KPX Amacron Omacron -40 + +KPX Amacron Oslash -40 + +KPX Amacron Otilde -40 + +KPX Amacron Q -40 + +KPX Amacron T -90 + +KPX Amacron Tcaron -90 + +KPX Amacron Tcommaaccent -90 + +KPX Amacron U -50 + +KPX Amacron Uacute -50 + +KPX Amacron Ucircumflex -50 + +KPX Amacron Udieresis -50 + +KPX Amacron Ugrave -50 + +KPX Amacron Uhungarumlaut -50 + +KPX Amacron Umacron -50 + +KPX Amacron Uogonek -50 + +KPX Amacron Uring -50 + +KPX Amacron V -80 + +KPX Amacron W -60 + +KPX Amacron Y -110 + +KPX Amacron Yacute -110 + +KPX Amacron Ydieresis -110 + +KPX Amacron u -30 + +KPX Amacron uacute -30 + +KPX Amacron ucircumflex -30 + +KPX Amacron udieresis -30 + +KPX Amacron ugrave -30 + +KPX Amacron uhungarumlaut -30 + +KPX Amacron umacron -30 + +KPX Amacron uogonek -30 + +KPX Amacron uring -30 + +KPX Amacron v -40 + +KPX Amacron w -30 + +KPX Amacron y -30 + +KPX Amacron yacute -30 + +KPX Amacron ydieresis -30 + +KPX Aogonek C -40 + +KPX Aogonek Cacute -40 + +KPX Aogonek Ccaron -40 + +KPX Aogonek Ccedilla -40 + +KPX Aogonek G -50 + +KPX Aogonek Gbreve -50 + +KPX Aogonek Gcommaaccent -50 + +KPX Aogonek O -40 + +KPX Aogonek Oacute -40 + +KPX Aogonek Ocircumflex -40 + +KPX Aogonek Odieresis -40 + +KPX Aogonek Ograve -40 + +KPX Aogonek Ohungarumlaut -40 + +KPX Aogonek Omacron -40 + +KPX Aogonek Oslash -40 + +KPX Aogonek Otilde -40 + +KPX Aogonek Q -40 + +KPX Aogonek T -90 + +KPX Aogonek Tcaron -90 + +KPX Aogonek Tcommaaccent -90 + +KPX Aogonek U -50 + +KPX Aogonek Uacute -50 + +KPX Aogonek Ucircumflex -50 + +KPX Aogonek Udieresis -50 + +KPX Aogonek Ugrave -50 + +KPX Aogonek Uhungarumlaut -50 + +KPX Aogonek Umacron -50 + +KPX Aogonek Uogonek -50 + +KPX Aogonek Uring -50 + +KPX Aogonek V -80 + +KPX Aogonek W -60 + +KPX Aogonek Y -110 + +KPX Aogonek Yacute -110 + +KPX Aogonek Ydieresis -110 + +KPX Aogonek u -30 + +KPX Aogonek uacute -30 + +KPX Aogonek ucircumflex -30 + +KPX Aogonek udieresis -30 + +KPX Aogonek ugrave -30 + +KPX Aogonek uhungarumlaut -30 + +KPX Aogonek umacron -30 + +KPX Aogonek uogonek -30 + +KPX Aogonek uring -30 + +KPX Aogonek v -40 + +KPX Aogonek w -30 + +KPX Aogonek y -30 + +KPX Aogonek yacute -30 + +KPX Aogonek ydieresis -30 + +KPX Aring C -40 + +KPX Aring Cacute -40 + +KPX Aring Ccaron -40 + +KPX Aring Ccedilla -40 + +KPX Aring G -50 + +KPX Aring Gbreve -50 + +KPX Aring Gcommaaccent -50 + +KPX Aring O -40 + +KPX Aring Oacute -40 + +KPX Aring Ocircumflex -40 + +KPX Aring Odieresis -40 + +KPX Aring Ograve -40 + +KPX Aring Ohungarumlaut -40 + +KPX Aring Omacron -40 + +KPX Aring Oslash -40 + +KPX Aring Otilde -40 + +KPX Aring Q -40 + +KPX Aring T -90 + +KPX Aring Tcaron -90 + +KPX Aring Tcommaaccent -90 + +KPX Aring U -50 + +KPX Aring Uacute -50 + +KPX Aring Ucircumflex -50 + +KPX Aring Udieresis -50 + +KPX Aring Ugrave -50 + +KPX Aring Uhungarumlaut -50 + +KPX Aring Umacron -50 + +KPX Aring Uogonek -50 + +KPX Aring Uring -50 + +KPX Aring V -80 + +KPX Aring W -60 + +KPX Aring Y -110 + +KPX Aring Yacute -110 + +KPX Aring Ydieresis -110 + +KPX Aring u -30 + +KPX Aring uacute -30 + +KPX Aring ucircumflex -30 + +KPX Aring udieresis -30 + +KPX Aring ugrave -30 + +KPX Aring uhungarumlaut -30 + +KPX Aring umacron -30 + +KPX Aring uogonek -30 + +KPX Aring uring -30 + +KPX Aring v -40 + +KPX Aring w -30 + +KPX Aring y -30 + +KPX Aring yacute -30 + +KPX Aring ydieresis -30 + +KPX Atilde C -40 + +KPX Atilde Cacute -40 + +KPX Atilde Ccaron -40 + +KPX Atilde Ccedilla -40 + +KPX Atilde G -50 + +KPX Atilde Gbreve -50 + +KPX Atilde Gcommaaccent -50 + +KPX Atilde O -40 + +KPX Atilde Oacute -40 + +KPX Atilde Ocircumflex -40 + +KPX Atilde Odieresis -40 + +KPX Atilde Ograve -40 + +KPX Atilde Ohungarumlaut -40 + +KPX Atilde Omacron -40 + +KPX Atilde Oslash -40 + +KPX Atilde Otilde -40 + +KPX Atilde Q -40 + +KPX Atilde T -90 + +KPX Atilde Tcaron -90 + +KPX Atilde Tcommaaccent -90 + +KPX Atilde U -50 + +KPX Atilde Uacute -50 + +KPX Atilde Ucircumflex -50 + +KPX Atilde Udieresis -50 + +KPX Atilde Ugrave -50 + +KPX Atilde Uhungarumlaut -50 + +KPX Atilde Umacron -50 + +KPX Atilde Uogonek -50 + +KPX Atilde Uring -50 + +KPX Atilde V -80 + +KPX Atilde W -60 + +KPX Atilde Y -110 + +KPX Atilde Yacute -110 + +KPX Atilde Ydieresis -110 + +KPX Atilde u -30 + +KPX Atilde uacute -30 + +KPX Atilde ucircumflex -30 + +KPX Atilde udieresis -30 + +KPX Atilde ugrave -30 + +KPX Atilde uhungarumlaut -30 + +KPX Atilde umacron -30 + +KPX Atilde uogonek -30 + +KPX Atilde uring -30 + +KPX Atilde v -40 + +KPX Atilde w -30 + +KPX Atilde y -30 + +KPX Atilde yacute -30 + +KPX Atilde ydieresis -30 + +KPX B A -30 + +KPX B Aacute -30 + +KPX B Abreve -30 + +KPX B Acircumflex -30 + +KPX B Adieresis -30 + +KPX B Agrave -30 + +KPX B Amacron -30 + +KPX B Aogonek -30 + +KPX B Aring -30 + +KPX B Atilde -30 + +KPX B U -10 + +KPX B Uacute -10 + +KPX B Ucircumflex -10 + +KPX B Udieresis -10 + +KPX B Ugrave -10 + +KPX B Uhungarumlaut -10 + +KPX B Umacron -10 + +KPX B Uogonek -10 + +KPX B Uring -10 + +KPX D A -40 + +KPX D Aacute -40 + +KPX D Abreve -40 + +KPX D Acircumflex -40 + +KPX D Adieresis -40 + +KPX D Agrave -40 + +KPX D Amacron -40 + +KPX D Aogonek -40 + +KPX D Aring -40 + +KPX D Atilde -40 + +KPX D V -40 + +KPX D W -40 + +KPX D Y -70 + +KPX D Yacute -70 + +KPX D Ydieresis -70 + +KPX D comma -30 + +KPX D period -30 + +KPX Dcaron A -40 + +KPX Dcaron Aacute -40 + +KPX Dcaron Abreve -40 + +KPX Dcaron Acircumflex -40 + +KPX Dcaron Adieresis -40 + +KPX Dcaron Agrave -40 + +KPX Dcaron Amacron -40 + +KPX Dcaron Aogonek -40 + +KPX Dcaron Aring -40 + +KPX Dcaron Atilde -40 + +KPX Dcaron V -40 + +KPX Dcaron W -40 + +KPX Dcaron Y -70 + +KPX Dcaron Yacute -70 + +KPX Dcaron Ydieresis -70 + +KPX Dcaron comma -30 + +KPX Dcaron period -30 + +KPX Dcroat A -40 + +KPX Dcroat Aacute -40 + +KPX Dcroat Abreve -40 + +KPX Dcroat Acircumflex -40 + +KPX Dcroat Adieresis -40 + +KPX Dcroat Agrave -40 + +KPX Dcroat Amacron -40 + +KPX Dcroat Aogonek -40 + +KPX Dcroat Aring -40 + +KPX Dcroat Atilde -40 + +KPX Dcroat V -40 + +KPX Dcroat W -40 + +KPX Dcroat Y -70 + +KPX Dcroat Yacute -70 + +KPX Dcroat Ydieresis -70 + +KPX Dcroat comma -30 + +KPX Dcroat period -30 + +KPX F A -80 + +KPX F Aacute -80 + +KPX F Abreve -80 + +KPX F Acircumflex -80 + +KPX F Adieresis -80 + +KPX F Agrave -80 + +KPX F Amacron -80 + +KPX F Aogonek -80 + +KPX F Aring -80 + +KPX F Atilde -80 + +KPX F a -20 + +KPX F aacute -20 + +KPX F abreve -20 + +KPX F acircumflex -20 + +KPX F adieresis -20 + +KPX F agrave -20 + +KPX F amacron -20 + +KPX F aogonek -20 + +KPX F aring -20 + +KPX F atilde -20 + +KPX F comma -100 + +KPX F period -100 + +KPX J A -20 + +KPX J Aacute -20 + +KPX J Abreve -20 + +KPX J Acircumflex -20 + +KPX J Adieresis -20 + +KPX J Agrave -20 + +KPX J Amacron -20 + +KPX J Aogonek -20 + +KPX J Aring -20 + +KPX J Atilde -20 + +KPX J comma -20 + +KPX J period -20 + +KPX J u -20 + +KPX J uacute -20 + +KPX J ucircumflex -20 + +KPX J udieresis -20 + +KPX J ugrave -20 + +KPX J uhungarumlaut -20 + +KPX J umacron -20 + +KPX J uogonek -20 + +KPX J uring -20 + +KPX K O -30 + +KPX K Oacute -30 + +KPX K Ocircumflex -30 + +KPX K Odieresis -30 + +KPX K Ograve -30 + +KPX K Ohungarumlaut -30 + +KPX K Omacron -30 + +KPX K Oslash -30 + +KPX K Otilde -30 + +KPX K e -15 + +KPX K eacute -15 + +KPX K ecaron -15 + +KPX K ecircumflex -15 + +KPX K edieresis -15 + +KPX K edotaccent -15 + +KPX K egrave -15 + +KPX K emacron -15 + +KPX K eogonek -15 + +KPX K o -35 + +KPX K oacute -35 + +KPX K ocircumflex -35 + +KPX K odieresis -35 + +KPX K ograve -35 + +KPX K ohungarumlaut -35 + +KPX K omacron -35 + +KPX K oslash -35 + +KPX K otilde -35 + +KPX K u -30 + +KPX K uacute -30 + +KPX K ucircumflex -30 + +KPX K udieresis -30 + +KPX K ugrave -30 + +KPX K uhungarumlaut -30 + +KPX K umacron -30 + +KPX K uogonek -30 + +KPX K uring -30 + +KPX K y -40 + +KPX K yacute -40 + +KPX K ydieresis -40 + +KPX Kcommaaccent O -30 + +KPX Kcommaaccent Oacute -30 + +KPX Kcommaaccent Ocircumflex -30 + +KPX Kcommaaccent Odieresis -30 + +KPX Kcommaaccent Ograve -30 + +KPX Kcommaaccent Ohungarumlaut -30 + +KPX Kcommaaccent Omacron -30 + +KPX Kcommaaccent Oslash -30 + +KPX Kcommaaccent Otilde -30 + +KPX Kcommaaccent e -15 + +KPX Kcommaaccent eacute -15 + +KPX Kcommaaccent ecaron -15 + +KPX Kcommaaccent ecircumflex -15 + +KPX Kcommaaccent edieresis -15 + +KPX Kcommaaccent edotaccent -15 + +KPX Kcommaaccent egrave -15 + +KPX Kcommaaccent emacron -15 + +KPX Kcommaaccent eogonek -15 + +KPX Kcommaaccent o -35 + +KPX Kcommaaccent oacute -35 + +KPX Kcommaaccent ocircumflex -35 + +KPX Kcommaaccent odieresis -35 + +KPX Kcommaaccent ograve -35 + +KPX Kcommaaccent ohungarumlaut -35 + +KPX Kcommaaccent omacron -35 + +KPX Kcommaaccent oslash -35 + +KPX Kcommaaccent otilde -35 + +KPX Kcommaaccent u -30 + +KPX Kcommaaccent uacute -30 + +KPX Kcommaaccent ucircumflex -30 + +KPX Kcommaaccent udieresis -30 + +KPX Kcommaaccent ugrave -30 + +KPX Kcommaaccent uhungarumlaut -30 + +KPX Kcommaaccent umacron -30 + +KPX Kcommaaccent uogonek -30 + +KPX Kcommaaccent uring -30 + +KPX Kcommaaccent y -40 + +KPX Kcommaaccent yacute -40 + +KPX Kcommaaccent ydieresis -40 + +KPX L T -90 + +KPX L Tcaron -90 + +KPX L Tcommaaccent -90 + +KPX L V -110 + +KPX L W -80 + +KPX L Y -120 + +KPX L Yacute -120 + +KPX L Ydieresis -120 + +KPX L quotedblright -140 + +KPX L quoteright -140 + +KPX L y -30 + +KPX L yacute -30 + +KPX L ydieresis -30 + +KPX Lacute T -90 + +KPX Lacute Tcaron -90 + +KPX Lacute Tcommaaccent -90 + +KPX Lacute V -110 + +KPX Lacute W -80 + +KPX Lacute Y -120 + +KPX Lacute Yacute -120 + +KPX Lacute Ydieresis -120 + +KPX Lacute quotedblright -140 + +KPX Lacute quoteright -140 + +KPX Lacute y -30 + +KPX Lacute yacute -30 + +KPX Lacute ydieresis -30 + +KPX Lcommaaccent T -90 + +KPX Lcommaaccent Tcaron -90 + +KPX Lcommaaccent Tcommaaccent -90 + +KPX Lcommaaccent V -110 + +KPX Lcommaaccent W -80 + +KPX Lcommaaccent Y -120 + +KPX Lcommaaccent Yacute -120 + +KPX Lcommaaccent Ydieresis -120 + +KPX Lcommaaccent quotedblright -140 + +KPX Lcommaaccent quoteright -140 + +KPX Lcommaaccent y -30 + +KPX Lcommaaccent yacute -30 + +KPX Lcommaaccent ydieresis -30 + +KPX Lslash T -90 + +KPX Lslash Tcaron -90 + +KPX Lslash Tcommaaccent -90 + +KPX Lslash V -110 + +KPX Lslash W -80 + +KPX Lslash Y -120 + +KPX Lslash Yacute -120 + +KPX Lslash Ydieresis -120 + +KPX Lslash quotedblright -140 + +KPX Lslash quoteright -140 + +KPX Lslash y -30 + +KPX Lslash yacute -30 + +KPX Lslash ydieresis -30 + +KPX O A -50 + +KPX O Aacute -50 + +KPX O Abreve -50 + +KPX O Acircumflex -50 + +KPX O Adieresis -50 + +KPX O Agrave -50 + +KPX O Amacron -50 + +KPX O Aogonek -50 + +KPX O Aring -50 + +KPX O Atilde -50 + +KPX O T -40 + +KPX O Tcaron -40 + +KPX O Tcommaaccent -40 + +KPX O V -50 + +KPX O W -50 + +KPX O X -50 + +KPX O Y -70 + +KPX O Yacute -70 + +KPX O Ydieresis -70 + +KPX O comma -40 + +KPX O period -40 + +KPX Oacute A -50 + +KPX Oacute Aacute -50 + +KPX Oacute Abreve -50 + +KPX Oacute Acircumflex -50 + +KPX Oacute Adieresis -50 + +KPX Oacute Agrave -50 + +KPX Oacute Amacron -50 + +KPX Oacute Aogonek -50 + +KPX Oacute Aring -50 + +KPX Oacute Atilde -50 + +KPX Oacute T -40 + +KPX Oacute Tcaron -40 + +KPX Oacute Tcommaaccent -40 + +KPX Oacute V -50 + +KPX Oacute W -50 + +KPX Oacute X -50 + +KPX Oacute Y -70 + +KPX Oacute Yacute -70 + +KPX Oacute Ydieresis -70 + +KPX Oacute comma -40 + +KPX Oacute period -40 + +KPX Ocircumflex A -50 + +KPX Ocircumflex Aacute -50 + +KPX Ocircumflex Abreve -50 + +KPX Ocircumflex Acircumflex -50 + +KPX Ocircumflex Adieresis -50 + +KPX Ocircumflex Agrave -50 + +KPX Ocircumflex Amacron -50 + +KPX Ocircumflex Aogonek -50 + +KPX Ocircumflex Aring -50 + +KPX Ocircumflex Atilde -50 + +KPX Ocircumflex T -40 + +KPX Ocircumflex Tcaron -40 + +KPX Ocircumflex Tcommaaccent -40 + +KPX Ocircumflex V -50 + +KPX Ocircumflex W -50 + +KPX Ocircumflex X -50 + +KPX Ocircumflex Y -70 + +KPX Ocircumflex Yacute -70 + +KPX Ocircumflex Ydieresis -70 + +KPX Ocircumflex comma -40 + +KPX Ocircumflex period -40 + +KPX Odieresis A -50 + +KPX Odieresis Aacute -50 + +KPX Odieresis Abreve -50 + +KPX Odieresis Acircumflex -50 + +KPX Odieresis Adieresis -50 + +KPX Odieresis Agrave -50 + +KPX Odieresis Amacron -50 + +KPX Odieresis Aogonek -50 + +KPX Odieresis Aring -50 + +KPX Odieresis Atilde -50 + +KPX Odieresis T -40 + +KPX Odieresis Tcaron -40 + +KPX Odieresis Tcommaaccent -40 + +KPX Odieresis V -50 + +KPX Odieresis W -50 + +KPX Odieresis X -50 + +KPX Odieresis Y -70 + +KPX Odieresis Yacute -70 + +KPX Odieresis Ydieresis -70 + +KPX Odieresis comma -40 + +KPX Odieresis period -40 + +KPX Ograve A -50 + +KPX Ograve Aacute -50 + +KPX Ograve Abreve -50 + +KPX Ograve Acircumflex -50 + +KPX Ograve Adieresis -50 + +KPX Ograve Agrave -50 + +KPX Ograve Amacron -50 + +KPX Ograve Aogonek -50 + +KPX Ograve Aring -50 + +KPX Ograve Atilde -50 + +KPX Ograve T -40 + +KPX Ograve Tcaron -40 + +KPX Ograve Tcommaaccent -40 + +KPX Ograve V -50 + +KPX Ograve W -50 + +KPX Ograve X -50 + +KPX Ograve Y -70 + +KPX Ograve Yacute -70 + +KPX Ograve Ydieresis -70 + +KPX Ograve comma -40 + +KPX Ograve period -40 + +KPX Ohungarumlaut A -50 + +KPX Ohungarumlaut Aacute -50 + +KPX Ohungarumlaut Abreve -50 + +KPX Ohungarumlaut Acircumflex -50 + +KPX Ohungarumlaut Adieresis -50 + +KPX Ohungarumlaut Agrave -50 + +KPX Ohungarumlaut Amacron -50 + +KPX Ohungarumlaut Aogonek -50 + +KPX Ohungarumlaut Aring -50 + +KPX Ohungarumlaut Atilde -50 + +KPX Ohungarumlaut T -40 + +KPX Ohungarumlaut Tcaron -40 + +KPX Ohungarumlaut Tcommaaccent -40 + +KPX Ohungarumlaut V -50 + +KPX Ohungarumlaut W -50 + +KPX Ohungarumlaut X -50 + +KPX Ohungarumlaut Y -70 + +KPX Ohungarumlaut Yacute -70 + +KPX Ohungarumlaut Ydieresis -70 + +KPX Ohungarumlaut comma -40 + +KPX Ohungarumlaut period -40 + +KPX Omacron A -50 + +KPX Omacron Aacute -50 + +KPX Omacron Abreve -50 + +KPX Omacron Acircumflex -50 + +KPX Omacron Adieresis -50 + +KPX Omacron Agrave -50 + +KPX Omacron Amacron -50 + +KPX Omacron Aogonek -50 + +KPX Omacron Aring -50 + +KPX Omacron Atilde -50 + +KPX Omacron T -40 + +KPX Omacron Tcaron -40 + +KPX Omacron Tcommaaccent -40 + +KPX Omacron V -50 + +KPX Omacron W -50 + +KPX Omacron X -50 + +KPX Omacron Y -70 + +KPX Omacron Yacute -70 + +KPX Omacron Ydieresis -70 + +KPX Omacron comma -40 + +KPX Omacron period -40 + +KPX Oslash A -50 + +KPX Oslash Aacute -50 + +KPX Oslash Abreve -50 + +KPX Oslash Acircumflex -50 + +KPX Oslash Adieresis -50 + +KPX Oslash Agrave -50 + +KPX Oslash Amacron -50 + +KPX Oslash Aogonek -50 + +KPX Oslash Aring -50 + +KPX Oslash Atilde -50 + +KPX Oslash T -40 + +KPX Oslash Tcaron -40 + +KPX Oslash Tcommaaccent -40 + +KPX Oslash V -50 + +KPX Oslash W -50 + +KPX Oslash X -50 + +KPX Oslash Y -70 + +KPX Oslash Yacute -70 + +KPX Oslash Ydieresis -70 + +KPX Oslash comma -40 + +KPX Oslash period -40 + +KPX Otilde A -50 + +KPX Otilde Aacute -50 + +KPX Otilde Abreve -50 + +KPX Otilde Acircumflex -50 + +KPX Otilde Adieresis -50 + +KPX Otilde Agrave -50 + +KPX Otilde Amacron -50 + +KPX Otilde Aogonek -50 + +KPX Otilde Aring -50 + +KPX Otilde Atilde -50 + +KPX Otilde T -40 + +KPX Otilde Tcaron -40 + +KPX Otilde Tcommaaccent -40 + +KPX Otilde V -50 + +KPX Otilde W -50 + +KPX Otilde X -50 + +KPX Otilde Y -70 + +KPX Otilde Yacute -70 + +KPX Otilde Ydieresis -70 + +KPX Otilde comma -40 + +KPX Otilde period -40 + +KPX P A -100 + +KPX P Aacute -100 + +KPX P Abreve -100 + +KPX P Acircumflex -100 + +KPX P Adieresis -100 + +KPX P Agrave -100 + +KPX P Amacron -100 + +KPX P Aogonek -100 + +KPX P Aring -100 + +KPX P Atilde -100 + +KPX P a -30 + +KPX P aacute -30 + +KPX P abreve -30 + +KPX P acircumflex -30 + +KPX P adieresis -30 + +KPX P agrave -30 + +KPX P amacron -30 + +KPX P aogonek -30 + +KPX P aring -30 + +KPX P atilde -30 + +KPX P comma -120 + +KPX P e -30 + +KPX P eacute -30 + +KPX P ecaron -30 + +KPX P ecircumflex -30 + +KPX P edieresis -30 + +KPX P edotaccent -30 + +KPX P egrave -30 + +KPX P emacron -30 + +KPX P eogonek -30 + +KPX P o -40 + +KPX P oacute -40 + +KPX P ocircumflex -40 + +KPX P odieresis -40 + +KPX P ograve -40 + +KPX P ohungarumlaut -40 + +KPX P omacron -40 + +KPX P oslash -40 + +KPX P otilde -40 + +KPX P period -120 + +KPX Q U -10 + +KPX Q Uacute -10 + +KPX Q Ucircumflex -10 + +KPX Q Udieresis -10 + +KPX Q Ugrave -10 + +KPX Q Uhungarumlaut -10 + +KPX Q Umacron -10 + +KPX Q Uogonek -10 + +KPX Q Uring -10 + +KPX Q comma 20 + +KPX Q period 20 + +KPX R O -20 + +KPX R Oacute -20 + +KPX R Ocircumflex -20 + +KPX R Odieresis -20 + +KPX R Ograve -20 + +KPX R Ohungarumlaut -20 + +KPX R Omacron -20 + +KPX R Oslash -20 + +KPX R Otilde -20 + +KPX R T -20 + +KPX R Tcaron -20 + +KPX R Tcommaaccent -20 + +KPX R U -20 + +KPX R Uacute -20 + +KPX R Ucircumflex -20 + +KPX R Udieresis -20 + +KPX R Ugrave -20 + +KPX R Uhungarumlaut -20 + +KPX R Umacron -20 + +KPX R Uogonek -20 + +KPX R Uring -20 + +KPX R V -50 + +KPX R W -40 + +KPX R Y -50 + +KPX R Yacute -50 + +KPX R Ydieresis -50 + +KPX Racute O -20 + +KPX Racute Oacute -20 + +KPX Racute Ocircumflex -20 + +KPX Racute Odieresis -20 + +KPX Racute Ograve -20 + +KPX Racute Ohungarumlaut -20 + +KPX Racute Omacron -20 + +KPX Racute Oslash -20 + +KPX Racute Otilde -20 + +KPX Racute T -20 + +KPX Racute Tcaron -20 + +KPX Racute Tcommaaccent -20 + +KPX Racute U -20 + +KPX Racute Uacute -20 + +KPX Racute Ucircumflex -20 + +KPX Racute Udieresis -20 + +KPX Racute Ugrave -20 + +KPX Racute Uhungarumlaut -20 + +KPX Racute Umacron -20 + +KPX Racute Uogonek -20 + +KPX Racute Uring -20 + +KPX Racute V -50 + +KPX Racute W -40 + +KPX Racute Y -50 + +KPX Racute Yacute -50 + +KPX Racute Ydieresis -50 + +KPX Rcaron O -20 + +KPX Rcaron Oacute -20 + +KPX Rcaron Ocircumflex -20 + +KPX Rcaron Odieresis -20 + +KPX Rcaron Ograve -20 + +KPX Rcaron Ohungarumlaut -20 + +KPX Rcaron Omacron -20 + +KPX Rcaron Oslash -20 + +KPX Rcaron Otilde -20 + +KPX Rcaron T -20 + +KPX Rcaron Tcaron -20 + +KPX Rcaron Tcommaaccent -20 + +KPX Rcaron U -20 + +KPX Rcaron Uacute -20 + +KPX Rcaron Ucircumflex -20 + +KPX Rcaron Udieresis -20 + +KPX Rcaron Ugrave -20 + +KPX Rcaron Uhungarumlaut -20 + +KPX Rcaron Umacron -20 + +KPX Rcaron Uogonek -20 + +KPX Rcaron Uring -20 + +KPX Rcaron V -50 + +KPX Rcaron W -40 + +KPX Rcaron Y -50 + +KPX Rcaron Yacute -50 + +KPX Rcaron Ydieresis -50 + +KPX Rcommaaccent O -20 + +KPX Rcommaaccent Oacute -20 + +KPX Rcommaaccent Ocircumflex -20 + +KPX Rcommaaccent Odieresis -20 + +KPX Rcommaaccent Ograve -20 + +KPX Rcommaaccent Ohungarumlaut -20 + +KPX Rcommaaccent Omacron -20 + +KPX Rcommaaccent Oslash -20 + +KPX Rcommaaccent Otilde -20 + +KPX Rcommaaccent T -20 + +KPX Rcommaaccent Tcaron -20 + +KPX Rcommaaccent Tcommaaccent -20 + +KPX Rcommaaccent U -20 + +KPX Rcommaaccent Uacute -20 + +KPX Rcommaaccent Ucircumflex -20 + +KPX Rcommaaccent Udieresis -20 + +KPX Rcommaaccent Ugrave -20 + +KPX Rcommaaccent Uhungarumlaut -20 + +KPX Rcommaaccent Umacron -20 + +KPX Rcommaaccent Uogonek -20 + +KPX Rcommaaccent Uring -20 + +KPX Rcommaaccent V -50 + +KPX Rcommaaccent W -40 + +KPX Rcommaaccent Y -50 + +KPX Rcommaaccent Yacute -50 + +KPX Rcommaaccent Ydieresis -50 + +KPX T A -90 + +KPX T Aacute -90 + +KPX T Abreve -90 + +KPX T Acircumflex -90 + +KPX T Adieresis -90 + +KPX T Agrave -90 + +KPX T Amacron -90 + +KPX T Aogonek -90 + +KPX T Aring -90 + +KPX T Atilde -90 + +KPX T O -40 + +KPX T Oacute -40 + +KPX T Ocircumflex -40 + +KPX T Odieresis -40 + +KPX T Ograve -40 + +KPX T Ohungarumlaut -40 + +KPX T Omacron -40 + +KPX T Oslash -40 + +KPX T Otilde -40 + +KPX T a -80 + +KPX T aacute -80 + +KPX T abreve -80 + +KPX T acircumflex -80 + +KPX T adieresis -80 + +KPX T agrave -80 + +KPX T amacron -80 + +KPX T aogonek -80 + +KPX T aring -80 + +KPX T atilde -80 + +KPX T colon -40 + +KPX T comma -80 + +KPX T e -60 + +KPX T eacute -60 + +KPX T ecaron -60 + +KPX T ecircumflex -60 + +KPX T edieresis -60 + +KPX T edotaccent -60 + +KPX T egrave -60 + +KPX T emacron -60 + +KPX T eogonek -60 + +KPX T hyphen -120 + +KPX T o -80 + +KPX T oacute -80 + +KPX T ocircumflex -80 + +KPX T odieresis -80 + +KPX T ograve -80 + +KPX T ohungarumlaut -80 + +KPX T omacron -80 + +KPX T oslash -80 + +KPX T otilde -80 + +KPX T period -80 + +KPX T r -80 + +KPX T racute -80 + +KPX T rcommaaccent -80 + +KPX T semicolon -40 + +KPX T u -90 + +KPX T uacute -90 + +KPX T ucircumflex -90 + +KPX T udieresis -90 + +KPX T ugrave -90 + +KPX T uhungarumlaut -90 + +KPX T umacron -90 + +KPX T uogonek -90 + +KPX T uring -90 + +KPX T w -60 + +KPX T y -60 + +KPX T yacute -60 + +KPX T ydieresis -60 + +KPX Tcaron A -90 + +KPX Tcaron Aacute -90 + +KPX Tcaron Abreve -90 + +KPX Tcaron Acircumflex -90 + +KPX Tcaron Adieresis -90 + +KPX Tcaron Agrave -90 + +KPX Tcaron Amacron -90 + +KPX Tcaron Aogonek -90 + +KPX Tcaron Aring -90 + +KPX Tcaron Atilde -90 + +KPX Tcaron O -40 + +KPX Tcaron Oacute -40 + +KPX Tcaron Ocircumflex -40 + +KPX Tcaron Odieresis -40 + +KPX Tcaron Ograve -40 + +KPX Tcaron Ohungarumlaut -40 + +KPX Tcaron Omacron -40 + +KPX Tcaron Oslash -40 + +KPX Tcaron Otilde -40 + +KPX Tcaron a -80 + +KPX Tcaron aacute -80 + +KPX Tcaron abreve -80 + +KPX Tcaron acircumflex -80 + +KPX Tcaron adieresis -80 + +KPX Tcaron agrave -80 + +KPX Tcaron amacron -80 + +KPX Tcaron aogonek -80 + +KPX Tcaron aring -80 + +KPX Tcaron atilde -80 + +KPX Tcaron colon -40 + +KPX Tcaron comma -80 + +KPX Tcaron e -60 + +KPX Tcaron eacute -60 + +KPX Tcaron ecaron -60 + +KPX Tcaron ecircumflex -60 + +KPX Tcaron edieresis -60 + +KPX Tcaron edotaccent -60 + +KPX Tcaron egrave -60 + +KPX Tcaron emacron -60 + +KPX Tcaron eogonek -60 + +KPX Tcaron hyphen -120 + +KPX Tcaron o -80 + +KPX Tcaron oacute -80 + +KPX Tcaron ocircumflex -80 + +KPX Tcaron odieresis -80 + +KPX Tcaron ograve -80 + +KPX Tcaron ohungarumlaut -80 + +KPX Tcaron omacron -80 + +KPX Tcaron oslash -80 + +KPX Tcaron otilde -80 + +KPX Tcaron period -80 + +KPX Tcaron r -80 + +KPX Tcaron racute -80 + +KPX Tcaron rcommaaccent -80 + +KPX Tcaron semicolon -40 + +KPX Tcaron u -90 + +KPX Tcaron uacute -90 + +KPX Tcaron ucircumflex -90 + +KPX Tcaron udieresis -90 + +KPX Tcaron ugrave -90 + +KPX Tcaron uhungarumlaut -90 + +KPX Tcaron umacron -90 + +KPX Tcaron uogonek -90 + +KPX Tcaron uring -90 + +KPX Tcaron w -60 + +KPX Tcaron y -60 + +KPX Tcaron yacute -60 + +KPX Tcaron ydieresis -60 + +KPX Tcommaaccent A -90 + +KPX Tcommaaccent Aacute -90 + +KPX Tcommaaccent Abreve -90 + +KPX Tcommaaccent Acircumflex -90 + +KPX Tcommaaccent Adieresis -90 + +KPX Tcommaaccent Agrave -90 + +KPX Tcommaaccent Amacron -90 + +KPX Tcommaaccent Aogonek -90 + +KPX Tcommaaccent Aring -90 + +KPX Tcommaaccent Atilde -90 + +KPX Tcommaaccent O -40 + +KPX Tcommaaccent Oacute -40 + +KPX Tcommaaccent Ocircumflex -40 + +KPX Tcommaaccent Odieresis -40 + +KPX Tcommaaccent Ograve -40 + +KPX Tcommaaccent Ohungarumlaut -40 + +KPX Tcommaaccent Omacron -40 + +KPX Tcommaaccent Oslash -40 + +KPX Tcommaaccent Otilde -40 + +KPX Tcommaaccent a -80 + +KPX Tcommaaccent aacute -80 + +KPX Tcommaaccent abreve -80 + +KPX Tcommaaccent acircumflex -80 + +KPX Tcommaaccent adieresis -80 + +KPX Tcommaaccent agrave -80 + +KPX Tcommaaccent amacron -80 + +KPX Tcommaaccent aogonek -80 + +KPX Tcommaaccent aring -80 + +KPX Tcommaaccent atilde -80 + +KPX Tcommaaccent colon -40 + +KPX Tcommaaccent comma -80 + +KPX Tcommaaccent e -60 + +KPX Tcommaaccent eacute -60 + +KPX Tcommaaccent ecaron -60 + +KPX Tcommaaccent ecircumflex -60 + +KPX Tcommaaccent edieresis -60 + +KPX Tcommaaccent edotaccent -60 + +KPX Tcommaaccent egrave -60 + +KPX Tcommaaccent emacron -60 + +KPX Tcommaaccent eogonek -60 + +KPX Tcommaaccent hyphen -120 + +KPX Tcommaaccent o -80 + +KPX Tcommaaccent oacute -80 + +KPX Tcommaaccent ocircumflex -80 + +KPX Tcommaaccent odieresis -80 + +KPX Tcommaaccent ograve -80 + +KPX Tcommaaccent ohungarumlaut -80 + +KPX Tcommaaccent omacron -80 + +KPX Tcommaaccent oslash -80 + +KPX Tcommaaccent otilde -80 + +KPX Tcommaaccent period -80 + +KPX Tcommaaccent r -80 + +KPX Tcommaaccent racute -80 + +KPX Tcommaaccent rcommaaccent -80 + +KPX Tcommaaccent semicolon -40 + +KPX Tcommaaccent u -90 + +KPX Tcommaaccent uacute -90 + +KPX Tcommaaccent ucircumflex -90 + +KPX Tcommaaccent udieresis -90 + +KPX Tcommaaccent ugrave -90 + +KPX Tcommaaccent uhungarumlaut -90 + +KPX Tcommaaccent umacron -90 + +KPX Tcommaaccent uogonek -90 + +KPX Tcommaaccent uring -90 + +KPX Tcommaaccent w -60 + +KPX Tcommaaccent y -60 + +KPX Tcommaaccent yacute -60 + +KPX Tcommaaccent ydieresis -60 + +KPX U A -50 + +KPX U Aacute -50 + +KPX U Abreve -50 + +KPX U Acircumflex -50 + +KPX U Adieresis -50 + +KPX U Agrave -50 + +KPX U Amacron -50 + +KPX U Aogonek -50 + +KPX U Aring -50 + +KPX U Atilde -50 + +KPX U comma -30 + +KPX U period -30 + +KPX Uacute A -50 + +KPX Uacute Aacute -50 + +KPX Uacute Abreve -50 + +KPX Uacute Acircumflex -50 + +KPX Uacute Adieresis -50 + +KPX Uacute Agrave -50 + +KPX Uacute Amacron -50 + +KPX Uacute Aogonek -50 + +KPX Uacute Aring -50 + +KPX Uacute Atilde -50 + +KPX Uacute comma -30 + +KPX Uacute period -30 + +KPX Ucircumflex A -50 + +KPX Ucircumflex Aacute -50 + +KPX Ucircumflex Abreve -50 + +KPX Ucircumflex Acircumflex -50 + +KPX Ucircumflex Adieresis -50 + +KPX Ucircumflex Agrave -50 + +KPX Ucircumflex Amacron -50 + +KPX Ucircumflex Aogonek -50 + +KPX Ucircumflex Aring -50 + +KPX Ucircumflex Atilde -50 + +KPX Ucircumflex comma -30 + +KPX Ucircumflex period -30 + +KPX Udieresis A -50 + +KPX Udieresis Aacute -50 + +KPX Udieresis Abreve -50 + +KPX Udieresis Acircumflex -50 + +KPX Udieresis Adieresis -50 + +KPX Udieresis Agrave -50 + +KPX Udieresis Amacron -50 + +KPX Udieresis Aogonek -50 + +KPX Udieresis Aring -50 + +KPX Udieresis Atilde -50 + +KPX Udieresis comma -30 + +KPX Udieresis period -30 + +KPX Ugrave A -50 + +KPX Ugrave Aacute -50 + +KPX Ugrave Abreve -50 + +KPX Ugrave Acircumflex -50 + +KPX Ugrave Adieresis -50 + +KPX Ugrave Agrave -50 + +KPX Ugrave Amacron -50 + +KPX Ugrave Aogonek -50 + +KPX Ugrave Aring -50 + +KPX Ugrave Atilde -50 + +KPX Ugrave comma -30 + +KPX Ugrave period -30 + +KPX Uhungarumlaut A -50 + +KPX Uhungarumlaut Aacute -50 + +KPX Uhungarumlaut Abreve -50 + +KPX Uhungarumlaut Acircumflex -50 + +KPX Uhungarumlaut Adieresis -50 + +KPX Uhungarumlaut Agrave -50 + +KPX Uhungarumlaut Amacron -50 + +KPX Uhungarumlaut Aogonek -50 + +KPX Uhungarumlaut Aring -50 + +KPX Uhungarumlaut Atilde -50 + +KPX Uhungarumlaut comma -30 + +KPX Uhungarumlaut period -30 + +KPX Umacron A -50 + +KPX Umacron Aacute -50 + +KPX Umacron Abreve -50 + +KPX Umacron Acircumflex -50 + +KPX Umacron Adieresis -50 + +KPX Umacron Agrave -50 + +KPX Umacron Amacron -50 + +KPX Umacron Aogonek -50 + +KPX Umacron Aring -50 + +KPX Umacron Atilde -50 + +KPX Umacron comma -30 + +KPX Umacron period -30 + +KPX Uogonek A -50 + +KPX Uogonek Aacute -50 + +KPX Uogonek Abreve -50 + +KPX Uogonek Acircumflex -50 + +KPX Uogonek Adieresis -50 + +KPX Uogonek Agrave -50 + +KPX Uogonek Amacron -50 + +KPX Uogonek Aogonek -50 + +KPX Uogonek Aring -50 + +KPX Uogonek Atilde -50 + +KPX Uogonek comma -30 + +KPX Uogonek period -30 + +KPX Uring A -50 + +KPX Uring Aacute -50 + +KPX Uring Abreve -50 + +KPX Uring Acircumflex -50 + +KPX Uring Adieresis -50 + +KPX Uring Agrave -50 + +KPX Uring Amacron -50 + +KPX Uring Aogonek -50 + +KPX Uring Aring -50 + +KPX Uring Atilde -50 + +KPX Uring comma -30 + +KPX Uring period -30 + +KPX V A -80 + +KPX V Aacute -80 + +KPX V Abreve -80 + +KPX V Acircumflex -80 + +KPX V Adieresis -80 + +KPX V Agrave -80 + +KPX V Amacron -80 + +KPX V Aogonek -80 + +KPX V Aring -80 + +KPX V Atilde -80 + +KPX V G -50 + +KPX V Gbreve -50 + +KPX V Gcommaaccent -50 + +KPX V O -50 + +KPX V Oacute -50 + +KPX V Ocircumflex -50 + +KPX V Odieresis -50 + +KPX V Ograve -50 + +KPX V Ohungarumlaut -50 + +KPX V Omacron -50 + +KPX V Oslash -50 + +KPX V Otilde -50 + +KPX V a -60 + +KPX V aacute -60 + +KPX V abreve -60 + +KPX V acircumflex -60 + +KPX V adieresis -60 + +KPX V agrave -60 + +KPX V amacron -60 + +KPX V aogonek -60 + +KPX V aring -60 + +KPX V atilde -60 + +KPX V colon -40 + +KPX V comma -120 + +KPX V e -50 + +KPX V eacute -50 + +KPX V ecaron -50 + +KPX V ecircumflex -50 + +KPX V edieresis -50 + +KPX V edotaccent -50 + +KPX V egrave -50 + +KPX V emacron -50 + +KPX V eogonek -50 + +KPX V hyphen -80 + +KPX V o -90 + +KPX V oacute -90 + +KPX V ocircumflex -90 + +KPX V odieresis -90 + +KPX V ograve -90 + +KPX V ohungarumlaut -90 + +KPX V omacron -90 + +KPX V oslash -90 + +KPX V otilde -90 + +KPX V period -120 + +KPX V semicolon -40 + +KPX V u -60 + +KPX V uacute -60 + +KPX V ucircumflex -60 + +KPX V udieresis -60 + +KPX V ugrave -60 + +KPX V uhungarumlaut -60 + +KPX V umacron -60 + +KPX V uogonek -60 + +KPX V uring -60 + +KPX W A -60 + +KPX W Aacute -60 + +KPX W Abreve -60 + +KPX W Acircumflex -60 + +KPX W Adieresis -60 + +KPX W Agrave -60 + +KPX W Amacron -60 + +KPX W Aogonek -60 + +KPX W Aring -60 + +KPX W Atilde -60 + +KPX W O -20 + +KPX W Oacute -20 + +KPX W Ocircumflex -20 + +KPX W Odieresis -20 + +KPX W Ograve -20 + +KPX W Ohungarumlaut -20 + +KPX W Omacron -20 + +KPX W Oslash -20 + +KPX W Otilde -20 + +KPX W a -40 + +KPX W aacute -40 + +KPX W abreve -40 + +KPX W acircumflex -40 + +KPX W adieresis -40 + +KPX W agrave -40 + +KPX W amacron -40 + +KPX W aogonek -40 + +KPX W aring -40 + +KPX W atilde -40 + +KPX W colon -10 + +KPX W comma -80 + +KPX W e -35 + +KPX W eacute -35 + +KPX W ecaron -35 + +KPX W ecircumflex -35 + +KPX W edieresis -35 + +KPX W edotaccent -35 + +KPX W egrave -35 + +KPX W emacron -35 + +KPX W eogonek -35 + +KPX W hyphen -40 + +KPX W o -60 + +KPX W oacute -60 + +KPX W ocircumflex -60 + +KPX W odieresis -60 + +KPX W ograve -60 + +KPX W ohungarumlaut -60 + +KPX W omacron -60 + +KPX W oslash -60 + +KPX W otilde -60 + +KPX W period -80 + +KPX W semicolon -10 + +KPX W u -45 + +KPX W uacute -45 + +KPX W ucircumflex -45 + +KPX W udieresis -45 + +KPX W ugrave -45 + +KPX W uhungarumlaut -45 + +KPX W umacron -45 + +KPX W uogonek -45 + +KPX W uring -45 + +KPX W y -20 + +KPX W yacute -20 + +KPX W ydieresis -20 + +KPX Y A -110 + +KPX Y Aacute -110 + +KPX Y Abreve -110 + +KPX Y Acircumflex -110 + +KPX Y Adieresis -110 + +KPX Y Agrave -110 + +KPX Y Amacron -110 + +KPX Y Aogonek -110 + +KPX Y Aring -110 + +KPX Y Atilde -110 + +KPX Y O -70 + +KPX Y Oacute -70 + +KPX Y Ocircumflex -70 + +KPX Y Odieresis -70 + +KPX Y Ograve -70 + +KPX Y Ohungarumlaut -70 + +KPX Y Omacron -70 + +KPX Y Oslash -70 + +KPX Y Otilde -70 + +KPX Y a -90 + +KPX Y aacute -90 + +KPX Y abreve -90 + +KPX Y acircumflex -90 + +KPX Y adieresis -90 + +KPX Y agrave -90 + +KPX Y amacron -90 + +KPX Y aogonek -90 + +KPX Y aring -90 + +KPX Y atilde -90 + +KPX Y colon -50 + +KPX Y comma -100 + +KPX Y e -80 + +KPX Y eacute -80 + +KPX Y ecaron -80 + +KPX Y ecircumflex -80 + +KPX Y edieresis -80 + +KPX Y edotaccent -80 + +KPX Y egrave -80 + +KPX Y emacron -80 + +KPX Y eogonek -80 + +KPX Y o -100 + +KPX Y oacute -100 + +KPX Y ocircumflex -100 + +KPX Y odieresis -100 + +KPX Y ograve -100 + +KPX Y ohungarumlaut -100 + +KPX Y omacron -100 + +KPX Y oslash -100 + +KPX Y otilde -100 + +KPX Y period -100 + +KPX Y semicolon -50 + +KPX Y u -100 + +KPX Y uacute -100 + +KPX Y ucircumflex -100 + +KPX Y udieresis -100 + +KPX Y ugrave -100 + +KPX Y uhungarumlaut -100 + +KPX Y umacron -100 + +KPX Y uogonek -100 + +KPX Y uring -100 + +KPX Yacute A -110 + +KPX Yacute Aacute -110 + +KPX Yacute Abreve -110 + +KPX Yacute Acircumflex -110 + +KPX Yacute Adieresis -110 + +KPX Yacute Agrave -110 + +KPX Yacute Amacron -110 + +KPX Yacute Aogonek -110 + +KPX Yacute Aring -110 + +KPX Yacute Atilde -110 + +KPX Yacute O -70 + +KPX Yacute Oacute -70 + +KPX Yacute Ocircumflex -70 + +KPX Yacute Odieresis -70 + +KPX Yacute Ograve -70 + +KPX Yacute Ohungarumlaut -70 + +KPX Yacute Omacron -70 + +KPX Yacute Oslash -70 + +KPX Yacute Otilde -70 + +KPX Yacute a -90 + +KPX Yacute aacute -90 + +KPX Yacute abreve -90 + +KPX Yacute acircumflex -90 + +KPX Yacute adieresis -90 + +KPX Yacute agrave -90 + +KPX Yacute amacron -90 + +KPX Yacute aogonek -90 + +KPX Yacute aring -90 + +KPX Yacute atilde -90 + +KPX Yacute colon -50 + +KPX Yacute comma -100 + +KPX Yacute e -80 + +KPX Yacute eacute -80 + +KPX Yacute ecaron -80 + +KPX Yacute ecircumflex -80 + +KPX Yacute edieresis -80 + +KPX Yacute edotaccent -80 + +KPX Yacute egrave -80 + +KPX Yacute emacron -80 + +KPX Yacute eogonek -80 + +KPX Yacute o -100 + +KPX Yacute oacute -100 + +KPX Yacute ocircumflex -100 + +KPX Yacute odieresis -100 + +KPX Yacute ograve -100 + +KPX Yacute ohungarumlaut -100 + +KPX Yacute omacron -100 + +KPX Yacute oslash -100 + +KPX Yacute otilde -100 + +KPX Yacute period -100 + +KPX Yacute semicolon -50 + +KPX Yacute u -100 + +KPX Yacute uacute -100 + +KPX Yacute ucircumflex -100 + +KPX Yacute udieresis -100 + +KPX Yacute ugrave -100 + +KPX Yacute uhungarumlaut -100 + +KPX Yacute umacron -100 + +KPX Yacute uogonek -100 + +KPX Yacute uring -100 + +KPX Ydieresis A -110 + +KPX Ydieresis Aacute -110 + +KPX Ydieresis Abreve -110 + +KPX Ydieresis Acircumflex -110 + +KPX Ydieresis Adieresis -110 + +KPX Ydieresis Agrave -110 + +KPX Ydieresis Amacron -110 + +KPX Ydieresis Aogonek -110 + +KPX Ydieresis Aring -110 + +KPX Ydieresis Atilde -110 + +KPX Ydieresis O -70 + +KPX Ydieresis Oacute -70 + +KPX Ydieresis Ocircumflex -70 + +KPX Ydieresis Odieresis -70 + +KPX Ydieresis Ograve -70 + +KPX Ydieresis Ohungarumlaut -70 + +KPX Ydieresis Omacron -70 + +KPX Ydieresis Oslash -70 + +KPX Ydieresis Otilde -70 + +KPX Ydieresis a -90 + +KPX Ydieresis aacute -90 + +KPX Ydieresis abreve -90 + +KPX Ydieresis acircumflex -90 + +KPX Ydieresis adieresis -90 + +KPX Ydieresis agrave -90 + +KPX Ydieresis amacron -90 + +KPX Ydieresis aogonek -90 + +KPX Ydieresis aring -90 + +KPX Ydieresis atilde -90 + +KPX Ydieresis colon -50 + +KPX Ydieresis comma -100 + +KPX Ydieresis e -80 + +KPX Ydieresis eacute -80 + +KPX Ydieresis ecaron -80 + +KPX Ydieresis ecircumflex -80 + +KPX Ydieresis edieresis -80 + +KPX Ydieresis edotaccent -80 + +KPX Ydieresis egrave -80 + +KPX Ydieresis emacron -80 + +KPX Ydieresis eogonek -80 + +KPX Ydieresis o -100 + +KPX Ydieresis oacute -100 + +KPX Ydieresis ocircumflex -100 + +KPX Ydieresis odieresis -100 + +KPX Ydieresis ograve -100 + +KPX Ydieresis ohungarumlaut -100 + +KPX Ydieresis omacron -100 + +KPX Ydieresis oslash -100 + +KPX Ydieresis otilde -100 + +KPX Ydieresis period -100 + +KPX Ydieresis semicolon -50 + +KPX Ydieresis u -100 + +KPX Ydieresis uacute -100 + +KPX Ydieresis ucircumflex -100 + +KPX Ydieresis udieresis -100 + +KPX Ydieresis ugrave -100 + +KPX Ydieresis uhungarumlaut -100 + +KPX Ydieresis umacron -100 + +KPX Ydieresis uogonek -100 + +KPX Ydieresis uring -100 + +KPX a g -10 + +KPX a gbreve -10 + +KPX a gcommaaccent -10 + +KPX a v -15 + +KPX a w -15 + +KPX a y -20 + +KPX a yacute -20 + +KPX a ydieresis -20 + +KPX aacute g -10 + +KPX aacute gbreve -10 + +KPX aacute gcommaaccent -10 + +KPX aacute v -15 + +KPX aacute w -15 + +KPX aacute y -20 + +KPX aacute yacute -20 + +KPX aacute ydieresis -20 + +KPX abreve g -10 + +KPX abreve gbreve -10 + +KPX abreve gcommaaccent -10 + +KPX abreve v -15 + +KPX abreve w -15 + +KPX abreve y -20 + +KPX abreve yacute -20 + +KPX abreve ydieresis -20 + +KPX acircumflex g -10 + +KPX acircumflex gbreve -10 + +KPX acircumflex gcommaaccent -10 + +KPX acircumflex v -15 + +KPX acircumflex w -15 + +KPX acircumflex y -20 + +KPX acircumflex yacute -20 + +KPX acircumflex ydieresis -20 + +KPX adieresis g -10 + +KPX adieresis gbreve -10 + +KPX adieresis gcommaaccent -10 + +KPX adieresis v -15 + +KPX adieresis w -15 + +KPX adieresis y -20 + +KPX adieresis yacute -20 + +KPX adieresis ydieresis -20 + +KPX agrave g -10 + +KPX agrave gbreve -10 + +KPX agrave gcommaaccent -10 + +KPX agrave v -15 + +KPX agrave w -15 + +KPX agrave y -20 + +KPX agrave yacute -20 + +KPX agrave ydieresis -20 + +KPX amacron g -10 + +KPX amacron gbreve -10 + +KPX amacron gcommaaccent -10 + +KPX amacron v -15 + +KPX amacron w -15 + +KPX amacron y -20 + +KPX amacron yacute -20 + +KPX amacron ydieresis -20 + +KPX aogonek g -10 + +KPX aogonek gbreve -10 + +KPX aogonek gcommaaccent -10 + +KPX aogonek v -15 + +KPX aogonek w -15 + +KPX aogonek y -20 + +KPX aogonek yacute -20 + +KPX aogonek ydieresis -20 + +KPX aring g -10 + +KPX aring gbreve -10 + +KPX aring gcommaaccent -10 + +KPX aring v -15 + +KPX aring w -15 + +KPX aring y -20 + +KPX aring yacute -20 + +KPX aring ydieresis -20 + +KPX atilde g -10 + +KPX atilde gbreve -10 + +KPX atilde gcommaaccent -10 + +KPX atilde v -15 + +KPX atilde w -15 + +KPX atilde y -20 + +KPX atilde yacute -20 + +KPX atilde ydieresis -20 + +KPX b l -10 + +KPX b lacute -10 + +KPX b lcommaaccent -10 + +KPX b lslash -10 + +KPX b u -20 + +KPX b uacute -20 + +KPX b ucircumflex -20 + +KPX b udieresis -20 + +KPX b ugrave -20 + +KPX b uhungarumlaut -20 + +KPX b umacron -20 + +KPX b uogonek -20 + +KPX b uring -20 + +KPX b v -20 + +KPX b y -20 + +KPX b yacute -20 + +KPX b ydieresis -20 + +KPX c h -10 + +KPX c k -20 + +KPX c kcommaaccent -20 + +KPX c l -20 + +KPX c lacute -20 + +KPX c lcommaaccent -20 + +KPX c lslash -20 + +KPX c y -10 + +KPX c yacute -10 + +KPX c ydieresis -10 + +KPX cacute h -10 + +KPX cacute k -20 + +KPX cacute kcommaaccent -20 + +KPX cacute l -20 + +KPX cacute lacute -20 + +KPX cacute lcommaaccent -20 + +KPX cacute lslash -20 + +KPX cacute y -10 + +KPX cacute yacute -10 + +KPX cacute ydieresis -10 + +KPX ccaron h -10 + +KPX ccaron k -20 + +KPX ccaron kcommaaccent -20 + +KPX ccaron l -20 + +KPX ccaron lacute -20 + +KPX ccaron lcommaaccent -20 + +KPX ccaron lslash -20 + +KPX ccaron y -10 + +KPX ccaron yacute -10 + +KPX ccaron ydieresis -10 + +KPX ccedilla h -10 + +KPX ccedilla k -20 + +KPX ccedilla kcommaaccent -20 + +KPX ccedilla l -20 + +KPX ccedilla lacute -20 + +KPX ccedilla lcommaaccent -20 + +KPX ccedilla lslash -20 + +KPX ccedilla y -10 + +KPX ccedilla yacute -10 + +KPX ccedilla ydieresis -10 + +KPX colon space -40 + +KPX comma quotedblright -120 + +KPX comma quoteright -120 + +KPX comma space -40 + +KPX d d -10 + +KPX d dcroat -10 + +KPX d v -15 + +KPX d w -15 + +KPX d y -15 + +KPX d yacute -15 + +KPX d ydieresis -15 + +KPX dcroat d -10 + +KPX dcroat dcroat -10 + +KPX dcroat v -15 + +KPX dcroat w -15 + +KPX dcroat y -15 + +KPX dcroat yacute -15 + +KPX dcroat ydieresis -15 + +KPX e comma 10 + +KPX e period 20 + +KPX e v -15 + +KPX e w -15 + +KPX e x -15 + +KPX e y -15 + +KPX e yacute -15 + +KPX e ydieresis -15 + +KPX eacute comma 10 + +KPX eacute period 20 + +KPX eacute v -15 + +KPX eacute w -15 + +KPX eacute x -15 + +KPX eacute y -15 + +KPX eacute yacute -15 + +KPX eacute ydieresis -15 + +KPX ecaron comma 10 + +KPX ecaron period 20 + +KPX ecaron v -15 + +KPX ecaron w -15 + +KPX ecaron x -15 + +KPX ecaron y -15 + +KPX ecaron yacute -15 + +KPX ecaron ydieresis -15 + +KPX ecircumflex comma 10 + +KPX ecircumflex period 20 + +KPX ecircumflex v -15 + +KPX ecircumflex w -15 + +KPX ecircumflex x -15 + +KPX ecircumflex y -15 + +KPX ecircumflex yacute -15 + +KPX ecircumflex ydieresis -15 + +KPX edieresis comma 10 + +KPX edieresis period 20 + +KPX edieresis v -15 + +KPX edieresis w -15 + +KPX edieresis x -15 + +KPX edieresis y -15 + +KPX edieresis yacute -15 + +KPX edieresis ydieresis -15 + +KPX edotaccent comma 10 + +KPX edotaccent period 20 + +KPX edotaccent v -15 + +KPX edotaccent w -15 + +KPX edotaccent x -15 + +KPX edotaccent y -15 + +KPX edotaccent yacute -15 + +KPX edotaccent ydieresis -15 + +KPX egrave comma 10 + +KPX egrave period 20 + +KPX egrave v -15 + +KPX egrave w -15 + +KPX egrave x -15 + +KPX egrave y -15 + +KPX egrave yacute -15 + +KPX egrave ydieresis -15 + +KPX emacron comma 10 + +KPX emacron period 20 + +KPX emacron v -15 + +KPX emacron w -15 + +KPX emacron x -15 + +KPX emacron y -15 + +KPX emacron yacute -15 + +KPX emacron ydieresis -15 + +KPX eogonek comma 10 + +KPX eogonek period 20 + +KPX eogonek v -15 + +KPX eogonek w -15 + +KPX eogonek x -15 + +KPX eogonek y -15 + +KPX eogonek yacute -15 + +KPX eogonek ydieresis -15 + +KPX f comma -10 + +KPX f e -10 + +KPX f eacute -10 + +KPX f ecaron -10 + +KPX f ecircumflex -10 + +KPX f edieresis -10 + +KPX f edotaccent -10 + +KPX f egrave -10 + +KPX f emacron -10 + +KPX f eogonek -10 + +KPX f o -20 + +KPX f oacute -20 + +KPX f ocircumflex -20 + +KPX f odieresis -20 + +KPX f ograve -20 + +KPX f ohungarumlaut -20 + +KPX f omacron -20 + +KPX f oslash -20 + +KPX f otilde -20 + +KPX f period -10 + +KPX f quotedblright 30 + +KPX f quoteright 30 + +KPX g e 10 + +KPX g eacute 10 + +KPX g ecaron 10 + +KPX g ecircumflex 10 + +KPX g edieresis 10 + +KPX g edotaccent 10 + +KPX g egrave 10 + +KPX g emacron 10 + +KPX g eogonek 10 + +KPX g g -10 + +KPX g gbreve -10 + +KPX g gcommaaccent -10 + +KPX gbreve e 10 + +KPX gbreve eacute 10 + +KPX gbreve ecaron 10 + +KPX gbreve ecircumflex 10 + +KPX gbreve edieresis 10 + +KPX gbreve edotaccent 10 + +KPX gbreve egrave 10 + +KPX gbreve emacron 10 + +KPX gbreve eogonek 10 + +KPX gbreve g -10 + +KPX gbreve gbreve -10 + +KPX gbreve gcommaaccent -10 + +KPX gcommaaccent e 10 + +KPX gcommaaccent eacute 10 + +KPX gcommaaccent ecaron 10 + +KPX gcommaaccent ecircumflex 10 + +KPX gcommaaccent edieresis 10 + +KPX gcommaaccent edotaccent 10 + +KPX gcommaaccent egrave 10 + +KPX gcommaaccent emacron 10 + +KPX gcommaaccent eogonek 10 + +KPX gcommaaccent g -10 + +KPX gcommaaccent gbreve -10 + +KPX gcommaaccent gcommaaccent -10 + +KPX h y -20 + +KPX h yacute -20 + +KPX h ydieresis -20 + +KPX k o -15 + +KPX k oacute -15 + +KPX k ocircumflex -15 + +KPX k odieresis -15 + +KPX k ograve -15 + +KPX k ohungarumlaut -15 + +KPX k omacron -15 + +KPX k oslash -15 + +KPX k otilde -15 + +KPX kcommaaccent o -15 + +KPX kcommaaccent oacute -15 + +KPX kcommaaccent ocircumflex -15 + +KPX kcommaaccent odieresis -15 + +KPX kcommaaccent ograve -15 + +KPX kcommaaccent ohungarumlaut -15 + +KPX kcommaaccent omacron -15 + +KPX kcommaaccent oslash -15 + +KPX kcommaaccent otilde -15 + +KPX l w -15 + +KPX l y -15 + +KPX l yacute -15 + +KPX l ydieresis -15 + +KPX lacute w -15 + +KPX lacute y -15 + +KPX lacute yacute -15 + +KPX lacute ydieresis -15 + +KPX lcommaaccent w -15 + +KPX lcommaaccent y -15 + +KPX lcommaaccent yacute -15 + +KPX lcommaaccent ydieresis -15 + +KPX lslash w -15 + +KPX lslash y -15 + +KPX lslash yacute -15 + +KPX lslash ydieresis -15 + +KPX m u -20 + +KPX m uacute -20 + +KPX m ucircumflex -20 + +KPX m udieresis -20 + +KPX m ugrave -20 + +KPX m uhungarumlaut -20 + +KPX m umacron -20 + +KPX m uogonek -20 + +KPX m uring -20 + +KPX m y -30 + +KPX m yacute -30 + +KPX m ydieresis -30 + +KPX n u -10 + +KPX n uacute -10 + +KPX n ucircumflex -10 + +KPX n udieresis -10 + +KPX n ugrave -10 + +KPX n uhungarumlaut -10 + +KPX n umacron -10 + +KPX n uogonek -10 + +KPX n uring -10 + +KPX n v -40 + +KPX n y -20 + +KPX n yacute -20 + +KPX n ydieresis -20 + +KPX nacute u -10 + +KPX nacute uacute -10 + +KPX nacute ucircumflex -10 + +KPX nacute udieresis -10 + +KPX nacute ugrave -10 + +KPX nacute uhungarumlaut -10 + +KPX nacute umacron -10 + +KPX nacute uogonek -10 + +KPX nacute uring -10 + +KPX nacute v -40 + +KPX nacute y -20 + +KPX nacute yacute -20 + +KPX nacute ydieresis -20 + +KPX ncaron u -10 + +KPX ncaron uacute -10 + +KPX ncaron ucircumflex -10 + +KPX ncaron udieresis -10 + +KPX ncaron ugrave -10 + +KPX ncaron uhungarumlaut -10 + +KPX ncaron umacron -10 + +KPX ncaron uogonek -10 + +KPX ncaron uring -10 + +KPX ncaron v -40 + +KPX ncaron y -20 + +KPX ncaron yacute -20 + +KPX ncaron ydieresis -20 + +KPX ncommaaccent u -10 + +KPX ncommaaccent uacute -10 + +KPX ncommaaccent ucircumflex -10 + +KPX ncommaaccent udieresis -10 + +KPX ncommaaccent ugrave -10 + +KPX ncommaaccent uhungarumlaut -10 + +KPX ncommaaccent umacron -10 + +KPX ncommaaccent uogonek -10 + +KPX ncommaaccent uring -10 + +KPX ncommaaccent v -40 + +KPX ncommaaccent y -20 + +KPX ncommaaccent yacute -20 + +KPX ncommaaccent ydieresis -20 + +KPX ntilde u -10 + +KPX ntilde uacute -10 + +KPX ntilde ucircumflex -10 + +KPX ntilde udieresis -10 + +KPX ntilde ugrave -10 + +KPX ntilde uhungarumlaut -10 + +KPX ntilde umacron -10 + +KPX ntilde uogonek -10 + +KPX ntilde uring -10 + +KPX ntilde v -40 + +KPX ntilde y -20 + +KPX ntilde yacute -20 + +KPX ntilde ydieresis -20 + +KPX o v -20 + +KPX o w -15 + +KPX o x -30 + +KPX o y -20 + +KPX o yacute -20 + +KPX o ydieresis -20 + +KPX oacute v -20 + +KPX oacute w -15 + +KPX oacute x -30 + +KPX oacute y -20 + +KPX oacute yacute -20 + +KPX oacute ydieresis -20 + +KPX ocircumflex v -20 + +KPX ocircumflex w -15 + +KPX ocircumflex x -30 + +KPX ocircumflex y -20 + +KPX ocircumflex yacute -20 + +KPX ocircumflex ydieresis -20 + +KPX odieresis v -20 + +KPX odieresis w -15 + +KPX odieresis x -30 + +KPX odieresis y -20 + +KPX odieresis yacute -20 + +KPX odieresis ydieresis -20 + +KPX ograve v -20 + +KPX ograve w -15 + +KPX ograve x -30 + +KPX ograve y -20 + +KPX ograve yacute -20 + +KPX ograve ydieresis -20 + +KPX ohungarumlaut v -20 + +KPX ohungarumlaut w -15 + +KPX ohungarumlaut x -30 + +KPX ohungarumlaut y -20 + +KPX ohungarumlaut yacute -20 + +KPX ohungarumlaut ydieresis -20 + +KPX omacron v -20 + +KPX omacron w -15 + +KPX omacron x -30 + +KPX omacron y -20 + +KPX omacron yacute -20 + +KPX omacron ydieresis -20 + +KPX oslash v -20 + +KPX oslash w -15 + +KPX oslash x -30 + +KPX oslash y -20 + +KPX oslash yacute -20 + +KPX oslash ydieresis -20 + +KPX otilde v -20 + +KPX otilde w -15 + +KPX otilde x -30 + +KPX otilde y -20 + +KPX otilde yacute -20 + +KPX otilde ydieresis -20 + +KPX p y -15 + +KPX p yacute -15 + +KPX p ydieresis -15 + +KPX period quotedblright -120 + +KPX period quoteright -120 + +KPX period space -40 + +KPX quotedblright space -80 + +KPX quoteleft quoteleft -46 + +KPX quoteright d -80 + +KPX quoteright dcroat -80 + +KPX quoteright l -20 + +KPX quoteright lacute -20 + +KPX quoteright lcommaaccent -20 + +KPX quoteright lslash -20 + +KPX quoteright quoteright -46 + +KPX quoteright r -40 + +KPX quoteright racute -40 + +KPX quoteright rcaron -40 + +KPX quoteright rcommaaccent -40 + +KPX quoteright s -60 + +KPX quoteright sacute -60 + +KPX quoteright scaron -60 + +KPX quoteright scedilla -60 + +KPX quoteright scommaaccent -60 + +KPX quoteright space -80 + +KPX quoteright v -20 + +KPX r c -20 + +KPX r cacute -20 + +KPX r ccaron -20 + +KPX r ccedilla -20 + +KPX r comma -60 + +KPX r d -20 + +KPX r dcroat -20 + +KPX r g -15 + +KPX r gbreve -15 + +KPX r gcommaaccent -15 + +KPX r hyphen -20 + +KPX r o -20 + +KPX r oacute -20 + +KPX r ocircumflex -20 + +KPX r odieresis -20 + +KPX r ograve -20 + +KPX r ohungarumlaut -20 + +KPX r omacron -20 + +KPX r oslash -20 + +KPX r otilde -20 + +KPX r period -60 + +KPX r q -20 + +KPX r s -15 + +KPX r sacute -15 + +KPX r scaron -15 + +KPX r scedilla -15 + +KPX r scommaaccent -15 + +KPX r t 20 + +KPX r tcommaaccent 20 + +KPX r v 10 + +KPX r y 10 + +KPX r yacute 10 + +KPX r ydieresis 10 + +KPX racute c -20 + +KPX racute cacute -20 + +KPX racute ccaron -20 + +KPX racute ccedilla -20 + +KPX racute comma -60 + +KPX racute d -20 + +KPX racute dcroat -20 + +KPX racute g -15 + +KPX racute gbreve -15 + +KPX racute gcommaaccent -15 + +KPX racute hyphen -20 + +KPX racute o -20 + +KPX racute oacute -20 + +KPX racute ocircumflex -20 + +KPX racute odieresis -20 + +KPX racute ograve -20 + +KPX racute ohungarumlaut -20 + +KPX racute omacron -20 + +KPX racute oslash -20 + +KPX racute otilde -20 + +KPX racute period -60 + +KPX racute q -20 + +KPX racute s -15 + +KPX racute sacute -15 + +KPX racute scaron -15 + +KPX racute scedilla -15 + +KPX racute scommaaccent -15 + +KPX racute t 20 + +KPX racute tcommaaccent 20 + +KPX racute v 10 + +KPX racute y 10 + +KPX racute yacute 10 + +KPX racute ydieresis 10 + +KPX rcaron c -20 + +KPX rcaron cacute -20 + +KPX rcaron ccaron -20 + +KPX rcaron ccedilla -20 + +KPX rcaron comma -60 + +KPX rcaron d -20 + +KPX rcaron dcroat -20 + +KPX rcaron g -15 + +KPX rcaron gbreve -15 + +KPX rcaron gcommaaccent -15 + +KPX rcaron hyphen -20 + +KPX rcaron o -20 + +KPX rcaron oacute -20 + +KPX rcaron ocircumflex -20 + +KPX rcaron odieresis -20 + +KPX rcaron ograve -20 + +KPX rcaron ohungarumlaut -20 + +KPX rcaron omacron -20 + +KPX rcaron oslash -20 + +KPX rcaron otilde -20 + +KPX rcaron period -60 + +KPX rcaron q -20 + +KPX rcaron s -15 + +KPX rcaron sacute -15 + +KPX rcaron scaron -15 + +KPX rcaron scedilla -15 + +KPX rcaron scommaaccent -15 + +KPX rcaron t 20 + +KPX rcaron tcommaaccent 20 + +KPX rcaron v 10 + +KPX rcaron y 10 + +KPX rcaron yacute 10 + +KPX rcaron ydieresis 10 + +KPX rcommaaccent c -20 + +KPX rcommaaccent cacute -20 + +KPX rcommaaccent ccaron -20 + +KPX rcommaaccent ccedilla -20 + +KPX rcommaaccent comma -60 + +KPX rcommaaccent d -20 + +KPX rcommaaccent dcroat -20 + +KPX rcommaaccent g -15 + +KPX rcommaaccent gbreve -15 + +KPX rcommaaccent gcommaaccent -15 + +KPX rcommaaccent hyphen -20 + +KPX rcommaaccent o -20 + +KPX rcommaaccent oacute -20 + +KPX rcommaaccent ocircumflex -20 + +KPX rcommaaccent odieresis -20 + +KPX rcommaaccent ograve -20 + +KPX rcommaaccent ohungarumlaut -20 + +KPX rcommaaccent omacron -20 + +KPX rcommaaccent oslash -20 + +KPX rcommaaccent otilde -20 + +KPX rcommaaccent period -60 + +KPX rcommaaccent q -20 + +KPX rcommaaccent s -15 + +KPX rcommaaccent sacute -15 + +KPX rcommaaccent scaron -15 + +KPX rcommaaccent scedilla -15 + +KPX rcommaaccent scommaaccent -15 + +KPX rcommaaccent t 20 + +KPX rcommaaccent tcommaaccent 20 + +KPX rcommaaccent v 10 + +KPX rcommaaccent y 10 + +KPX rcommaaccent yacute 10 + +KPX rcommaaccent ydieresis 10 + +KPX s w -15 + +KPX sacute w -15 + +KPX scaron w -15 + +KPX scedilla w -15 + +KPX scommaaccent w -15 + +KPX semicolon space -40 + +KPX space T -100 + +KPX space Tcaron -100 + +KPX space Tcommaaccent -100 + +KPX space V -80 + +KPX space W -80 + +KPX space Y -120 + +KPX space Yacute -120 + +KPX space Ydieresis -120 + +KPX space quotedblleft -80 + +KPX space quoteleft -60 + +KPX v a -20 + +KPX v aacute -20 + +KPX v abreve -20 + +KPX v acircumflex -20 + +KPX v adieresis -20 + +KPX v agrave -20 + +KPX v amacron -20 + +KPX v aogonek -20 + +KPX v aring -20 + +KPX v atilde -20 + +KPX v comma -80 + +KPX v o -30 + +KPX v oacute -30 + +KPX v ocircumflex -30 + +KPX v odieresis -30 + +KPX v ograve -30 + +KPX v ohungarumlaut -30 + +KPX v omacron -30 + +KPX v oslash -30 + +KPX v otilde -30 + +KPX v period -80 + +KPX w comma -40 + +KPX w o -20 + +KPX w oacute -20 + +KPX w ocircumflex -20 + +KPX w odieresis -20 + +KPX w ograve -20 + +KPX w ohungarumlaut -20 + +KPX w omacron -20 + +KPX w oslash -20 + +KPX w otilde -20 + +KPX w period -40 + +KPX x e -10 + +KPX x eacute -10 + +KPX x ecaron -10 + +KPX x ecircumflex -10 + +KPX x edieresis -10 + +KPX x edotaccent -10 + +KPX x egrave -10 + +KPX x emacron -10 + +KPX x eogonek -10 + +KPX y a -30 + +KPX y aacute -30 + +KPX y abreve -30 + +KPX y acircumflex -30 + +KPX y adieresis -30 + +KPX y agrave -30 + +KPX y amacron -30 + +KPX y aogonek -30 + +KPX y aring -30 + +KPX y atilde -30 + +KPX y comma -80 + +KPX y e -10 + +KPX y eacute -10 + +KPX y ecaron -10 + +KPX y ecircumflex -10 + +KPX y edieresis -10 + +KPX y edotaccent -10 + +KPX y egrave -10 + +KPX y emacron -10 + +KPX y eogonek -10 + +KPX y o -25 + +KPX y oacute -25 + +KPX y ocircumflex -25 + +KPX y odieresis -25 + +KPX y ograve -25 + +KPX y ohungarumlaut -25 + +KPX y omacron -25 + +KPX y oslash -25 + +KPX y otilde -25 + +KPX y period -80 + +KPX yacute a -30 + +KPX yacute aacute -30 + +KPX yacute abreve -30 + +KPX yacute acircumflex -30 + +KPX yacute adieresis -30 + +KPX yacute agrave -30 + +KPX yacute amacron -30 + +KPX yacute aogonek -30 + +KPX yacute aring -30 + +KPX yacute atilde -30 + +KPX yacute comma -80 + +KPX yacute e -10 + +KPX yacute eacute -10 + +KPX yacute ecaron -10 + +KPX yacute ecircumflex -10 + +KPX yacute edieresis -10 + +KPX yacute edotaccent -10 + +KPX yacute egrave -10 + +KPX yacute emacron -10 + +KPX yacute eogonek -10 + +KPX yacute o -25 + +KPX yacute oacute -25 + +KPX yacute ocircumflex -25 + +KPX yacute odieresis -25 + +KPX yacute ograve -25 + +KPX yacute ohungarumlaut -25 + +KPX yacute omacron -25 + +KPX yacute oslash -25 + +KPX yacute otilde -25 + +KPX yacute period -80 + +KPX ydieresis a -30 + +KPX ydieresis aacute -30 + +KPX ydieresis abreve -30 + +KPX ydieresis acircumflex -30 + +KPX ydieresis adieresis -30 + +KPX ydieresis agrave -30 + +KPX ydieresis amacron -30 + +KPX ydieresis aogonek -30 + +KPX ydieresis aring -30 + +KPX ydieresis atilde -30 + +KPX ydieresis comma -80 + +KPX ydieresis e -10 + +KPX ydieresis eacute -10 + +KPX ydieresis ecaron -10 + +KPX ydieresis ecircumflex -10 + +KPX ydieresis edieresis -10 + +KPX ydieresis edotaccent -10 + +KPX ydieresis egrave -10 + +KPX ydieresis emacron -10 + +KPX ydieresis eogonek -10 + +KPX ydieresis o -25 + +KPX ydieresis oacute -25 + +KPX ydieresis ocircumflex -25 + +KPX ydieresis odieresis -25 + +KPX ydieresis ograve -25 + +KPX ydieresis ohungarumlaut -25 + +KPX ydieresis omacron -25 + +KPX ydieresis oslash -25 + +KPX ydieresis otilde -25 + +KPX ydieresis period -80 + +KPX z e 10 + +KPX z eacute 10 + +KPX z ecaron 10 + +KPX z ecircumflex 10 + +KPX z edieresis 10 + +KPX z edotaccent 10 + +KPX z egrave 10 + +KPX z emacron 10 + +KPX z eogonek 10 + +KPX zacute e 10 + +KPX zacute eacute 10 + +KPX zacute ecaron 10 + +KPX zacute ecircumflex 10 + +KPX zacute edieresis 10 + +KPX zacute edotaccent 10 + +KPX zacute egrave 10 + +KPX zacute emacron 10 + +KPX zacute eogonek 10 + +KPX zcaron e 10 + +KPX zcaron eacute 10 + +KPX zcaron ecaron 10 + +KPX zcaron ecircumflex 10 + +KPX zcaron edieresis 10 + +KPX zcaron edotaccent 10 + +KPX zcaron egrave 10 + +KPX zcaron emacron 10 + +KPX zcaron eogonek 10 + +KPX zdotaccent e 10 + +KPX zdotaccent eacute 10 + +KPX zdotaccent ecaron 10 + +KPX zdotaccent ecircumflex 10 + +KPX zdotaccent edieresis 10 + +KPX zdotaccent edotaccent 10 + +KPX zdotaccent egrave 10 + +KPX zdotaccent emacron 10 + +KPX zdotaccent eogonek 10 + +EndKernPairs + +EndKernData + +EndFontMetrics + diff --git a/src/Broadside/Fonts/Data/Afm/Helvetica-BoldOblique.afm b/src/Broadside/Fonts/Data/Afm/Helvetica-BoldOblique.afm new file mode 100644 index 00000000..ff021a54 --- /dev/null +++ b/src/Broadside/Fonts/Data/Afm/Helvetica-BoldOblique.afm @@ -0,0 +1,5654 @@ +StartFontMetrics 4.1 + +Comment Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved. + +Comment Creation Date: Thu May 1 12:45:12 1997 + +Comment UniqueID 43053 + +Comment VMusage 14482 68586 + +FontName Helvetica-BoldOblique + +FullName Helvetica Bold Oblique + +FamilyName Helvetica + +Weight Bold + +ItalicAngle -12 + +IsFixedPitch false + +CharacterSet ExtendedRoman + +FontBBox -174 -228 1114 962 + +UnderlinePosition -100 + +UnderlineThickness 50 + +Version 002.000 + +Notice Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.Helvetica is a trademark of Linotype-Hell AG and/or its subsidiaries. + +EncodingScheme AdobeStandardEncoding + +CapHeight 718 + +XHeight 532 + +Ascender 718 + +Descender -207 + +StdHW 118 + +StdVW 140 + +StartCharMetrics 315 + +C 32 ; WX 278 ; N space ; B 0 0 0 0 ; + +C 33 ; WX 333 ; N exclam ; B 94 0 397 718 ; + +C 34 ; WX 474 ; N quotedbl ; B 193 447 529 718 ; + +C 35 ; WX 556 ; N numbersign ; B 60 0 644 698 ; + +C 36 ; WX 556 ; N dollar ; B 67 -115 622 775 ; + +C 37 ; WX 889 ; N percent ; B 136 -19 901 710 ; + +C 38 ; WX 722 ; N ampersand ; B 89 -19 732 718 ; + +C 39 ; WX 278 ; N quoteright ; B 167 445 362 718 ; + +C 40 ; WX 333 ; N parenleft ; B 76 -208 470 734 ; + +C 41 ; WX 333 ; N parenright ; B -25 -208 369 734 ; + +C 42 ; WX 389 ; N asterisk ; B 146 387 481 718 ; + +C 43 ; WX 584 ; N plus ; B 82 0 610 506 ; + +C 44 ; WX 278 ; N comma ; B 28 -168 245 146 ; + +C 45 ; WX 333 ; N hyphen ; B 73 215 379 345 ; + +C 46 ; WX 278 ; N period ; B 64 0 245 146 ; + +C 47 ; WX 278 ; N slash ; B -37 -19 468 737 ; + +C 48 ; WX 556 ; N zero ; B 86 -19 617 710 ; + +C 49 ; WX 556 ; N one ; B 173 0 529 710 ; + +C 50 ; WX 556 ; N two ; B 26 0 619 710 ; + +C 51 ; WX 556 ; N three ; B 65 -19 608 710 ; + +C 52 ; WX 556 ; N four ; B 60 0 598 710 ; + +C 53 ; WX 556 ; N five ; B 64 -19 636 698 ; + +C 54 ; WX 556 ; N six ; B 85 -19 619 710 ; + +C 55 ; WX 556 ; N seven ; B 125 0 676 698 ; + +C 56 ; WX 556 ; N eight ; B 69 -19 616 710 ; + +C 57 ; WX 556 ; N nine ; B 78 -19 615 710 ; + +C 58 ; WX 333 ; N colon ; B 92 0 351 512 ; + +C 59 ; WX 333 ; N semicolon ; B 56 -168 351 512 ; + +C 60 ; WX 584 ; N less ; B 82 -8 655 514 ; + +C 61 ; WX 584 ; N equal ; B 58 87 633 419 ; + +C 62 ; WX 584 ; N greater ; B 36 -8 609 514 ; + +C 63 ; WX 611 ; N question ; B 165 0 671 727 ; + +C 64 ; WX 975 ; N at ; B 186 -19 954 737 ; + +C 65 ; WX 722 ; N A ; B 20 0 702 718 ; + +C 66 ; WX 722 ; N B ; B 76 0 764 718 ; + +C 67 ; WX 722 ; N C ; B 107 -19 789 737 ; + +C 68 ; WX 722 ; N D ; B 76 0 777 718 ; + +C 69 ; WX 667 ; N E ; B 76 0 757 718 ; + +C 70 ; WX 611 ; N F ; B 76 0 740 718 ; + +C 71 ; WX 778 ; N G ; B 108 -19 817 737 ; + +C 72 ; WX 722 ; N H ; B 71 0 804 718 ; + +C 73 ; WX 278 ; N I ; B 64 0 367 718 ; + +C 74 ; WX 556 ; N J ; B 60 -18 637 718 ; + +C 75 ; WX 722 ; N K ; B 87 0 858 718 ; + +C 76 ; WX 611 ; N L ; B 76 0 611 718 ; + +C 77 ; WX 833 ; N M ; B 69 0 918 718 ; + +C 78 ; WX 722 ; N N ; B 69 0 807 718 ; + +C 79 ; WX 778 ; N O ; B 107 -19 823 737 ; + +C 80 ; WX 667 ; N P ; B 76 0 738 718 ; + +C 81 ; WX 778 ; N Q ; B 107 -52 823 737 ; + +C 82 ; WX 722 ; N R ; B 76 0 778 718 ; + +C 83 ; WX 667 ; N S ; B 81 -19 718 737 ; + +C 84 ; WX 611 ; N T ; B 140 0 751 718 ; + +C 85 ; WX 722 ; N U ; B 116 -19 804 718 ; + +C 86 ; WX 667 ; N V ; B 172 0 801 718 ; + +C 87 ; WX 944 ; N W ; B 169 0 1082 718 ; + +C 88 ; WX 667 ; N X ; B 14 0 791 718 ; + +C 89 ; WX 667 ; N Y ; B 168 0 806 718 ; + +C 90 ; WX 611 ; N Z ; B 25 0 737 718 ; + +C 91 ; WX 333 ; N bracketleft ; B 21 -196 462 722 ; + +C 92 ; WX 278 ; N backslash ; B 124 -19 307 737 ; + +C 93 ; WX 333 ; N bracketright ; B -18 -196 423 722 ; + +C 94 ; WX 584 ; N asciicircum ; B 131 323 591 698 ; + +C 95 ; WX 556 ; N underscore ; B -27 -125 540 -75 ; + +C 96 ; WX 278 ; N quoteleft ; B 165 454 361 727 ; + +C 97 ; WX 556 ; N a ; B 55 -14 583 546 ; + +C 98 ; WX 611 ; N b ; B 61 -14 645 718 ; + +C 99 ; WX 556 ; N c ; B 79 -14 599 546 ; + +C 100 ; WX 611 ; N d ; B 82 -14 704 718 ; + +C 101 ; WX 556 ; N e ; B 70 -14 593 546 ; + +C 102 ; WX 333 ; N f ; B 87 0 469 727 ; L i fi ; L l fl ; + +C 103 ; WX 611 ; N g ; B 38 -217 666 546 ; + +C 104 ; WX 611 ; N h ; B 65 0 629 718 ; + +C 105 ; WX 278 ; N i ; B 69 0 363 725 ; + +C 106 ; WX 278 ; N j ; B -42 -214 363 725 ; + +C 107 ; WX 556 ; N k ; B 69 0 670 718 ; + +C 108 ; WX 278 ; N l ; B 69 0 362 718 ; + +C 109 ; WX 889 ; N m ; B 64 0 909 546 ; + +C 110 ; WX 611 ; N n ; B 65 0 629 546 ; + +C 111 ; WX 611 ; N o ; B 82 -14 643 546 ; + +C 112 ; WX 611 ; N p ; B 18 -207 645 546 ; + +C 113 ; WX 611 ; N q ; B 80 -207 665 546 ; + +C 114 ; WX 389 ; N r ; B 64 0 489 546 ; + +C 115 ; WX 556 ; N s ; B 63 -14 584 546 ; + +C 116 ; WX 333 ; N t ; B 100 -6 422 676 ; + +C 117 ; WX 611 ; N u ; B 98 -14 658 532 ; + +C 118 ; WX 556 ; N v ; B 126 0 656 532 ; + +C 119 ; WX 778 ; N w ; B 123 0 882 532 ; + +C 120 ; WX 556 ; N x ; B 15 0 648 532 ; + +C 121 ; WX 556 ; N y ; B 42 -214 652 532 ; + +C 122 ; WX 500 ; N z ; B 20 0 583 532 ; + +C 123 ; WX 389 ; N braceleft ; B 94 -196 518 722 ; + +C 124 ; WX 280 ; N bar ; B 36 -225 361 775 ; + +C 125 ; WX 389 ; N braceright ; B -18 -196 407 722 ; + +C 126 ; WX 584 ; N asciitilde ; B 115 163 577 343 ; + +C 161 ; WX 333 ; N exclamdown ; B 50 -186 353 532 ; + +C 162 ; WX 556 ; N cent ; B 79 -118 599 628 ; + +C 163 ; WX 556 ; N sterling ; B 50 -16 635 718 ; + +C 164 ; WX 167 ; N fraction ; B -174 -19 487 710 ; + +C 165 ; WX 556 ; N yen ; B 60 0 713 698 ; + +C 166 ; WX 556 ; N florin ; B -50 -210 669 737 ; + +C 167 ; WX 556 ; N section ; B 61 -184 598 727 ; + +C 168 ; WX 556 ; N currency ; B 27 76 680 636 ; + +C 169 ; WX 238 ; N quotesingle ; B 165 447 321 718 ; + +C 170 ; WX 500 ; N quotedblleft ; B 160 454 588 727 ; + +C 171 ; WX 556 ; N guillemotleft ; B 135 76 571 484 ; + +C 172 ; WX 333 ; N guilsinglleft ; B 130 76 353 484 ; + +C 173 ; WX 333 ; N guilsinglright ; B 99 76 322 484 ; + +C 174 ; WX 611 ; N fi ; B 87 0 696 727 ; + +C 175 ; WX 611 ; N fl ; B 87 0 695 727 ; + +C 177 ; WX 556 ; N endash ; B 48 227 627 333 ; + +C 178 ; WX 556 ; N dagger ; B 118 -171 626 718 ; + +C 179 ; WX 556 ; N daggerdbl ; B 46 -171 628 718 ; + +C 180 ; WX 278 ; N periodcentered ; B 110 172 276 334 ; + +C 182 ; WX 556 ; N paragraph ; B 98 -191 688 700 ; + +C 183 ; WX 350 ; N bullet ; B 83 194 420 524 ; + +C 184 ; WX 278 ; N quotesinglbase ; B 41 -146 236 127 ; + +C 185 ; WX 500 ; N quotedblbase ; B 36 -146 463 127 ; + +C 186 ; WX 500 ; N quotedblright ; B 162 445 589 718 ; + +C 187 ; WX 556 ; N guillemotright ; B 104 76 540 484 ; + +C 188 ; WX 1000 ; N ellipsis ; B 92 0 939 146 ; + +C 189 ; WX 1000 ; N perthousand ; B 76 -19 1038 710 ; + +C 191 ; WX 611 ; N questiondown ; B 53 -195 559 532 ; + +C 193 ; WX 333 ; N grave ; B 136 604 353 750 ; + +C 194 ; WX 333 ; N acute ; B 236 604 515 750 ; + +C 195 ; WX 333 ; N circumflex ; B 118 604 471 750 ; + +C 196 ; WX 333 ; N tilde ; B 113 610 507 737 ; + +C 197 ; WX 333 ; N macron ; B 122 604 483 678 ; + +C 198 ; WX 333 ; N breve ; B 156 604 494 750 ; + +C 199 ; WX 333 ; N dotaccent ; B 235 614 385 729 ; + +C 200 ; WX 333 ; N dieresis ; B 137 614 482 729 ; + +C 202 ; WX 333 ; N ring ; B 200 568 420 776 ; + +C 203 ; WX 333 ; N cedilla ; B -37 -228 220 0 ; + +C 205 ; WX 333 ; N hungarumlaut ; B 137 604 645 750 ; + +C 206 ; WX 333 ; N ogonek ; B 41 -228 264 0 ; + +C 207 ; WX 333 ; N caron ; B 149 604 502 750 ; + +C 208 ; WX 1000 ; N emdash ; B 48 227 1071 333 ; + +C 225 ; WX 1000 ; N AE ; B 5 0 1100 718 ; + +C 227 ; WX 370 ; N ordfeminine ; B 125 401 465 737 ; + +C 232 ; WX 611 ; N Lslash ; B 34 0 611 718 ; + +C 233 ; WX 778 ; N Oslash ; B 35 -27 894 745 ; + +C 234 ; WX 1000 ; N OE ; B 99 -19 1114 737 ; + +C 235 ; WX 365 ; N ordmasculine ; B 123 401 485 737 ; + +C 241 ; WX 889 ; N ae ; B 56 -14 923 546 ; + +C 245 ; WX 278 ; N dotlessi ; B 69 0 322 532 ; + +C 248 ; WX 278 ; N lslash ; B 40 0 407 718 ; + +C 249 ; WX 611 ; N oslash ; B 22 -29 701 560 ; + +C 250 ; WX 944 ; N oe ; B 82 -14 977 546 ; + +C 251 ; WX 611 ; N germandbls ; B 69 -14 657 731 ; + +C -1 ; WX 278 ; N Idieresis ; B 64 0 494 915 ; + +C -1 ; WX 556 ; N eacute ; B 70 -14 627 750 ; + +C -1 ; WX 556 ; N abreve ; B 55 -14 606 750 ; + +C -1 ; WX 611 ; N uhungarumlaut ; B 98 -14 784 750 ; + +C -1 ; WX 556 ; N ecaron ; B 70 -14 614 750 ; + +C -1 ; WX 667 ; N Ydieresis ; B 168 0 806 915 ; + +C -1 ; WX 584 ; N divide ; B 82 -42 610 548 ; + +C -1 ; WX 667 ; N Yacute ; B 168 0 806 936 ; + +C -1 ; WX 722 ; N Acircumflex ; B 20 0 706 936 ; + +C -1 ; WX 556 ; N aacute ; B 55 -14 627 750 ; + +C -1 ; WX 722 ; N Ucircumflex ; B 116 -19 804 936 ; + +C -1 ; WX 556 ; N yacute ; B 42 -214 652 750 ; + +C -1 ; WX 556 ; N scommaaccent ; B 63 -228 584 546 ; + +C -1 ; WX 556 ; N ecircumflex ; B 70 -14 593 750 ; + +C -1 ; WX 722 ; N Uring ; B 116 -19 804 962 ; + +C -1 ; WX 722 ; N Udieresis ; B 116 -19 804 915 ; + +C -1 ; WX 556 ; N aogonek ; B 55 -224 583 546 ; + +C -1 ; WX 722 ; N Uacute ; B 116 -19 804 936 ; + +C -1 ; WX 611 ; N uogonek ; B 98 -228 658 532 ; + +C -1 ; WX 667 ; N Edieresis ; B 76 0 757 915 ; + +C -1 ; WX 722 ; N Dcroat ; B 62 0 777 718 ; + +C -1 ; WX 250 ; N commaaccent ; B 16 -228 188 -50 ; + +C -1 ; WX 737 ; N copyright ; B 56 -19 835 737 ; + +C -1 ; WX 667 ; N Emacron ; B 76 0 757 864 ; + +C -1 ; WX 556 ; N ccaron ; B 79 -14 614 750 ; + +C -1 ; WX 556 ; N aring ; B 55 -14 583 776 ; + +C -1 ; WX 722 ; N Ncommaaccent ; B 69 -228 807 718 ; + +C -1 ; WX 278 ; N lacute ; B 69 0 528 936 ; + +C -1 ; WX 556 ; N agrave ; B 55 -14 583 750 ; + +C -1 ; WX 611 ; N Tcommaaccent ; B 140 -228 751 718 ; + +C -1 ; WX 722 ; N Cacute ; B 107 -19 789 936 ; + +C -1 ; WX 556 ; N atilde ; B 55 -14 619 737 ; + +C -1 ; WX 667 ; N Edotaccent ; B 76 0 757 915 ; + +C -1 ; WX 556 ; N scaron ; B 63 -14 614 750 ; + +C -1 ; WX 556 ; N scedilla ; B 63 -228 584 546 ; + +C -1 ; WX 278 ; N iacute ; B 69 0 488 750 ; + +C -1 ; WX 494 ; N lozenge ; B 90 0 564 745 ; + +C -1 ; WX 722 ; N Rcaron ; B 76 0 778 936 ; + +C -1 ; WX 778 ; N Gcommaaccent ; B 108 -228 817 737 ; + +C -1 ; WX 611 ; N ucircumflex ; B 98 -14 658 750 ; + +C -1 ; WX 556 ; N acircumflex ; B 55 -14 583 750 ; + +C -1 ; WX 722 ; N Amacron ; B 20 0 718 864 ; + +C -1 ; WX 389 ; N rcaron ; B 64 0 530 750 ; + +C -1 ; WX 556 ; N ccedilla ; B 79 -228 599 546 ; + +C -1 ; WX 611 ; N Zdotaccent ; B 25 0 737 915 ; + +C -1 ; WX 667 ; N Thorn ; B 76 0 716 718 ; + +C -1 ; WX 778 ; N Omacron ; B 107 -19 823 864 ; + +C -1 ; WX 722 ; N Racute ; B 76 0 778 936 ; + +C -1 ; WX 667 ; N Sacute ; B 81 -19 722 936 ; + +C -1 ; WX 743 ; N dcaron ; B 82 -14 903 718 ; + +C -1 ; WX 722 ; N Umacron ; B 116 -19 804 864 ; + +C -1 ; WX 611 ; N uring ; B 98 -14 658 776 ; + +C -1 ; WX 333 ; N threesuperior ; B 91 271 441 710 ; + +C -1 ; WX 778 ; N Ograve ; B 107 -19 823 936 ; + +C -1 ; WX 722 ; N Agrave ; B 20 0 702 936 ; + +C -1 ; WX 722 ; N Abreve ; B 20 0 729 936 ; + +C -1 ; WX 584 ; N multiply ; B 57 1 635 505 ; + +C -1 ; WX 611 ; N uacute ; B 98 -14 658 750 ; + +C -1 ; WX 611 ; N Tcaron ; B 140 0 751 936 ; + +C -1 ; WX 494 ; N partialdiff ; B 43 -21 585 750 ; + +C -1 ; WX 556 ; N ydieresis ; B 42 -214 652 729 ; + +C -1 ; WX 722 ; N Nacute ; B 69 0 807 936 ; + +C -1 ; WX 278 ; N icircumflex ; B 69 0 444 750 ; + +C -1 ; WX 667 ; N Ecircumflex ; B 76 0 757 936 ; + +C -1 ; WX 556 ; N adieresis ; B 55 -14 594 729 ; + +C -1 ; WX 556 ; N edieresis ; B 70 -14 594 729 ; + +C -1 ; WX 556 ; N cacute ; B 79 -14 627 750 ; + +C -1 ; WX 611 ; N nacute ; B 65 0 654 750 ; + +C -1 ; WX 611 ; N umacron ; B 98 -14 658 678 ; + +C -1 ; WX 722 ; N Ncaron ; B 69 0 807 936 ; + +C -1 ; WX 278 ; N Iacute ; B 64 0 528 936 ; + +C -1 ; WX 584 ; N plusminus ; B 40 0 625 506 ; + +C -1 ; WX 280 ; N brokenbar ; B 52 -150 345 700 ; + +C -1 ; WX 737 ; N registered ; B 55 -19 834 737 ; + +C -1 ; WX 778 ; N Gbreve ; B 108 -19 817 936 ; + +C -1 ; WX 278 ; N Idotaccent ; B 64 0 397 915 ; + +C -1 ; WX 600 ; N summation ; B 14 -10 670 706 ; + +C -1 ; WX 667 ; N Egrave ; B 76 0 757 936 ; + +C -1 ; WX 389 ; N racute ; B 64 0 543 750 ; + +C -1 ; WX 611 ; N omacron ; B 82 -14 643 678 ; + +C -1 ; WX 611 ; N Zacute ; B 25 0 737 936 ; + +C -1 ; WX 611 ; N Zcaron ; B 25 0 737 936 ; + +C -1 ; WX 549 ; N greaterequal ; B 26 0 629 704 ; + +C -1 ; WX 722 ; N Eth ; B 62 0 777 718 ; + +C -1 ; WX 722 ; N Ccedilla ; B 107 -228 789 737 ; + +C -1 ; WX 278 ; N lcommaaccent ; B 30 -228 362 718 ; + +C -1 ; WX 389 ; N tcaron ; B 100 -6 608 878 ; + +C -1 ; WX 556 ; N eogonek ; B 70 -228 593 546 ; + +C -1 ; WX 722 ; N Uogonek ; B 116 -228 804 718 ; + +C -1 ; WX 722 ; N Aacute ; B 20 0 750 936 ; + +C -1 ; WX 722 ; N Adieresis ; B 20 0 716 915 ; + +C -1 ; WX 556 ; N egrave ; B 70 -14 593 750 ; + +C -1 ; WX 500 ; N zacute ; B 20 0 599 750 ; + +C -1 ; WX 278 ; N iogonek ; B -14 -224 363 725 ; + +C -1 ; WX 778 ; N Oacute ; B 107 -19 823 936 ; + +C -1 ; WX 611 ; N oacute ; B 82 -14 654 750 ; + +C -1 ; WX 556 ; N amacron ; B 55 -14 595 678 ; + +C -1 ; WX 556 ; N sacute ; B 63 -14 627 750 ; + +C -1 ; WX 278 ; N idieresis ; B 69 0 455 729 ; + +C -1 ; WX 778 ; N Ocircumflex ; B 107 -19 823 936 ; + +C -1 ; WX 722 ; N Ugrave ; B 116 -19 804 936 ; + +C -1 ; WX 612 ; N Delta ; B 6 0 608 688 ; + +C -1 ; WX 611 ; N thorn ; B 18 -208 645 718 ; + +C -1 ; WX 333 ; N twosuperior ; B 69 283 449 710 ; + +C -1 ; WX 778 ; N Odieresis ; B 107 -19 823 915 ; + +C -1 ; WX 611 ; N mu ; B 22 -207 658 532 ; + +C -1 ; WX 278 ; N igrave ; B 69 0 326 750 ; + +C -1 ; WX 611 ; N ohungarumlaut ; B 82 -14 784 750 ; + +C -1 ; WX 667 ; N Eogonek ; B 76 -224 757 718 ; + +C -1 ; WX 611 ; N dcroat ; B 82 -14 789 718 ; + +C -1 ; WX 834 ; N threequarters ; B 99 -19 839 710 ; + +C -1 ; WX 667 ; N Scedilla ; B 81 -228 718 737 ; + +C -1 ; WX 400 ; N lcaron ; B 69 0 561 718 ; + +C -1 ; WX 722 ; N Kcommaaccent ; B 87 -228 858 718 ; + +C -1 ; WX 611 ; N Lacute ; B 76 0 611 936 ; + +C -1 ; WX 1000 ; N trademark ; B 179 306 1109 718 ; + +C -1 ; WX 556 ; N edotaccent ; B 70 -14 593 729 ; + +C -1 ; WX 278 ; N Igrave ; B 64 0 367 936 ; + +C -1 ; WX 278 ; N Imacron ; B 64 0 496 864 ; + +C -1 ; WX 611 ; N Lcaron ; B 76 0 643 718 ; + +C -1 ; WX 834 ; N onehalf ; B 132 -19 858 710 ; + +C -1 ; WX 549 ; N lessequal ; B 29 0 676 704 ; + +C -1 ; WX 611 ; N ocircumflex ; B 82 -14 643 750 ; + +C -1 ; WX 611 ; N ntilde ; B 65 0 646 737 ; + +C -1 ; WX 722 ; N Uhungarumlaut ; B 116 -19 880 936 ; + +C -1 ; WX 667 ; N Eacute ; B 76 0 757 936 ; + +C -1 ; WX 556 ; N emacron ; B 70 -14 595 678 ; + +C -1 ; WX 611 ; N gbreve ; B 38 -217 666 750 ; + +C -1 ; WX 834 ; N onequarter ; B 132 -19 806 710 ; + +C -1 ; WX 667 ; N Scaron ; B 81 -19 718 936 ; + +C -1 ; WX 667 ; N Scommaaccent ; B 81 -228 718 737 ; + +C -1 ; WX 778 ; N Ohungarumlaut ; B 107 -19 908 936 ; + +C -1 ; WX 400 ; N degree ; B 175 426 467 712 ; + +C -1 ; WX 611 ; N ograve ; B 82 -14 643 750 ; + +C -1 ; WX 722 ; N Ccaron ; B 107 -19 789 936 ; + +C -1 ; WX 611 ; N ugrave ; B 98 -14 658 750 ; + +C -1 ; WX 549 ; N radical ; B 112 -46 689 850 ; + +C -1 ; WX 722 ; N Dcaron ; B 76 0 777 936 ; + +C -1 ; WX 389 ; N rcommaaccent ; B 26 -228 489 546 ; + +C -1 ; WX 722 ; N Ntilde ; B 69 0 807 923 ; + +C -1 ; WX 611 ; N otilde ; B 82 -14 646 737 ; + +C -1 ; WX 722 ; N Rcommaaccent ; B 76 -228 778 718 ; + +C -1 ; WX 611 ; N Lcommaaccent ; B 76 -228 611 718 ; + +C -1 ; WX 722 ; N Atilde ; B 20 0 741 923 ; + +C -1 ; WX 722 ; N Aogonek ; B 20 -224 702 718 ; + +C -1 ; WX 722 ; N Aring ; B 20 0 702 962 ; + +C -1 ; WX 778 ; N Otilde ; B 107 -19 823 923 ; + +C -1 ; WX 500 ; N zdotaccent ; B 20 0 583 729 ; + +C -1 ; WX 667 ; N Ecaron ; B 76 0 757 936 ; + +C -1 ; WX 278 ; N Iogonek ; B -41 -228 367 718 ; + +C -1 ; WX 556 ; N kcommaaccent ; B 69 -228 670 718 ; + +C -1 ; WX 584 ; N minus ; B 82 197 610 309 ; + +C -1 ; WX 278 ; N Icircumflex ; B 64 0 484 936 ; + +C -1 ; WX 611 ; N ncaron ; B 65 0 641 750 ; + +C -1 ; WX 333 ; N tcommaaccent ; B 58 -228 422 676 ; + +C -1 ; WX 584 ; N logicalnot ; B 105 108 633 419 ; + +C -1 ; WX 611 ; N odieresis ; B 82 -14 643 729 ; + +C -1 ; WX 611 ; N udieresis ; B 98 -14 658 729 ; + +C -1 ; WX 549 ; N notequal ; B 32 -49 630 570 ; + +C -1 ; WX 611 ; N gcommaaccent ; B 38 -217 666 850 ; + +C -1 ; WX 611 ; N eth ; B 82 -14 670 737 ; + +C -1 ; WX 500 ; N zcaron ; B 20 0 586 750 ; + +C -1 ; WX 611 ; N ncommaaccent ; B 65 -228 629 546 ; + +C -1 ; WX 333 ; N onesuperior ; B 148 283 388 710 ; + +C -1 ; WX 278 ; N imacron ; B 69 0 429 678 ; + +C -1 ; WX 556 ; N Euro ; B 0 0 0 0 ; + +EndCharMetrics + +StartKernData + +StartKernPairs 2481 + +KPX A C -40 + +KPX A Cacute -40 + +KPX A Ccaron -40 + +KPX A Ccedilla -40 + +KPX A G -50 + +KPX A Gbreve -50 + +KPX A Gcommaaccent -50 + +KPX A O -40 + +KPX A Oacute -40 + +KPX A Ocircumflex -40 + +KPX A Odieresis -40 + +KPX A Ograve -40 + +KPX A Ohungarumlaut -40 + +KPX A Omacron -40 + +KPX A Oslash -40 + +KPX A Otilde -40 + +KPX A Q -40 + +KPX A T -90 + +KPX A Tcaron -90 + +KPX A Tcommaaccent -90 + +KPX A U -50 + +KPX A Uacute -50 + +KPX A Ucircumflex -50 + +KPX A Udieresis -50 + +KPX A Ugrave -50 + +KPX A Uhungarumlaut -50 + +KPX A Umacron -50 + +KPX A Uogonek -50 + +KPX A Uring -50 + +KPX A V -80 + +KPX A W -60 + +KPX A Y -110 + +KPX A Yacute -110 + +KPX A Ydieresis -110 + +KPX A u -30 + +KPX A uacute -30 + +KPX A ucircumflex -30 + +KPX A udieresis -30 + +KPX A ugrave -30 + +KPX A uhungarumlaut -30 + +KPX A umacron -30 + +KPX A uogonek -30 + +KPX A uring -30 + +KPX A v -40 + +KPX A w -30 + +KPX A y -30 + +KPX A yacute -30 + +KPX A ydieresis -30 + +KPX Aacute C -40 + +KPX Aacute Cacute -40 + +KPX Aacute Ccaron -40 + +KPX Aacute Ccedilla -40 + +KPX Aacute G -50 + +KPX Aacute Gbreve -50 + +KPX Aacute Gcommaaccent -50 + +KPX Aacute O -40 + +KPX Aacute Oacute -40 + +KPX Aacute Ocircumflex -40 + +KPX Aacute Odieresis -40 + +KPX Aacute Ograve -40 + +KPX Aacute Ohungarumlaut -40 + +KPX Aacute Omacron -40 + +KPX Aacute Oslash -40 + +KPX Aacute Otilde -40 + +KPX Aacute Q -40 + +KPX Aacute T -90 + +KPX Aacute Tcaron -90 + +KPX Aacute Tcommaaccent -90 + +KPX Aacute U -50 + +KPX Aacute Uacute -50 + +KPX Aacute Ucircumflex -50 + +KPX Aacute Udieresis -50 + +KPX Aacute Ugrave -50 + +KPX Aacute Uhungarumlaut -50 + +KPX Aacute Umacron -50 + +KPX Aacute Uogonek -50 + +KPX Aacute Uring -50 + +KPX Aacute V -80 + +KPX Aacute W -60 + +KPX Aacute Y -110 + +KPX Aacute Yacute -110 + +KPX Aacute Ydieresis -110 + +KPX Aacute u -30 + +KPX Aacute uacute -30 + +KPX Aacute ucircumflex -30 + +KPX Aacute udieresis -30 + +KPX Aacute ugrave -30 + +KPX Aacute uhungarumlaut -30 + +KPX Aacute umacron -30 + +KPX Aacute uogonek -30 + +KPX Aacute uring -30 + +KPX Aacute v -40 + +KPX Aacute w -30 + +KPX Aacute y -30 + +KPX Aacute yacute -30 + +KPX Aacute ydieresis -30 + +KPX Abreve C -40 + +KPX Abreve Cacute -40 + +KPX Abreve Ccaron -40 + +KPX Abreve Ccedilla -40 + +KPX Abreve G -50 + +KPX Abreve Gbreve -50 + +KPX Abreve Gcommaaccent -50 + +KPX Abreve O -40 + +KPX Abreve Oacute -40 + +KPX Abreve Ocircumflex -40 + +KPX Abreve Odieresis -40 + +KPX Abreve Ograve -40 + +KPX Abreve Ohungarumlaut -40 + +KPX Abreve Omacron -40 + +KPX Abreve Oslash -40 + +KPX Abreve Otilde -40 + +KPX Abreve Q -40 + +KPX Abreve T -90 + +KPX Abreve Tcaron -90 + +KPX Abreve Tcommaaccent -90 + +KPX Abreve U -50 + +KPX Abreve Uacute -50 + +KPX Abreve Ucircumflex -50 + +KPX Abreve Udieresis -50 + +KPX Abreve Ugrave -50 + +KPX Abreve Uhungarumlaut -50 + +KPX Abreve Umacron -50 + +KPX Abreve Uogonek -50 + +KPX Abreve Uring -50 + +KPX Abreve V -80 + +KPX Abreve W -60 + +KPX Abreve Y -110 + +KPX Abreve Yacute -110 + +KPX Abreve Ydieresis -110 + +KPX Abreve u -30 + +KPX Abreve uacute -30 + +KPX Abreve ucircumflex -30 + +KPX Abreve udieresis -30 + +KPX Abreve ugrave -30 + +KPX Abreve uhungarumlaut -30 + +KPX Abreve umacron -30 + +KPX Abreve uogonek -30 + +KPX Abreve uring -30 + +KPX Abreve v -40 + +KPX Abreve w -30 + +KPX Abreve y -30 + +KPX Abreve yacute -30 + +KPX Abreve ydieresis -30 + +KPX Acircumflex C -40 + +KPX Acircumflex Cacute -40 + +KPX Acircumflex Ccaron -40 + +KPX Acircumflex Ccedilla -40 + +KPX Acircumflex G -50 + +KPX Acircumflex Gbreve -50 + +KPX Acircumflex Gcommaaccent -50 + +KPX Acircumflex O -40 + +KPX Acircumflex Oacute -40 + +KPX Acircumflex Ocircumflex -40 + +KPX Acircumflex Odieresis -40 + +KPX Acircumflex Ograve -40 + +KPX Acircumflex Ohungarumlaut -40 + +KPX Acircumflex Omacron -40 + +KPX Acircumflex Oslash -40 + +KPX Acircumflex Otilde -40 + +KPX Acircumflex Q -40 + +KPX Acircumflex T -90 + +KPX Acircumflex Tcaron -90 + +KPX Acircumflex Tcommaaccent -90 + +KPX Acircumflex U -50 + +KPX Acircumflex Uacute -50 + +KPX Acircumflex Ucircumflex -50 + +KPX Acircumflex Udieresis -50 + +KPX Acircumflex Ugrave -50 + +KPX Acircumflex Uhungarumlaut -50 + +KPX Acircumflex Umacron -50 + +KPX Acircumflex Uogonek -50 + +KPX Acircumflex Uring -50 + +KPX Acircumflex V -80 + +KPX Acircumflex W -60 + +KPX Acircumflex Y -110 + +KPX Acircumflex Yacute -110 + +KPX Acircumflex Ydieresis -110 + +KPX Acircumflex u -30 + +KPX Acircumflex uacute -30 + +KPX Acircumflex ucircumflex -30 + +KPX Acircumflex udieresis -30 + +KPX Acircumflex ugrave -30 + +KPX Acircumflex uhungarumlaut -30 + +KPX Acircumflex umacron -30 + +KPX Acircumflex uogonek -30 + +KPX Acircumflex uring -30 + +KPX Acircumflex v -40 + +KPX Acircumflex w -30 + +KPX Acircumflex y -30 + +KPX Acircumflex yacute -30 + +KPX Acircumflex ydieresis -30 + +KPX Adieresis C -40 + +KPX Adieresis Cacute -40 + +KPX Adieresis Ccaron -40 + +KPX Adieresis Ccedilla -40 + +KPX Adieresis G -50 + +KPX Adieresis Gbreve -50 + +KPX Adieresis Gcommaaccent -50 + +KPX Adieresis O -40 + +KPX Adieresis Oacute -40 + +KPX Adieresis Ocircumflex -40 + +KPX Adieresis Odieresis -40 + +KPX Adieresis Ograve -40 + +KPX Adieresis Ohungarumlaut -40 + +KPX Adieresis Omacron -40 + +KPX Adieresis Oslash -40 + +KPX Adieresis Otilde -40 + +KPX Adieresis Q -40 + +KPX Adieresis T -90 + +KPX Adieresis Tcaron -90 + +KPX Adieresis Tcommaaccent -90 + +KPX Adieresis U -50 + +KPX Adieresis Uacute -50 + +KPX Adieresis Ucircumflex -50 + +KPX Adieresis Udieresis -50 + +KPX Adieresis Ugrave -50 + +KPX Adieresis Uhungarumlaut -50 + +KPX Adieresis Umacron -50 + +KPX Adieresis Uogonek -50 + +KPX Adieresis Uring -50 + +KPX Adieresis V -80 + +KPX Adieresis W -60 + +KPX Adieresis Y -110 + +KPX Adieresis Yacute -110 + +KPX Adieresis Ydieresis -110 + +KPX Adieresis u -30 + +KPX Adieresis uacute -30 + +KPX Adieresis ucircumflex -30 + +KPX Adieresis udieresis -30 + +KPX Adieresis ugrave -30 + +KPX Adieresis uhungarumlaut -30 + +KPX Adieresis umacron -30 + +KPX Adieresis uogonek -30 + +KPX Adieresis uring -30 + +KPX Adieresis v -40 + +KPX Adieresis w -30 + +KPX Adieresis y -30 + +KPX Adieresis yacute -30 + +KPX Adieresis ydieresis -30 + +KPX Agrave C -40 + +KPX Agrave Cacute -40 + +KPX Agrave Ccaron -40 + +KPX Agrave Ccedilla -40 + +KPX Agrave G -50 + +KPX Agrave Gbreve -50 + +KPX Agrave Gcommaaccent -50 + +KPX Agrave O -40 + +KPX Agrave Oacute -40 + +KPX Agrave Ocircumflex -40 + +KPX Agrave Odieresis -40 + +KPX Agrave Ograve -40 + +KPX Agrave Ohungarumlaut -40 + +KPX Agrave Omacron -40 + +KPX Agrave Oslash -40 + +KPX Agrave Otilde -40 + +KPX Agrave Q -40 + +KPX Agrave T -90 + +KPX Agrave Tcaron -90 + +KPX Agrave Tcommaaccent -90 + +KPX Agrave U -50 + +KPX Agrave Uacute -50 + +KPX Agrave Ucircumflex -50 + +KPX Agrave Udieresis -50 + +KPX Agrave Ugrave -50 + +KPX Agrave Uhungarumlaut -50 + +KPX Agrave Umacron -50 + +KPX Agrave Uogonek -50 + +KPX Agrave Uring -50 + +KPX Agrave V -80 + +KPX Agrave W -60 + +KPX Agrave Y -110 + +KPX Agrave Yacute -110 + +KPX Agrave Ydieresis -110 + +KPX Agrave u -30 + +KPX Agrave uacute -30 + +KPX Agrave ucircumflex -30 + +KPX Agrave udieresis -30 + +KPX Agrave ugrave -30 + +KPX Agrave uhungarumlaut -30 + +KPX Agrave umacron -30 + +KPX Agrave uogonek -30 + +KPX Agrave uring -30 + +KPX Agrave v -40 + +KPX Agrave w -30 + +KPX Agrave y -30 + +KPX Agrave yacute -30 + +KPX Agrave ydieresis -30 + +KPX Amacron C -40 + +KPX Amacron Cacute -40 + +KPX Amacron Ccaron -40 + +KPX Amacron Ccedilla -40 + +KPX Amacron G -50 + +KPX Amacron Gbreve -50 + +KPX Amacron Gcommaaccent -50 + +KPX Amacron O -40 + +KPX Amacron Oacute -40 + +KPX Amacron Ocircumflex -40 + +KPX Amacron Odieresis -40 + +KPX Amacron Ograve -40 + +KPX Amacron Ohungarumlaut -40 + +KPX Amacron Omacron -40 + +KPX Amacron Oslash -40 + +KPX Amacron Otilde -40 + +KPX Amacron Q -40 + +KPX Amacron T -90 + +KPX Amacron Tcaron -90 + +KPX Amacron Tcommaaccent -90 + +KPX Amacron U -50 + +KPX Amacron Uacute -50 + +KPX Amacron Ucircumflex -50 + +KPX Amacron Udieresis -50 + +KPX Amacron Ugrave -50 + +KPX Amacron Uhungarumlaut -50 + +KPX Amacron Umacron -50 + +KPX Amacron Uogonek -50 + +KPX Amacron Uring -50 + +KPX Amacron V -80 + +KPX Amacron W -60 + +KPX Amacron Y -110 + +KPX Amacron Yacute -110 + +KPX Amacron Ydieresis -110 + +KPX Amacron u -30 + +KPX Amacron uacute -30 + +KPX Amacron ucircumflex -30 + +KPX Amacron udieresis -30 + +KPX Amacron ugrave -30 + +KPX Amacron uhungarumlaut -30 + +KPX Amacron umacron -30 + +KPX Amacron uogonek -30 + +KPX Amacron uring -30 + +KPX Amacron v -40 + +KPX Amacron w -30 + +KPX Amacron y -30 + +KPX Amacron yacute -30 + +KPX Amacron ydieresis -30 + +KPX Aogonek C -40 + +KPX Aogonek Cacute -40 + +KPX Aogonek Ccaron -40 + +KPX Aogonek Ccedilla -40 + +KPX Aogonek G -50 + +KPX Aogonek Gbreve -50 + +KPX Aogonek Gcommaaccent -50 + +KPX Aogonek O -40 + +KPX Aogonek Oacute -40 + +KPX Aogonek Ocircumflex -40 + +KPX Aogonek Odieresis -40 + +KPX Aogonek Ograve -40 + +KPX Aogonek Ohungarumlaut -40 + +KPX Aogonek Omacron -40 + +KPX Aogonek Oslash -40 + +KPX Aogonek Otilde -40 + +KPX Aogonek Q -40 + +KPX Aogonek T -90 + +KPX Aogonek Tcaron -90 + +KPX Aogonek Tcommaaccent -90 + +KPX Aogonek U -50 + +KPX Aogonek Uacute -50 + +KPX Aogonek Ucircumflex -50 + +KPX Aogonek Udieresis -50 + +KPX Aogonek Ugrave -50 + +KPX Aogonek Uhungarumlaut -50 + +KPX Aogonek Umacron -50 + +KPX Aogonek Uogonek -50 + +KPX Aogonek Uring -50 + +KPX Aogonek V -80 + +KPX Aogonek W -60 + +KPX Aogonek Y -110 + +KPX Aogonek Yacute -110 + +KPX Aogonek Ydieresis -110 + +KPX Aogonek u -30 + +KPX Aogonek uacute -30 + +KPX Aogonek ucircumflex -30 + +KPX Aogonek udieresis -30 + +KPX Aogonek ugrave -30 + +KPX Aogonek uhungarumlaut -30 + +KPX Aogonek umacron -30 + +KPX Aogonek uogonek -30 + +KPX Aogonek uring -30 + +KPX Aogonek v -40 + +KPX Aogonek w -30 + +KPX Aogonek y -30 + +KPX Aogonek yacute -30 + +KPX Aogonek ydieresis -30 + +KPX Aring C -40 + +KPX Aring Cacute -40 + +KPX Aring Ccaron -40 + +KPX Aring Ccedilla -40 + +KPX Aring G -50 + +KPX Aring Gbreve -50 + +KPX Aring Gcommaaccent -50 + +KPX Aring O -40 + +KPX Aring Oacute -40 + +KPX Aring Ocircumflex -40 + +KPX Aring Odieresis -40 + +KPX Aring Ograve -40 + +KPX Aring Ohungarumlaut -40 + +KPX Aring Omacron -40 + +KPX Aring Oslash -40 + +KPX Aring Otilde -40 + +KPX Aring Q -40 + +KPX Aring T -90 + +KPX Aring Tcaron -90 + +KPX Aring Tcommaaccent -90 + +KPX Aring U -50 + +KPX Aring Uacute -50 + +KPX Aring Ucircumflex -50 + +KPX Aring Udieresis -50 + +KPX Aring Ugrave -50 + +KPX Aring Uhungarumlaut -50 + +KPX Aring Umacron -50 + +KPX Aring Uogonek -50 + +KPX Aring Uring -50 + +KPX Aring V -80 + +KPX Aring W -60 + +KPX Aring Y -110 + +KPX Aring Yacute -110 + +KPX Aring Ydieresis -110 + +KPX Aring u -30 + +KPX Aring uacute -30 + +KPX Aring ucircumflex -30 + +KPX Aring udieresis -30 + +KPX Aring ugrave -30 + +KPX Aring uhungarumlaut -30 + +KPX Aring umacron -30 + +KPX Aring uogonek -30 + +KPX Aring uring -30 + +KPX Aring v -40 + +KPX Aring w -30 + +KPX Aring y -30 + +KPX Aring yacute -30 + +KPX Aring ydieresis -30 + +KPX Atilde C -40 + +KPX Atilde Cacute -40 + +KPX Atilde Ccaron -40 + +KPX Atilde Ccedilla -40 + +KPX Atilde G -50 + +KPX Atilde Gbreve -50 + +KPX Atilde Gcommaaccent -50 + +KPX Atilde O -40 + +KPX Atilde Oacute -40 + +KPX Atilde Ocircumflex -40 + +KPX Atilde Odieresis -40 + +KPX Atilde Ograve -40 + +KPX Atilde Ohungarumlaut -40 + +KPX Atilde Omacron -40 + +KPX Atilde Oslash -40 + +KPX Atilde Otilde -40 + +KPX Atilde Q -40 + +KPX Atilde T -90 + +KPX Atilde Tcaron -90 + +KPX Atilde Tcommaaccent -90 + +KPX Atilde U -50 + +KPX Atilde Uacute -50 + +KPX Atilde Ucircumflex -50 + +KPX Atilde Udieresis -50 + +KPX Atilde Ugrave -50 + +KPX Atilde Uhungarumlaut -50 + +KPX Atilde Umacron -50 + +KPX Atilde Uogonek -50 + +KPX Atilde Uring -50 + +KPX Atilde V -80 + +KPX Atilde W -60 + +KPX Atilde Y -110 + +KPX Atilde Yacute -110 + +KPX Atilde Ydieresis -110 + +KPX Atilde u -30 + +KPX Atilde uacute -30 + +KPX Atilde ucircumflex -30 + +KPX Atilde udieresis -30 + +KPX Atilde ugrave -30 + +KPX Atilde uhungarumlaut -30 + +KPX Atilde umacron -30 + +KPX Atilde uogonek -30 + +KPX Atilde uring -30 + +KPX Atilde v -40 + +KPX Atilde w -30 + +KPX Atilde y -30 + +KPX Atilde yacute -30 + +KPX Atilde ydieresis -30 + +KPX B A -30 + +KPX B Aacute -30 + +KPX B Abreve -30 + +KPX B Acircumflex -30 + +KPX B Adieresis -30 + +KPX B Agrave -30 + +KPX B Amacron -30 + +KPX B Aogonek -30 + +KPX B Aring -30 + +KPX B Atilde -30 + +KPX B U -10 + +KPX B Uacute -10 + +KPX B Ucircumflex -10 + +KPX B Udieresis -10 + +KPX B Ugrave -10 + +KPX B Uhungarumlaut -10 + +KPX B Umacron -10 + +KPX B Uogonek -10 + +KPX B Uring -10 + +KPX D A -40 + +KPX D Aacute -40 + +KPX D Abreve -40 + +KPX D Acircumflex -40 + +KPX D Adieresis -40 + +KPX D Agrave -40 + +KPX D Amacron -40 + +KPX D Aogonek -40 + +KPX D Aring -40 + +KPX D Atilde -40 + +KPX D V -40 + +KPX D W -40 + +KPX D Y -70 + +KPX D Yacute -70 + +KPX D Ydieresis -70 + +KPX D comma -30 + +KPX D period -30 + +KPX Dcaron A -40 + +KPX Dcaron Aacute -40 + +KPX Dcaron Abreve -40 + +KPX Dcaron Acircumflex -40 + +KPX Dcaron Adieresis -40 + +KPX Dcaron Agrave -40 + +KPX Dcaron Amacron -40 + +KPX Dcaron Aogonek -40 + +KPX Dcaron Aring -40 + +KPX Dcaron Atilde -40 + +KPX Dcaron V -40 + +KPX Dcaron W -40 + +KPX Dcaron Y -70 + +KPX Dcaron Yacute -70 + +KPX Dcaron Ydieresis -70 + +KPX Dcaron comma -30 + +KPX Dcaron period -30 + +KPX Dcroat A -40 + +KPX Dcroat Aacute -40 + +KPX Dcroat Abreve -40 + +KPX Dcroat Acircumflex -40 + +KPX Dcroat Adieresis -40 + +KPX Dcroat Agrave -40 + +KPX Dcroat Amacron -40 + +KPX Dcroat Aogonek -40 + +KPX Dcroat Aring -40 + +KPX Dcroat Atilde -40 + +KPX Dcroat V -40 + +KPX Dcroat W -40 + +KPX Dcroat Y -70 + +KPX Dcroat Yacute -70 + +KPX Dcroat Ydieresis -70 + +KPX Dcroat comma -30 + +KPX Dcroat period -30 + +KPX F A -80 + +KPX F Aacute -80 + +KPX F Abreve -80 + +KPX F Acircumflex -80 + +KPX F Adieresis -80 + +KPX F Agrave -80 + +KPX F Amacron -80 + +KPX F Aogonek -80 + +KPX F Aring -80 + +KPX F Atilde -80 + +KPX F a -20 + +KPX F aacute -20 + +KPX F abreve -20 + +KPX F acircumflex -20 + +KPX F adieresis -20 + +KPX F agrave -20 + +KPX F amacron -20 + +KPX F aogonek -20 + +KPX F aring -20 + +KPX F atilde -20 + +KPX F comma -100 + +KPX F period -100 + +KPX J A -20 + +KPX J Aacute -20 + +KPX J Abreve -20 + +KPX J Acircumflex -20 + +KPX J Adieresis -20 + +KPX J Agrave -20 + +KPX J Amacron -20 + +KPX J Aogonek -20 + +KPX J Aring -20 + +KPX J Atilde -20 + +KPX J comma -20 + +KPX J period -20 + +KPX J u -20 + +KPX J uacute -20 + +KPX J ucircumflex -20 + +KPX J udieresis -20 + +KPX J ugrave -20 + +KPX J uhungarumlaut -20 + +KPX J umacron -20 + +KPX J uogonek -20 + +KPX J uring -20 + +KPX K O -30 + +KPX K Oacute -30 + +KPX K Ocircumflex -30 + +KPX K Odieresis -30 + +KPX K Ograve -30 + +KPX K Ohungarumlaut -30 + +KPX K Omacron -30 + +KPX K Oslash -30 + +KPX K Otilde -30 + +KPX K e -15 + +KPX K eacute -15 + +KPX K ecaron -15 + +KPX K ecircumflex -15 + +KPX K edieresis -15 + +KPX K edotaccent -15 + +KPX K egrave -15 + +KPX K emacron -15 + +KPX K eogonek -15 + +KPX K o -35 + +KPX K oacute -35 + +KPX K ocircumflex -35 + +KPX K odieresis -35 + +KPX K ograve -35 + +KPX K ohungarumlaut -35 + +KPX K omacron -35 + +KPX K oslash -35 + +KPX K otilde -35 + +KPX K u -30 + +KPX K uacute -30 + +KPX K ucircumflex -30 + +KPX K udieresis -30 + +KPX K ugrave -30 + +KPX K uhungarumlaut -30 + +KPX K umacron -30 + +KPX K uogonek -30 + +KPX K uring -30 + +KPX K y -40 + +KPX K yacute -40 + +KPX K ydieresis -40 + +KPX Kcommaaccent O -30 + +KPX Kcommaaccent Oacute -30 + +KPX Kcommaaccent Ocircumflex -30 + +KPX Kcommaaccent Odieresis -30 + +KPX Kcommaaccent Ograve -30 + +KPX Kcommaaccent Ohungarumlaut -30 + +KPX Kcommaaccent Omacron -30 + +KPX Kcommaaccent Oslash -30 + +KPX Kcommaaccent Otilde -30 + +KPX Kcommaaccent e -15 + +KPX Kcommaaccent eacute -15 + +KPX Kcommaaccent ecaron -15 + +KPX Kcommaaccent ecircumflex -15 + +KPX Kcommaaccent edieresis -15 + +KPX Kcommaaccent edotaccent -15 + +KPX Kcommaaccent egrave -15 + +KPX Kcommaaccent emacron -15 + +KPX Kcommaaccent eogonek -15 + +KPX Kcommaaccent o -35 + +KPX Kcommaaccent oacute -35 + +KPX Kcommaaccent ocircumflex -35 + +KPX Kcommaaccent odieresis -35 + +KPX Kcommaaccent ograve -35 + +KPX Kcommaaccent ohungarumlaut -35 + +KPX Kcommaaccent omacron -35 + +KPX Kcommaaccent oslash -35 + +KPX Kcommaaccent otilde -35 + +KPX Kcommaaccent u -30 + +KPX Kcommaaccent uacute -30 + +KPX Kcommaaccent ucircumflex -30 + +KPX Kcommaaccent udieresis -30 + +KPX Kcommaaccent ugrave -30 + +KPX Kcommaaccent uhungarumlaut -30 + +KPX Kcommaaccent umacron -30 + +KPX Kcommaaccent uogonek -30 + +KPX Kcommaaccent uring -30 + +KPX Kcommaaccent y -40 + +KPX Kcommaaccent yacute -40 + +KPX Kcommaaccent ydieresis -40 + +KPX L T -90 + +KPX L Tcaron -90 + +KPX L Tcommaaccent -90 + +KPX L V -110 + +KPX L W -80 + +KPX L Y -120 + +KPX L Yacute -120 + +KPX L Ydieresis -120 + +KPX L quotedblright -140 + +KPX L quoteright -140 + +KPX L y -30 + +KPX L yacute -30 + +KPX L ydieresis -30 + +KPX Lacute T -90 + +KPX Lacute Tcaron -90 + +KPX Lacute Tcommaaccent -90 + +KPX Lacute V -110 + +KPX Lacute W -80 + +KPX Lacute Y -120 + +KPX Lacute Yacute -120 + +KPX Lacute Ydieresis -120 + +KPX Lacute quotedblright -140 + +KPX Lacute quoteright -140 + +KPX Lacute y -30 + +KPX Lacute yacute -30 + +KPX Lacute ydieresis -30 + +KPX Lcommaaccent T -90 + +KPX Lcommaaccent Tcaron -90 + +KPX Lcommaaccent Tcommaaccent -90 + +KPX Lcommaaccent V -110 + +KPX Lcommaaccent W -80 + +KPX Lcommaaccent Y -120 + +KPX Lcommaaccent Yacute -120 + +KPX Lcommaaccent Ydieresis -120 + +KPX Lcommaaccent quotedblright -140 + +KPX Lcommaaccent quoteright -140 + +KPX Lcommaaccent y -30 + +KPX Lcommaaccent yacute -30 + +KPX Lcommaaccent ydieresis -30 + +KPX Lslash T -90 + +KPX Lslash Tcaron -90 + +KPX Lslash Tcommaaccent -90 + +KPX Lslash V -110 + +KPX Lslash W -80 + +KPX Lslash Y -120 + +KPX Lslash Yacute -120 + +KPX Lslash Ydieresis -120 + +KPX Lslash quotedblright -140 + +KPX Lslash quoteright -140 + +KPX Lslash y -30 + +KPX Lslash yacute -30 + +KPX Lslash ydieresis -30 + +KPX O A -50 + +KPX O Aacute -50 + +KPX O Abreve -50 + +KPX O Acircumflex -50 + +KPX O Adieresis -50 + +KPX O Agrave -50 + +KPX O Amacron -50 + +KPX O Aogonek -50 + +KPX O Aring -50 + +KPX O Atilde -50 + +KPX O T -40 + +KPX O Tcaron -40 + +KPX O Tcommaaccent -40 + +KPX O V -50 + +KPX O W -50 + +KPX O X -50 + +KPX O Y -70 + +KPX O Yacute -70 + +KPX O Ydieresis -70 + +KPX O comma -40 + +KPX O period -40 + +KPX Oacute A -50 + +KPX Oacute Aacute -50 + +KPX Oacute Abreve -50 + +KPX Oacute Acircumflex -50 + +KPX Oacute Adieresis -50 + +KPX Oacute Agrave -50 + +KPX Oacute Amacron -50 + +KPX Oacute Aogonek -50 + +KPX Oacute Aring -50 + +KPX Oacute Atilde -50 + +KPX Oacute T -40 + +KPX Oacute Tcaron -40 + +KPX Oacute Tcommaaccent -40 + +KPX Oacute V -50 + +KPX Oacute W -50 + +KPX Oacute X -50 + +KPX Oacute Y -70 + +KPX Oacute Yacute -70 + +KPX Oacute Ydieresis -70 + +KPX Oacute comma -40 + +KPX Oacute period -40 + +KPX Ocircumflex A -50 + +KPX Ocircumflex Aacute -50 + +KPX Ocircumflex Abreve -50 + +KPX Ocircumflex Acircumflex -50 + +KPX Ocircumflex Adieresis -50 + +KPX Ocircumflex Agrave -50 + +KPX Ocircumflex Amacron -50 + +KPX Ocircumflex Aogonek -50 + +KPX Ocircumflex Aring -50 + +KPX Ocircumflex Atilde -50 + +KPX Ocircumflex T -40 + +KPX Ocircumflex Tcaron -40 + +KPX Ocircumflex Tcommaaccent -40 + +KPX Ocircumflex V -50 + +KPX Ocircumflex W -50 + +KPX Ocircumflex X -50 + +KPX Ocircumflex Y -70 + +KPX Ocircumflex Yacute -70 + +KPX Ocircumflex Ydieresis -70 + +KPX Ocircumflex comma -40 + +KPX Ocircumflex period -40 + +KPX Odieresis A -50 + +KPX Odieresis Aacute -50 + +KPX Odieresis Abreve -50 + +KPX Odieresis Acircumflex -50 + +KPX Odieresis Adieresis -50 + +KPX Odieresis Agrave -50 + +KPX Odieresis Amacron -50 + +KPX Odieresis Aogonek -50 + +KPX Odieresis Aring -50 + +KPX Odieresis Atilde -50 + +KPX Odieresis T -40 + +KPX Odieresis Tcaron -40 + +KPX Odieresis Tcommaaccent -40 + +KPX Odieresis V -50 + +KPX Odieresis W -50 + +KPX Odieresis X -50 + +KPX Odieresis Y -70 + +KPX Odieresis Yacute -70 + +KPX Odieresis Ydieresis -70 + +KPX Odieresis comma -40 + +KPX Odieresis period -40 + +KPX Ograve A -50 + +KPX Ograve Aacute -50 + +KPX Ograve Abreve -50 + +KPX Ograve Acircumflex -50 + +KPX Ograve Adieresis -50 + +KPX Ograve Agrave -50 + +KPX Ograve Amacron -50 + +KPX Ograve Aogonek -50 + +KPX Ograve Aring -50 + +KPX Ograve Atilde -50 + +KPX Ograve T -40 + +KPX Ograve Tcaron -40 + +KPX Ograve Tcommaaccent -40 + +KPX Ograve V -50 + +KPX Ograve W -50 + +KPX Ograve X -50 + +KPX Ograve Y -70 + +KPX Ograve Yacute -70 + +KPX Ograve Ydieresis -70 + +KPX Ograve comma -40 + +KPX Ograve period -40 + +KPX Ohungarumlaut A -50 + +KPX Ohungarumlaut Aacute -50 + +KPX Ohungarumlaut Abreve -50 + +KPX Ohungarumlaut Acircumflex -50 + +KPX Ohungarumlaut Adieresis -50 + +KPX Ohungarumlaut Agrave -50 + +KPX Ohungarumlaut Amacron -50 + +KPX Ohungarumlaut Aogonek -50 + +KPX Ohungarumlaut Aring -50 + +KPX Ohungarumlaut Atilde -50 + +KPX Ohungarumlaut T -40 + +KPX Ohungarumlaut Tcaron -40 + +KPX Ohungarumlaut Tcommaaccent -40 + +KPX Ohungarumlaut V -50 + +KPX Ohungarumlaut W -50 + +KPX Ohungarumlaut X -50 + +KPX Ohungarumlaut Y -70 + +KPX Ohungarumlaut Yacute -70 + +KPX Ohungarumlaut Ydieresis -70 + +KPX Ohungarumlaut comma -40 + +KPX Ohungarumlaut period -40 + +KPX Omacron A -50 + +KPX Omacron Aacute -50 + +KPX Omacron Abreve -50 + +KPX Omacron Acircumflex -50 + +KPX Omacron Adieresis -50 + +KPX Omacron Agrave -50 + +KPX Omacron Amacron -50 + +KPX Omacron Aogonek -50 + +KPX Omacron Aring -50 + +KPX Omacron Atilde -50 + +KPX Omacron T -40 + +KPX Omacron Tcaron -40 + +KPX Omacron Tcommaaccent -40 + +KPX Omacron V -50 + +KPX Omacron W -50 + +KPX Omacron X -50 + +KPX Omacron Y -70 + +KPX Omacron Yacute -70 + +KPX Omacron Ydieresis -70 + +KPX Omacron comma -40 + +KPX Omacron period -40 + +KPX Oslash A -50 + +KPX Oslash Aacute -50 + +KPX Oslash Abreve -50 + +KPX Oslash Acircumflex -50 + +KPX Oslash Adieresis -50 + +KPX Oslash Agrave -50 + +KPX Oslash Amacron -50 + +KPX Oslash Aogonek -50 + +KPX Oslash Aring -50 + +KPX Oslash Atilde -50 + +KPX Oslash T -40 + +KPX Oslash Tcaron -40 + +KPX Oslash Tcommaaccent -40 + +KPX Oslash V -50 + +KPX Oslash W -50 + +KPX Oslash X -50 + +KPX Oslash Y -70 + +KPX Oslash Yacute -70 + +KPX Oslash Ydieresis -70 + +KPX Oslash comma -40 + +KPX Oslash period -40 + +KPX Otilde A -50 + +KPX Otilde Aacute -50 + +KPX Otilde Abreve -50 + +KPX Otilde Acircumflex -50 + +KPX Otilde Adieresis -50 + +KPX Otilde Agrave -50 + +KPX Otilde Amacron -50 + +KPX Otilde Aogonek -50 + +KPX Otilde Aring -50 + +KPX Otilde Atilde -50 + +KPX Otilde T -40 + +KPX Otilde Tcaron -40 + +KPX Otilde Tcommaaccent -40 + +KPX Otilde V -50 + +KPX Otilde W -50 + +KPX Otilde X -50 + +KPX Otilde Y -70 + +KPX Otilde Yacute -70 + +KPX Otilde Ydieresis -70 + +KPX Otilde comma -40 + +KPX Otilde period -40 + +KPX P A -100 + +KPX P Aacute -100 + +KPX P Abreve -100 + +KPX P Acircumflex -100 + +KPX P Adieresis -100 + +KPX P Agrave -100 + +KPX P Amacron -100 + +KPX P Aogonek -100 + +KPX P Aring -100 + +KPX P Atilde -100 + +KPX P a -30 + +KPX P aacute -30 + +KPX P abreve -30 + +KPX P acircumflex -30 + +KPX P adieresis -30 + +KPX P agrave -30 + +KPX P amacron -30 + +KPX P aogonek -30 + +KPX P aring -30 + +KPX P atilde -30 + +KPX P comma -120 + +KPX P e -30 + +KPX P eacute -30 + +KPX P ecaron -30 + +KPX P ecircumflex -30 + +KPX P edieresis -30 + +KPX P edotaccent -30 + +KPX P egrave -30 + +KPX P emacron -30 + +KPX P eogonek -30 + +KPX P o -40 + +KPX P oacute -40 + +KPX P ocircumflex -40 + +KPX P odieresis -40 + +KPX P ograve -40 + +KPX P ohungarumlaut -40 + +KPX P omacron -40 + +KPX P oslash -40 + +KPX P otilde -40 + +KPX P period -120 + +KPX Q U -10 + +KPX Q Uacute -10 + +KPX Q Ucircumflex -10 + +KPX Q Udieresis -10 + +KPX Q Ugrave -10 + +KPX Q Uhungarumlaut -10 + +KPX Q Umacron -10 + +KPX Q Uogonek -10 + +KPX Q Uring -10 + +KPX Q comma 20 + +KPX Q period 20 + +KPX R O -20 + +KPX R Oacute -20 + +KPX R Ocircumflex -20 + +KPX R Odieresis -20 + +KPX R Ograve -20 + +KPX R Ohungarumlaut -20 + +KPX R Omacron -20 + +KPX R Oslash -20 + +KPX R Otilde -20 + +KPX R T -20 + +KPX R Tcaron -20 + +KPX R Tcommaaccent -20 + +KPX R U -20 + +KPX R Uacute -20 + +KPX R Ucircumflex -20 + +KPX R Udieresis -20 + +KPX R Ugrave -20 + +KPX R Uhungarumlaut -20 + +KPX R Umacron -20 + +KPX R Uogonek -20 + +KPX R Uring -20 + +KPX R V -50 + +KPX R W -40 + +KPX R Y -50 + +KPX R Yacute -50 + +KPX R Ydieresis -50 + +KPX Racute O -20 + +KPX Racute Oacute -20 + +KPX Racute Ocircumflex -20 + +KPX Racute Odieresis -20 + +KPX Racute Ograve -20 + +KPX Racute Ohungarumlaut -20 + +KPX Racute Omacron -20 + +KPX Racute Oslash -20 + +KPX Racute Otilde -20 + +KPX Racute T -20 + +KPX Racute Tcaron -20 + +KPX Racute Tcommaaccent -20 + +KPX Racute U -20 + +KPX Racute Uacute -20 + +KPX Racute Ucircumflex -20 + +KPX Racute Udieresis -20 + +KPX Racute Ugrave -20 + +KPX Racute Uhungarumlaut -20 + +KPX Racute Umacron -20 + +KPX Racute Uogonek -20 + +KPX Racute Uring -20 + +KPX Racute V -50 + +KPX Racute W -40 + +KPX Racute Y -50 + +KPX Racute Yacute -50 + +KPX Racute Ydieresis -50 + +KPX Rcaron O -20 + +KPX Rcaron Oacute -20 + +KPX Rcaron Ocircumflex -20 + +KPX Rcaron Odieresis -20 + +KPX Rcaron Ograve -20 + +KPX Rcaron Ohungarumlaut -20 + +KPX Rcaron Omacron -20 + +KPX Rcaron Oslash -20 + +KPX Rcaron Otilde -20 + +KPX Rcaron T -20 + +KPX Rcaron Tcaron -20 + +KPX Rcaron Tcommaaccent -20 + +KPX Rcaron U -20 + +KPX Rcaron Uacute -20 + +KPX Rcaron Ucircumflex -20 + +KPX Rcaron Udieresis -20 + +KPX Rcaron Ugrave -20 + +KPX Rcaron Uhungarumlaut -20 + +KPX Rcaron Umacron -20 + +KPX Rcaron Uogonek -20 + +KPX Rcaron Uring -20 + +KPX Rcaron V -50 + +KPX Rcaron W -40 + +KPX Rcaron Y -50 + +KPX Rcaron Yacute -50 + +KPX Rcaron Ydieresis -50 + +KPX Rcommaaccent O -20 + +KPX Rcommaaccent Oacute -20 + +KPX Rcommaaccent Ocircumflex -20 + +KPX Rcommaaccent Odieresis -20 + +KPX Rcommaaccent Ograve -20 + +KPX Rcommaaccent Ohungarumlaut -20 + +KPX Rcommaaccent Omacron -20 + +KPX Rcommaaccent Oslash -20 + +KPX Rcommaaccent Otilde -20 + +KPX Rcommaaccent T -20 + +KPX Rcommaaccent Tcaron -20 + +KPX Rcommaaccent Tcommaaccent -20 + +KPX Rcommaaccent U -20 + +KPX Rcommaaccent Uacute -20 + +KPX Rcommaaccent Ucircumflex -20 + +KPX Rcommaaccent Udieresis -20 + +KPX Rcommaaccent Ugrave -20 + +KPX Rcommaaccent Uhungarumlaut -20 + +KPX Rcommaaccent Umacron -20 + +KPX Rcommaaccent Uogonek -20 + +KPX Rcommaaccent Uring -20 + +KPX Rcommaaccent V -50 + +KPX Rcommaaccent W -40 + +KPX Rcommaaccent Y -50 + +KPX Rcommaaccent Yacute -50 + +KPX Rcommaaccent Ydieresis -50 + +KPX T A -90 + +KPX T Aacute -90 + +KPX T Abreve -90 + +KPX T Acircumflex -90 + +KPX T Adieresis -90 + +KPX T Agrave -90 + +KPX T Amacron -90 + +KPX T Aogonek -90 + +KPX T Aring -90 + +KPX T Atilde -90 + +KPX T O -40 + +KPX T Oacute -40 + +KPX T Ocircumflex -40 + +KPX T Odieresis -40 + +KPX T Ograve -40 + +KPX T Ohungarumlaut -40 + +KPX T Omacron -40 + +KPX T Oslash -40 + +KPX T Otilde -40 + +KPX T a -80 + +KPX T aacute -80 + +KPX T abreve -80 + +KPX T acircumflex -80 + +KPX T adieresis -80 + +KPX T agrave -80 + +KPX T amacron -80 + +KPX T aogonek -80 + +KPX T aring -80 + +KPX T atilde -80 + +KPX T colon -40 + +KPX T comma -80 + +KPX T e -60 + +KPX T eacute -60 + +KPX T ecaron -60 + +KPX T ecircumflex -60 + +KPX T edieresis -60 + +KPX T edotaccent -60 + +KPX T egrave -60 + +KPX T emacron -60 + +KPX T eogonek -60 + +KPX T hyphen -120 + +KPX T o -80 + +KPX T oacute -80 + +KPX T ocircumflex -80 + +KPX T odieresis -80 + +KPX T ograve -80 + +KPX T ohungarumlaut -80 + +KPX T omacron -80 + +KPX T oslash -80 + +KPX T otilde -80 + +KPX T period -80 + +KPX T r -80 + +KPX T racute -80 + +KPX T rcommaaccent -80 + +KPX T semicolon -40 + +KPX T u -90 + +KPX T uacute -90 + +KPX T ucircumflex -90 + +KPX T udieresis -90 + +KPX T ugrave -90 + +KPX T uhungarumlaut -90 + +KPX T umacron -90 + +KPX T uogonek -90 + +KPX T uring -90 + +KPX T w -60 + +KPX T y -60 + +KPX T yacute -60 + +KPX T ydieresis -60 + +KPX Tcaron A -90 + +KPX Tcaron Aacute -90 + +KPX Tcaron Abreve -90 + +KPX Tcaron Acircumflex -90 + +KPX Tcaron Adieresis -90 + +KPX Tcaron Agrave -90 + +KPX Tcaron Amacron -90 + +KPX Tcaron Aogonek -90 + +KPX Tcaron Aring -90 + +KPX Tcaron Atilde -90 + +KPX Tcaron O -40 + +KPX Tcaron Oacute -40 + +KPX Tcaron Ocircumflex -40 + +KPX Tcaron Odieresis -40 + +KPX Tcaron Ograve -40 + +KPX Tcaron Ohungarumlaut -40 + +KPX Tcaron Omacron -40 + +KPX Tcaron Oslash -40 + +KPX Tcaron Otilde -40 + +KPX Tcaron a -80 + +KPX Tcaron aacute -80 + +KPX Tcaron abreve -80 + +KPX Tcaron acircumflex -80 + +KPX Tcaron adieresis -80 + +KPX Tcaron agrave -80 + +KPX Tcaron amacron -80 + +KPX Tcaron aogonek -80 + +KPX Tcaron aring -80 + +KPX Tcaron atilde -80 + +KPX Tcaron colon -40 + +KPX Tcaron comma -80 + +KPX Tcaron e -60 + +KPX Tcaron eacute -60 + +KPX Tcaron ecaron -60 + +KPX Tcaron ecircumflex -60 + +KPX Tcaron edieresis -60 + +KPX Tcaron edotaccent -60 + +KPX Tcaron egrave -60 + +KPX Tcaron emacron -60 + +KPX Tcaron eogonek -60 + +KPX Tcaron hyphen -120 + +KPX Tcaron o -80 + +KPX Tcaron oacute -80 + +KPX Tcaron ocircumflex -80 + +KPX Tcaron odieresis -80 + +KPX Tcaron ograve -80 + +KPX Tcaron ohungarumlaut -80 + +KPX Tcaron omacron -80 + +KPX Tcaron oslash -80 + +KPX Tcaron otilde -80 + +KPX Tcaron period -80 + +KPX Tcaron r -80 + +KPX Tcaron racute -80 + +KPX Tcaron rcommaaccent -80 + +KPX Tcaron semicolon -40 + +KPX Tcaron u -90 + +KPX Tcaron uacute -90 + +KPX Tcaron ucircumflex -90 + +KPX Tcaron udieresis -90 + +KPX Tcaron ugrave -90 + +KPX Tcaron uhungarumlaut -90 + +KPX Tcaron umacron -90 + +KPX Tcaron uogonek -90 + +KPX Tcaron uring -90 + +KPX Tcaron w -60 + +KPX Tcaron y -60 + +KPX Tcaron yacute -60 + +KPX Tcaron ydieresis -60 + +KPX Tcommaaccent A -90 + +KPX Tcommaaccent Aacute -90 + +KPX Tcommaaccent Abreve -90 + +KPX Tcommaaccent Acircumflex -90 + +KPX Tcommaaccent Adieresis -90 + +KPX Tcommaaccent Agrave -90 + +KPX Tcommaaccent Amacron -90 + +KPX Tcommaaccent Aogonek -90 + +KPX Tcommaaccent Aring -90 + +KPX Tcommaaccent Atilde -90 + +KPX Tcommaaccent O -40 + +KPX Tcommaaccent Oacute -40 + +KPX Tcommaaccent Ocircumflex -40 + +KPX Tcommaaccent Odieresis -40 + +KPX Tcommaaccent Ograve -40 + +KPX Tcommaaccent Ohungarumlaut -40 + +KPX Tcommaaccent Omacron -40 + +KPX Tcommaaccent Oslash -40 + +KPX Tcommaaccent Otilde -40 + +KPX Tcommaaccent a -80 + +KPX Tcommaaccent aacute -80 + +KPX Tcommaaccent abreve -80 + +KPX Tcommaaccent acircumflex -80 + +KPX Tcommaaccent adieresis -80 + +KPX Tcommaaccent agrave -80 + +KPX Tcommaaccent amacron -80 + +KPX Tcommaaccent aogonek -80 + +KPX Tcommaaccent aring -80 + +KPX Tcommaaccent atilde -80 + +KPX Tcommaaccent colon -40 + +KPX Tcommaaccent comma -80 + +KPX Tcommaaccent e -60 + +KPX Tcommaaccent eacute -60 + +KPX Tcommaaccent ecaron -60 + +KPX Tcommaaccent ecircumflex -60 + +KPX Tcommaaccent edieresis -60 + +KPX Tcommaaccent edotaccent -60 + +KPX Tcommaaccent egrave -60 + +KPX Tcommaaccent emacron -60 + +KPX Tcommaaccent eogonek -60 + +KPX Tcommaaccent hyphen -120 + +KPX Tcommaaccent o -80 + +KPX Tcommaaccent oacute -80 + +KPX Tcommaaccent ocircumflex -80 + +KPX Tcommaaccent odieresis -80 + +KPX Tcommaaccent ograve -80 + +KPX Tcommaaccent ohungarumlaut -80 + +KPX Tcommaaccent omacron -80 + +KPX Tcommaaccent oslash -80 + +KPX Tcommaaccent otilde -80 + +KPX Tcommaaccent period -80 + +KPX Tcommaaccent r -80 + +KPX Tcommaaccent racute -80 + +KPX Tcommaaccent rcommaaccent -80 + +KPX Tcommaaccent semicolon -40 + +KPX Tcommaaccent u -90 + +KPX Tcommaaccent uacute -90 + +KPX Tcommaaccent ucircumflex -90 + +KPX Tcommaaccent udieresis -90 + +KPX Tcommaaccent ugrave -90 + +KPX Tcommaaccent uhungarumlaut -90 + +KPX Tcommaaccent umacron -90 + +KPX Tcommaaccent uogonek -90 + +KPX Tcommaaccent uring -90 + +KPX Tcommaaccent w -60 + +KPX Tcommaaccent y -60 + +KPX Tcommaaccent yacute -60 + +KPX Tcommaaccent ydieresis -60 + +KPX U A -50 + +KPX U Aacute -50 + +KPX U Abreve -50 + +KPX U Acircumflex -50 + +KPX U Adieresis -50 + +KPX U Agrave -50 + +KPX U Amacron -50 + +KPX U Aogonek -50 + +KPX U Aring -50 + +KPX U Atilde -50 + +KPX U comma -30 + +KPX U period -30 + +KPX Uacute A -50 + +KPX Uacute Aacute -50 + +KPX Uacute Abreve -50 + +KPX Uacute Acircumflex -50 + +KPX Uacute Adieresis -50 + +KPX Uacute Agrave -50 + +KPX Uacute Amacron -50 + +KPX Uacute Aogonek -50 + +KPX Uacute Aring -50 + +KPX Uacute Atilde -50 + +KPX Uacute comma -30 + +KPX Uacute period -30 + +KPX Ucircumflex A -50 + +KPX Ucircumflex Aacute -50 + +KPX Ucircumflex Abreve -50 + +KPX Ucircumflex Acircumflex -50 + +KPX Ucircumflex Adieresis -50 + +KPX Ucircumflex Agrave -50 + +KPX Ucircumflex Amacron -50 + +KPX Ucircumflex Aogonek -50 + +KPX Ucircumflex Aring -50 + +KPX Ucircumflex Atilde -50 + +KPX Ucircumflex comma -30 + +KPX Ucircumflex period -30 + +KPX Udieresis A -50 + +KPX Udieresis Aacute -50 + +KPX Udieresis Abreve -50 + +KPX Udieresis Acircumflex -50 + +KPX Udieresis Adieresis -50 + +KPX Udieresis Agrave -50 + +KPX Udieresis Amacron -50 + +KPX Udieresis Aogonek -50 + +KPX Udieresis Aring -50 + +KPX Udieresis Atilde -50 + +KPX Udieresis comma -30 + +KPX Udieresis period -30 + +KPX Ugrave A -50 + +KPX Ugrave Aacute -50 + +KPX Ugrave Abreve -50 + +KPX Ugrave Acircumflex -50 + +KPX Ugrave Adieresis -50 + +KPX Ugrave Agrave -50 + +KPX Ugrave Amacron -50 + +KPX Ugrave Aogonek -50 + +KPX Ugrave Aring -50 + +KPX Ugrave Atilde -50 + +KPX Ugrave comma -30 + +KPX Ugrave period -30 + +KPX Uhungarumlaut A -50 + +KPX Uhungarumlaut Aacute -50 + +KPX Uhungarumlaut Abreve -50 + +KPX Uhungarumlaut Acircumflex -50 + +KPX Uhungarumlaut Adieresis -50 + +KPX Uhungarumlaut Agrave -50 + +KPX Uhungarumlaut Amacron -50 + +KPX Uhungarumlaut Aogonek -50 + +KPX Uhungarumlaut Aring -50 + +KPX Uhungarumlaut Atilde -50 + +KPX Uhungarumlaut comma -30 + +KPX Uhungarumlaut period -30 + +KPX Umacron A -50 + +KPX Umacron Aacute -50 + +KPX Umacron Abreve -50 + +KPX Umacron Acircumflex -50 + +KPX Umacron Adieresis -50 + +KPX Umacron Agrave -50 + +KPX Umacron Amacron -50 + +KPX Umacron Aogonek -50 + +KPX Umacron Aring -50 + +KPX Umacron Atilde -50 + +KPX Umacron comma -30 + +KPX Umacron period -30 + +KPX Uogonek A -50 + +KPX Uogonek Aacute -50 + +KPX Uogonek Abreve -50 + +KPX Uogonek Acircumflex -50 + +KPX Uogonek Adieresis -50 + +KPX Uogonek Agrave -50 + +KPX Uogonek Amacron -50 + +KPX Uogonek Aogonek -50 + +KPX Uogonek Aring -50 + +KPX Uogonek Atilde -50 + +KPX Uogonek comma -30 + +KPX Uogonek period -30 + +KPX Uring A -50 + +KPX Uring Aacute -50 + +KPX Uring Abreve -50 + +KPX Uring Acircumflex -50 + +KPX Uring Adieresis -50 + +KPX Uring Agrave -50 + +KPX Uring Amacron -50 + +KPX Uring Aogonek -50 + +KPX Uring Aring -50 + +KPX Uring Atilde -50 + +KPX Uring comma -30 + +KPX Uring period -30 + +KPX V A -80 + +KPX V Aacute -80 + +KPX V Abreve -80 + +KPX V Acircumflex -80 + +KPX V Adieresis -80 + +KPX V Agrave -80 + +KPX V Amacron -80 + +KPX V Aogonek -80 + +KPX V Aring -80 + +KPX V Atilde -80 + +KPX V G -50 + +KPX V Gbreve -50 + +KPX V Gcommaaccent -50 + +KPX V O -50 + +KPX V Oacute -50 + +KPX V Ocircumflex -50 + +KPX V Odieresis -50 + +KPX V Ograve -50 + +KPX V Ohungarumlaut -50 + +KPX V Omacron -50 + +KPX V Oslash -50 + +KPX V Otilde -50 + +KPX V a -60 + +KPX V aacute -60 + +KPX V abreve -60 + +KPX V acircumflex -60 + +KPX V adieresis -60 + +KPX V agrave -60 + +KPX V amacron -60 + +KPX V aogonek -60 + +KPX V aring -60 + +KPX V atilde -60 + +KPX V colon -40 + +KPX V comma -120 + +KPX V e -50 + +KPX V eacute -50 + +KPX V ecaron -50 + +KPX V ecircumflex -50 + +KPX V edieresis -50 + +KPX V edotaccent -50 + +KPX V egrave -50 + +KPX V emacron -50 + +KPX V eogonek -50 + +KPX V hyphen -80 + +KPX V o -90 + +KPX V oacute -90 + +KPX V ocircumflex -90 + +KPX V odieresis -90 + +KPX V ograve -90 + +KPX V ohungarumlaut -90 + +KPX V omacron -90 + +KPX V oslash -90 + +KPX V otilde -90 + +KPX V period -120 + +KPX V semicolon -40 + +KPX V u -60 + +KPX V uacute -60 + +KPX V ucircumflex -60 + +KPX V udieresis -60 + +KPX V ugrave -60 + +KPX V uhungarumlaut -60 + +KPX V umacron -60 + +KPX V uogonek -60 + +KPX V uring -60 + +KPX W A -60 + +KPX W Aacute -60 + +KPX W Abreve -60 + +KPX W Acircumflex -60 + +KPX W Adieresis -60 + +KPX W Agrave -60 + +KPX W Amacron -60 + +KPX W Aogonek -60 + +KPX W Aring -60 + +KPX W Atilde -60 + +KPX W O -20 + +KPX W Oacute -20 + +KPX W Ocircumflex -20 + +KPX W Odieresis -20 + +KPX W Ograve -20 + +KPX W Ohungarumlaut -20 + +KPX W Omacron -20 + +KPX W Oslash -20 + +KPX W Otilde -20 + +KPX W a -40 + +KPX W aacute -40 + +KPX W abreve -40 + +KPX W acircumflex -40 + +KPX W adieresis -40 + +KPX W agrave -40 + +KPX W amacron -40 + +KPX W aogonek -40 + +KPX W aring -40 + +KPX W atilde -40 + +KPX W colon -10 + +KPX W comma -80 + +KPX W e -35 + +KPX W eacute -35 + +KPX W ecaron -35 + +KPX W ecircumflex -35 + +KPX W edieresis -35 + +KPX W edotaccent -35 + +KPX W egrave -35 + +KPX W emacron -35 + +KPX W eogonek -35 + +KPX W hyphen -40 + +KPX W o -60 + +KPX W oacute -60 + +KPX W ocircumflex -60 + +KPX W odieresis -60 + +KPX W ograve -60 + +KPX W ohungarumlaut -60 + +KPX W omacron -60 + +KPX W oslash -60 + +KPX W otilde -60 + +KPX W period -80 + +KPX W semicolon -10 + +KPX W u -45 + +KPX W uacute -45 + +KPX W ucircumflex -45 + +KPX W udieresis -45 + +KPX W ugrave -45 + +KPX W uhungarumlaut -45 + +KPX W umacron -45 + +KPX W uogonek -45 + +KPX W uring -45 + +KPX W y -20 + +KPX W yacute -20 + +KPX W ydieresis -20 + +KPX Y A -110 + +KPX Y Aacute -110 + +KPX Y Abreve -110 + +KPX Y Acircumflex -110 + +KPX Y Adieresis -110 + +KPX Y Agrave -110 + +KPX Y Amacron -110 + +KPX Y Aogonek -110 + +KPX Y Aring -110 + +KPX Y Atilde -110 + +KPX Y O -70 + +KPX Y Oacute -70 + +KPX Y Ocircumflex -70 + +KPX Y Odieresis -70 + +KPX Y Ograve -70 + +KPX Y Ohungarumlaut -70 + +KPX Y Omacron -70 + +KPX Y Oslash -70 + +KPX Y Otilde -70 + +KPX Y a -90 + +KPX Y aacute -90 + +KPX Y abreve -90 + +KPX Y acircumflex -90 + +KPX Y adieresis -90 + +KPX Y agrave -90 + +KPX Y amacron -90 + +KPX Y aogonek -90 + +KPX Y aring -90 + +KPX Y atilde -90 + +KPX Y colon -50 + +KPX Y comma -100 + +KPX Y e -80 + +KPX Y eacute -80 + +KPX Y ecaron -80 + +KPX Y ecircumflex -80 + +KPX Y edieresis -80 + +KPX Y edotaccent -80 + +KPX Y egrave -80 + +KPX Y emacron -80 + +KPX Y eogonek -80 + +KPX Y o -100 + +KPX Y oacute -100 + +KPX Y ocircumflex -100 + +KPX Y odieresis -100 + +KPX Y ograve -100 + +KPX Y ohungarumlaut -100 + +KPX Y omacron -100 + +KPX Y oslash -100 + +KPX Y otilde -100 + +KPX Y period -100 + +KPX Y semicolon -50 + +KPX Y u -100 + +KPX Y uacute -100 + +KPX Y ucircumflex -100 + +KPX Y udieresis -100 + +KPX Y ugrave -100 + +KPX Y uhungarumlaut -100 + +KPX Y umacron -100 + +KPX Y uogonek -100 + +KPX Y uring -100 + +KPX Yacute A -110 + +KPX Yacute Aacute -110 + +KPX Yacute Abreve -110 + +KPX Yacute Acircumflex -110 + +KPX Yacute Adieresis -110 + +KPX Yacute Agrave -110 + +KPX Yacute Amacron -110 + +KPX Yacute Aogonek -110 + +KPX Yacute Aring -110 + +KPX Yacute Atilde -110 + +KPX Yacute O -70 + +KPX Yacute Oacute -70 + +KPX Yacute Ocircumflex -70 + +KPX Yacute Odieresis -70 + +KPX Yacute Ograve -70 + +KPX Yacute Ohungarumlaut -70 + +KPX Yacute Omacron -70 + +KPX Yacute Oslash -70 + +KPX Yacute Otilde -70 + +KPX Yacute a -90 + +KPX Yacute aacute -90 + +KPX Yacute abreve -90 + +KPX Yacute acircumflex -90 + +KPX Yacute adieresis -90 + +KPX Yacute agrave -90 + +KPX Yacute amacron -90 + +KPX Yacute aogonek -90 + +KPX Yacute aring -90 + +KPX Yacute atilde -90 + +KPX Yacute colon -50 + +KPX Yacute comma -100 + +KPX Yacute e -80 + +KPX Yacute eacute -80 + +KPX Yacute ecaron -80 + +KPX Yacute ecircumflex -80 + +KPX Yacute edieresis -80 + +KPX Yacute edotaccent -80 + +KPX Yacute egrave -80 + +KPX Yacute emacron -80 + +KPX Yacute eogonek -80 + +KPX Yacute o -100 + +KPX Yacute oacute -100 + +KPX Yacute ocircumflex -100 + +KPX Yacute odieresis -100 + +KPX Yacute ograve -100 + +KPX Yacute ohungarumlaut -100 + +KPX Yacute omacron -100 + +KPX Yacute oslash -100 + +KPX Yacute otilde -100 + +KPX Yacute period -100 + +KPX Yacute semicolon -50 + +KPX Yacute u -100 + +KPX Yacute uacute -100 + +KPX Yacute ucircumflex -100 + +KPX Yacute udieresis -100 + +KPX Yacute ugrave -100 + +KPX Yacute uhungarumlaut -100 + +KPX Yacute umacron -100 + +KPX Yacute uogonek -100 + +KPX Yacute uring -100 + +KPX Ydieresis A -110 + +KPX Ydieresis Aacute -110 + +KPX Ydieresis Abreve -110 + +KPX Ydieresis Acircumflex -110 + +KPX Ydieresis Adieresis -110 + +KPX Ydieresis Agrave -110 + +KPX Ydieresis Amacron -110 + +KPX Ydieresis Aogonek -110 + +KPX Ydieresis Aring -110 + +KPX Ydieresis Atilde -110 + +KPX Ydieresis O -70 + +KPX Ydieresis Oacute -70 + +KPX Ydieresis Ocircumflex -70 + +KPX Ydieresis Odieresis -70 + +KPX Ydieresis Ograve -70 + +KPX Ydieresis Ohungarumlaut -70 + +KPX Ydieresis Omacron -70 + +KPX Ydieresis Oslash -70 + +KPX Ydieresis Otilde -70 + +KPX Ydieresis a -90 + +KPX Ydieresis aacute -90 + +KPX Ydieresis abreve -90 + +KPX Ydieresis acircumflex -90 + +KPX Ydieresis adieresis -90 + +KPX Ydieresis agrave -90 + +KPX Ydieresis amacron -90 + +KPX Ydieresis aogonek -90 + +KPX Ydieresis aring -90 + +KPX Ydieresis atilde -90 + +KPX Ydieresis colon -50 + +KPX Ydieresis comma -100 + +KPX Ydieresis e -80 + +KPX Ydieresis eacute -80 + +KPX Ydieresis ecaron -80 + +KPX Ydieresis ecircumflex -80 + +KPX Ydieresis edieresis -80 + +KPX Ydieresis edotaccent -80 + +KPX Ydieresis egrave -80 + +KPX Ydieresis emacron -80 + +KPX Ydieresis eogonek -80 + +KPX Ydieresis o -100 + +KPX Ydieresis oacute -100 + +KPX Ydieresis ocircumflex -100 + +KPX Ydieresis odieresis -100 + +KPX Ydieresis ograve -100 + +KPX Ydieresis ohungarumlaut -100 + +KPX Ydieresis omacron -100 + +KPX Ydieresis oslash -100 + +KPX Ydieresis otilde -100 + +KPX Ydieresis period -100 + +KPX Ydieresis semicolon -50 + +KPX Ydieresis u -100 + +KPX Ydieresis uacute -100 + +KPX Ydieresis ucircumflex -100 + +KPX Ydieresis udieresis -100 + +KPX Ydieresis ugrave -100 + +KPX Ydieresis uhungarumlaut -100 + +KPX Ydieresis umacron -100 + +KPX Ydieresis uogonek -100 + +KPX Ydieresis uring -100 + +KPX a g -10 + +KPX a gbreve -10 + +KPX a gcommaaccent -10 + +KPX a v -15 + +KPX a w -15 + +KPX a y -20 + +KPX a yacute -20 + +KPX a ydieresis -20 + +KPX aacute g -10 + +KPX aacute gbreve -10 + +KPX aacute gcommaaccent -10 + +KPX aacute v -15 + +KPX aacute w -15 + +KPX aacute y -20 + +KPX aacute yacute -20 + +KPX aacute ydieresis -20 + +KPX abreve g -10 + +KPX abreve gbreve -10 + +KPX abreve gcommaaccent -10 + +KPX abreve v -15 + +KPX abreve w -15 + +KPX abreve y -20 + +KPX abreve yacute -20 + +KPX abreve ydieresis -20 + +KPX acircumflex g -10 + +KPX acircumflex gbreve -10 + +KPX acircumflex gcommaaccent -10 + +KPX acircumflex v -15 + +KPX acircumflex w -15 + +KPX acircumflex y -20 + +KPX acircumflex yacute -20 + +KPX acircumflex ydieresis -20 + +KPX adieresis g -10 + +KPX adieresis gbreve -10 + +KPX adieresis gcommaaccent -10 + +KPX adieresis v -15 + +KPX adieresis w -15 + +KPX adieresis y -20 + +KPX adieresis yacute -20 + +KPX adieresis ydieresis -20 + +KPX agrave g -10 + +KPX agrave gbreve -10 + +KPX agrave gcommaaccent -10 + +KPX agrave v -15 + +KPX agrave w -15 + +KPX agrave y -20 + +KPX agrave yacute -20 + +KPX agrave ydieresis -20 + +KPX amacron g -10 + +KPX amacron gbreve -10 + +KPX amacron gcommaaccent -10 + +KPX amacron v -15 + +KPX amacron w -15 + +KPX amacron y -20 + +KPX amacron yacute -20 + +KPX amacron ydieresis -20 + +KPX aogonek g -10 + +KPX aogonek gbreve -10 + +KPX aogonek gcommaaccent -10 + +KPX aogonek v -15 + +KPX aogonek w -15 + +KPX aogonek y -20 + +KPX aogonek yacute -20 + +KPX aogonek ydieresis -20 + +KPX aring g -10 + +KPX aring gbreve -10 + +KPX aring gcommaaccent -10 + +KPX aring v -15 + +KPX aring w -15 + +KPX aring y -20 + +KPX aring yacute -20 + +KPX aring ydieresis -20 + +KPX atilde g -10 + +KPX atilde gbreve -10 + +KPX atilde gcommaaccent -10 + +KPX atilde v -15 + +KPX atilde w -15 + +KPX atilde y -20 + +KPX atilde yacute -20 + +KPX atilde ydieresis -20 + +KPX b l -10 + +KPX b lacute -10 + +KPX b lcommaaccent -10 + +KPX b lslash -10 + +KPX b u -20 + +KPX b uacute -20 + +KPX b ucircumflex -20 + +KPX b udieresis -20 + +KPX b ugrave -20 + +KPX b uhungarumlaut -20 + +KPX b umacron -20 + +KPX b uogonek -20 + +KPX b uring -20 + +KPX b v -20 + +KPX b y -20 + +KPX b yacute -20 + +KPX b ydieresis -20 + +KPX c h -10 + +KPX c k -20 + +KPX c kcommaaccent -20 + +KPX c l -20 + +KPX c lacute -20 + +KPX c lcommaaccent -20 + +KPX c lslash -20 + +KPX c y -10 + +KPX c yacute -10 + +KPX c ydieresis -10 + +KPX cacute h -10 + +KPX cacute k -20 + +KPX cacute kcommaaccent -20 + +KPX cacute l -20 + +KPX cacute lacute -20 + +KPX cacute lcommaaccent -20 + +KPX cacute lslash -20 + +KPX cacute y -10 + +KPX cacute yacute -10 + +KPX cacute ydieresis -10 + +KPX ccaron h -10 + +KPX ccaron k -20 + +KPX ccaron kcommaaccent -20 + +KPX ccaron l -20 + +KPX ccaron lacute -20 + +KPX ccaron lcommaaccent -20 + +KPX ccaron lslash -20 + +KPX ccaron y -10 + +KPX ccaron yacute -10 + +KPX ccaron ydieresis -10 + +KPX ccedilla h -10 + +KPX ccedilla k -20 + +KPX ccedilla kcommaaccent -20 + +KPX ccedilla l -20 + +KPX ccedilla lacute -20 + +KPX ccedilla lcommaaccent -20 + +KPX ccedilla lslash -20 + +KPX ccedilla y -10 + +KPX ccedilla yacute -10 + +KPX ccedilla ydieresis -10 + +KPX colon space -40 + +KPX comma quotedblright -120 + +KPX comma quoteright -120 + +KPX comma space -40 + +KPX d d -10 + +KPX d dcroat -10 + +KPX d v -15 + +KPX d w -15 + +KPX d y -15 + +KPX d yacute -15 + +KPX d ydieresis -15 + +KPX dcroat d -10 + +KPX dcroat dcroat -10 + +KPX dcroat v -15 + +KPX dcroat w -15 + +KPX dcroat y -15 + +KPX dcroat yacute -15 + +KPX dcroat ydieresis -15 + +KPX e comma 10 + +KPX e period 20 + +KPX e v -15 + +KPX e w -15 + +KPX e x -15 + +KPX e y -15 + +KPX e yacute -15 + +KPX e ydieresis -15 + +KPX eacute comma 10 + +KPX eacute period 20 + +KPX eacute v -15 + +KPX eacute w -15 + +KPX eacute x -15 + +KPX eacute y -15 + +KPX eacute yacute -15 + +KPX eacute ydieresis -15 + +KPX ecaron comma 10 + +KPX ecaron period 20 + +KPX ecaron v -15 + +KPX ecaron w -15 + +KPX ecaron x -15 + +KPX ecaron y -15 + +KPX ecaron yacute -15 + +KPX ecaron ydieresis -15 + +KPX ecircumflex comma 10 + +KPX ecircumflex period 20 + +KPX ecircumflex v -15 + +KPX ecircumflex w -15 + +KPX ecircumflex x -15 + +KPX ecircumflex y -15 + +KPX ecircumflex yacute -15 + +KPX ecircumflex ydieresis -15 + +KPX edieresis comma 10 + +KPX edieresis period 20 + +KPX edieresis v -15 + +KPX edieresis w -15 + +KPX edieresis x -15 + +KPX edieresis y -15 + +KPX edieresis yacute -15 + +KPX edieresis ydieresis -15 + +KPX edotaccent comma 10 + +KPX edotaccent period 20 + +KPX edotaccent v -15 + +KPX edotaccent w -15 + +KPX edotaccent x -15 + +KPX edotaccent y -15 + +KPX edotaccent yacute -15 + +KPX edotaccent ydieresis -15 + +KPX egrave comma 10 + +KPX egrave period 20 + +KPX egrave v -15 + +KPX egrave w -15 + +KPX egrave x -15 + +KPX egrave y -15 + +KPX egrave yacute -15 + +KPX egrave ydieresis -15 + +KPX emacron comma 10 + +KPX emacron period 20 + +KPX emacron v -15 + +KPX emacron w -15 + +KPX emacron x -15 + +KPX emacron y -15 + +KPX emacron yacute -15 + +KPX emacron ydieresis -15 + +KPX eogonek comma 10 + +KPX eogonek period 20 + +KPX eogonek v -15 + +KPX eogonek w -15 + +KPX eogonek x -15 + +KPX eogonek y -15 + +KPX eogonek yacute -15 + +KPX eogonek ydieresis -15 + +KPX f comma -10 + +KPX f e -10 + +KPX f eacute -10 + +KPX f ecaron -10 + +KPX f ecircumflex -10 + +KPX f edieresis -10 + +KPX f edotaccent -10 + +KPX f egrave -10 + +KPX f emacron -10 + +KPX f eogonek -10 + +KPX f o -20 + +KPX f oacute -20 + +KPX f ocircumflex -20 + +KPX f odieresis -20 + +KPX f ograve -20 + +KPX f ohungarumlaut -20 + +KPX f omacron -20 + +KPX f oslash -20 + +KPX f otilde -20 + +KPX f period -10 + +KPX f quotedblright 30 + +KPX f quoteright 30 + +KPX g e 10 + +KPX g eacute 10 + +KPX g ecaron 10 + +KPX g ecircumflex 10 + +KPX g edieresis 10 + +KPX g edotaccent 10 + +KPX g egrave 10 + +KPX g emacron 10 + +KPX g eogonek 10 + +KPX g g -10 + +KPX g gbreve -10 + +KPX g gcommaaccent -10 + +KPX gbreve e 10 + +KPX gbreve eacute 10 + +KPX gbreve ecaron 10 + +KPX gbreve ecircumflex 10 + +KPX gbreve edieresis 10 + +KPX gbreve edotaccent 10 + +KPX gbreve egrave 10 + +KPX gbreve emacron 10 + +KPX gbreve eogonek 10 + +KPX gbreve g -10 + +KPX gbreve gbreve -10 + +KPX gbreve gcommaaccent -10 + +KPX gcommaaccent e 10 + +KPX gcommaaccent eacute 10 + +KPX gcommaaccent ecaron 10 + +KPX gcommaaccent ecircumflex 10 + +KPX gcommaaccent edieresis 10 + +KPX gcommaaccent edotaccent 10 + +KPX gcommaaccent egrave 10 + +KPX gcommaaccent emacron 10 + +KPX gcommaaccent eogonek 10 + +KPX gcommaaccent g -10 + +KPX gcommaaccent gbreve -10 + +KPX gcommaaccent gcommaaccent -10 + +KPX h y -20 + +KPX h yacute -20 + +KPX h ydieresis -20 + +KPX k o -15 + +KPX k oacute -15 + +KPX k ocircumflex -15 + +KPX k odieresis -15 + +KPX k ograve -15 + +KPX k ohungarumlaut -15 + +KPX k omacron -15 + +KPX k oslash -15 + +KPX k otilde -15 + +KPX kcommaaccent o -15 + +KPX kcommaaccent oacute -15 + +KPX kcommaaccent ocircumflex -15 + +KPX kcommaaccent odieresis -15 + +KPX kcommaaccent ograve -15 + +KPX kcommaaccent ohungarumlaut -15 + +KPX kcommaaccent omacron -15 + +KPX kcommaaccent oslash -15 + +KPX kcommaaccent otilde -15 + +KPX l w -15 + +KPX l y -15 + +KPX l yacute -15 + +KPX l ydieresis -15 + +KPX lacute w -15 + +KPX lacute y -15 + +KPX lacute yacute -15 + +KPX lacute ydieresis -15 + +KPX lcommaaccent w -15 + +KPX lcommaaccent y -15 + +KPX lcommaaccent yacute -15 + +KPX lcommaaccent ydieresis -15 + +KPX lslash w -15 + +KPX lslash y -15 + +KPX lslash yacute -15 + +KPX lslash ydieresis -15 + +KPX m u -20 + +KPX m uacute -20 + +KPX m ucircumflex -20 + +KPX m udieresis -20 + +KPX m ugrave -20 + +KPX m uhungarumlaut -20 + +KPX m umacron -20 + +KPX m uogonek -20 + +KPX m uring -20 + +KPX m y -30 + +KPX m yacute -30 + +KPX m ydieresis -30 + +KPX n u -10 + +KPX n uacute -10 + +KPX n ucircumflex -10 + +KPX n udieresis -10 + +KPX n ugrave -10 + +KPX n uhungarumlaut -10 + +KPX n umacron -10 + +KPX n uogonek -10 + +KPX n uring -10 + +KPX n v -40 + +KPX n y -20 + +KPX n yacute -20 + +KPX n ydieresis -20 + +KPX nacute u -10 + +KPX nacute uacute -10 + +KPX nacute ucircumflex -10 + +KPX nacute udieresis -10 + +KPX nacute ugrave -10 + +KPX nacute uhungarumlaut -10 + +KPX nacute umacron -10 + +KPX nacute uogonek -10 + +KPX nacute uring -10 + +KPX nacute v -40 + +KPX nacute y -20 + +KPX nacute yacute -20 + +KPX nacute ydieresis -20 + +KPX ncaron u -10 + +KPX ncaron uacute -10 + +KPX ncaron ucircumflex -10 + +KPX ncaron udieresis -10 + +KPX ncaron ugrave -10 + +KPX ncaron uhungarumlaut -10 + +KPX ncaron umacron -10 + +KPX ncaron uogonek -10 + +KPX ncaron uring -10 + +KPX ncaron v -40 + +KPX ncaron y -20 + +KPX ncaron yacute -20 + +KPX ncaron ydieresis -20 + +KPX ncommaaccent u -10 + +KPX ncommaaccent uacute -10 + +KPX ncommaaccent ucircumflex -10 + +KPX ncommaaccent udieresis -10 + +KPX ncommaaccent ugrave -10 + +KPX ncommaaccent uhungarumlaut -10 + +KPX ncommaaccent umacron -10 + +KPX ncommaaccent uogonek -10 + +KPX ncommaaccent uring -10 + +KPX ncommaaccent v -40 + +KPX ncommaaccent y -20 + +KPX ncommaaccent yacute -20 + +KPX ncommaaccent ydieresis -20 + +KPX ntilde u -10 + +KPX ntilde uacute -10 + +KPX ntilde ucircumflex -10 + +KPX ntilde udieresis -10 + +KPX ntilde ugrave -10 + +KPX ntilde uhungarumlaut -10 + +KPX ntilde umacron -10 + +KPX ntilde uogonek -10 + +KPX ntilde uring -10 + +KPX ntilde v -40 + +KPX ntilde y -20 + +KPX ntilde yacute -20 + +KPX ntilde ydieresis -20 + +KPX o v -20 + +KPX o w -15 + +KPX o x -30 + +KPX o y -20 + +KPX o yacute -20 + +KPX o ydieresis -20 + +KPX oacute v -20 + +KPX oacute w -15 + +KPX oacute x -30 + +KPX oacute y -20 + +KPX oacute yacute -20 + +KPX oacute ydieresis -20 + +KPX ocircumflex v -20 + +KPX ocircumflex w -15 + +KPX ocircumflex x -30 + +KPX ocircumflex y -20 + +KPX ocircumflex yacute -20 + +KPX ocircumflex ydieresis -20 + +KPX odieresis v -20 + +KPX odieresis w -15 + +KPX odieresis x -30 + +KPX odieresis y -20 + +KPX odieresis yacute -20 + +KPX odieresis ydieresis -20 + +KPX ograve v -20 + +KPX ograve w -15 + +KPX ograve x -30 + +KPX ograve y -20 + +KPX ograve yacute -20 + +KPX ograve ydieresis -20 + +KPX ohungarumlaut v -20 + +KPX ohungarumlaut w -15 + +KPX ohungarumlaut x -30 + +KPX ohungarumlaut y -20 + +KPX ohungarumlaut yacute -20 + +KPX ohungarumlaut ydieresis -20 + +KPX omacron v -20 + +KPX omacron w -15 + +KPX omacron x -30 + +KPX omacron y -20 + +KPX omacron yacute -20 + +KPX omacron ydieresis -20 + +KPX oslash v -20 + +KPX oslash w -15 + +KPX oslash x -30 + +KPX oslash y -20 + +KPX oslash yacute -20 + +KPX oslash ydieresis -20 + +KPX otilde v -20 + +KPX otilde w -15 + +KPX otilde x -30 + +KPX otilde y -20 + +KPX otilde yacute -20 + +KPX otilde ydieresis -20 + +KPX p y -15 + +KPX p yacute -15 + +KPX p ydieresis -15 + +KPX period quotedblright -120 + +KPX period quoteright -120 + +KPX period space -40 + +KPX quotedblright space -80 + +KPX quoteleft quoteleft -46 + +KPX quoteright d -80 + +KPX quoteright dcroat -80 + +KPX quoteright l -20 + +KPX quoteright lacute -20 + +KPX quoteright lcommaaccent -20 + +KPX quoteright lslash -20 + +KPX quoteright quoteright -46 + +KPX quoteright r -40 + +KPX quoteright racute -40 + +KPX quoteright rcaron -40 + +KPX quoteright rcommaaccent -40 + +KPX quoteright s -60 + +KPX quoteright sacute -60 + +KPX quoteright scaron -60 + +KPX quoteright scedilla -60 + +KPX quoteright scommaaccent -60 + +KPX quoteright space -80 + +KPX quoteright v -20 + +KPX r c -20 + +KPX r cacute -20 + +KPX r ccaron -20 + +KPX r ccedilla -20 + +KPX r comma -60 + +KPX r d -20 + +KPX r dcroat -20 + +KPX r g -15 + +KPX r gbreve -15 + +KPX r gcommaaccent -15 + +KPX r hyphen -20 + +KPX r o -20 + +KPX r oacute -20 + +KPX r ocircumflex -20 + +KPX r odieresis -20 + +KPX r ograve -20 + +KPX r ohungarumlaut -20 + +KPX r omacron -20 + +KPX r oslash -20 + +KPX r otilde -20 + +KPX r period -60 + +KPX r q -20 + +KPX r s -15 + +KPX r sacute -15 + +KPX r scaron -15 + +KPX r scedilla -15 + +KPX r scommaaccent -15 + +KPX r t 20 + +KPX r tcommaaccent 20 + +KPX r v 10 + +KPX r y 10 + +KPX r yacute 10 + +KPX r ydieresis 10 + +KPX racute c -20 + +KPX racute cacute -20 + +KPX racute ccaron -20 + +KPX racute ccedilla -20 + +KPX racute comma -60 + +KPX racute d -20 + +KPX racute dcroat -20 + +KPX racute g -15 + +KPX racute gbreve -15 + +KPX racute gcommaaccent -15 + +KPX racute hyphen -20 + +KPX racute o -20 + +KPX racute oacute -20 + +KPX racute ocircumflex -20 + +KPX racute odieresis -20 + +KPX racute ograve -20 + +KPX racute ohungarumlaut -20 + +KPX racute omacron -20 + +KPX racute oslash -20 + +KPX racute otilde -20 + +KPX racute period -60 + +KPX racute q -20 + +KPX racute s -15 + +KPX racute sacute -15 + +KPX racute scaron -15 + +KPX racute scedilla -15 + +KPX racute scommaaccent -15 + +KPX racute t 20 + +KPX racute tcommaaccent 20 + +KPX racute v 10 + +KPX racute y 10 + +KPX racute yacute 10 + +KPX racute ydieresis 10 + +KPX rcaron c -20 + +KPX rcaron cacute -20 + +KPX rcaron ccaron -20 + +KPX rcaron ccedilla -20 + +KPX rcaron comma -60 + +KPX rcaron d -20 + +KPX rcaron dcroat -20 + +KPX rcaron g -15 + +KPX rcaron gbreve -15 + +KPX rcaron gcommaaccent -15 + +KPX rcaron hyphen -20 + +KPX rcaron o -20 + +KPX rcaron oacute -20 + +KPX rcaron ocircumflex -20 + +KPX rcaron odieresis -20 + +KPX rcaron ograve -20 + +KPX rcaron ohungarumlaut -20 + +KPX rcaron omacron -20 + +KPX rcaron oslash -20 + +KPX rcaron otilde -20 + +KPX rcaron period -60 + +KPX rcaron q -20 + +KPX rcaron s -15 + +KPX rcaron sacute -15 + +KPX rcaron scaron -15 + +KPX rcaron scedilla -15 + +KPX rcaron scommaaccent -15 + +KPX rcaron t 20 + +KPX rcaron tcommaaccent 20 + +KPX rcaron v 10 + +KPX rcaron y 10 + +KPX rcaron yacute 10 + +KPX rcaron ydieresis 10 + +KPX rcommaaccent c -20 + +KPX rcommaaccent cacute -20 + +KPX rcommaaccent ccaron -20 + +KPX rcommaaccent ccedilla -20 + +KPX rcommaaccent comma -60 + +KPX rcommaaccent d -20 + +KPX rcommaaccent dcroat -20 + +KPX rcommaaccent g -15 + +KPX rcommaaccent gbreve -15 + +KPX rcommaaccent gcommaaccent -15 + +KPX rcommaaccent hyphen -20 + +KPX rcommaaccent o -20 + +KPX rcommaaccent oacute -20 + +KPX rcommaaccent ocircumflex -20 + +KPX rcommaaccent odieresis -20 + +KPX rcommaaccent ograve -20 + +KPX rcommaaccent ohungarumlaut -20 + +KPX rcommaaccent omacron -20 + +KPX rcommaaccent oslash -20 + +KPX rcommaaccent otilde -20 + +KPX rcommaaccent period -60 + +KPX rcommaaccent q -20 + +KPX rcommaaccent s -15 + +KPX rcommaaccent sacute -15 + +KPX rcommaaccent scaron -15 + +KPX rcommaaccent scedilla -15 + +KPX rcommaaccent scommaaccent -15 + +KPX rcommaaccent t 20 + +KPX rcommaaccent tcommaaccent 20 + +KPX rcommaaccent v 10 + +KPX rcommaaccent y 10 + +KPX rcommaaccent yacute 10 + +KPX rcommaaccent ydieresis 10 + +KPX s w -15 + +KPX sacute w -15 + +KPX scaron w -15 + +KPX scedilla w -15 + +KPX scommaaccent w -15 + +KPX semicolon space -40 + +KPX space T -100 + +KPX space Tcaron -100 + +KPX space Tcommaaccent -100 + +KPX space V -80 + +KPX space W -80 + +KPX space Y -120 + +KPX space Yacute -120 + +KPX space Ydieresis -120 + +KPX space quotedblleft -80 + +KPX space quoteleft -60 + +KPX v a -20 + +KPX v aacute -20 + +KPX v abreve -20 + +KPX v acircumflex -20 + +KPX v adieresis -20 + +KPX v agrave -20 + +KPX v amacron -20 + +KPX v aogonek -20 + +KPX v aring -20 + +KPX v atilde -20 + +KPX v comma -80 + +KPX v o -30 + +KPX v oacute -30 + +KPX v ocircumflex -30 + +KPX v odieresis -30 + +KPX v ograve -30 + +KPX v ohungarumlaut -30 + +KPX v omacron -30 + +KPX v oslash -30 + +KPX v otilde -30 + +KPX v period -80 + +KPX w comma -40 + +KPX w o -20 + +KPX w oacute -20 + +KPX w ocircumflex -20 + +KPX w odieresis -20 + +KPX w ograve -20 + +KPX w ohungarumlaut -20 + +KPX w omacron -20 + +KPX w oslash -20 + +KPX w otilde -20 + +KPX w period -40 + +KPX x e -10 + +KPX x eacute -10 + +KPX x ecaron -10 + +KPX x ecircumflex -10 + +KPX x edieresis -10 + +KPX x edotaccent -10 + +KPX x egrave -10 + +KPX x emacron -10 + +KPX x eogonek -10 + +KPX y a -30 + +KPX y aacute -30 + +KPX y abreve -30 + +KPX y acircumflex -30 + +KPX y adieresis -30 + +KPX y agrave -30 + +KPX y amacron -30 + +KPX y aogonek -30 + +KPX y aring -30 + +KPX y atilde -30 + +KPX y comma -80 + +KPX y e -10 + +KPX y eacute -10 + +KPX y ecaron -10 + +KPX y ecircumflex -10 + +KPX y edieresis -10 + +KPX y edotaccent -10 + +KPX y egrave -10 + +KPX y emacron -10 + +KPX y eogonek -10 + +KPX y o -25 + +KPX y oacute -25 + +KPX y ocircumflex -25 + +KPX y odieresis -25 + +KPX y ograve -25 + +KPX y ohungarumlaut -25 + +KPX y omacron -25 + +KPX y oslash -25 + +KPX y otilde -25 + +KPX y period -80 + +KPX yacute a -30 + +KPX yacute aacute -30 + +KPX yacute abreve -30 + +KPX yacute acircumflex -30 + +KPX yacute adieresis -30 + +KPX yacute agrave -30 + +KPX yacute amacron -30 + +KPX yacute aogonek -30 + +KPX yacute aring -30 + +KPX yacute atilde -30 + +KPX yacute comma -80 + +KPX yacute e -10 + +KPX yacute eacute -10 + +KPX yacute ecaron -10 + +KPX yacute ecircumflex -10 + +KPX yacute edieresis -10 + +KPX yacute edotaccent -10 + +KPX yacute egrave -10 + +KPX yacute emacron -10 + +KPX yacute eogonek -10 + +KPX yacute o -25 + +KPX yacute oacute -25 + +KPX yacute ocircumflex -25 + +KPX yacute odieresis -25 + +KPX yacute ograve -25 + +KPX yacute ohungarumlaut -25 + +KPX yacute omacron -25 + +KPX yacute oslash -25 + +KPX yacute otilde -25 + +KPX yacute period -80 + +KPX ydieresis a -30 + +KPX ydieresis aacute -30 + +KPX ydieresis abreve -30 + +KPX ydieresis acircumflex -30 + +KPX ydieresis adieresis -30 + +KPX ydieresis agrave -30 + +KPX ydieresis amacron -30 + +KPX ydieresis aogonek -30 + +KPX ydieresis aring -30 + +KPX ydieresis atilde -30 + +KPX ydieresis comma -80 + +KPX ydieresis e -10 + +KPX ydieresis eacute -10 + +KPX ydieresis ecaron -10 + +KPX ydieresis ecircumflex -10 + +KPX ydieresis edieresis -10 + +KPX ydieresis edotaccent -10 + +KPX ydieresis egrave -10 + +KPX ydieresis emacron -10 + +KPX ydieresis eogonek -10 + +KPX ydieresis o -25 + +KPX ydieresis oacute -25 + +KPX ydieresis ocircumflex -25 + +KPX ydieresis odieresis -25 + +KPX ydieresis ograve -25 + +KPX ydieresis ohungarumlaut -25 + +KPX ydieresis omacron -25 + +KPX ydieresis oslash -25 + +KPX ydieresis otilde -25 + +KPX ydieresis period -80 + +KPX z e 10 + +KPX z eacute 10 + +KPX z ecaron 10 + +KPX z ecircumflex 10 + +KPX z edieresis 10 + +KPX z edotaccent 10 + +KPX z egrave 10 + +KPX z emacron 10 + +KPX z eogonek 10 + +KPX zacute e 10 + +KPX zacute eacute 10 + +KPX zacute ecaron 10 + +KPX zacute ecircumflex 10 + +KPX zacute edieresis 10 + +KPX zacute edotaccent 10 + +KPX zacute egrave 10 + +KPX zacute emacron 10 + +KPX zacute eogonek 10 + +KPX zcaron e 10 + +KPX zcaron eacute 10 + +KPX zcaron ecaron 10 + +KPX zcaron ecircumflex 10 + +KPX zcaron edieresis 10 + +KPX zcaron edotaccent 10 + +KPX zcaron egrave 10 + +KPX zcaron emacron 10 + +KPX zcaron eogonek 10 + +KPX zdotaccent e 10 + +KPX zdotaccent eacute 10 + +KPX zdotaccent ecaron 10 + +KPX zdotaccent ecircumflex 10 + +KPX zdotaccent edieresis 10 + +KPX zdotaccent edotaccent 10 + +KPX zdotaccent egrave 10 + +KPX zdotaccent emacron 10 + +KPX zdotaccent eogonek 10 + +EndKernPairs + +EndKernData + +EndFontMetrics + diff --git a/src/Broadside/Fonts/Data/Afm/Helvetica-Oblique.afm b/src/Broadside/Fonts/Data/Afm/Helvetica-Oblique.afm new file mode 100644 index 00000000..170da91e --- /dev/null +++ b/src/Broadside/Fonts/Data/Afm/Helvetica-Oblique.afm @@ -0,0 +1,6102 @@ +StartFontMetrics 4.1 + +Comment Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved. + +Comment Creation Date: Thu May 1 12:44:31 1997 + +Comment UniqueID 43055 + +Comment VMusage 14960 69346 + +FontName Helvetica-Oblique + +FullName Helvetica Oblique + +FamilyName Helvetica + +Weight Medium + +ItalicAngle -12 + +IsFixedPitch false + +CharacterSet ExtendedRoman + +FontBBox -170 -225 1116 931 + +UnderlinePosition -100 + +UnderlineThickness 50 + +Version 002.000 + +Notice Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.Helvetica is a trademark of Linotype-Hell AG and/or its subsidiaries. + +EncodingScheme AdobeStandardEncoding + +CapHeight 718 + +XHeight 523 + +Ascender 718 + +Descender -207 + +StdHW 76 + +StdVW 88 + +StartCharMetrics 315 + +C 32 ; WX 278 ; N space ; B 0 0 0 0 ; + +C 33 ; WX 278 ; N exclam ; B 90 0 340 718 ; + +C 34 ; WX 355 ; N quotedbl ; B 168 463 438 718 ; + +C 35 ; WX 556 ; N numbersign ; B 73 0 631 688 ; + +C 36 ; WX 556 ; N dollar ; B 69 -115 617 775 ; + +C 37 ; WX 889 ; N percent ; B 147 -19 889 703 ; + +C 38 ; WX 667 ; N ampersand ; B 77 -15 647 718 ; + +C 39 ; WX 222 ; N quoteright ; B 151 463 310 718 ; + +C 40 ; WX 333 ; N parenleft ; B 108 -207 454 733 ; + +C 41 ; WX 333 ; N parenright ; B -9 -207 337 733 ; + +C 42 ; WX 389 ; N asterisk ; B 165 431 475 718 ; + +C 43 ; WX 584 ; N plus ; B 85 0 606 505 ; + +C 44 ; WX 278 ; N comma ; B 56 -147 214 106 ; + +C 45 ; WX 333 ; N hyphen ; B 93 232 357 322 ; + +C 46 ; WX 278 ; N period ; B 87 0 214 106 ; + +C 47 ; WX 278 ; N slash ; B -21 -19 452 737 ; + +C 48 ; WX 556 ; N zero ; B 93 -19 608 703 ; + +C 49 ; WX 556 ; N one ; B 207 0 508 703 ; + +C 50 ; WX 556 ; N two ; B 26 0 617 703 ; + +C 51 ; WX 556 ; N three ; B 75 -19 610 703 ; + +C 52 ; WX 556 ; N four ; B 61 0 576 703 ; + +C 53 ; WX 556 ; N five ; B 68 -19 621 688 ; + +C 54 ; WX 556 ; N six ; B 91 -19 615 703 ; + +C 55 ; WX 556 ; N seven ; B 137 0 669 688 ; + +C 56 ; WX 556 ; N eight ; B 74 -19 607 703 ; + +C 57 ; WX 556 ; N nine ; B 82 -19 609 703 ; + +C 58 ; WX 278 ; N colon ; B 87 0 301 516 ; + +C 59 ; WX 278 ; N semicolon ; B 56 -147 301 516 ; + +C 60 ; WX 584 ; N less ; B 94 11 641 495 ; + +C 61 ; WX 584 ; N equal ; B 63 115 628 390 ; + +C 62 ; WX 584 ; N greater ; B 50 11 597 495 ; + +C 63 ; WX 556 ; N question ; B 161 0 610 727 ; + +C 64 ; WX 1015 ; N at ; B 215 -19 965 737 ; + +C 65 ; WX 667 ; N A ; B 14 0 654 718 ; + +C 66 ; WX 667 ; N B ; B 74 0 712 718 ; + +C 67 ; WX 722 ; N C ; B 108 -19 782 737 ; + +C 68 ; WX 722 ; N D ; B 81 0 764 718 ; + +C 69 ; WX 667 ; N E ; B 86 0 762 718 ; + +C 70 ; WX 611 ; N F ; B 86 0 736 718 ; + +C 71 ; WX 778 ; N G ; B 111 -19 799 737 ; + +C 72 ; WX 722 ; N H ; B 77 0 799 718 ; + +C 73 ; WX 278 ; N I ; B 91 0 341 718 ; + +C 74 ; WX 500 ; N J ; B 47 -19 581 718 ; + +C 75 ; WX 667 ; N K ; B 76 0 808 718 ; + +C 76 ; WX 556 ; N L ; B 76 0 555 718 ; + +C 77 ; WX 833 ; N M ; B 73 0 914 718 ; + +C 78 ; WX 722 ; N N ; B 76 0 799 718 ; + +C 79 ; WX 778 ; N O ; B 105 -19 826 737 ; + +C 80 ; WX 667 ; N P ; B 86 0 737 718 ; + +C 81 ; WX 778 ; N Q ; B 105 -56 826 737 ; + +C 82 ; WX 722 ; N R ; B 88 0 773 718 ; + +C 83 ; WX 667 ; N S ; B 90 -19 713 737 ; + +C 84 ; WX 611 ; N T ; B 148 0 750 718 ; + +C 85 ; WX 722 ; N U ; B 123 -19 797 718 ; + +C 86 ; WX 667 ; N V ; B 173 0 800 718 ; + +C 87 ; WX 944 ; N W ; B 169 0 1081 718 ; + +C 88 ; WX 667 ; N X ; B 19 0 790 718 ; + +C 89 ; WX 667 ; N Y ; B 167 0 806 718 ; + +C 90 ; WX 611 ; N Z ; B 23 0 741 718 ; + +C 91 ; WX 278 ; N bracketleft ; B 21 -196 403 722 ; + +C 92 ; WX 278 ; N backslash ; B 140 -19 291 737 ; + +C 93 ; WX 278 ; N bracketright ; B -14 -196 368 722 ; + +C 94 ; WX 469 ; N asciicircum ; B 42 264 539 688 ; + +C 95 ; WX 556 ; N underscore ; B -27 -125 540 -75 ; + +C 96 ; WX 222 ; N quoteleft ; B 165 470 323 725 ; + +C 97 ; WX 556 ; N a ; B 61 -15 559 538 ; + +C 98 ; WX 556 ; N b ; B 58 -15 584 718 ; + +C 99 ; WX 500 ; N c ; B 74 -15 553 538 ; + +C 100 ; WX 556 ; N d ; B 84 -15 652 718 ; + +C 101 ; WX 556 ; N e ; B 84 -15 578 538 ; + +C 102 ; WX 278 ; N f ; B 86 0 416 728 ; L i fi ; L l fl ; + +C 103 ; WX 556 ; N g ; B 42 -220 610 538 ; + +C 104 ; WX 556 ; N h ; B 65 0 573 718 ; + +C 105 ; WX 222 ; N i ; B 67 0 308 718 ; + +C 106 ; WX 222 ; N j ; B -60 -210 308 718 ; + +C 107 ; WX 500 ; N k ; B 67 0 600 718 ; + +C 108 ; WX 222 ; N l ; B 67 0 308 718 ; + +C 109 ; WX 833 ; N m ; B 65 0 852 538 ; + +C 110 ; WX 556 ; N n ; B 65 0 573 538 ; + +C 111 ; WX 556 ; N o ; B 83 -14 585 538 ; + +C 112 ; WX 556 ; N p ; B 14 -207 584 538 ; + +C 113 ; WX 556 ; N q ; B 84 -207 605 538 ; + +C 114 ; WX 333 ; N r ; B 77 0 446 538 ; + +C 115 ; WX 500 ; N s ; B 63 -15 529 538 ; + +C 116 ; WX 278 ; N t ; B 102 -7 368 669 ; + +C 117 ; WX 556 ; N u ; B 94 -15 600 523 ; + +C 118 ; WX 500 ; N v ; B 119 0 603 523 ; + +C 119 ; WX 722 ; N w ; B 125 0 820 523 ; + +C 120 ; WX 500 ; N x ; B 11 0 594 523 ; + +C 121 ; WX 500 ; N y ; B 15 -214 600 523 ; + +C 122 ; WX 500 ; N z ; B 31 0 571 523 ; + +C 123 ; WX 334 ; N braceleft ; B 92 -196 445 722 ; + +C 124 ; WX 260 ; N bar ; B 46 -225 332 775 ; + +C 125 ; WX 334 ; N braceright ; B 0 -196 354 722 ; + +C 126 ; WX 584 ; N asciitilde ; B 111 180 580 326 ; + +C 161 ; WX 333 ; N exclamdown ; B 77 -195 326 523 ; + +C 162 ; WX 556 ; N cent ; B 95 -115 584 623 ; + +C 163 ; WX 556 ; N sterling ; B 49 -16 634 718 ; + +C 164 ; WX 167 ; N fraction ; B -170 -19 482 703 ; + +C 165 ; WX 556 ; N yen ; B 81 0 699 688 ; + +C 166 ; WX 556 ; N florin ; B -52 -207 654 737 ; + +C 167 ; WX 556 ; N section ; B 76 -191 584 737 ; + +C 168 ; WX 556 ; N currency ; B 60 99 646 603 ; + +C 169 ; WX 191 ; N quotesingle ; B 157 463 285 718 ; + +C 170 ; WX 333 ; N quotedblleft ; B 138 470 461 725 ; + +C 171 ; WX 556 ; N guillemotleft ; B 146 108 554 446 ; + +C 172 ; WX 333 ; N guilsinglleft ; B 137 108 340 446 ; + +C 173 ; WX 333 ; N guilsinglright ; B 111 108 314 446 ; + +C 174 ; WX 500 ; N fi ; B 86 0 587 728 ; + +C 175 ; WX 500 ; N fl ; B 86 0 585 728 ; + +C 177 ; WX 556 ; N endash ; B 51 240 623 313 ; + +C 178 ; WX 556 ; N dagger ; B 135 -159 622 718 ; + +C 179 ; WX 556 ; N daggerdbl ; B 52 -159 623 718 ; + +C 180 ; WX 278 ; N periodcentered ; B 129 190 257 315 ; + +C 182 ; WX 537 ; N paragraph ; B 126 -173 650 718 ; + +C 183 ; WX 350 ; N bullet ; B 91 202 413 517 ; + +C 184 ; WX 222 ; N quotesinglbase ; B 21 -149 180 106 ; + +C 185 ; WX 333 ; N quotedblbase ; B -6 -149 318 106 ; + +C 186 ; WX 333 ; N quotedblright ; B 124 463 448 718 ; + +C 187 ; WX 556 ; N guillemotright ; B 120 108 528 446 ; + +C 188 ; WX 1000 ; N ellipsis ; B 115 0 908 106 ; + +C 189 ; WX 1000 ; N perthousand ; B 88 -19 1029 703 ; + +C 191 ; WX 611 ; N questiondown ; B 85 -201 534 525 ; + +C 193 ; WX 333 ; N grave ; B 170 593 337 734 ; + +C 194 ; WX 333 ; N acute ; B 248 593 475 734 ; + +C 195 ; WX 333 ; N circumflex ; B 147 593 438 734 ; + +C 196 ; WX 333 ; N tilde ; B 125 606 490 722 ; + +C 197 ; WX 333 ; N macron ; B 143 627 468 684 ; + +C 198 ; WX 333 ; N breve ; B 167 595 476 731 ; + +C 199 ; WX 333 ; N dotaccent ; B 249 604 362 706 ; + +C 200 ; WX 333 ; N dieresis ; B 168 604 443 706 ; + +C 202 ; WX 333 ; N ring ; B 214 572 402 756 ; + +C 203 ; WX 333 ; N cedilla ; B 2 -225 232 0 ; + +C 205 ; WX 333 ; N hungarumlaut ; B 157 593 565 734 ; + +C 206 ; WX 333 ; N ogonek ; B 43 -225 249 0 ; + +C 207 ; WX 333 ; N caron ; B 177 593 468 734 ; + +C 208 ; WX 1000 ; N emdash ; B 51 240 1067 313 ; + +C 225 ; WX 1000 ; N AE ; B 8 0 1097 718 ; + +C 227 ; WX 370 ; N ordfeminine ; B 127 405 449 737 ; + +C 232 ; WX 556 ; N Lslash ; B 41 0 555 718 ; + +C 233 ; WX 778 ; N Oslash ; B 43 -19 890 737 ; + +C 234 ; WX 1000 ; N OE ; B 98 -19 1116 737 ; + +C 235 ; WX 365 ; N ordmasculine ; B 141 405 468 737 ; + +C 241 ; WX 889 ; N ae ; B 61 -15 909 538 ; + +C 245 ; WX 278 ; N dotlessi ; B 95 0 294 523 ; + +C 248 ; WX 222 ; N lslash ; B 41 0 347 718 ; + +C 249 ; WX 611 ; N oslash ; B 29 -22 647 545 ; + +C 250 ; WX 944 ; N oe ; B 83 -15 964 538 ; + +C 251 ; WX 611 ; N germandbls ; B 67 -15 658 728 ; + +C -1 ; WX 278 ; N Idieresis ; B 91 0 458 901 ; + +C -1 ; WX 556 ; N eacute ; B 84 -15 587 734 ; + +C -1 ; WX 556 ; N abreve ; B 61 -15 578 731 ; + +C -1 ; WX 556 ; N uhungarumlaut ; B 94 -15 677 734 ; + +C -1 ; WX 556 ; N ecaron ; B 84 -15 580 734 ; + +C -1 ; WX 667 ; N Ydieresis ; B 167 0 806 901 ; + +C -1 ; WX 584 ; N divide ; B 85 -19 606 524 ; + +C -1 ; WX 667 ; N Yacute ; B 167 0 806 929 ; + +C -1 ; WX 667 ; N Acircumflex ; B 14 0 654 929 ; + +C -1 ; WX 556 ; N aacute ; B 61 -15 587 734 ; + +C -1 ; WX 722 ; N Ucircumflex ; B 123 -19 797 929 ; + +C -1 ; WX 500 ; N yacute ; B 15 -214 600 734 ; + +C -1 ; WX 500 ; N scommaaccent ; B 63 -225 529 538 ; + +C -1 ; WX 556 ; N ecircumflex ; B 84 -15 578 734 ; + +C -1 ; WX 722 ; N Uring ; B 123 -19 797 931 ; + +C -1 ; WX 722 ; N Udieresis ; B 123 -19 797 901 ; + +C -1 ; WX 556 ; N aogonek ; B 61 -220 559 538 ; + +C -1 ; WX 722 ; N Uacute ; B 123 -19 797 929 ; + +C -1 ; WX 556 ; N uogonek ; B 94 -225 600 523 ; + +C -1 ; WX 667 ; N Edieresis ; B 86 0 762 901 ; + +C -1 ; WX 722 ; N Dcroat ; B 69 0 764 718 ; + +C -1 ; WX 250 ; N commaaccent ; B 39 -225 172 -40 ; + +C -1 ; WX 737 ; N copyright ; B 54 -19 837 737 ; + +C -1 ; WX 667 ; N Emacron ; B 86 0 762 879 ; + +C -1 ; WX 500 ; N ccaron ; B 74 -15 553 734 ; + +C -1 ; WX 556 ; N aring ; B 61 -15 559 756 ; + +C -1 ; WX 722 ; N Ncommaaccent ; B 76 -225 799 718 ; + +C -1 ; WX 222 ; N lacute ; B 67 0 461 929 ; + +C -1 ; WX 556 ; N agrave ; B 61 -15 559 734 ; + +C -1 ; WX 611 ; N Tcommaaccent ; B 148 -225 750 718 ; + +C -1 ; WX 722 ; N Cacute ; B 108 -19 782 929 ; + +C -1 ; WX 556 ; N atilde ; B 61 -15 592 722 ; + +C -1 ; WX 667 ; N Edotaccent ; B 86 0 762 901 ; + +C -1 ; WX 500 ; N scaron ; B 63 -15 552 734 ; + +C -1 ; WX 500 ; N scedilla ; B 63 -225 529 538 ; + +C -1 ; WX 278 ; N iacute ; B 95 0 448 734 ; + +C -1 ; WX 471 ; N lozenge ; B 88 0 540 728 ; + +C -1 ; WX 722 ; N Rcaron ; B 88 0 773 929 ; + +C -1 ; WX 778 ; N Gcommaaccent ; B 111 -225 799 737 ; + +C -1 ; WX 556 ; N ucircumflex ; B 94 -15 600 734 ; + +C -1 ; WX 556 ; N acircumflex ; B 61 -15 559 734 ; + +C -1 ; WX 667 ; N Amacron ; B 14 0 677 879 ; + +C -1 ; WX 333 ; N rcaron ; B 77 0 508 734 ; + +C -1 ; WX 500 ; N ccedilla ; B 74 -225 553 538 ; + +C -1 ; WX 611 ; N Zdotaccent ; B 23 0 741 901 ; + +C -1 ; WX 667 ; N Thorn ; B 86 0 712 718 ; + +C -1 ; WX 778 ; N Omacron ; B 105 -19 826 879 ; + +C -1 ; WX 722 ; N Racute ; B 88 0 773 929 ; + +C -1 ; WX 667 ; N Sacute ; B 90 -19 713 929 ; + +C -1 ; WX 643 ; N dcaron ; B 84 -15 808 718 ; + +C -1 ; WX 722 ; N Umacron ; B 123 -19 797 879 ; + +C -1 ; WX 556 ; N uring ; B 94 -15 600 756 ; + +C -1 ; WX 333 ; N threesuperior ; B 90 270 436 703 ; + +C -1 ; WX 778 ; N Ograve ; B 105 -19 826 929 ; + +C -1 ; WX 667 ; N Agrave ; B 14 0 654 929 ; + +C -1 ; WX 667 ; N Abreve ; B 14 0 685 926 ; + +C -1 ; WX 584 ; N multiply ; B 50 0 642 506 ; + +C -1 ; WX 556 ; N uacute ; B 94 -15 600 734 ; + +C -1 ; WX 611 ; N Tcaron ; B 148 0 750 929 ; + +C -1 ; WX 476 ; N partialdiff ; B 41 -38 550 714 ; + +C -1 ; WX 500 ; N ydieresis ; B 15 -214 600 706 ; + +C -1 ; WX 722 ; N Nacute ; B 76 0 799 929 ; + +C -1 ; WX 278 ; N icircumflex ; B 95 0 411 734 ; + +C -1 ; WX 667 ; N Ecircumflex ; B 86 0 762 929 ; + +C -1 ; WX 556 ; N adieresis ; B 61 -15 559 706 ; + +C -1 ; WX 556 ; N edieresis ; B 84 -15 578 706 ; + +C -1 ; WX 500 ; N cacute ; B 74 -15 559 734 ; + +C -1 ; WX 556 ; N nacute ; B 65 0 587 734 ; + +C -1 ; WX 556 ; N umacron ; B 94 -15 600 684 ; + +C -1 ; WX 722 ; N Ncaron ; B 76 0 799 929 ; + +C -1 ; WX 278 ; N Iacute ; B 91 0 489 929 ; + +C -1 ; WX 584 ; N plusminus ; B 39 0 618 506 ; + +C -1 ; WX 260 ; N brokenbar ; B 62 -150 316 700 ; + +C -1 ; WX 737 ; N registered ; B 54 -19 837 737 ; + +C -1 ; WX 778 ; N Gbreve ; B 111 -19 799 926 ; + +C -1 ; WX 278 ; N Idotaccent ; B 91 0 377 901 ; + +C -1 ; WX 600 ; N summation ; B 15 -10 671 706 ; + +C -1 ; WX 667 ; N Egrave ; B 86 0 762 929 ; + +C -1 ; WX 333 ; N racute ; B 77 0 475 734 ; + +C -1 ; WX 556 ; N omacron ; B 83 -14 585 684 ; + +C -1 ; WX 611 ; N Zacute ; B 23 0 741 929 ; + +C -1 ; WX 611 ; N Zcaron ; B 23 0 741 929 ; + +C -1 ; WX 549 ; N greaterequal ; B 26 0 620 674 ; + +C -1 ; WX 722 ; N Eth ; B 69 0 764 718 ; + +C -1 ; WX 722 ; N Ccedilla ; B 108 -225 782 737 ; + +C -1 ; WX 222 ; N lcommaaccent ; B 25 -225 308 718 ; + +C -1 ; WX 317 ; N tcaron ; B 102 -7 501 808 ; + +C -1 ; WX 556 ; N eogonek ; B 84 -225 578 538 ; + +C -1 ; WX 722 ; N Uogonek ; B 123 -225 797 718 ; + +C -1 ; WX 667 ; N Aacute ; B 14 0 683 929 ; + +C -1 ; WX 667 ; N Adieresis ; B 14 0 654 901 ; + +C -1 ; WX 556 ; N egrave ; B 84 -15 578 734 ; + +C -1 ; WX 500 ; N zacute ; B 31 0 571 734 ; + +C -1 ; WX 222 ; N iogonek ; B -61 -225 308 718 ; + +C -1 ; WX 778 ; N Oacute ; B 105 -19 826 929 ; + +C -1 ; WX 556 ; N oacute ; B 83 -14 587 734 ; + +C -1 ; WX 556 ; N amacron ; B 61 -15 580 684 ; + +C -1 ; WX 500 ; N sacute ; B 63 -15 559 734 ; + +C -1 ; WX 278 ; N idieresis ; B 95 0 416 706 ; + +C -1 ; WX 778 ; N Ocircumflex ; B 105 -19 826 929 ; + +C -1 ; WX 722 ; N Ugrave ; B 123 -19 797 929 ; + +C -1 ; WX 612 ; N Delta ; B 6 0 608 688 ; + +C -1 ; WX 556 ; N thorn ; B 14 -207 584 718 ; + +C -1 ; WX 333 ; N twosuperior ; B 64 281 449 703 ; + +C -1 ; WX 778 ; N Odieresis ; B 105 -19 826 901 ; + +C -1 ; WX 556 ; N mu ; B 24 -207 600 523 ; + +C -1 ; WX 278 ; N igrave ; B 95 0 310 734 ; + +C -1 ; WX 556 ; N ohungarumlaut ; B 83 -14 677 734 ; + +C -1 ; WX 667 ; N Eogonek ; B 86 -220 762 718 ; + +C -1 ; WX 556 ; N dcroat ; B 84 -15 689 718 ; + +C -1 ; WX 834 ; N threequarters ; B 130 -19 861 703 ; + +C -1 ; WX 667 ; N Scedilla ; B 90 -225 713 737 ; + +C -1 ; WX 299 ; N lcaron ; B 67 0 464 718 ; + +C -1 ; WX 667 ; N Kcommaaccent ; B 76 -225 808 718 ; + +C -1 ; WX 556 ; N Lacute ; B 76 0 555 929 ; + +C -1 ; WX 1000 ; N trademark ; B 186 306 1056 718 ; + +C -1 ; WX 556 ; N edotaccent ; B 84 -15 578 706 ; + +C -1 ; WX 278 ; N Igrave ; B 91 0 351 929 ; + +C -1 ; WX 278 ; N Imacron ; B 91 0 483 879 ; + +C -1 ; WX 556 ; N Lcaron ; B 76 0 570 718 ; + +C -1 ; WX 834 ; N onehalf ; B 114 -19 839 703 ; + +C -1 ; WX 549 ; N lessequal ; B 26 0 666 674 ; + +C -1 ; WX 556 ; N ocircumflex ; B 83 -14 585 734 ; + +C -1 ; WX 556 ; N ntilde ; B 65 0 592 722 ; + +C -1 ; WX 722 ; N Uhungarumlaut ; B 123 -19 801 929 ; + +C -1 ; WX 667 ; N Eacute ; B 86 0 762 929 ; + +C -1 ; WX 556 ; N emacron ; B 84 -15 580 684 ; + +C -1 ; WX 556 ; N gbreve ; B 42 -220 610 731 ; + +C -1 ; WX 834 ; N onequarter ; B 150 -19 802 703 ; + +C -1 ; WX 667 ; N Scaron ; B 90 -19 713 929 ; + +C -1 ; WX 667 ; N Scommaaccent ; B 90 -225 713 737 ; + +C -1 ; WX 778 ; N Ohungarumlaut ; B 105 -19 829 929 ; + +C -1 ; WX 400 ; N degree ; B 169 411 468 703 ; + +C -1 ; WX 556 ; N ograve ; B 83 -14 585 734 ; + +C -1 ; WX 722 ; N Ccaron ; B 108 -19 782 929 ; + +C -1 ; WX 556 ; N ugrave ; B 94 -15 600 734 ; + +C -1 ; WX 453 ; N radical ; B 79 -80 617 762 ; + +C -1 ; WX 722 ; N Dcaron ; B 81 0 764 929 ; + +C -1 ; WX 333 ; N rcommaaccent ; B 30 -225 446 538 ; + +C -1 ; WX 722 ; N Ntilde ; B 76 0 799 917 ; + +C -1 ; WX 556 ; N otilde ; B 83 -14 602 722 ; + +C -1 ; WX 722 ; N Rcommaaccent ; B 88 -225 773 718 ; + +C -1 ; WX 556 ; N Lcommaaccent ; B 76 -225 555 718 ; + +C -1 ; WX 667 ; N Atilde ; B 14 0 699 917 ; + +C -1 ; WX 667 ; N Aogonek ; B 14 -225 654 718 ; + +C -1 ; WX 667 ; N Aring ; B 14 0 654 931 ; + +C -1 ; WX 778 ; N Otilde ; B 105 -19 826 917 ; + +C -1 ; WX 500 ; N zdotaccent ; B 31 0 571 706 ; + +C -1 ; WX 667 ; N Ecaron ; B 86 0 762 929 ; + +C -1 ; WX 278 ; N Iogonek ; B -33 -225 341 718 ; + +C -1 ; WX 500 ; N kcommaaccent ; B 67 -225 600 718 ; + +C -1 ; WX 584 ; N minus ; B 85 216 606 289 ; + +C -1 ; WX 278 ; N Icircumflex ; B 91 0 452 929 ; + +C -1 ; WX 556 ; N ncaron ; B 65 0 580 734 ; + +C -1 ; WX 278 ; N tcommaaccent ; B 63 -225 368 669 ; + +C -1 ; WX 584 ; N logicalnot ; B 106 108 628 390 ; + +C -1 ; WX 556 ; N odieresis ; B 83 -14 585 706 ; + +C -1 ; WX 556 ; N udieresis ; B 94 -15 600 706 ; + +C -1 ; WX 549 ; N notequal ; B 34 -35 623 551 ; + +C -1 ; WX 556 ; N gcommaaccent ; B 42 -220 610 822 ; + +C -1 ; WX 556 ; N eth ; B 81 -15 617 737 ; + +C -1 ; WX 500 ; N zcaron ; B 31 0 571 734 ; + +C -1 ; WX 556 ; N ncommaaccent ; B 65 -225 573 538 ; + +C -1 ; WX 333 ; N onesuperior ; B 166 281 371 703 ; + +C -1 ; WX 278 ; N imacron ; B 95 0 417 684 ; + +C -1 ; WX 556 ; N Euro ; B 0 0 0 0 ; + +EndCharMetrics + +StartKernData + +StartKernPairs 2705 + +KPX A C -30 + +KPX A Cacute -30 + +KPX A Ccaron -30 + +KPX A Ccedilla -30 + +KPX A G -30 + +KPX A Gbreve -30 + +KPX A Gcommaaccent -30 + +KPX A O -30 + +KPX A Oacute -30 + +KPX A Ocircumflex -30 + +KPX A Odieresis -30 + +KPX A Ograve -30 + +KPX A Ohungarumlaut -30 + +KPX A Omacron -30 + +KPX A Oslash -30 + +KPX A Otilde -30 + +KPX A Q -30 + +KPX A T -120 + +KPX A Tcaron -120 + +KPX A Tcommaaccent -120 + +KPX A U -50 + +KPX A Uacute -50 + +KPX A Ucircumflex -50 + +KPX A Udieresis -50 + +KPX A Ugrave -50 + +KPX A Uhungarumlaut -50 + +KPX A Umacron -50 + +KPX A Uogonek -50 + +KPX A Uring -50 + +KPX A V -70 + +KPX A W -50 + +KPX A Y -100 + +KPX A Yacute -100 + +KPX A Ydieresis -100 + +KPX A u -30 + +KPX A uacute -30 + +KPX A ucircumflex -30 + +KPX A udieresis -30 + +KPX A ugrave -30 + +KPX A uhungarumlaut -30 + +KPX A umacron -30 + +KPX A uogonek -30 + +KPX A uring -30 + +KPX A v -40 + +KPX A w -40 + +KPX A y -40 + +KPX A yacute -40 + +KPX A ydieresis -40 + +KPX Aacute C -30 + +KPX Aacute Cacute -30 + +KPX Aacute Ccaron -30 + +KPX Aacute Ccedilla -30 + +KPX Aacute G -30 + +KPX Aacute Gbreve -30 + +KPX Aacute Gcommaaccent -30 + +KPX Aacute O -30 + +KPX Aacute Oacute -30 + +KPX Aacute Ocircumflex -30 + +KPX Aacute Odieresis -30 + +KPX Aacute Ograve -30 + +KPX Aacute Ohungarumlaut -30 + +KPX Aacute Omacron -30 + +KPX Aacute Oslash -30 + +KPX Aacute Otilde -30 + +KPX Aacute Q -30 + +KPX Aacute T -120 + +KPX Aacute Tcaron -120 + +KPX Aacute Tcommaaccent -120 + +KPX Aacute U -50 + +KPX Aacute Uacute -50 + +KPX Aacute Ucircumflex -50 + +KPX Aacute Udieresis -50 + +KPX Aacute Ugrave -50 + +KPX Aacute Uhungarumlaut -50 + +KPX Aacute Umacron -50 + +KPX Aacute Uogonek -50 + +KPX Aacute Uring -50 + +KPX Aacute V -70 + +KPX Aacute W -50 + +KPX Aacute Y -100 + +KPX Aacute Yacute -100 + +KPX Aacute Ydieresis -100 + +KPX Aacute u -30 + +KPX Aacute uacute -30 + +KPX Aacute ucircumflex -30 + +KPX Aacute udieresis -30 + +KPX Aacute ugrave -30 + +KPX Aacute uhungarumlaut -30 + +KPX Aacute umacron -30 + +KPX Aacute uogonek -30 + +KPX Aacute uring -30 + +KPX Aacute v -40 + +KPX Aacute w -40 + +KPX Aacute y -40 + +KPX Aacute yacute -40 + +KPX Aacute ydieresis -40 + +KPX Abreve C -30 + +KPX Abreve Cacute -30 + +KPX Abreve Ccaron -30 + +KPX Abreve Ccedilla -30 + +KPX Abreve G -30 + +KPX Abreve Gbreve -30 + +KPX Abreve Gcommaaccent -30 + +KPX Abreve O -30 + +KPX Abreve Oacute -30 + +KPX Abreve Ocircumflex -30 + +KPX Abreve Odieresis -30 + +KPX Abreve Ograve -30 + +KPX Abreve Ohungarumlaut -30 + +KPX Abreve Omacron -30 + +KPX Abreve Oslash -30 + +KPX Abreve Otilde -30 + +KPX Abreve Q -30 + +KPX Abreve T -120 + +KPX Abreve Tcaron -120 + +KPX Abreve Tcommaaccent -120 + +KPX Abreve U -50 + +KPX Abreve Uacute -50 + +KPX Abreve Ucircumflex -50 + +KPX Abreve Udieresis -50 + +KPX Abreve Ugrave -50 + +KPX Abreve Uhungarumlaut -50 + +KPX Abreve Umacron -50 + +KPX Abreve Uogonek -50 + +KPX Abreve Uring -50 + +KPX Abreve V -70 + +KPX Abreve W -50 + +KPX Abreve Y -100 + +KPX Abreve Yacute -100 + +KPX Abreve Ydieresis -100 + +KPX Abreve u -30 + +KPX Abreve uacute -30 + +KPX Abreve ucircumflex -30 + +KPX Abreve udieresis -30 + +KPX Abreve ugrave -30 + +KPX Abreve uhungarumlaut -30 + +KPX Abreve umacron -30 + +KPX Abreve uogonek -30 + +KPX Abreve uring -30 + +KPX Abreve v -40 + +KPX Abreve w -40 + +KPX Abreve y -40 + +KPX Abreve yacute -40 + +KPX Abreve ydieresis -40 + +KPX Acircumflex C -30 + +KPX Acircumflex Cacute -30 + +KPX Acircumflex Ccaron -30 + +KPX Acircumflex Ccedilla -30 + +KPX Acircumflex G -30 + +KPX Acircumflex Gbreve -30 + +KPX Acircumflex Gcommaaccent -30 + +KPX Acircumflex O -30 + +KPX Acircumflex Oacute -30 + +KPX Acircumflex Ocircumflex -30 + +KPX Acircumflex Odieresis -30 + +KPX Acircumflex Ograve -30 + +KPX Acircumflex Ohungarumlaut -30 + +KPX Acircumflex Omacron -30 + +KPX Acircumflex Oslash -30 + +KPX Acircumflex Otilde -30 + +KPX Acircumflex Q -30 + +KPX Acircumflex T -120 + +KPX Acircumflex Tcaron -120 + +KPX Acircumflex Tcommaaccent -120 + +KPX Acircumflex U -50 + +KPX Acircumflex Uacute -50 + +KPX Acircumflex Ucircumflex -50 + +KPX Acircumflex Udieresis -50 + +KPX Acircumflex Ugrave -50 + +KPX Acircumflex Uhungarumlaut -50 + +KPX Acircumflex Umacron -50 + +KPX Acircumflex Uogonek -50 + +KPX Acircumflex Uring -50 + +KPX Acircumflex V -70 + +KPX Acircumflex W -50 + +KPX Acircumflex Y -100 + +KPX Acircumflex Yacute -100 + +KPX Acircumflex Ydieresis -100 + +KPX Acircumflex u -30 + +KPX Acircumflex uacute -30 + +KPX Acircumflex ucircumflex -30 + +KPX Acircumflex udieresis -30 + +KPX Acircumflex ugrave -30 + +KPX Acircumflex uhungarumlaut -30 + +KPX Acircumflex umacron -30 + +KPX Acircumflex uogonek -30 + +KPX Acircumflex uring -30 + +KPX Acircumflex v -40 + +KPX Acircumflex w -40 + +KPX Acircumflex y -40 + +KPX Acircumflex yacute -40 + +KPX Acircumflex ydieresis -40 + +KPX Adieresis C -30 + +KPX Adieresis Cacute -30 + +KPX Adieresis Ccaron -30 + +KPX Adieresis Ccedilla -30 + +KPX Adieresis G -30 + +KPX Adieresis Gbreve -30 + +KPX Adieresis Gcommaaccent -30 + +KPX Adieresis O -30 + +KPX Adieresis Oacute -30 + +KPX Adieresis Ocircumflex -30 + +KPX Adieresis Odieresis -30 + +KPX Adieresis Ograve -30 + +KPX Adieresis Ohungarumlaut -30 + +KPX Adieresis Omacron -30 + +KPX Adieresis Oslash -30 + +KPX Adieresis Otilde -30 + +KPX Adieresis Q -30 + +KPX Adieresis T -120 + +KPX Adieresis Tcaron -120 + +KPX Adieresis Tcommaaccent -120 + +KPX Adieresis U -50 + +KPX Adieresis Uacute -50 + +KPX Adieresis Ucircumflex -50 + +KPX Adieresis Udieresis -50 + +KPX Adieresis Ugrave -50 + +KPX Adieresis Uhungarumlaut -50 + +KPX Adieresis Umacron -50 + +KPX Adieresis Uogonek -50 + +KPX Adieresis Uring -50 + +KPX Adieresis V -70 + +KPX Adieresis W -50 + +KPX Adieresis Y -100 + +KPX Adieresis Yacute -100 + +KPX Adieresis Ydieresis -100 + +KPX Adieresis u -30 + +KPX Adieresis uacute -30 + +KPX Adieresis ucircumflex -30 + +KPX Adieresis udieresis -30 + +KPX Adieresis ugrave -30 + +KPX Adieresis uhungarumlaut -30 + +KPX Adieresis umacron -30 + +KPX Adieresis uogonek -30 + +KPX Adieresis uring -30 + +KPX Adieresis v -40 + +KPX Adieresis w -40 + +KPX Adieresis y -40 + +KPX Adieresis yacute -40 + +KPX Adieresis ydieresis -40 + +KPX Agrave C -30 + +KPX Agrave Cacute -30 + +KPX Agrave Ccaron -30 + +KPX Agrave Ccedilla -30 + +KPX Agrave G -30 + +KPX Agrave Gbreve -30 + +KPX Agrave Gcommaaccent -30 + +KPX Agrave O -30 + +KPX Agrave Oacute -30 + +KPX Agrave Ocircumflex -30 + +KPX Agrave Odieresis -30 + +KPX Agrave Ograve -30 + +KPX Agrave Ohungarumlaut -30 + +KPX Agrave Omacron -30 + +KPX Agrave Oslash -30 + +KPX Agrave Otilde -30 + +KPX Agrave Q -30 + +KPX Agrave T -120 + +KPX Agrave Tcaron -120 + +KPX Agrave Tcommaaccent -120 + +KPX Agrave U -50 + +KPX Agrave Uacute -50 + +KPX Agrave Ucircumflex -50 + +KPX Agrave Udieresis -50 + +KPX Agrave Ugrave -50 + +KPX Agrave Uhungarumlaut -50 + +KPX Agrave Umacron -50 + +KPX Agrave Uogonek -50 + +KPX Agrave Uring -50 + +KPX Agrave V -70 + +KPX Agrave W -50 + +KPX Agrave Y -100 + +KPX Agrave Yacute -100 + +KPX Agrave Ydieresis -100 + +KPX Agrave u -30 + +KPX Agrave uacute -30 + +KPX Agrave ucircumflex -30 + +KPX Agrave udieresis -30 + +KPX Agrave ugrave -30 + +KPX Agrave uhungarumlaut -30 + +KPX Agrave umacron -30 + +KPX Agrave uogonek -30 + +KPX Agrave uring -30 + +KPX Agrave v -40 + +KPX Agrave w -40 + +KPX Agrave y -40 + +KPX Agrave yacute -40 + +KPX Agrave ydieresis -40 + +KPX Amacron C -30 + +KPX Amacron Cacute -30 + +KPX Amacron Ccaron -30 + +KPX Amacron Ccedilla -30 + +KPX Amacron G -30 + +KPX Amacron Gbreve -30 + +KPX Amacron Gcommaaccent -30 + +KPX Amacron O -30 + +KPX Amacron Oacute -30 + +KPX Amacron Ocircumflex -30 + +KPX Amacron Odieresis -30 + +KPX Amacron Ograve -30 + +KPX Amacron Ohungarumlaut -30 + +KPX Amacron Omacron -30 + +KPX Amacron Oslash -30 + +KPX Amacron Otilde -30 + +KPX Amacron Q -30 + +KPX Amacron T -120 + +KPX Amacron Tcaron -120 + +KPX Amacron Tcommaaccent -120 + +KPX Amacron U -50 + +KPX Amacron Uacute -50 + +KPX Amacron Ucircumflex -50 + +KPX Amacron Udieresis -50 + +KPX Amacron Ugrave -50 + +KPX Amacron Uhungarumlaut -50 + +KPX Amacron Umacron -50 + +KPX Amacron Uogonek -50 + +KPX Amacron Uring -50 + +KPX Amacron V -70 + +KPX Amacron W -50 + +KPX Amacron Y -100 + +KPX Amacron Yacute -100 + +KPX Amacron Ydieresis -100 + +KPX Amacron u -30 + +KPX Amacron uacute -30 + +KPX Amacron ucircumflex -30 + +KPX Amacron udieresis -30 + +KPX Amacron ugrave -30 + +KPX Amacron uhungarumlaut -30 + +KPX Amacron umacron -30 + +KPX Amacron uogonek -30 + +KPX Amacron uring -30 + +KPX Amacron v -40 + +KPX Amacron w -40 + +KPX Amacron y -40 + +KPX Amacron yacute -40 + +KPX Amacron ydieresis -40 + +KPX Aogonek C -30 + +KPX Aogonek Cacute -30 + +KPX Aogonek Ccaron -30 + +KPX Aogonek Ccedilla -30 + +KPX Aogonek G -30 + +KPX Aogonek Gbreve -30 + +KPX Aogonek Gcommaaccent -30 + +KPX Aogonek O -30 + +KPX Aogonek Oacute -30 + +KPX Aogonek Ocircumflex -30 + +KPX Aogonek Odieresis -30 + +KPX Aogonek Ograve -30 + +KPX Aogonek Ohungarumlaut -30 + +KPX Aogonek Omacron -30 + +KPX Aogonek Oslash -30 + +KPX Aogonek Otilde -30 + +KPX Aogonek Q -30 + +KPX Aogonek T -120 + +KPX Aogonek Tcaron -120 + +KPX Aogonek Tcommaaccent -120 + +KPX Aogonek U -50 + +KPX Aogonek Uacute -50 + +KPX Aogonek Ucircumflex -50 + +KPX Aogonek Udieresis -50 + +KPX Aogonek Ugrave -50 + +KPX Aogonek Uhungarumlaut -50 + +KPX Aogonek Umacron -50 + +KPX Aogonek Uogonek -50 + +KPX Aogonek Uring -50 + +KPX Aogonek V -70 + +KPX Aogonek W -50 + +KPX Aogonek Y -100 + +KPX Aogonek Yacute -100 + +KPX Aogonek Ydieresis -100 + +KPX Aogonek u -30 + +KPX Aogonek uacute -30 + +KPX Aogonek ucircumflex -30 + +KPX Aogonek udieresis -30 + +KPX Aogonek ugrave -30 + +KPX Aogonek uhungarumlaut -30 + +KPX Aogonek umacron -30 + +KPX Aogonek uogonek -30 + +KPX Aogonek uring -30 + +KPX Aogonek v -40 + +KPX Aogonek w -40 + +KPX Aogonek y -40 + +KPX Aogonek yacute -40 + +KPX Aogonek ydieresis -40 + +KPX Aring C -30 + +KPX Aring Cacute -30 + +KPX Aring Ccaron -30 + +KPX Aring Ccedilla -30 + +KPX Aring G -30 + +KPX Aring Gbreve -30 + +KPX Aring Gcommaaccent -30 + +KPX Aring O -30 + +KPX Aring Oacute -30 + +KPX Aring Ocircumflex -30 + +KPX Aring Odieresis -30 + +KPX Aring Ograve -30 + +KPX Aring Ohungarumlaut -30 + +KPX Aring Omacron -30 + +KPX Aring Oslash -30 + +KPX Aring Otilde -30 + +KPX Aring Q -30 + +KPX Aring T -120 + +KPX Aring Tcaron -120 + +KPX Aring Tcommaaccent -120 + +KPX Aring U -50 + +KPX Aring Uacute -50 + +KPX Aring Ucircumflex -50 + +KPX Aring Udieresis -50 + +KPX Aring Ugrave -50 + +KPX Aring Uhungarumlaut -50 + +KPX Aring Umacron -50 + +KPX Aring Uogonek -50 + +KPX Aring Uring -50 + +KPX Aring V -70 + +KPX Aring W -50 + +KPX Aring Y -100 + +KPX Aring Yacute -100 + +KPX Aring Ydieresis -100 + +KPX Aring u -30 + +KPX Aring uacute -30 + +KPX Aring ucircumflex -30 + +KPX Aring udieresis -30 + +KPX Aring ugrave -30 + +KPX Aring uhungarumlaut -30 + +KPX Aring umacron -30 + +KPX Aring uogonek -30 + +KPX Aring uring -30 + +KPX Aring v -40 + +KPX Aring w -40 + +KPX Aring y -40 + +KPX Aring yacute -40 + +KPX Aring ydieresis -40 + +KPX Atilde C -30 + +KPX Atilde Cacute -30 + +KPX Atilde Ccaron -30 + +KPX Atilde Ccedilla -30 + +KPX Atilde G -30 + +KPX Atilde Gbreve -30 + +KPX Atilde Gcommaaccent -30 + +KPX Atilde O -30 + +KPX Atilde Oacute -30 + +KPX Atilde Ocircumflex -30 + +KPX Atilde Odieresis -30 + +KPX Atilde Ograve -30 + +KPX Atilde Ohungarumlaut -30 + +KPX Atilde Omacron -30 + +KPX Atilde Oslash -30 + +KPX Atilde Otilde -30 + +KPX Atilde Q -30 + +KPX Atilde T -120 + +KPX Atilde Tcaron -120 + +KPX Atilde Tcommaaccent -120 + +KPX Atilde U -50 + +KPX Atilde Uacute -50 + +KPX Atilde Ucircumflex -50 + +KPX Atilde Udieresis -50 + +KPX Atilde Ugrave -50 + +KPX Atilde Uhungarumlaut -50 + +KPX Atilde Umacron -50 + +KPX Atilde Uogonek -50 + +KPX Atilde Uring -50 + +KPX Atilde V -70 + +KPX Atilde W -50 + +KPX Atilde Y -100 + +KPX Atilde Yacute -100 + +KPX Atilde Ydieresis -100 + +KPX Atilde u -30 + +KPX Atilde uacute -30 + +KPX Atilde ucircumflex -30 + +KPX Atilde udieresis -30 + +KPX Atilde ugrave -30 + +KPX Atilde uhungarumlaut -30 + +KPX Atilde umacron -30 + +KPX Atilde uogonek -30 + +KPX Atilde uring -30 + +KPX Atilde v -40 + +KPX Atilde w -40 + +KPX Atilde y -40 + +KPX Atilde yacute -40 + +KPX Atilde ydieresis -40 + +KPX B U -10 + +KPX B Uacute -10 + +KPX B Ucircumflex -10 + +KPX B Udieresis -10 + +KPX B Ugrave -10 + +KPX B Uhungarumlaut -10 + +KPX B Umacron -10 + +KPX B Uogonek -10 + +KPX B Uring -10 + +KPX B comma -20 + +KPX B period -20 + +KPX C comma -30 + +KPX C period -30 + +KPX Cacute comma -30 + +KPX Cacute period -30 + +KPX Ccaron comma -30 + +KPX Ccaron period -30 + +KPX Ccedilla comma -30 + +KPX Ccedilla period -30 + +KPX D A -40 + +KPX D Aacute -40 + +KPX D Abreve -40 + +KPX D Acircumflex -40 + +KPX D Adieresis -40 + +KPX D Agrave -40 + +KPX D Amacron -40 + +KPX D Aogonek -40 + +KPX D Aring -40 + +KPX D Atilde -40 + +KPX D V -70 + +KPX D W -40 + +KPX D Y -90 + +KPX D Yacute -90 + +KPX D Ydieresis -90 + +KPX D comma -70 + +KPX D period -70 + +KPX Dcaron A -40 + +KPX Dcaron Aacute -40 + +KPX Dcaron Abreve -40 + +KPX Dcaron Acircumflex -40 + +KPX Dcaron Adieresis -40 + +KPX Dcaron Agrave -40 + +KPX Dcaron Amacron -40 + +KPX Dcaron Aogonek -40 + +KPX Dcaron Aring -40 + +KPX Dcaron Atilde -40 + +KPX Dcaron V -70 + +KPX Dcaron W -40 + +KPX Dcaron Y -90 + +KPX Dcaron Yacute -90 + +KPX Dcaron Ydieresis -90 + +KPX Dcaron comma -70 + +KPX Dcaron period -70 + +KPX Dcroat A -40 + +KPX Dcroat Aacute -40 + +KPX Dcroat Abreve -40 + +KPX Dcroat Acircumflex -40 + +KPX Dcroat Adieresis -40 + +KPX Dcroat Agrave -40 + +KPX Dcroat Amacron -40 + +KPX Dcroat Aogonek -40 + +KPX Dcroat Aring -40 + +KPX Dcroat Atilde -40 + +KPX Dcroat V -70 + +KPX Dcroat W -40 + +KPX Dcroat Y -90 + +KPX Dcroat Yacute -90 + +KPX Dcroat Ydieresis -90 + +KPX Dcroat comma -70 + +KPX Dcroat period -70 + +KPX F A -80 + +KPX F Aacute -80 + +KPX F Abreve -80 + +KPX F Acircumflex -80 + +KPX F Adieresis -80 + +KPX F Agrave -80 + +KPX F Amacron -80 + +KPX F Aogonek -80 + +KPX F Aring -80 + +KPX F Atilde -80 + +KPX F a -50 + +KPX F aacute -50 + +KPX F abreve -50 + +KPX F acircumflex -50 + +KPX F adieresis -50 + +KPX F agrave -50 + +KPX F amacron -50 + +KPX F aogonek -50 + +KPX F aring -50 + +KPX F atilde -50 + +KPX F comma -150 + +KPX F e -30 + +KPX F eacute -30 + +KPX F ecaron -30 + +KPX F ecircumflex -30 + +KPX F edieresis -30 + +KPX F edotaccent -30 + +KPX F egrave -30 + +KPX F emacron -30 + +KPX F eogonek -30 + +KPX F o -30 + +KPX F oacute -30 + +KPX F ocircumflex -30 + +KPX F odieresis -30 + +KPX F ograve -30 + +KPX F ohungarumlaut -30 + +KPX F omacron -30 + +KPX F oslash -30 + +KPX F otilde -30 + +KPX F period -150 + +KPX F r -45 + +KPX F racute -45 + +KPX F rcaron -45 + +KPX F rcommaaccent -45 + +KPX J A -20 + +KPX J Aacute -20 + +KPX J Abreve -20 + +KPX J Acircumflex -20 + +KPX J Adieresis -20 + +KPX J Agrave -20 + +KPX J Amacron -20 + +KPX J Aogonek -20 + +KPX J Aring -20 + +KPX J Atilde -20 + +KPX J a -20 + +KPX J aacute -20 + +KPX J abreve -20 + +KPX J acircumflex -20 + +KPX J adieresis -20 + +KPX J agrave -20 + +KPX J amacron -20 + +KPX J aogonek -20 + +KPX J aring -20 + +KPX J atilde -20 + +KPX J comma -30 + +KPX J period -30 + +KPX J u -20 + +KPX J uacute -20 + +KPX J ucircumflex -20 + +KPX J udieresis -20 + +KPX J ugrave -20 + +KPX J uhungarumlaut -20 + +KPX J umacron -20 + +KPX J uogonek -20 + +KPX J uring -20 + +KPX K O -50 + +KPX K Oacute -50 + +KPX K Ocircumflex -50 + +KPX K Odieresis -50 + +KPX K Ograve -50 + +KPX K Ohungarumlaut -50 + +KPX K Omacron -50 + +KPX K Oslash -50 + +KPX K Otilde -50 + +KPX K e -40 + +KPX K eacute -40 + +KPX K ecaron -40 + +KPX K ecircumflex -40 + +KPX K edieresis -40 + +KPX K edotaccent -40 + +KPX K egrave -40 + +KPX K emacron -40 + +KPX K eogonek -40 + +KPX K o -40 + +KPX K oacute -40 + +KPX K ocircumflex -40 + +KPX K odieresis -40 + +KPX K ograve -40 + +KPX K ohungarumlaut -40 + +KPX K omacron -40 + +KPX K oslash -40 + +KPX K otilde -40 + +KPX K u -30 + +KPX K uacute -30 + +KPX K ucircumflex -30 + +KPX K udieresis -30 + +KPX K ugrave -30 + +KPX K uhungarumlaut -30 + +KPX K umacron -30 + +KPX K uogonek -30 + +KPX K uring -30 + +KPX K y -50 + +KPX K yacute -50 + +KPX K ydieresis -50 + +KPX Kcommaaccent O -50 + +KPX Kcommaaccent Oacute -50 + +KPX Kcommaaccent Ocircumflex -50 + +KPX Kcommaaccent Odieresis -50 + +KPX Kcommaaccent Ograve -50 + +KPX Kcommaaccent Ohungarumlaut -50 + +KPX Kcommaaccent Omacron -50 + +KPX Kcommaaccent Oslash -50 + +KPX Kcommaaccent Otilde -50 + +KPX Kcommaaccent e -40 + +KPX Kcommaaccent eacute -40 + +KPX Kcommaaccent ecaron -40 + +KPX Kcommaaccent ecircumflex -40 + +KPX Kcommaaccent edieresis -40 + +KPX Kcommaaccent edotaccent -40 + +KPX Kcommaaccent egrave -40 + +KPX Kcommaaccent emacron -40 + +KPX Kcommaaccent eogonek -40 + +KPX Kcommaaccent o -40 + +KPX Kcommaaccent oacute -40 + +KPX Kcommaaccent ocircumflex -40 + +KPX Kcommaaccent odieresis -40 + +KPX Kcommaaccent ograve -40 + +KPX Kcommaaccent ohungarumlaut -40 + +KPX Kcommaaccent omacron -40 + +KPX Kcommaaccent oslash -40 + +KPX Kcommaaccent otilde -40 + +KPX Kcommaaccent u -30 + +KPX Kcommaaccent uacute -30 + +KPX Kcommaaccent ucircumflex -30 + +KPX Kcommaaccent udieresis -30 + +KPX Kcommaaccent ugrave -30 + +KPX Kcommaaccent uhungarumlaut -30 + +KPX Kcommaaccent umacron -30 + +KPX Kcommaaccent uogonek -30 + +KPX Kcommaaccent uring -30 + +KPX Kcommaaccent y -50 + +KPX Kcommaaccent yacute -50 + +KPX Kcommaaccent ydieresis -50 + +KPX L T -110 + +KPX L Tcaron -110 + +KPX L Tcommaaccent -110 + +KPX L V -110 + +KPX L W -70 + +KPX L Y -140 + +KPX L Yacute -140 + +KPX L Ydieresis -140 + +KPX L quotedblright -140 + +KPX L quoteright -160 + +KPX L y -30 + +KPX L yacute -30 + +KPX L ydieresis -30 + +KPX Lacute T -110 + +KPX Lacute Tcaron -110 + +KPX Lacute Tcommaaccent -110 + +KPX Lacute V -110 + +KPX Lacute W -70 + +KPX Lacute Y -140 + +KPX Lacute Yacute -140 + +KPX Lacute Ydieresis -140 + +KPX Lacute quotedblright -140 + +KPX Lacute quoteright -160 + +KPX Lacute y -30 + +KPX Lacute yacute -30 + +KPX Lacute ydieresis -30 + +KPX Lcaron T -110 + +KPX Lcaron Tcaron -110 + +KPX Lcaron Tcommaaccent -110 + +KPX Lcaron V -110 + +KPX Lcaron W -70 + +KPX Lcaron Y -140 + +KPX Lcaron Yacute -140 + +KPX Lcaron Ydieresis -140 + +KPX Lcaron quotedblright -140 + +KPX Lcaron quoteright -160 + +KPX Lcaron y -30 + +KPX Lcaron yacute -30 + +KPX Lcaron ydieresis -30 + +KPX Lcommaaccent T -110 + +KPX Lcommaaccent Tcaron -110 + +KPX Lcommaaccent Tcommaaccent -110 + +KPX Lcommaaccent V -110 + +KPX Lcommaaccent W -70 + +KPX Lcommaaccent Y -140 + +KPX Lcommaaccent Yacute -140 + +KPX Lcommaaccent Ydieresis -140 + +KPX Lcommaaccent quotedblright -140 + +KPX Lcommaaccent quoteright -160 + +KPX Lcommaaccent y -30 + +KPX Lcommaaccent yacute -30 + +KPX Lcommaaccent ydieresis -30 + +KPX Lslash T -110 + +KPX Lslash Tcaron -110 + +KPX Lslash Tcommaaccent -110 + +KPX Lslash V -110 + +KPX Lslash W -70 + +KPX Lslash Y -140 + +KPX Lslash Yacute -140 + +KPX Lslash Ydieresis -140 + +KPX Lslash quotedblright -140 + +KPX Lslash quoteright -160 + +KPX Lslash y -30 + +KPX Lslash yacute -30 + +KPX Lslash ydieresis -30 + +KPX O A -20 + +KPX O Aacute -20 + +KPX O Abreve -20 + +KPX O Acircumflex -20 + +KPX O Adieresis -20 + +KPX O Agrave -20 + +KPX O Amacron -20 + +KPX O Aogonek -20 + +KPX O Aring -20 + +KPX O Atilde -20 + +KPX O T -40 + +KPX O Tcaron -40 + +KPX O Tcommaaccent -40 + +KPX O V -50 + +KPX O W -30 + +KPX O X -60 + +KPX O Y -70 + +KPX O Yacute -70 + +KPX O Ydieresis -70 + +KPX O comma -40 + +KPX O period -40 + +KPX Oacute A -20 + +KPX Oacute Aacute -20 + +KPX Oacute Abreve -20 + +KPX Oacute Acircumflex -20 + +KPX Oacute Adieresis -20 + +KPX Oacute Agrave -20 + +KPX Oacute Amacron -20 + +KPX Oacute Aogonek -20 + +KPX Oacute Aring -20 + +KPX Oacute Atilde -20 + +KPX Oacute T -40 + +KPX Oacute Tcaron -40 + +KPX Oacute Tcommaaccent -40 + +KPX Oacute V -50 + +KPX Oacute W -30 + +KPX Oacute X -60 + +KPX Oacute Y -70 + +KPX Oacute Yacute -70 + +KPX Oacute Ydieresis -70 + +KPX Oacute comma -40 + +KPX Oacute period -40 + +KPX Ocircumflex A -20 + +KPX Ocircumflex Aacute -20 + +KPX Ocircumflex Abreve -20 + +KPX Ocircumflex Acircumflex -20 + +KPX Ocircumflex Adieresis -20 + +KPX Ocircumflex Agrave -20 + +KPX Ocircumflex Amacron -20 + +KPX Ocircumflex Aogonek -20 + +KPX Ocircumflex Aring -20 + +KPX Ocircumflex Atilde -20 + +KPX Ocircumflex T -40 + +KPX Ocircumflex Tcaron -40 + +KPX Ocircumflex Tcommaaccent -40 + +KPX Ocircumflex V -50 + +KPX Ocircumflex W -30 + +KPX Ocircumflex X -60 + +KPX Ocircumflex Y -70 + +KPX Ocircumflex Yacute -70 + +KPX Ocircumflex Ydieresis -70 + +KPX Ocircumflex comma -40 + +KPX Ocircumflex period -40 + +KPX Odieresis A -20 + +KPX Odieresis Aacute -20 + +KPX Odieresis Abreve -20 + +KPX Odieresis Acircumflex -20 + +KPX Odieresis Adieresis -20 + +KPX Odieresis Agrave -20 + +KPX Odieresis Amacron -20 + +KPX Odieresis Aogonek -20 + +KPX Odieresis Aring -20 + +KPX Odieresis Atilde -20 + +KPX Odieresis T -40 + +KPX Odieresis Tcaron -40 + +KPX Odieresis Tcommaaccent -40 + +KPX Odieresis V -50 + +KPX Odieresis W -30 + +KPX Odieresis X -60 + +KPX Odieresis Y -70 + +KPX Odieresis Yacute -70 + +KPX Odieresis Ydieresis -70 + +KPX Odieresis comma -40 + +KPX Odieresis period -40 + +KPX Ograve A -20 + +KPX Ograve Aacute -20 + +KPX Ograve Abreve -20 + +KPX Ograve Acircumflex -20 + +KPX Ograve Adieresis -20 + +KPX Ograve Agrave -20 + +KPX Ograve Amacron -20 + +KPX Ograve Aogonek -20 + +KPX Ograve Aring -20 + +KPX Ograve Atilde -20 + +KPX Ograve T -40 + +KPX Ograve Tcaron -40 + +KPX Ograve Tcommaaccent -40 + +KPX Ograve V -50 + +KPX Ograve W -30 + +KPX Ograve X -60 + +KPX Ograve Y -70 + +KPX Ograve Yacute -70 + +KPX Ograve Ydieresis -70 + +KPX Ograve comma -40 + +KPX Ograve period -40 + +KPX Ohungarumlaut A -20 + +KPX Ohungarumlaut Aacute -20 + +KPX Ohungarumlaut Abreve -20 + +KPX Ohungarumlaut Acircumflex -20 + +KPX Ohungarumlaut Adieresis -20 + +KPX Ohungarumlaut Agrave -20 + +KPX Ohungarumlaut Amacron -20 + +KPX Ohungarumlaut Aogonek -20 + +KPX Ohungarumlaut Aring -20 + +KPX Ohungarumlaut Atilde -20 + +KPX Ohungarumlaut T -40 + +KPX Ohungarumlaut Tcaron -40 + +KPX Ohungarumlaut Tcommaaccent -40 + +KPX Ohungarumlaut V -50 + +KPX Ohungarumlaut W -30 + +KPX Ohungarumlaut X -60 + +KPX Ohungarumlaut Y -70 + +KPX Ohungarumlaut Yacute -70 + +KPX Ohungarumlaut Ydieresis -70 + +KPX Ohungarumlaut comma -40 + +KPX Ohungarumlaut period -40 + +KPX Omacron A -20 + +KPX Omacron Aacute -20 + +KPX Omacron Abreve -20 + +KPX Omacron Acircumflex -20 + +KPX Omacron Adieresis -20 + +KPX Omacron Agrave -20 + +KPX Omacron Amacron -20 + +KPX Omacron Aogonek -20 + +KPX Omacron Aring -20 + +KPX Omacron Atilde -20 + +KPX Omacron T -40 + +KPX Omacron Tcaron -40 + +KPX Omacron Tcommaaccent -40 + +KPX Omacron V -50 + +KPX Omacron W -30 + +KPX Omacron X -60 + +KPX Omacron Y -70 + +KPX Omacron Yacute -70 + +KPX Omacron Ydieresis -70 + +KPX Omacron comma -40 + +KPX Omacron period -40 + +KPX Oslash A -20 + +KPX Oslash Aacute -20 + +KPX Oslash Abreve -20 + +KPX Oslash Acircumflex -20 + +KPX Oslash Adieresis -20 + +KPX Oslash Agrave -20 + +KPX Oslash Amacron -20 + +KPX Oslash Aogonek -20 + +KPX Oslash Aring -20 + +KPX Oslash Atilde -20 + +KPX Oslash T -40 + +KPX Oslash Tcaron -40 + +KPX Oslash Tcommaaccent -40 + +KPX Oslash V -50 + +KPX Oslash W -30 + +KPX Oslash X -60 + +KPX Oslash Y -70 + +KPX Oslash Yacute -70 + +KPX Oslash Ydieresis -70 + +KPX Oslash comma -40 + +KPX Oslash period -40 + +KPX Otilde A -20 + +KPX Otilde Aacute -20 + +KPX Otilde Abreve -20 + +KPX Otilde Acircumflex -20 + +KPX Otilde Adieresis -20 + +KPX Otilde Agrave -20 + +KPX Otilde Amacron -20 + +KPX Otilde Aogonek -20 + +KPX Otilde Aring -20 + +KPX Otilde Atilde -20 + +KPX Otilde T -40 + +KPX Otilde Tcaron -40 + +KPX Otilde Tcommaaccent -40 + +KPX Otilde V -50 + +KPX Otilde W -30 + +KPX Otilde X -60 + +KPX Otilde Y -70 + +KPX Otilde Yacute -70 + +KPX Otilde Ydieresis -70 + +KPX Otilde comma -40 + +KPX Otilde period -40 + +KPX P A -120 + +KPX P Aacute -120 + +KPX P Abreve -120 + +KPX P Acircumflex -120 + +KPX P Adieresis -120 + +KPX P Agrave -120 + +KPX P Amacron -120 + +KPX P Aogonek -120 + +KPX P Aring -120 + +KPX P Atilde -120 + +KPX P a -40 + +KPX P aacute -40 + +KPX P abreve -40 + +KPX P acircumflex -40 + +KPX P adieresis -40 + +KPX P agrave -40 + +KPX P amacron -40 + +KPX P aogonek -40 + +KPX P aring -40 + +KPX P atilde -40 + +KPX P comma -180 + +KPX P e -50 + +KPX P eacute -50 + +KPX P ecaron -50 + +KPX P ecircumflex -50 + +KPX P edieresis -50 + +KPX P edotaccent -50 + +KPX P egrave -50 + +KPX P emacron -50 + +KPX P eogonek -50 + +KPX P o -50 + +KPX P oacute -50 + +KPX P ocircumflex -50 + +KPX P odieresis -50 + +KPX P ograve -50 + +KPX P ohungarumlaut -50 + +KPX P omacron -50 + +KPX P oslash -50 + +KPX P otilde -50 + +KPX P period -180 + +KPX Q U -10 + +KPX Q Uacute -10 + +KPX Q Ucircumflex -10 + +KPX Q Udieresis -10 + +KPX Q Ugrave -10 + +KPX Q Uhungarumlaut -10 + +KPX Q Umacron -10 + +KPX Q Uogonek -10 + +KPX Q Uring -10 + +KPX R O -20 + +KPX R Oacute -20 + +KPX R Ocircumflex -20 + +KPX R Odieresis -20 + +KPX R Ograve -20 + +KPX R Ohungarumlaut -20 + +KPX R Omacron -20 + +KPX R Oslash -20 + +KPX R Otilde -20 + +KPX R T -30 + +KPX R Tcaron -30 + +KPX R Tcommaaccent -30 + +KPX R U -40 + +KPX R Uacute -40 + +KPX R Ucircumflex -40 + +KPX R Udieresis -40 + +KPX R Ugrave -40 + +KPX R Uhungarumlaut -40 + +KPX R Umacron -40 + +KPX R Uogonek -40 + +KPX R Uring -40 + +KPX R V -50 + +KPX R W -30 + +KPX R Y -50 + +KPX R Yacute -50 + +KPX R Ydieresis -50 + +KPX Racute O -20 + +KPX Racute Oacute -20 + +KPX Racute Ocircumflex -20 + +KPX Racute Odieresis -20 + +KPX Racute Ograve -20 + +KPX Racute Ohungarumlaut -20 + +KPX Racute Omacron -20 + +KPX Racute Oslash -20 + +KPX Racute Otilde -20 + +KPX Racute T -30 + +KPX Racute Tcaron -30 + +KPX Racute Tcommaaccent -30 + +KPX Racute U -40 + +KPX Racute Uacute -40 + +KPX Racute Ucircumflex -40 + +KPX Racute Udieresis -40 + +KPX Racute Ugrave -40 + +KPX Racute Uhungarumlaut -40 + +KPX Racute Umacron -40 + +KPX Racute Uogonek -40 + +KPX Racute Uring -40 + +KPX Racute V -50 + +KPX Racute W -30 + +KPX Racute Y -50 + +KPX Racute Yacute -50 + +KPX Racute Ydieresis -50 + +KPX Rcaron O -20 + +KPX Rcaron Oacute -20 + +KPX Rcaron Ocircumflex -20 + +KPX Rcaron Odieresis -20 + +KPX Rcaron Ograve -20 + +KPX Rcaron Ohungarumlaut -20 + +KPX Rcaron Omacron -20 + +KPX Rcaron Oslash -20 + +KPX Rcaron Otilde -20 + +KPX Rcaron T -30 + +KPX Rcaron Tcaron -30 + +KPX Rcaron Tcommaaccent -30 + +KPX Rcaron U -40 + +KPX Rcaron Uacute -40 + +KPX Rcaron Ucircumflex -40 + +KPX Rcaron Udieresis -40 + +KPX Rcaron Ugrave -40 + +KPX Rcaron Uhungarumlaut -40 + +KPX Rcaron Umacron -40 + +KPX Rcaron Uogonek -40 + +KPX Rcaron Uring -40 + +KPX Rcaron V -50 + +KPX Rcaron W -30 + +KPX Rcaron Y -50 + +KPX Rcaron Yacute -50 + +KPX Rcaron Ydieresis -50 + +KPX Rcommaaccent O -20 + +KPX Rcommaaccent Oacute -20 + +KPX Rcommaaccent Ocircumflex -20 + +KPX Rcommaaccent Odieresis -20 + +KPX Rcommaaccent Ograve -20 + +KPX Rcommaaccent Ohungarumlaut -20 + +KPX Rcommaaccent Omacron -20 + +KPX Rcommaaccent Oslash -20 + +KPX Rcommaaccent Otilde -20 + +KPX Rcommaaccent T -30 + +KPX Rcommaaccent Tcaron -30 + +KPX Rcommaaccent Tcommaaccent -30 + +KPX Rcommaaccent U -40 + +KPX Rcommaaccent Uacute -40 + +KPX Rcommaaccent Ucircumflex -40 + +KPX Rcommaaccent Udieresis -40 + +KPX Rcommaaccent Ugrave -40 + +KPX Rcommaaccent Uhungarumlaut -40 + +KPX Rcommaaccent Umacron -40 + +KPX Rcommaaccent Uogonek -40 + +KPX Rcommaaccent Uring -40 + +KPX Rcommaaccent V -50 + +KPX Rcommaaccent W -30 + +KPX Rcommaaccent Y -50 + +KPX Rcommaaccent Yacute -50 + +KPX Rcommaaccent Ydieresis -50 + +KPX S comma -20 + +KPX S period -20 + +KPX Sacute comma -20 + +KPX Sacute period -20 + +KPX Scaron comma -20 + +KPX Scaron period -20 + +KPX Scedilla comma -20 + +KPX Scedilla period -20 + +KPX Scommaaccent comma -20 + +KPX Scommaaccent period -20 + +KPX T A -120 + +KPX T Aacute -120 + +KPX T Abreve -120 + +KPX T Acircumflex -120 + +KPX T Adieresis -120 + +KPX T Agrave -120 + +KPX T Amacron -120 + +KPX T Aogonek -120 + +KPX T Aring -120 + +KPX T Atilde -120 + +KPX T O -40 + +KPX T Oacute -40 + +KPX T Ocircumflex -40 + +KPX T Odieresis -40 + +KPX T Ograve -40 + +KPX T Ohungarumlaut -40 + +KPX T Omacron -40 + +KPX T Oslash -40 + +KPX T Otilde -40 + +KPX T a -120 + +KPX T aacute -120 + +KPX T abreve -60 + +KPX T acircumflex -120 + +KPX T adieresis -120 + +KPX T agrave -120 + +KPX T amacron -60 + +KPX T aogonek -120 + +KPX T aring -120 + +KPX T atilde -60 + +KPX T colon -20 + +KPX T comma -120 + +KPX T e -120 + +KPX T eacute -120 + +KPX T ecaron -120 + +KPX T ecircumflex -120 + +KPX T edieresis -120 + +KPX T edotaccent -120 + +KPX T egrave -60 + +KPX T emacron -60 + +KPX T eogonek -120 + +KPX T hyphen -140 + +KPX T o -120 + +KPX T oacute -120 + +KPX T ocircumflex -120 + +KPX T odieresis -120 + +KPX T ograve -120 + +KPX T ohungarumlaut -120 + +KPX T omacron -60 + +KPX T oslash -120 + +KPX T otilde -60 + +KPX T period -120 + +KPX T r -120 + +KPX T racute -120 + +KPX T rcaron -120 + +KPX T rcommaaccent -120 + +KPX T semicolon -20 + +KPX T u -120 + +KPX T uacute -120 + +KPX T ucircumflex -120 + +KPX T udieresis -120 + +KPX T ugrave -120 + +KPX T uhungarumlaut -120 + +KPX T umacron -60 + +KPX T uogonek -120 + +KPX T uring -120 + +KPX T w -120 + +KPX T y -120 + +KPX T yacute -120 + +KPX T ydieresis -60 + +KPX Tcaron A -120 + +KPX Tcaron Aacute -120 + +KPX Tcaron Abreve -120 + +KPX Tcaron Acircumflex -120 + +KPX Tcaron Adieresis -120 + +KPX Tcaron Agrave -120 + +KPX Tcaron Amacron -120 + +KPX Tcaron Aogonek -120 + +KPX Tcaron Aring -120 + +KPX Tcaron Atilde -120 + +KPX Tcaron O -40 + +KPX Tcaron Oacute -40 + +KPX Tcaron Ocircumflex -40 + +KPX Tcaron Odieresis -40 + +KPX Tcaron Ograve -40 + +KPX Tcaron Ohungarumlaut -40 + +KPX Tcaron Omacron -40 + +KPX Tcaron Oslash -40 + +KPX Tcaron Otilde -40 + +KPX Tcaron a -120 + +KPX Tcaron aacute -120 + +KPX Tcaron abreve -60 + +KPX Tcaron acircumflex -120 + +KPX Tcaron adieresis -120 + +KPX Tcaron agrave -120 + +KPX Tcaron amacron -60 + +KPX Tcaron aogonek -120 + +KPX Tcaron aring -120 + +KPX Tcaron atilde -60 + +KPX Tcaron colon -20 + +KPX Tcaron comma -120 + +KPX Tcaron e -120 + +KPX Tcaron eacute -120 + +KPX Tcaron ecaron -120 + +KPX Tcaron ecircumflex -120 + +KPX Tcaron edieresis -120 + +KPX Tcaron edotaccent -120 + +KPX Tcaron egrave -60 + +KPX Tcaron emacron -60 + +KPX Tcaron eogonek -120 + +KPX Tcaron hyphen -140 + +KPX Tcaron o -120 + +KPX Tcaron oacute -120 + +KPX Tcaron ocircumflex -120 + +KPX Tcaron odieresis -120 + +KPX Tcaron ograve -120 + +KPX Tcaron ohungarumlaut -120 + +KPX Tcaron omacron -60 + +KPX Tcaron oslash -120 + +KPX Tcaron otilde -60 + +KPX Tcaron period -120 + +KPX Tcaron r -120 + +KPX Tcaron racute -120 + +KPX Tcaron rcaron -120 + +KPX Tcaron rcommaaccent -120 + +KPX Tcaron semicolon -20 + +KPX Tcaron u -120 + +KPX Tcaron uacute -120 + +KPX Tcaron ucircumflex -120 + +KPX Tcaron udieresis -120 + +KPX Tcaron ugrave -120 + +KPX Tcaron uhungarumlaut -120 + +KPX Tcaron umacron -60 + +KPX Tcaron uogonek -120 + +KPX Tcaron uring -120 + +KPX Tcaron w -120 + +KPX Tcaron y -120 + +KPX Tcaron yacute -120 + +KPX Tcaron ydieresis -60 + +KPX Tcommaaccent A -120 + +KPX Tcommaaccent Aacute -120 + +KPX Tcommaaccent Abreve -120 + +KPX Tcommaaccent Acircumflex -120 + +KPX Tcommaaccent Adieresis -120 + +KPX Tcommaaccent Agrave -120 + +KPX Tcommaaccent Amacron -120 + +KPX Tcommaaccent Aogonek -120 + +KPX Tcommaaccent Aring -120 + +KPX Tcommaaccent Atilde -120 + +KPX Tcommaaccent O -40 + +KPX Tcommaaccent Oacute -40 + +KPX Tcommaaccent Ocircumflex -40 + +KPX Tcommaaccent Odieresis -40 + +KPX Tcommaaccent Ograve -40 + +KPX Tcommaaccent Ohungarumlaut -40 + +KPX Tcommaaccent Omacron -40 + +KPX Tcommaaccent Oslash -40 + +KPX Tcommaaccent Otilde -40 + +KPX Tcommaaccent a -120 + +KPX Tcommaaccent aacute -120 + +KPX Tcommaaccent abreve -60 + +KPX Tcommaaccent acircumflex -120 + +KPX Tcommaaccent adieresis -120 + +KPX Tcommaaccent agrave -120 + +KPX Tcommaaccent amacron -60 + +KPX Tcommaaccent aogonek -120 + +KPX Tcommaaccent aring -120 + +KPX Tcommaaccent atilde -60 + +KPX Tcommaaccent colon -20 + +KPX Tcommaaccent comma -120 + +KPX Tcommaaccent e -120 + +KPX Tcommaaccent eacute -120 + +KPX Tcommaaccent ecaron -120 + +KPX Tcommaaccent ecircumflex -120 + +KPX Tcommaaccent edieresis -120 + +KPX Tcommaaccent edotaccent -120 + +KPX Tcommaaccent egrave -60 + +KPX Tcommaaccent emacron -60 + +KPX Tcommaaccent eogonek -120 + +KPX Tcommaaccent hyphen -140 + +KPX Tcommaaccent o -120 + +KPX Tcommaaccent oacute -120 + +KPX Tcommaaccent ocircumflex -120 + +KPX Tcommaaccent odieresis -120 + +KPX Tcommaaccent ograve -120 + +KPX Tcommaaccent ohungarumlaut -120 + +KPX Tcommaaccent omacron -60 + +KPX Tcommaaccent oslash -120 + +KPX Tcommaaccent otilde -60 + +KPX Tcommaaccent period -120 + +KPX Tcommaaccent r -120 + +KPX Tcommaaccent racute -120 + +KPX Tcommaaccent rcaron -120 + +KPX Tcommaaccent rcommaaccent -120 + +KPX Tcommaaccent semicolon -20 + +KPX Tcommaaccent u -120 + +KPX Tcommaaccent uacute -120 + +KPX Tcommaaccent ucircumflex -120 + +KPX Tcommaaccent udieresis -120 + +KPX Tcommaaccent ugrave -120 + +KPX Tcommaaccent uhungarumlaut -120 + +KPX Tcommaaccent umacron -60 + +KPX Tcommaaccent uogonek -120 + +KPX Tcommaaccent uring -120 + +KPX Tcommaaccent w -120 + +KPX Tcommaaccent y -120 + +KPX Tcommaaccent yacute -120 + +KPX Tcommaaccent ydieresis -60 + +KPX U A -40 + +KPX U Aacute -40 + +KPX U Abreve -40 + +KPX U Acircumflex -40 + +KPX U Adieresis -40 + +KPX U Agrave -40 + +KPX U Amacron -40 + +KPX U Aogonek -40 + +KPX U Aring -40 + +KPX U Atilde -40 + +KPX U comma -40 + +KPX U period -40 + +KPX Uacute A -40 + +KPX Uacute Aacute -40 + +KPX Uacute Abreve -40 + +KPX Uacute Acircumflex -40 + +KPX Uacute Adieresis -40 + +KPX Uacute Agrave -40 + +KPX Uacute Amacron -40 + +KPX Uacute Aogonek -40 + +KPX Uacute Aring -40 + +KPX Uacute Atilde -40 + +KPX Uacute comma -40 + +KPX Uacute period -40 + +KPX Ucircumflex A -40 + +KPX Ucircumflex Aacute -40 + +KPX Ucircumflex Abreve -40 + +KPX Ucircumflex Acircumflex -40 + +KPX Ucircumflex Adieresis -40 + +KPX Ucircumflex Agrave -40 + +KPX Ucircumflex Amacron -40 + +KPX Ucircumflex Aogonek -40 + +KPX Ucircumflex Aring -40 + +KPX Ucircumflex Atilde -40 + +KPX Ucircumflex comma -40 + +KPX Ucircumflex period -40 + +KPX Udieresis A -40 + +KPX Udieresis Aacute -40 + +KPX Udieresis Abreve -40 + +KPX Udieresis Acircumflex -40 + +KPX Udieresis Adieresis -40 + +KPX Udieresis Agrave -40 + +KPX Udieresis Amacron -40 + +KPX Udieresis Aogonek -40 + +KPX Udieresis Aring -40 + +KPX Udieresis Atilde -40 + +KPX Udieresis comma -40 + +KPX Udieresis period -40 + +KPX Ugrave A -40 + +KPX Ugrave Aacute -40 + +KPX Ugrave Abreve -40 + +KPX Ugrave Acircumflex -40 + +KPX Ugrave Adieresis -40 + +KPX Ugrave Agrave -40 + +KPX Ugrave Amacron -40 + +KPX Ugrave Aogonek -40 + +KPX Ugrave Aring -40 + +KPX Ugrave Atilde -40 + +KPX Ugrave comma -40 + +KPX Ugrave period -40 + +KPX Uhungarumlaut A -40 + +KPX Uhungarumlaut Aacute -40 + +KPX Uhungarumlaut Abreve -40 + +KPX Uhungarumlaut Acircumflex -40 + +KPX Uhungarumlaut Adieresis -40 + +KPX Uhungarumlaut Agrave -40 + +KPX Uhungarumlaut Amacron -40 + +KPX Uhungarumlaut Aogonek -40 + +KPX Uhungarumlaut Aring -40 + +KPX Uhungarumlaut Atilde -40 + +KPX Uhungarumlaut comma -40 + +KPX Uhungarumlaut period -40 + +KPX Umacron A -40 + +KPX Umacron Aacute -40 + +KPX Umacron Abreve -40 + +KPX Umacron Acircumflex -40 + +KPX Umacron Adieresis -40 + +KPX Umacron Agrave -40 + +KPX Umacron Amacron -40 + +KPX Umacron Aogonek -40 + +KPX Umacron Aring -40 + +KPX Umacron Atilde -40 + +KPX Umacron comma -40 + +KPX Umacron period -40 + +KPX Uogonek A -40 + +KPX Uogonek Aacute -40 + +KPX Uogonek Abreve -40 + +KPX Uogonek Acircumflex -40 + +KPX Uogonek Adieresis -40 + +KPX Uogonek Agrave -40 + +KPX Uogonek Amacron -40 + +KPX Uogonek Aogonek -40 + +KPX Uogonek Aring -40 + +KPX Uogonek Atilde -40 + +KPX Uogonek comma -40 + +KPX Uogonek period -40 + +KPX Uring A -40 + +KPX Uring Aacute -40 + +KPX Uring Abreve -40 + +KPX Uring Acircumflex -40 + +KPX Uring Adieresis -40 + +KPX Uring Agrave -40 + +KPX Uring Amacron -40 + +KPX Uring Aogonek -40 + +KPX Uring Aring -40 + +KPX Uring Atilde -40 + +KPX Uring comma -40 + +KPX Uring period -40 + +KPX V A -80 + +KPX V Aacute -80 + +KPX V Abreve -80 + +KPX V Acircumflex -80 + +KPX V Adieresis -80 + +KPX V Agrave -80 + +KPX V Amacron -80 + +KPX V Aogonek -80 + +KPX V Aring -80 + +KPX V Atilde -80 + +KPX V G -40 + +KPX V Gbreve -40 + +KPX V Gcommaaccent -40 + +KPX V O -40 + +KPX V Oacute -40 + +KPX V Ocircumflex -40 + +KPX V Odieresis -40 + +KPX V Ograve -40 + +KPX V Ohungarumlaut -40 + +KPX V Omacron -40 + +KPX V Oslash -40 + +KPX V Otilde -40 + +KPX V a -70 + +KPX V aacute -70 + +KPX V abreve -70 + +KPX V acircumflex -70 + +KPX V adieresis -70 + +KPX V agrave -70 + +KPX V amacron -70 + +KPX V aogonek -70 + +KPX V aring -70 + +KPX V atilde -70 + +KPX V colon -40 + +KPX V comma -125 + +KPX V e -80 + +KPX V eacute -80 + +KPX V ecaron -80 + +KPX V ecircumflex -80 + +KPX V edieresis -80 + +KPX V edotaccent -80 + +KPX V egrave -80 + +KPX V emacron -80 + +KPX V eogonek -80 + +KPX V hyphen -80 + +KPX V o -80 + +KPX V oacute -80 + +KPX V ocircumflex -80 + +KPX V odieresis -80 + +KPX V ograve -80 + +KPX V ohungarumlaut -80 + +KPX V omacron -80 + +KPX V oslash -80 + +KPX V otilde -80 + +KPX V period -125 + +KPX V semicolon -40 + +KPX V u -70 + +KPX V uacute -70 + +KPX V ucircumflex -70 + +KPX V udieresis -70 + +KPX V ugrave -70 + +KPX V uhungarumlaut -70 + +KPX V umacron -70 + +KPX V uogonek -70 + +KPX V uring -70 + +KPX W A -50 + +KPX W Aacute -50 + +KPX W Abreve -50 + +KPX W Acircumflex -50 + +KPX W Adieresis -50 + +KPX W Agrave -50 + +KPX W Amacron -50 + +KPX W Aogonek -50 + +KPX W Aring -50 + +KPX W Atilde -50 + +KPX W O -20 + +KPX W Oacute -20 + +KPX W Ocircumflex -20 + +KPX W Odieresis -20 + +KPX W Ograve -20 + +KPX W Ohungarumlaut -20 + +KPX W Omacron -20 + +KPX W Oslash -20 + +KPX W Otilde -20 + +KPX W a -40 + +KPX W aacute -40 + +KPX W abreve -40 + +KPX W acircumflex -40 + +KPX W adieresis -40 + +KPX W agrave -40 + +KPX W amacron -40 + +KPX W aogonek -40 + +KPX W aring -40 + +KPX W atilde -40 + +KPX W comma -80 + +KPX W e -30 + +KPX W eacute -30 + +KPX W ecaron -30 + +KPX W ecircumflex -30 + +KPX W edieresis -30 + +KPX W edotaccent -30 + +KPX W egrave -30 + +KPX W emacron -30 + +KPX W eogonek -30 + +KPX W hyphen -40 + +KPX W o -30 + +KPX W oacute -30 + +KPX W ocircumflex -30 + +KPX W odieresis -30 + +KPX W ograve -30 + +KPX W ohungarumlaut -30 + +KPX W omacron -30 + +KPX W oslash -30 + +KPX W otilde -30 + +KPX W period -80 + +KPX W u -30 + +KPX W uacute -30 + +KPX W ucircumflex -30 + +KPX W udieresis -30 + +KPX W ugrave -30 + +KPX W uhungarumlaut -30 + +KPX W umacron -30 + +KPX W uogonek -30 + +KPX W uring -30 + +KPX W y -20 + +KPX W yacute -20 + +KPX W ydieresis -20 + +KPX Y A -110 + +KPX Y Aacute -110 + +KPX Y Abreve -110 + +KPX Y Acircumflex -110 + +KPX Y Adieresis -110 + +KPX Y Agrave -110 + +KPX Y Amacron -110 + +KPX Y Aogonek -110 + +KPX Y Aring -110 + +KPX Y Atilde -110 + +KPX Y O -85 + +KPX Y Oacute -85 + +KPX Y Ocircumflex -85 + +KPX Y Odieresis -85 + +KPX Y Ograve -85 + +KPX Y Ohungarumlaut -85 + +KPX Y Omacron -85 + +KPX Y Oslash -85 + +KPX Y Otilde -85 + +KPX Y a -140 + +KPX Y aacute -140 + +KPX Y abreve -70 + +KPX Y acircumflex -140 + +KPX Y adieresis -140 + +KPX Y agrave -140 + +KPX Y amacron -70 + +KPX Y aogonek -140 + +KPX Y aring -140 + +KPX Y atilde -140 + +KPX Y colon -60 + +KPX Y comma -140 + +KPX Y e -140 + +KPX Y eacute -140 + +KPX Y ecaron -140 + +KPX Y ecircumflex -140 + +KPX Y edieresis -140 + +KPX Y edotaccent -140 + +KPX Y egrave -140 + +KPX Y emacron -70 + +KPX Y eogonek -140 + +KPX Y hyphen -140 + +KPX Y i -20 + +KPX Y iacute -20 + +KPX Y iogonek -20 + +KPX Y o -140 + +KPX Y oacute -140 + +KPX Y ocircumflex -140 + +KPX Y odieresis -140 + +KPX Y ograve -140 + +KPX Y ohungarumlaut -140 + +KPX Y omacron -140 + +KPX Y oslash -140 + +KPX Y otilde -140 + +KPX Y period -140 + +KPX Y semicolon -60 + +KPX Y u -110 + +KPX Y uacute -110 + +KPX Y ucircumflex -110 + +KPX Y udieresis -110 + +KPX Y ugrave -110 + +KPX Y uhungarumlaut -110 + +KPX Y umacron -110 + +KPX Y uogonek -110 + +KPX Y uring -110 + +KPX Yacute A -110 + +KPX Yacute Aacute -110 + +KPX Yacute Abreve -110 + +KPX Yacute Acircumflex -110 + +KPX Yacute Adieresis -110 + +KPX Yacute Agrave -110 + +KPX Yacute Amacron -110 + +KPX Yacute Aogonek -110 + +KPX Yacute Aring -110 + +KPX Yacute Atilde -110 + +KPX Yacute O -85 + +KPX Yacute Oacute -85 + +KPX Yacute Ocircumflex -85 + +KPX Yacute Odieresis -85 + +KPX Yacute Ograve -85 + +KPX Yacute Ohungarumlaut -85 + +KPX Yacute Omacron -85 + +KPX Yacute Oslash -85 + +KPX Yacute Otilde -85 + +KPX Yacute a -140 + +KPX Yacute aacute -140 + +KPX Yacute abreve -70 + +KPX Yacute acircumflex -140 + +KPX Yacute adieresis -140 + +KPX Yacute agrave -140 + +KPX Yacute amacron -70 + +KPX Yacute aogonek -140 + +KPX Yacute aring -140 + +KPX Yacute atilde -70 + +KPX Yacute colon -60 + +KPX Yacute comma -140 + +KPX Yacute e -140 + +KPX Yacute eacute -140 + +KPX Yacute ecaron -140 + +KPX Yacute ecircumflex -140 + +KPX Yacute edieresis -140 + +KPX Yacute edotaccent -140 + +KPX Yacute egrave -140 + +KPX Yacute emacron -70 + +KPX Yacute eogonek -140 + +KPX Yacute hyphen -140 + +KPX Yacute i -20 + +KPX Yacute iacute -20 + +KPX Yacute iogonek -20 + +KPX Yacute o -140 + +KPX Yacute oacute -140 + +KPX Yacute ocircumflex -140 + +KPX Yacute odieresis -140 + +KPX Yacute ograve -140 + +KPX Yacute ohungarumlaut -140 + +KPX Yacute omacron -70 + +KPX Yacute oslash -140 + +KPX Yacute otilde -140 + +KPX Yacute period -140 + +KPX Yacute semicolon -60 + +KPX Yacute u -110 + +KPX Yacute uacute -110 + +KPX Yacute ucircumflex -110 + +KPX Yacute udieresis -110 + +KPX Yacute ugrave -110 + +KPX Yacute uhungarumlaut -110 + +KPX Yacute umacron -110 + +KPX Yacute uogonek -110 + +KPX Yacute uring -110 + +KPX Ydieresis A -110 + +KPX Ydieresis Aacute -110 + +KPX Ydieresis Abreve -110 + +KPX Ydieresis Acircumflex -110 + +KPX Ydieresis Adieresis -110 + +KPX Ydieresis Agrave -110 + +KPX Ydieresis Amacron -110 + +KPX Ydieresis Aogonek -110 + +KPX Ydieresis Aring -110 + +KPX Ydieresis Atilde -110 + +KPX Ydieresis O -85 + +KPX Ydieresis Oacute -85 + +KPX Ydieresis Ocircumflex -85 + +KPX Ydieresis Odieresis -85 + +KPX Ydieresis Ograve -85 + +KPX Ydieresis Ohungarumlaut -85 + +KPX Ydieresis Omacron -85 + +KPX Ydieresis Oslash -85 + +KPX Ydieresis Otilde -85 + +KPX Ydieresis a -140 + +KPX Ydieresis aacute -140 + +KPX Ydieresis abreve -70 + +KPX Ydieresis acircumflex -140 + +KPX Ydieresis adieresis -140 + +KPX Ydieresis agrave -140 + +KPX Ydieresis amacron -70 + +KPX Ydieresis aogonek -140 + +KPX Ydieresis aring -140 + +KPX Ydieresis atilde -70 + +KPX Ydieresis colon -60 + +KPX Ydieresis comma -140 + +KPX Ydieresis e -140 + +KPX Ydieresis eacute -140 + +KPX Ydieresis ecaron -140 + +KPX Ydieresis ecircumflex -140 + +KPX Ydieresis edieresis -140 + +KPX Ydieresis edotaccent -140 + +KPX Ydieresis egrave -140 + +KPX Ydieresis emacron -70 + +KPX Ydieresis eogonek -140 + +KPX Ydieresis hyphen -140 + +KPX Ydieresis i -20 + +KPX Ydieresis iacute -20 + +KPX Ydieresis iogonek -20 + +KPX Ydieresis o -140 + +KPX Ydieresis oacute -140 + +KPX Ydieresis ocircumflex -140 + +KPX Ydieresis odieresis -140 + +KPX Ydieresis ograve -140 + +KPX Ydieresis ohungarumlaut -140 + +KPX Ydieresis omacron -140 + +KPX Ydieresis oslash -140 + +KPX Ydieresis otilde -140 + +KPX Ydieresis period -140 + +KPX Ydieresis semicolon -60 + +KPX Ydieresis u -110 + +KPX Ydieresis uacute -110 + +KPX Ydieresis ucircumflex -110 + +KPX Ydieresis udieresis -110 + +KPX Ydieresis ugrave -110 + +KPX Ydieresis uhungarumlaut -110 + +KPX Ydieresis umacron -110 + +KPX Ydieresis uogonek -110 + +KPX Ydieresis uring -110 + +KPX a v -20 + +KPX a w -20 + +KPX a y -30 + +KPX a yacute -30 + +KPX a ydieresis -30 + +KPX aacute v -20 + +KPX aacute w -20 + +KPX aacute y -30 + +KPX aacute yacute -30 + +KPX aacute ydieresis -30 + +KPX abreve v -20 + +KPX abreve w -20 + +KPX abreve y -30 + +KPX abreve yacute -30 + +KPX abreve ydieresis -30 + +KPX acircumflex v -20 + +KPX acircumflex w -20 + +KPX acircumflex y -30 + +KPX acircumflex yacute -30 + +KPX acircumflex ydieresis -30 + +KPX adieresis v -20 + +KPX adieresis w -20 + +KPX adieresis y -30 + +KPX adieresis yacute -30 + +KPX adieresis ydieresis -30 + +KPX agrave v -20 + +KPX agrave w -20 + +KPX agrave y -30 + +KPX agrave yacute -30 + +KPX agrave ydieresis -30 + +KPX amacron v -20 + +KPX amacron w -20 + +KPX amacron y -30 + +KPX amacron yacute -30 + +KPX amacron ydieresis -30 + +KPX aogonek v -20 + +KPX aogonek w -20 + +KPX aogonek y -30 + +KPX aogonek yacute -30 + +KPX aogonek ydieresis -30 + +KPX aring v -20 + +KPX aring w -20 + +KPX aring y -30 + +KPX aring yacute -30 + +KPX aring ydieresis -30 + +KPX atilde v -20 + +KPX atilde w -20 + +KPX atilde y -30 + +KPX atilde yacute -30 + +KPX atilde ydieresis -30 + +KPX b b -10 + +KPX b comma -40 + +KPX b l -20 + +KPX b lacute -20 + +KPX b lcommaaccent -20 + +KPX b lslash -20 + +KPX b period -40 + +KPX b u -20 + +KPX b uacute -20 + +KPX b ucircumflex -20 + +KPX b udieresis -20 + +KPX b ugrave -20 + +KPX b uhungarumlaut -20 + +KPX b umacron -20 + +KPX b uogonek -20 + +KPX b uring -20 + +KPX b v -20 + +KPX b y -20 + +KPX b yacute -20 + +KPX b ydieresis -20 + +KPX c comma -15 + +KPX c k -20 + +KPX c kcommaaccent -20 + +KPX cacute comma -15 + +KPX cacute k -20 + +KPX cacute kcommaaccent -20 + +KPX ccaron comma -15 + +KPX ccaron k -20 + +KPX ccaron kcommaaccent -20 + +KPX ccedilla comma -15 + +KPX ccedilla k -20 + +KPX ccedilla kcommaaccent -20 + +KPX colon space -50 + +KPX comma quotedblright -100 + +KPX comma quoteright -100 + +KPX e comma -15 + +KPX e period -15 + +KPX e v -30 + +KPX e w -20 + +KPX e x -30 + +KPX e y -20 + +KPX e yacute -20 + +KPX e ydieresis -20 + +KPX eacute comma -15 + +KPX eacute period -15 + +KPX eacute v -30 + +KPX eacute w -20 + +KPX eacute x -30 + +KPX eacute y -20 + +KPX eacute yacute -20 + +KPX eacute ydieresis -20 + +KPX ecaron comma -15 + +KPX ecaron period -15 + +KPX ecaron v -30 + +KPX ecaron w -20 + +KPX ecaron x -30 + +KPX ecaron y -20 + +KPX ecaron yacute -20 + +KPX ecaron ydieresis -20 + +KPX ecircumflex comma -15 + +KPX ecircumflex period -15 + +KPX ecircumflex v -30 + +KPX ecircumflex w -20 + +KPX ecircumflex x -30 + +KPX ecircumflex y -20 + +KPX ecircumflex yacute -20 + +KPX ecircumflex ydieresis -20 + +KPX edieresis comma -15 + +KPX edieresis period -15 + +KPX edieresis v -30 + +KPX edieresis w -20 + +KPX edieresis x -30 + +KPX edieresis y -20 + +KPX edieresis yacute -20 + +KPX edieresis ydieresis -20 + +KPX edotaccent comma -15 + +KPX edotaccent period -15 + +KPX edotaccent v -30 + +KPX edotaccent w -20 + +KPX edotaccent x -30 + +KPX edotaccent y -20 + +KPX edotaccent yacute -20 + +KPX edotaccent ydieresis -20 + +KPX egrave comma -15 + +KPX egrave period -15 + +KPX egrave v -30 + +KPX egrave w -20 + +KPX egrave x -30 + +KPX egrave y -20 + +KPX egrave yacute -20 + +KPX egrave ydieresis -20 + +KPX emacron comma -15 + +KPX emacron period -15 + +KPX emacron v -30 + +KPX emacron w -20 + +KPX emacron x -30 + +KPX emacron y -20 + +KPX emacron yacute -20 + +KPX emacron ydieresis -20 + +KPX eogonek comma -15 + +KPX eogonek period -15 + +KPX eogonek v -30 + +KPX eogonek w -20 + +KPX eogonek x -30 + +KPX eogonek y -20 + +KPX eogonek yacute -20 + +KPX eogonek ydieresis -20 + +KPX f a -30 + +KPX f aacute -30 + +KPX f abreve -30 + +KPX f acircumflex -30 + +KPX f adieresis -30 + +KPX f agrave -30 + +KPX f amacron -30 + +KPX f aogonek -30 + +KPX f aring -30 + +KPX f atilde -30 + +KPX f comma -30 + +KPX f dotlessi -28 + +KPX f e -30 + +KPX f eacute -30 + +KPX f ecaron -30 + +KPX f ecircumflex -30 + +KPX f edieresis -30 + +KPX f edotaccent -30 + +KPX f egrave -30 + +KPX f emacron -30 + +KPX f eogonek -30 + +KPX f o -30 + +KPX f oacute -30 + +KPX f ocircumflex -30 + +KPX f odieresis -30 + +KPX f ograve -30 + +KPX f ohungarumlaut -30 + +KPX f omacron -30 + +KPX f oslash -30 + +KPX f otilde -30 + +KPX f period -30 + +KPX f quotedblright 60 + +KPX f quoteright 50 + +KPX g r -10 + +KPX g racute -10 + +KPX g rcaron -10 + +KPX g rcommaaccent -10 + +KPX gbreve r -10 + +KPX gbreve racute -10 + +KPX gbreve rcaron -10 + +KPX gbreve rcommaaccent -10 + +KPX gcommaaccent r -10 + +KPX gcommaaccent racute -10 + +KPX gcommaaccent rcaron -10 + +KPX gcommaaccent rcommaaccent -10 + +KPX h y -30 + +KPX h yacute -30 + +KPX h ydieresis -30 + +KPX k e -20 + +KPX k eacute -20 + +KPX k ecaron -20 + +KPX k ecircumflex -20 + +KPX k edieresis -20 + +KPX k edotaccent -20 + +KPX k egrave -20 + +KPX k emacron -20 + +KPX k eogonek -20 + +KPX k o -20 + +KPX k oacute -20 + +KPX k ocircumflex -20 + +KPX k odieresis -20 + +KPX k ograve -20 + +KPX k ohungarumlaut -20 + +KPX k omacron -20 + +KPX k oslash -20 + +KPX k otilde -20 + +KPX kcommaaccent e -20 + +KPX kcommaaccent eacute -20 + +KPX kcommaaccent ecaron -20 + +KPX kcommaaccent ecircumflex -20 + +KPX kcommaaccent edieresis -20 + +KPX kcommaaccent edotaccent -20 + +KPX kcommaaccent egrave -20 + +KPX kcommaaccent emacron -20 + +KPX kcommaaccent eogonek -20 + +KPX kcommaaccent o -20 + +KPX kcommaaccent oacute -20 + +KPX kcommaaccent ocircumflex -20 + +KPX kcommaaccent odieresis -20 + +KPX kcommaaccent ograve -20 + +KPX kcommaaccent ohungarumlaut -20 + +KPX kcommaaccent omacron -20 + +KPX kcommaaccent oslash -20 + +KPX kcommaaccent otilde -20 + +KPX m u -10 + +KPX m uacute -10 + +KPX m ucircumflex -10 + +KPX m udieresis -10 + +KPX m ugrave -10 + +KPX m uhungarumlaut -10 + +KPX m umacron -10 + +KPX m uogonek -10 + +KPX m uring -10 + +KPX m y -15 + +KPX m yacute -15 + +KPX m ydieresis -15 + +KPX n u -10 + +KPX n uacute -10 + +KPX n ucircumflex -10 + +KPX n udieresis -10 + +KPX n ugrave -10 + +KPX n uhungarumlaut -10 + +KPX n umacron -10 + +KPX n uogonek -10 + +KPX n uring -10 + +KPX n v -20 + +KPX n y -15 + +KPX n yacute -15 + +KPX n ydieresis -15 + +KPX nacute u -10 + +KPX nacute uacute -10 + +KPX nacute ucircumflex -10 + +KPX nacute udieresis -10 + +KPX nacute ugrave -10 + +KPX nacute uhungarumlaut -10 + +KPX nacute umacron -10 + +KPX nacute uogonek -10 + +KPX nacute uring -10 + +KPX nacute v -20 + +KPX nacute y -15 + +KPX nacute yacute -15 + +KPX nacute ydieresis -15 + +KPX ncaron u -10 + +KPX ncaron uacute -10 + +KPX ncaron ucircumflex -10 + +KPX ncaron udieresis -10 + +KPX ncaron ugrave -10 + +KPX ncaron uhungarumlaut -10 + +KPX ncaron umacron -10 + +KPX ncaron uogonek -10 + +KPX ncaron uring -10 + +KPX ncaron v -20 + +KPX ncaron y -15 + +KPX ncaron yacute -15 + +KPX ncaron ydieresis -15 + +KPX ncommaaccent u -10 + +KPX ncommaaccent uacute -10 + +KPX ncommaaccent ucircumflex -10 + +KPX ncommaaccent udieresis -10 + +KPX ncommaaccent ugrave -10 + +KPX ncommaaccent uhungarumlaut -10 + +KPX ncommaaccent umacron -10 + +KPX ncommaaccent uogonek -10 + +KPX ncommaaccent uring -10 + +KPX ncommaaccent v -20 + +KPX ncommaaccent y -15 + +KPX ncommaaccent yacute -15 + +KPX ncommaaccent ydieresis -15 + +KPX ntilde u -10 + +KPX ntilde uacute -10 + +KPX ntilde ucircumflex -10 + +KPX ntilde udieresis -10 + +KPX ntilde ugrave -10 + +KPX ntilde uhungarumlaut -10 + +KPX ntilde umacron -10 + +KPX ntilde uogonek -10 + +KPX ntilde uring -10 + +KPX ntilde v -20 + +KPX ntilde y -15 + +KPX ntilde yacute -15 + +KPX ntilde ydieresis -15 + +KPX o comma -40 + +KPX o period -40 + +KPX o v -15 + +KPX o w -15 + +KPX o x -30 + +KPX o y -30 + +KPX o yacute -30 + +KPX o ydieresis -30 + +KPX oacute comma -40 + +KPX oacute period -40 + +KPX oacute v -15 + +KPX oacute w -15 + +KPX oacute x -30 + +KPX oacute y -30 + +KPX oacute yacute -30 + +KPX oacute ydieresis -30 + +KPX ocircumflex comma -40 + +KPX ocircumflex period -40 + +KPX ocircumflex v -15 + +KPX ocircumflex w -15 + +KPX ocircumflex x -30 + +KPX ocircumflex y -30 + +KPX ocircumflex yacute -30 + +KPX ocircumflex ydieresis -30 + +KPX odieresis comma -40 + +KPX odieresis period -40 + +KPX odieresis v -15 + +KPX odieresis w -15 + +KPX odieresis x -30 + +KPX odieresis y -30 + +KPX odieresis yacute -30 + +KPX odieresis ydieresis -30 + +KPX ograve comma -40 + +KPX ograve period -40 + +KPX ograve v -15 + +KPX ograve w -15 + +KPX ograve x -30 + +KPX ograve y -30 + +KPX ograve yacute -30 + +KPX ograve ydieresis -30 + +KPX ohungarumlaut comma -40 + +KPX ohungarumlaut period -40 + +KPX ohungarumlaut v -15 + +KPX ohungarumlaut w -15 + +KPX ohungarumlaut x -30 + +KPX ohungarumlaut y -30 + +KPX ohungarumlaut yacute -30 + +KPX ohungarumlaut ydieresis -30 + +KPX omacron comma -40 + +KPX omacron period -40 + +KPX omacron v -15 + +KPX omacron w -15 + +KPX omacron x -30 + +KPX omacron y -30 + +KPX omacron yacute -30 + +KPX omacron ydieresis -30 + +KPX oslash a -55 + +KPX oslash aacute -55 + +KPX oslash abreve -55 + +KPX oslash acircumflex -55 + +KPX oslash adieresis -55 + +KPX oslash agrave -55 + +KPX oslash amacron -55 + +KPX oslash aogonek -55 + +KPX oslash aring -55 + +KPX oslash atilde -55 + +KPX oslash b -55 + +KPX oslash c -55 + +KPX oslash cacute -55 + +KPX oslash ccaron -55 + +KPX oslash ccedilla -55 + +KPX oslash comma -95 + +KPX oslash d -55 + +KPX oslash dcroat -55 + +KPX oslash e -55 + +KPX oslash eacute -55 + +KPX oslash ecaron -55 + +KPX oslash ecircumflex -55 + +KPX oslash edieresis -55 + +KPX oslash edotaccent -55 + +KPX oslash egrave -55 + +KPX oslash emacron -55 + +KPX oslash eogonek -55 + +KPX oslash f -55 + +KPX oslash g -55 + +KPX oslash gbreve -55 + +KPX oslash gcommaaccent -55 + +KPX oslash h -55 + +KPX oslash i -55 + +KPX oslash iacute -55 + +KPX oslash icircumflex -55 + +KPX oslash idieresis -55 + +KPX oslash igrave -55 + +KPX oslash imacron -55 + +KPX oslash iogonek -55 + +KPX oslash j -55 + +KPX oslash k -55 + +KPX oslash kcommaaccent -55 + +KPX oslash l -55 + +KPX oslash lacute -55 + +KPX oslash lcommaaccent -55 + +KPX oslash lslash -55 + +KPX oslash m -55 + +KPX oslash n -55 + +KPX oslash nacute -55 + +KPX oslash ncaron -55 + +KPX oslash ncommaaccent -55 + +KPX oslash ntilde -55 + +KPX oslash o -55 + +KPX oslash oacute -55 + +KPX oslash ocircumflex -55 + +KPX oslash odieresis -55 + +KPX oslash ograve -55 + +KPX oslash ohungarumlaut -55 + +KPX oslash omacron -55 + +KPX oslash oslash -55 + +KPX oslash otilde -55 + +KPX oslash p -55 + +KPX oslash period -95 + +KPX oslash q -55 + +KPX oslash r -55 + +KPX oslash racute -55 + +KPX oslash rcaron -55 + +KPX oslash rcommaaccent -55 + +KPX oslash s -55 + +KPX oslash sacute -55 + +KPX oslash scaron -55 + +KPX oslash scedilla -55 + +KPX oslash scommaaccent -55 + +KPX oslash t -55 + +KPX oslash tcommaaccent -55 + +KPX oslash u -55 + +KPX oslash uacute -55 + +KPX oslash ucircumflex -55 + +KPX oslash udieresis -55 + +KPX oslash ugrave -55 + +KPX oslash uhungarumlaut -55 + +KPX oslash umacron -55 + +KPX oslash uogonek -55 + +KPX oslash uring -55 + +KPX oslash v -70 + +KPX oslash w -70 + +KPX oslash x -85 + +KPX oslash y -70 + +KPX oslash yacute -70 + +KPX oslash ydieresis -70 + +KPX oslash z -55 + +KPX oslash zacute -55 + +KPX oslash zcaron -55 + +KPX oslash zdotaccent -55 + +KPX otilde comma -40 + +KPX otilde period -40 + +KPX otilde v -15 + +KPX otilde w -15 + +KPX otilde x -30 + +KPX otilde y -30 + +KPX otilde yacute -30 + +KPX otilde ydieresis -30 + +KPX p comma -35 + +KPX p period -35 + +KPX p y -30 + +KPX p yacute -30 + +KPX p ydieresis -30 + +KPX period quotedblright -100 + +KPX period quoteright -100 + +KPX period space -60 + +KPX quotedblright space -40 + +KPX quoteleft quoteleft -57 + +KPX quoteright d -50 + +KPX quoteright dcroat -50 + +KPX quoteright quoteright -57 + +KPX quoteright r -50 + +KPX quoteright racute -50 + +KPX quoteright rcaron -50 + +KPX quoteright rcommaaccent -50 + +KPX quoteright s -50 + +KPX quoteright sacute -50 + +KPX quoteright scaron -50 + +KPX quoteright scedilla -50 + +KPX quoteright scommaaccent -50 + +KPX quoteright space -70 + +KPX r a -10 + +KPX r aacute -10 + +KPX r abreve -10 + +KPX r acircumflex -10 + +KPX r adieresis -10 + +KPX r agrave -10 + +KPX r amacron -10 + +KPX r aogonek -10 + +KPX r aring -10 + +KPX r atilde -10 + +KPX r colon 30 + +KPX r comma -50 + +KPX r i 15 + +KPX r iacute 15 + +KPX r icircumflex 15 + +KPX r idieresis 15 + +KPX r igrave 15 + +KPX r imacron 15 + +KPX r iogonek 15 + +KPX r k 15 + +KPX r kcommaaccent 15 + +KPX r l 15 + +KPX r lacute 15 + +KPX r lcommaaccent 15 + +KPX r lslash 15 + +KPX r m 25 + +KPX r n 25 + +KPX r nacute 25 + +KPX r ncaron 25 + +KPX r ncommaaccent 25 + +KPX r ntilde 25 + +KPX r p 30 + +KPX r period -50 + +KPX r semicolon 30 + +KPX r t 40 + +KPX r tcommaaccent 40 + +KPX r u 15 + +KPX r uacute 15 + +KPX r ucircumflex 15 + +KPX r udieresis 15 + +KPX r ugrave 15 + +KPX r uhungarumlaut 15 + +KPX r umacron 15 + +KPX r uogonek 15 + +KPX r uring 15 + +KPX r v 30 + +KPX r y 30 + +KPX r yacute 30 + +KPX r ydieresis 30 + +KPX racute a -10 + +KPX racute aacute -10 + +KPX racute abreve -10 + +KPX racute acircumflex -10 + +KPX racute adieresis -10 + +KPX racute agrave -10 + +KPX racute amacron -10 + +KPX racute aogonek -10 + +KPX racute aring -10 + +KPX racute atilde -10 + +KPX racute colon 30 + +KPX racute comma -50 + +KPX racute i 15 + +KPX racute iacute 15 + +KPX racute icircumflex 15 + +KPX racute idieresis 15 + +KPX racute igrave 15 + +KPX racute imacron 15 + +KPX racute iogonek 15 + +KPX racute k 15 + +KPX racute kcommaaccent 15 + +KPX racute l 15 + +KPX racute lacute 15 + +KPX racute lcommaaccent 15 + +KPX racute lslash 15 + +KPX racute m 25 + +KPX racute n 25 + +KPX racute nacute 25 + +KPX racute ncaron 25 + +KPX racute ncommaaccent 25 + +KPX racute ntilde 25 + +KPX racute p 30 + +KPX racute period -50 + +KPX racute semicolon 30 + +KPX racute t 40 + +KPX racute tcommaaccent 40 + +KPX racute u 15 + +KPX racute uacute 15 + +KPX racute ucircumflex 15 + +KPX racute udieresis 15 + +KPX racute ugrave 15 + +KPX racute uhungarumlaut 15 + +KPX racute umacron 15 + +KPX racute uogonek 15 + +KPX racute uring 15 + +KPX racute v 30 + +KPX racute y 30 + +KPX racute yacute 30 + +KPX racute ydieresis 30 + +KPX rcaron a -10 + +KPX rcaron aacute -10 + +KPX rcaron abreve -10 + +KPX rcaron acircumflex -10 + +KPX rcaron adieresis -10 + +KPX rcaron agrave -10 + +KPX rcaron amacron -10 + +KPX rcaron aogonek -10 + +KPX rcaron aring -10 + +KPX rcaron atilde -10 + +KPX rcaron colon 30 + +KPX rcaron comma -50 + +KPX rcaron i 15 + +KPX rcaron iacute 15 + +KPX rcaron icircumflex 15 + +KPX rcaron idieresis 15 + +KPX rcaron igrave 15 + +KPX rcaron imacron 15 + +KPX rcaron iogonek 15 + +KPX rcaron k 15 + +KPX rcaron kcommaaccent 15 + +KPX rcaron l 15 + +KPX rcaron lacute 15 + +KPX rcaron lcommaaccent 15 + +KPX rcaron lslash 15 + +KPX rcaron m 25 + +KPX rcaron n 25 + +KPX rcaron nacute 25 + +KPX rcaron ncaron 25 + +KPX rcaron ncommaaccent 25 + +KPX rcaron ntilde 25 + +KPX rcaron p 30 + +KPX rcaron period -50 + +KPX rcaron semicolon 30 + +KPX rcaron t 40 + +KPX rcaron tcommaaccent 40 + +KPX rcaron u 15 + +KPX rcaron uacute 15 + +KPX rcaron ucircumflex 15 + +KPX rcaron udieresis 15 + +KPX rcaron ugrave 15 + +KPX rcaron uhungarumlaut 15 + +KPX rcaron umacron 15 + +KPX rcaron uogonek 15 + +KPX rcaron uring 15 + +KPX rcaron v 30 + +KPX rcaron y 30 + +KPX rcaron yacute 30 + +KPX rcaron ydieresis 30 + +KPX rcommaaccent a -10 + +KPX rcommaaccent aacute -10 + +KPX rcommaaccent abreve -10 + +KPX rcommaaccent acircumflex -10 + +KPX rcommaaccent adieresis -10 + +KPX rcommaaccent agrave -10 + +KPX rcommaaccent amacron -10 + +KPX rcommaaccent aogonek -10 + +KPX rcommaaccent aring -10 + +KPX rcommaaccent atilde -10 + +KPX rcommaaccent colon 30 + +KPX rcommaaccent comma -50 + +KPX rcommaaccent i 15 + +KPX rcommaaccent iacute 15 + +KPX rcommaaccent icircumflex 15 + +KPX rcommaaccent idieresis 15 + +KPX rcommaaccent igrave 15 + +KPX rcommaaccent imacron 15 + +KPX rcommaaccent iogonek 15 + +KPX rcommaaccent k 15 + +KPX rcommaaccent kcommaaccent 15 + +KPX rcommaaccent l 15 + +KPX rcommaaccent lacute 15 + +KPX rcommaaccent lcommaaccent 15 + +KPX rcommaaccent lslash 15 + +KPX rcommaaccent m 25 + +KPX rcommaaccent n 25 + +KPX rcommaaccent nacute 25 + +KPX rcommaaccent ncaron 25 + +KPX rcommaaccent ncommaaccent 25 + +KPX rcommaaccent ntilde 25 + +KPX rcommaaccent p 30 + +KPX rcommaaccent period -50 + +KPX rcommaaccent semicolon 30 + +KPX rcommaaccent t 40 + +KPX rcommaaccent tcommaaccent 40 + +KPX rcommaaccent u 15 + +KPX rcommaaccent uacute 15 + +KPX rcommaaccent ucircumflex 15 + +KPX rcommaaccent udieresis 15 + +KPX rcommaaccent ugrave 15 + +KPX rcommaaccent uhungarumlaut 15 + +KPX rcommaaccent umacron 15 + +KPX rcommaaccent uogonek 15 + +KPX rcommaaccent uring 15 + +KPX rcommaaccent v 30 + +KPX rcommaaccent y 30 + +KPX rcommaaccent yacute 30 + +KPX rcommaaccent ydieresis 30 + +KPX s comma -15 + +KPX s period -15 + +KPX s w -30 + +KPX sacute comma -15 + +KPX sacute period -15 + +KPX sacute w -30 + +KPX scaron comma -15 + +KPX scaron period -15 + +KPX scaron w -30 + +KPX scedilla comma -15 + +KPX scedilla period -15 + +KPX scedilla w -30 + +KPX scommaaccent comma -15 + +KPX scommaaccent period -15 + +KPX scommaaccent w -30 + +KPX semicolon space -50 + +KPX space T -50 + +KPX space Tcaron -50 + +KPX space Tcommaaccent -50 + +KPX space V -50 + +KPX space W -40 + +KPX space Y -90 + +KPX space Yacute -90 + +KPX space Ydieresis -90 + +KPX space quotedblleft -30 + +KPX space quoteleft -60 + +KPX v a -25 + +KPX v aacute -25 + +KPX v abreve -25 + +KPX v acircumflex -25 + +KPX v adieresis -25 + +KPX v agrave -25 + +KPX v amacron -25 + +KPX v aogonek -25 + +KPX v aring -25 + +KPX v atilde -25 + +KPX v comma -80 + +KPX v e -25 + +KPX v eacute -25 + +KPX v ecaron -25 + +KPX v ecircumflex -25 + +KPX v edieresis -25 + +KPX v edotaccent -25 + +KPX v egrave -25 + +KPX v emacron -25 + +KPX v eogonek -25 + +KPX v o -25 + +KPX v oacute -25 + +KPX v ocircumflex -25 + +KPX v odieresis -25 + +KPX v ograve -25 + +KPX v ohungarumlaut -25 + +KPX v omacron -25 + +KPX v oslash -25 + +KPX v otilde -25 + +KPX v period -80 + +KPX w a -15 + +KPX w aacute -15 + +KPX w abreve -15 + +KPX w acircumflex -15 + +KPX w adieresis -15 + +KPX w agrave -15 + +KPX w amacron -15 + +KPX w aogonek -15 + +KPX w aring -15 + +KPX w atilde -15 + +KPX w comma -60 + +KPX w e -10 + +KPX w eacute -10 + +KPX w ecaron -10 + +KPX w ecircumflex -10 + +KPX w edieresis -10 + +KPX w edotaccent -10 + +KPX w egrave -10 + +KPX w emacron -10 + +KPX w eogonek -10 + +KPX w o -10 + +KPX w oacute -10 + +KPX w ocircumflex -10 + +KPX w odieresis -10 + +KPX w ograve -10 + +KPX w ohungarumlaut -10 + +KPX w omacron -10 + +KPX w oslash -10 + +KPX w otilde -10 + +KPX w period -60 + +KPX x e -30 + +KPX x eacute -30 + +KPX x ecaron -30 + +KPX x ecircumflex -30 + +KPX x edieresis -30 + +KPX x edotaccent -30 + +KPX x egrave -30 + +KPX x emacron -30 + +KPX x eogonek -30 + +KPX y a -20 + +KPX y aacute -20 + +KPX y abreve -20 + +KPX y acircumflex -20 + +KPX y adieresis -20 + +KPX y agrave -20 + +KPX y amacron -20 + +KPX y aogonek -20 + +KPX y aring -20 + +KPX y atilde -20 + +KPX y comma -100 + +KPX y e -20 + +KPX y eacute -20 + +KPX y ecaron -20 + +KPX y ecircumflex -20 + +KPX y edieresis -20 + +KPX y edotaccent -20 + +KPX y egrave -20 + +KPX y emacron -20 + +KPX y eogonek -20 + +KPX y o -20 + +KPX y oacute -20 + +KPX y ocircumflex -20 + +KPX y odieresis -20 + +KPX y ograve -20 + +KPX y ohungarumlaut -20 + +KPX y omacron -20 + +KPX y oslash -20 + +KPX y otilde -20 + +KPX y period -100 + +KPX yacute a -20 + +KPX yacute aacute -20 + +KPX yacute abreve -20 + +KPX yacute acircumflex -20 + +KPX yacute adieresis -20 + +KPX yacute agrave -20 + +KPX yacute amacron -20 + +KPX yacute aogonek -20 + +KPX yacute aring -20 + +KPX yacute atilde -20 + +KPX yacute comma -100 + +KPX yacute e -20 + +KPX yacute eacute -20 + +KPX yacute ecaron -20 + +KPX yacute ecircumflex -20 + +KPX yacute edieresis -20 + +KPX yacute edotaccent -20 + +KPX yacute egrave -20 + +KPX yacute emacron -20 + +KPX yacute eogonek -20 + +KPX yacute o -20 + +KPX yacute oacute -20 + +KPX yacute ocircumflex -20 + +KPX yacute odieresis -20 + +KPX yacute ograve -20 + +KPX yacute ohungarumlaut -20 + +KPX yacute omacron -20 + +KPX yacute oslash -20 + +KPX yacute otilde -20 + +KPX yacute period -100 + +KPX ydieresis a -20 + +KPX ydieresis aacute -20 + +KPX ydieresis abreve -20 + +KPX ydieresis acircumflex -20 + +KPX ydieresis adieresis -20 + +KPX ydieresis agrave -20 + +KPX ydieresis amacron -20 + +KPX ydieresis aogonek -20 + +KPX ydieresis aring -20 + +KPX ydieresis atilde -20 + +KPX ydieresis comma -100 + +KPX ydieresis e -20 + +KPX ydieresis eacute -20 + +KPX ydieresis ecaron -20 + +KPX ydieresis ecircumflex -20 + +KPX ydieresis edieresis -20 + +KPX ydieresis edotaccent -20 + +KPX ydieresis egrave -20 + +KPX ydieresis emacron -20 + +KPX ydieresis eogonek -20 + +KPX ydieresis o -20 + +KPX ydieresis oacute -20 + +KPX ydieresis ocircumflex -20 + +KPX ydieresis odieresis -20 + +KPX ydieresis ograve -20 + +KPX ydieresis ohungarumlaut -20 + +KPX ydieresis omacron -20 + +KPX ydieresis oslash -20 + +KPX ydieresis otilde -20 + +KPX ydieresis period -100 + +KPX z e -15 + +KPX z eacute -15 + +KPX z ecaron -15 + +KPX z ecircumflex -15 + +KPX z edieresis -15 + +KPX z edotaccent -15 + +KPX z egrave -15 + +KPX z emacron -15 + +KPX z eogonek -15 + +KPX z o -15 + +KPX z oacute -15 + +KPX z ocircumflex -15 + +KPX z odieresis -15 + +KPX z ograve -15 + +KPX z ohungarumlaut -15 + +KPX z omacron -15 + +KPX z oslash -15 + +KPX z otilde -15 + +KPX zacute e -15 + +KPX zacute eacute -15 + +KPX zacute ecaron -15 + +KPX zacute ecircumflex -15 + +KPX zacute edieresis -15 + +KPX zacute edotaccent -15 + +KPX zacute egrave -15 + +KPX zacute emacron -15 + +KPX zacute eogonek -15 + +KPX zacute o -15 + +KPX zacute oacute -15 + +KPX zacute ocircumflex -15 + +KPX zacute odieresis -15 + +KPX zacute ograve -15 + +KPX zacute ohungarumlaut -15 + +KPX zacute omacron -15 + +KPX zacute oslash -15 + +KPX zacute otilde -15 + +KPX zcaron e -15 + +KPX zcaron eacute -15 + +KPX zcaron ecaron -15 + +KPX zcaron ecircumflex -15 + +KPX zcaron edieresis -15 + +KPX zcaron edotaccent -15 + +KPX zcaron egrave -15 + +KPX zcaron emacron -15 + +KPX zcaron eogonek -15 + +KPX zcaron o -15 + +KPX zcaron oacute -15 + +KPX zcaron ocircumflex -15 + +KPX zcaron odieresis -15 + +KPX zcaron ograve -15 + +KPX zcaron ohungarumlaut -15 + +KPX zcaron omacron -15 + +KPX zcaron oslash -15 + +KPX zcaron otilde -15 + +KPX zdotaccent e -15 + +KPX zdotaccent eacute -15 + +KPX zdotaccent ecaron -15 + +KPX zdotaccent ecircumflex -15 + +KPX zdotaccent edieresis -15 + +KPX zdotaccent edotaccent -15 + +KPX zdotaccent egrave -15 + +KPX zdotaccent emacron -15 + +KPX zdotaccent eogonek -15 + +KPX zdotaccent o -15 + +KPX zdotaccent oacute -15 + +KPX zdotaccent ocircumflex -15 + +KPX zdotaccent odieresis -15 + +KPX zdotaccent ograve -15 + +KPX zdotaccent ohungarumlaut -15 + +KPX zdotaccent omacron -15 + +KPX zdotaccent oslash -15 + +KPX zdotaccent otilde -15 + +EndKernPairs + +EndKernData + +EndFontMetrics + diff --git a/src/Broadside/Fonts/Data/Afm/Helvetica.afm b/src/Broadside/Fonts/Data/Afm/Helvetica.afm new file mode 100644 index 00000000..e695b91e --- /dev/null +++ b/src/Broadside/Fonts/Data/Afm/Helvetica.afm @@ -0,0 +1,6102 @@ +StartFontMetrics 4.1 + +Comment Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved. + +Comment Creation Date: Thu May 1 12:38:23 1997 + +Comment UniqueID 43054 + +Comment VMusage 37069 48094 + +FontName Helvetica + +FullName Helvetica + +FamilyName Helvetica + +Weight Medium + +ItalicAngle 0 + +IsFixedPitch false + +CharacterSet ExtendedRoman + +FontBBox -166 -225 1000 931 + +UnderlinePosition -100 + +UnderlineThickness 50 + +Version 002.000 + +Notice Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.Helvetica is a trademark of Linotype-Hell AG and/or its subsidiaries. + +EncodingScheme AdobeStandardEncoding + +CapHeight 718 + +XHeight 523 + +Ascender 718 + +Descender -207 + +StdHW 76 + +StdVW 88 + +StartCharMetrics 315 + +C 32 ; WX 278 ; N space ; B 0 0 0 0 ; + +C 33 ; WX 278 ; N exclam ; B 90 0 187 718 ; + +C 34 ; WX 355 ; N quotedbl ; B 70 463 285 718 ; + +C 35 ; WX 556 ; N numbersign ; B 28 0 529 688 ; + +C 36 ; WX 556 ; N dollar ; B 32 -115 520 775 ; + +C 37 ; WX 889 ; N percent ; B 39 -19 850 703 ; + +C 38 ; WX 667 ; N ampersand ; B 44 -15 645 718 ; + +C 39 ; WX 222 ; N quoteright ; B 53 463 157 718 ; + +C 40 ; WX 333 ; N parenleft ; B 68 -207 299 733 ; + +C 41 ; WX 333 ; N parenright ; B 34 -207 265 733 ; + +C 42 ; WX 389 ; N asterisk ; B 39 431 349 718 ; + +C 43 ; WX 584 ; N plus ; B 39 0 545 505 ; + +C 44 ; WX 278 ; N comma ; B 87 -147 191 106 ; + +C 45 ; WX 333 ; N hyphen ; B 44 232 289 322 ; + +C 46 ; WX 278 ; N period ; B 87 0 191 106 ; + +C 47 ; WX 278 ; N slash ; B -17 -19 295 737 ; + +C 48 ; WX 556 ; N zero ; B 37 -19 519 703 ; + +C 49 ; WX 556 ; N one ; B 101 0 359 703 ; + +C 50 ; WX 556 ; N two ; B 26 0 507 703 ; + +C 51 ; WX 556 ; N three ; B 34 -19 522 703 ; + +C 52 ; WX 556 ; N four ; B 25 0 523 703 ; + +C 53 ; WX 556 ; N five ; B 32 -19 514 688 ; + +C 54 ; WX 556 ; N six ; B 38 -19 518 703 ; + +C 55 ; WX 556 ; N seven ; B 37 0 523 688 ; + +C 56 ; WX 556 ; N eight ; B 38 -19 517 703 ; + +C 57 ; WX 556 ; N nine ; B 42 -19 514 703 ; + +C 58 ; WX 278 ; N colon ; B 87 0 191 516 ; + +C 59 ; WX 278 ; N semicolon ; B 87 -147 191 516 ; + +C 60 ; WX 584 ; N less ; B 48 11 536 495 ; + +C 61 ; WX 584 ; N equal ; B 39 115 545 390 ; + +C 62 ; WX 584 ; N greater ; B 48 11 536 495 ; + +C 63 ; WX 556 ; N question ; B 56 0 492 727 ; + +C 64 ; WX 1015 ; N at ; B 147 -19 868 737 ; + +C 65 ; WX 667 ; N A ; B 14 0 654 718 ; + +C 66 ; WX 667 ; N B ; B 74 0 627 718 ; + +C 67 ; WX 722 ; N C ; B 44 -19 681 737 ; + +C 68 ; WX 722 ; N D ; B 81 0 674 718 ; + +C 69 ; WX 667 ; N E ; B 86 0 616 718 ; + +C 70 ; WX 611 ; N F ; B 86 0 583 718 ; + +C 71 ; WX 778 ; N G ; B 48 -19 704 737 ; + +C 72 ; WX 722 ; N H ; B 77 0 646 718 ; + +C 73 ; WX 278 ; N I ; B 91 0 188 718 ; + +C 74 ; WX 500 ; N J ; B 17 -19 428 718 ; + +C 75 ; WX 667 ; N K ; B 76 0 663 718 ; + +C 76 ; WX 556 ; N L ; B 76 0 537 718 ; + +C 77 ; WX 833 ; N M ; B 73 0 761 718 ; + +C 78 ; WX 722 ; N N ; B 76 0 646 718 ; + +C 79 ; WX 778 ; N O ; B 39 -19 739 737 ; + +C 80 ; WX 667 ; N P ; B 86 0 622 718 ; + +C 81 ; WX 778 ; N Q ; B 39 -56 739 737 ; + +C 82 ; WX 722 ; N R ; B 88 0 684 718 ; + +C 83 ; WX 667 ; N S ; B 49 -19 620 737 ; + +C 84 ; WX 611 ; N T ; B 14 0 597 718 ; + +C 85 ; WX 722 ; N U ; B 79 -19 644 718 ; + +C 86 ; WX 667 ; N V ; B 20 0 647 718 ; + +C 87 ; WX 944 ; N W ; B 16 0 928 718 ; + +C 88 ; WX 667 ; N X ; B 19 0 648 718 ; + +C 89 ; WX 667 ; N Y ; B 14 0 653 718 ; + +C 90 ; WX 611 ; N Z ; B 23 0 588 718 ; + +C 91 ; WX 278 ; N bracketleft ; B 63 -196 250 722 ; + +C 92 ; WX 278 ; N backslash ; B -17 -19 295 737 ; + +C 93 ; WX 278 ; N bracketright ; B 28 -196 215 722 ; + +C 94 ; WX 469 ; N asciicircum ; B -14 264 483 688 ; + +C 95 ; WX 556 ; N underscore ; B 0 -125 556 -75 ; + +C 96 ; WX 222 ; N quoteleft ; B 65 470 169 725 ; + +C 97 ; WX 556 ; N a ; B 36 -15 530 538 ; + +C 98 ; WX 556 ; N b ; B 58 -15 517 718 ; + +C 99 ; WX 500 ; N c ; B 30 -15 477 538 ; + +C 100 ; WX 556 ; N d ; B 35 -15 499 718 ; + +C 101 ; WX 556 ; N e ; B 40 -15 516 538 ; + +C 102 ; WX 278 ; N f ; B 14 0 262 728 ; L i fi ; L l fl ; + +C 103 ; WX 556 ; N g ; B 40 -220 499 538 ; + +C 104 ; WX 556 ; N h ; B 65 0 491 718 ; + +C 105 ; WX 222 ; N i ; B 67 0 155 718 ; + +C 106 ; WX 222 ; N j ; B -16 -210 155 718 ; + +C 107 ; WX 500 ; N k ; B 67 0 501 718 ; + +C 108 ; WX 222 ; N l ; B 67 0 155 718 ; + +C 109 ; WX 833 ; N m ; B 65 0 769 538 ; + +C 110 ; WX 556 ; N n ; B 65 0 491 538 ; + +C 111 ; WX 556 ; N o ; B 35 -14 521 538 ; + +C 112 ; WX 556 ; N p ; B 58 -207 517 538 ; + +C 113 ; WX 556 ; N q ; B 35 -207 494 538 ; + +C 114 ; WX 333 ; N r ; B 77 0 332 538 ; + +C 115 ; WX 500 ; N s ; B 32 -15 464 538 ; + +C 116 ; WX 278 ; N t ; B 14 -7 257 669 ; + +C 117 ; WX 556 ; N u ; B 68 -15 489 523 ; + +C 118 ; WX 500 ; N v ; B 8 0 492 523 ; + +C 119 ; WX 722 ; N w ; B 14 0 709 523 ; + +C 120 ; WX 500 ; N x ; B 11 0 490 523 ; + +C 121 ; WX 500 ; N y ; B 11 -214 489 523 ; + +C 122 ; WX 500 ; N z ; B 31 0 469 523 ; + +C 123 ; WX 334 ; N braceleft ; B 42 -196 292 722 ; + +C 124 ; WX 260 ; N bar ; B 94 -225 167 775 ; + +C 125 ; WX 334 ; N braceright ; B 42 -196 292 722 ; + +C 126 ; WX 584 ; N asciitilde ; B 61 180 523 326 ; + +C 161 ; WX 333 ; N exclamdown ; B 118 -195 215 523 ; + +C 162 ; WX 556 ; N cent ; B 51 -115 513 623 ; + +C 163 ; WX 556 ; N sterling ; B 33 -16 539 718 ; + +C 164 ; WX 167 ; N fraction ; B -166 -19 333 703 ; + +C 165 ; WX 556 ; N yen ; B 3 0 553 688 ; + +C 166 ; WX 556 ; N florin ; B -11 -207 501 737 ; + +C 167 ; WX 556 ; N section ; B 43 -191 512 737 ; + +C 168 ; WX 556 ; N currency ; B 28 99 528 603 ; + +C 169 ; WX 191 ; N quotesingle ; B 59 463 132 718 ; + +C 170 ; WX 333 ; N quotedblleft ; B 38 470 307 725 ; + +C 171 ; WX 556 ; N guillemotleft ; B 97 108 459 446 ; + +C 172 ; WX 333 ; N guilsinglleft ; B 88 108 245 446 ; + +C 173 ; WX 333 ; N guilsinglright ; B 88 108 245 446 ; + +C 174 ; WX 500 ; N fi ; B 14 0 434 728 ; + +C 175 ; WX 500 ; N fl ; B 14 0 432 728 ; + +C 177 ; WX 556 ; N endash ; B 0 240 556 313 ; + +C 178 ; WX 556 ; N dagger ; B 43 -159 514 718 ; + +C 179 ; WX 556 ; N daggerdbl ; B 43 -159 514 718 ; + +C 180 ; WX 278 ; N periodcentered ; B 77 190 202 315 ; + +C 182 ; WX 537 ; N paragraph ; B 18 -173 497 718 ; + +C 183 ; WX 350 ; N bullet ; B 18 202 333 517 ; + +C 184 ; WX 222 ; N quotesinglbase ; B 53 -149 157 106 ; + +C 185 ; WX 333 ; N quotedblbase ; B 26 -149 295 106 ; + +C 186 ; WX 333 ; N quotedblright ; B 26 463 295 718 ; + +C 187 ; WX 556 ; N guillemotright ; B 97 108 459 446 ; + +C 188 ; WX 1000 ; N ellipsis ; B 115 0 885 106 ; + +C 189 ; WX 1000 ; N perthousand ; B 7 -19 994 703 ; + +C 191 ; WX 611 ; N questiondown ; B 91 -201 527 525 ; + +C 193 ; WX 333 ; N grave ; B 14 593 211 734 ; + +C 194 ; WX 333 ; N acute ; B 122 593 319 734 ; + +C 195 ; WX 333 ; N circumflex ; B 21 593 312 734 ; + +C 196 ; WX 333 ; N tilde ; B -4 606 337 722 ; + +C 197 ; WX 333 ; N macron ; B 10 627 323 684 ; + +C 198 ; WX 333 ; N breve ; B 13 595 321 731 ; + +C 199 ; WX 333 ; N dotaccent ; B 121 604 212 706 ; + +C 200 ; WX 333 ; N dieresis ; B 40 604 293 706 ; + +C 202 ; WX 333 ; N ring ; B 75 572 259 756 ; + +C 203 ; WX 333 ; N cedilla ; B 45 -225 259 0 ; + +C 205 ; WX 333 ; N hungarumlaut ; B 31 593 409 734 ; + +C 206 ; WX 333 ; N ogonek ; B 73 -225 287 0 ; + +C 207 ; WX 333 ; N caron ; B 21 593 312 734 ; + +C 208 ; WX 1000 ; N emdash ; B 0 240 1000 313 ; + +C 225 ; WX 1000 ; N AE ; B 8 0 951 718 ; + +C 227 ; WX 370 ; N ordfeminine ; B 24 405 346 737 ; + +C 232 ; WX 556 ; N Lslash ; B -20 0 537 718 ; + +C 233 ; WX 778 ; N Oslash ; B 39 -19 740 737 ; + +C 234 ; WX 1000 ; N OE ; B 36 -19 965 737 ; + +C 235 ; WX 365 ; N ordmasculine ; B 25 405 341 737 ; + +C 241 ; WX 889 ; N ae ; B 36 -15 847 538 ; + +C 245 ; WX 278 ; N dotlessi ; B 95 0 183 523 ; + +C 248 ; WX 222 ; N lslash ; B -20 0 242 718 ; + +C 249 ; WX 611 ; N oslash ; B 28 -22 537 545 ; + +C 250 ; WX 944 ; N oe ; B 35 -15 902 538 ; + +C 251 ; WX 611 ; N germandbls ; B 67 -15 571 728 ; + +C -1 ; WX 278 ; N Idieresis ; B 13 0 266 901 ; + +C -1 ; WX 556 ; N eacute ; B 40 -15 516 734 ; + +C -1 ; WX 556 ; N abreve ; B 36 -15 530 731 ; + +C -1 ; WX 556 ; N uhungarumlaut ; B 68 -15 521 734 ; + +C -1 ; WX 556 ; N ecaron ; B 40 -15 516 734 ; + +C -1 ; WX 667 ; N Ydieresis ; B 14 0 653 901 ; + +C -1 ; WX 584 ; N divide ; B 39 -19 545 524 ; + +C -1 ; WX 667 ; N Yacute ; B 14 0 653 929 ; + +C -1 ; WX 667 ; N Acircumflex ; B 14 0 654 929 ; + +C -1 ; WX 556 ; N aacute ; B 36 -15 530 734 ; + +C -1 ; WX 722 ; N Ucircumflex ; B 79 -19 644 929 ; + +C -1 ; WX 500 ; N yacute ; B 11 -214 489 734 ; + +C -1 ; WX 500 ; N scommaaccent ; B 32 -225 464 538 ; + +C -1 ; WX 556 ; N ecircumflex ; B 40 -15 516 734 ; + +C -1 ; WX 722 ; N Uring ; B 79 -19 644 931 ; + +C -1 ; WX 722 ; N Udieresis ; B 79 -19 644 901 ; + +C -1 ; WX 556 ; N aogonek ; B 36 -220 547 538 ; + +C -1 ; WX 722 ; N Uacute ; B 79 -19 644 929 ; + +C -1 ; WX 556 ; N uogonek ; B 68 -225 519 523 ; + +C -1 ; WX 667 ; N Edieresis ; B 86 0 616 901 ; + +C -1 ; WX 722 ; N Dcroat ; B 0 0 674 718 ; + +C -1 ; WX 250 ; N commaaccent ; B 87 -225 181 -40 ; + +C -1 ; WX 737 ; N copyright ; B -14 -19 752 737 ; + +C -1 ; WX 667 ; N Emacron ; B 86 0 616 879 ; + +C -1 ; WX 500 ; N ccaron ; B 30 -15 477 734 ; + +C -1 ; WX 556 ; N aring ; B 36 -15 530 756 ; + +C -1 ; WX 722 ; N Ncommaaccent ; B 76 -225 646 718 ; + +C -1 ; WX 222 ; N lacute ; B 67 0 264 929 ; + +C -1 ; WX 556 ; N agrave ; B 36 -15 530 734 ; + +C -1 ; WX 611 ; N Tcommaaccent ; B 14 -225 597 718 ; + +C -1 ; WX 722 ; N Cacute ; B 44 -19 681 929 ; + +C -1 ; WX 556 ; N atilde ; B 36 -15 530 722 ; + +C -1 ; WX 667 ; N Edotaccent ; B 86 0 616 901 ; + +C -1 ; WX 500 ; N scaron ; B 32 -15 464 734 ; + +C -1 ; WX 500 ; N scedilla ; B 32 -225 464 538 ; + +C -1 ; WX 278 ; N iacute ; B 95 0 292 734 ; + +C -1 ; WX 471 ; N lozenge ; B 10 0 462 728 ; + +C -1 ; WX 722 ; N Rcaron ; B 88 0 684 929 ; + +C -1 ; WX 778 ; N Gcommaaccent ; B 48 -225 704 737 ; + +C -1 ; WX 556 ; N ucircumflex ; B 68 -15 489 734 ; + +C -1 ; WX 556 ; N acircumflex ; B 36 -15 530 734 ; + +C -1 ; WX 667 ; N Amacron ; B 14 0 654 879 ; + +C -1 ; WX 333 ; N rcaron ; B 61 0 352 734 ; + +C -1 ; WX 500 ; N ccedilla ; B 30 -225 477 538 ; + +C -1 ; WX 611 ; N Zdotaccent ; B 23 0 588 901 ; + +C -1 ; WX 667 ; N Thorn ; B 86 0 622 718 ; + +C -1 ; WX 778 ; N Omacron ; B 39 -19 739 879 ; + +C -1 ; WX 722 ; N Racute ; B 88 0 684 929 ; + +C -1 ; WX 667 ; N Sacute ; B 49 -19 620 929 ; + +C -1 ; WX 643 ; N dcaron ; B 35 -15 655 718 ; + +C -1 ; WX 722 ; N Umacron ; B 79 -19 644 879 ; + +C -1 ; WX 556 ; N uring ; B 68 -15 489 756 ; + +C -1 ; WX 333 ; N threesuperior ; B 5 270 325 703 ; + +C -1 ; WX 778 ; N Ograve ; B 39 -19 739 929 ; + +C -1 ; WX 667 ; N Agrave ; B 14 0 654 929 ; + +C -1 ; WX 667 ; N Abreve ; B 14 0 654 926 ; + +C -1 ; WX 584 ; N multiply ; B 39 0 545 506 ; + +C -1 ; WX 556 ; N uacute ; B 68 -15 489 734 ; + +C -1 ; WX 611 ; N Tcaron ; B 14 0 597 929 ; + +C -1 ; WX 476 ; N partialdiff ; B 13 -38 463 714 ; + +C -1 ; WX 500 ; N ydieresis ; B 11 -214 489 706 ; + +C -1 ; WX 722 ; N Nacute ; B 76 0 646 929 ; + +C -1 ; WX 278 ; N icircumflex ; B -6 0 285 734 ; + +C -1 ; WX 667 ; N Ecircumflex ; B 86 0 616 929 ; + +C -1 ; WX 556 ; N adieresis ; B 36 -15 530 706 ; + +C -1 ; WX 556 ; N edieresis ; B 40 -15 516 706 ; + +C -1 ; WX 500 ; N cacute ; B 30 -15 477 734 ; + +C -1 ; WX 556 ; N nacute ; B 65 0 491 734 ; + +C -1 ; WX 556 ; N umacron ; B 68 -15 489 684 ; + +C -1 ; WX 722 ; N Ncaron ; B 76 0 646 929 ; + +C -1 ; WX 278 ; N Iacute ; B 91 0 292 929 ; + +C -1 ; WX 584 ; N plusminus ; B 39 0 545 506 ; + +C -1 ; WX 260 ; N brokenbar ; B 94 -150 167 700 ; + +C -1 ; WX 737 ; N registered ; B -14 -19 752 737 ; + +C -1 ; WX 778 ; N Gbreve ; B 48 -19 704 926 ; + +C -1 ; WX 278 ; N Idotaccent ; B 91 0 188 901 ; + +C -1 ; WX 600 ; N summation ; B 15 -10 586 706 ; + +C -1 ; WX 667 ; N Egrave ; B 86 0 616 929 ; + +C -1 ; WX 333 ; N racute ; B 77 0 332 734 ; + +C -1 ; WX 556 ; N omacron ; B 35 -14 521 684 ; + +C -1 ; WX 611 ; N Zacute ; B 23 0 588 929 ; + +C -1 ; WX 611 ; N Zcaron ; B 23 0 588 929 ; + +C -1 ; WX 549 ; N greaterequal ; B 26 0 523 674 ; + +C -1 ; WX 722 ; N Eth ; B 0 0 674 718 ; + +C -1 ; WX 722 ; N Ccedilla ; B 44 -225 681 737 ; + +C -1 ; WX 222 ; N lcommaaccent ; B 67 -225 167 718 ; + +C -1 ; WX 317 ; N tcaron ; B 14 -7 329 808 ; + +C -1 ; WX 556 ; N eogonek ; B 40 -225 516 538 ; + +C -1 ; WX 722 ; N Uogonek ; B 79 -225 644 718 ; + +C -1 ; WX 667 ; N Aacute ; B 14 0 654 929 ; + +C -1 ; WX 667 ; N Adieresis ; B 14 0 654 901 ; + +C -1 ; WX 556 ; N egrave ; B 40 -15 516 734 ; + +C -1 ; WX 500 ; N zacute ; B 31 0 469 734 ; + +C -1 ; WX 222 ; N iogonek ; B -31 -225 183 718 ; + +C -1 ; WX 778 ; N Oacute ; B 39 -19 739 929 ; + +C -1 ; WX 556 ; N oacute ; B 35 -14 521 734 ; + +C -1 ; WX 556 ; N amacron ; B 36 -15 530 684 ; + +C -1 ; WX 500 ; N sacute ; B 32 -15 464 734 ; + +C -1 ; WX 278 ; N idieresis ; B 13 0 266 706 ; + +C -1 ; WX 778 ; N Ocircumflex ; B 39 -19 739 929 ; + +C -1 ; WX 722 ; N Ugrave ; B 79 -19 644 929 ; + +C -1 ; WX 612 ; N Delta ; B 6 0 608 688 ; + +C -1 ; WX 556 ; N thorn ; B 58 -207 517 718 ; + +C -1 ; WX 333 ; N twosuperior ; B 4 281 323 703 ; + +C -1 ; WX 778 ; N Odieresis ; B 39 -19 739 901 ; + +C -1 ; WX 556 ; N mu ; B 68 -207 489 523 ; + +C -1 ; WX 278 ; N igrave ; B -13 0 184 734 ; + +C -1 ; WX 556 ; N ohungarumlaut ; B 35 -14 521 734 ; + +C -1 ; WX 667 ; N Eogonek ; B 86 -220 633 718 ; + +C -1 ; WX 556 ; N dcroat ; B 35 -15 550 718 ; + +C -1 ; WX 834 ; N threequarters ; B 45 -19 810 703 ; + +C -1 ; WX 667 ; N Scedilla ; B 49 -225 620 737 ; + +C -1 ; WX 299 ; N lcaron ; B 67 0 311 718 ; + +C -1 ; WX 667 ; N Kcommaaccent ; B 76 -225 663 718 ; + +C -1 ; WX 556 ; N Lacute ; B 76 0 537 929 ; + +C -1 ; WX 1000 ; N trademark ; B 46 306 903 718 ; + +C -1 ; WX 556 ; N edotaccent ; B 40 -15 516 706 ; + +C -1 ; WX 278 ; N Igrave ; B -13 0 188 929 ; + +C -1 ; WX 278 ; N Imacron ; B -17 0 296 879 ; + +C -1 ; WX 556 ; N Lcaron ; B 76 0 537 718 ; + +C -1 ; WX 834 ; N onehalf ; B 43 -19 773 703 ; + +C -1 ; WX 549 ; N lessequal ; B 26 0 523 674 ; + +C -1 ; WX 556 ; N ocircumflex ; B 35 -14 521 734 ; + +C -1 ; WX 556 ; N ntilde ; B 65 0 491 722 ; + +C -1 ; WX 722 ; N Uhungarumlaut ; B 79 -19 644 929 ; + +C -1 ; WX 667 ; N Eacute ; B 86 0 616 929 ; + +C -1 ; WX 556 ; N emacron ; B 40 -15 516 684 ; + +C -1 ; WX 556 ; N gbreve ; B 40 -220 499 731 ; + +C -1 ; WX 834 ; N onequarter ; B 73 -19 756 703 ; + +C -1 ; WX 667 ; N Scaron ; B 49 -19 620 929 ; + +C -1 ; WX 667 ; N Scommaaccent ; B 49 -225 620 737 ; + +C -1 ; WX 778 ; N Ohungarumlaut ; B 39 -19 739 929 ; + +C -1 ; WX 400 ; N degree ; B 54 411 346 703 ; + +C -1 ; WX 556 ; N ograve ; B 35 -14 521 734 ; + +C -1 ; WX 722 ; N Ccaron ; B 44 -19 681 929 ; + +C -1 ; WX 556 ; N ugrave ; B 68 -15 489 734 ; + +C -1 ; WX 453 ; N radical ; B -4 -80 458 762 ; + +C -1 ; WX 722 ; N Dcaron ; B 81 0 674 929 ; + +C -1 ; WX 333 ; N rcommaaccent ; B 77 -225 332 538 ; + +C -1 ; WX 722 ; N Ntilde ; B 76 0 646 917 ; + +C -1 ; WX 556 ; N otilde ; B 35 -14 521 722 ; + +C -1 ; WX 722 ; N Rcommaaccent ; B 88 -225 684 718 ; + +C -1 ; WX 556 ; N Lcommaaccent ; B 76 -225 537 718 ; + +C -1 ; WX 667 ; N Atilde ; B 14 0 654 917 ; + +C -1 ; WX 667 ; N Aogonek ; B 14 -225 654 718 ; + +C -1 ; WX 667 ; N Aring ; B 14 0 654 931 ; + +C -1 ; WX 778 ; N Otilde ; B 39 -19 739 917 ; + +C -1 ; WX 500 ; N zdotaccent ; B 31 0 469 706 ; + +C -1 ; WX 667 ; N Ecaron ; B 86 0 616 929 ; + +C -1 ; WX 278 ; N Iogonek ; B -3 -225 211 718 ; + +C -1 ; WX 500 ; N kcommaaccent ; B 67 -225 501 718 ; + +C -1 ; WX 584 ; N minus ; B 39 216 545 289 ; + +C -1 ; WX 278 ; N Icircumflex ; B -6 0 285 929 ; + +C -1 ; WX 556 ; N ncaron ; B 65 0 491 734 ; + +C -1 ; WX 278 ; N tcommaaccent ; B 14 -225 257 669 ; + +C -1 ; WX 584 ; N logicalnot ; B 39 108 545 390 ; + +C -1 ; WX 556 ; N odieresis ; B 35 -14 521 706 ; + +C -1 ; WX 556 ; N udieresis ; B 68 -15 489 706 ; + +C -1 ; WX 549 ; N notequal ; B 12 -35 537 551 ; + +C -1 ; WX 556 ; N gcommaaccent ; B 40 -220 499 822 ; + +C -1 ; WX 556 ; N eth ; B 35 -15 522 737 ; + +C -1 ; WX 500 ; N zcaron ; B 31 0 469 734 ; + +C -1 ; WX 556 ; N ncommaaccent ; B 65 -225 491 538 ; + +C -1 ; WX 333 ; N onesuperior ; B 43 281 222 703 ; + +C -1 ; WX 278 ; N imacron ; B 5 0 272 684 ; + +C -1 ; WX 556 ; N Euro ; B 0 0 0 0 ; + +EndCharMetrics + +StartKernData + +StartKernPairs 2705 + +KPX A C -30 + +KPX A Cacute -30 + +KPX A Ccaron -30 + +KPX A Ccedilla -30 + +KPX A G -30 + +KPX A Gbreve -30 + +KPX A Gcommaaccent -30 + +KPX A O -30 + +KPX A Oacute -30 + +KPX A Ocircumflex -30 + +KPX A Odieresis -30 + +KPX A Ograve -30 + +KPX A Ohungarumlaut -30 + +KPX A Omacron -30 + +KPX A Oslash -30 + +KPX A Otilde -30 + +KPX A Q -30 + +KPX A T -120 + +KPX A Tcaron -120 + +KPX A Tcommaaccent -120 + +KPX A U -50 + +KPX A Uacute -50 + +KPX A Ucircumflex -50 + +KPX A Udieresis -50 + +KPX A Ugrave -50 + +KPX A Uhungarumlaut -50 + +KPX A Umacron -50 + +KPX A Uogonek -50 + +KPX A Uring -50 + +KPX A V -70 + +KPX A W -50 + +KPX A Y -100 + +KPX A Yacute -100 + +KPX A Ydieresis -100 + +KPX A u -30 + +KPX A uacute -30 + +KPX A ucircumflex -30 + +KPX A udieresis -30 + +KPX A ugrave -30 + +KPX A uhungarumlaut -30 + +KPX A umacron -30 + +KPX A uogonek -30 + +KPX A uring -30 + +KPX A v -40 + +KPX A w -40 + +KPX A y -40 + +KPX A yacute -40 + +KPX A ydieresis -40 + +KPX Aacute C -30 + +KPX Aacute Cacute -30 + +KPX Aacute Ccaron -30 + +KPX Aacute Ccedilla -30 + +KPX Aacute G -30 + +KPX Aacute Gbreve -30 + +KPX Aacute Gcommaaccent -30 + +KPX Aacute O -30 + +KPX Aacute Oacute -30 + +KPX Aacute Ocircumflex -30 + +KPX Aacute Odieresis -30 + +KPX Aacute Ograve -30 + +KPX Aacute Ohungarumlaut -30 + +KPX Aacute Omacron -30 + +KPX Aacute Oslash -30 + +KPX Aacute Otilde -30 + +KPX Aacute Q -30 + +KPX Aacute T -120 + +KPX Aacute Tcaron -120 + +KPX Aacute Tcommaaccent -120 + +KPX Aacute U -50 + +KPX Aacute Uacute -50 + +KPX Aacute Ucircumflex -50 + +KPX Aacute Udieresis -50 + +KPX Aacute Ugrave -50 + +KPX Aacute Uhungarumlaut -50 + +KPX Aacute Umacron -50 + +KPX Aacute Uogonek -50 + +KPX Aacute Uring -50 + +KPX Aacute V -70 + +KPX Aacute W -50 + +KPX Aacute Y -100 + +KPX Aacute Yacute -100 + +KPX Aacute Ydieresis -100 + +KPX Aacute u -30 + +KPX Aacute uacute -30 + +KPX Aacute ucircumflex -30 + +KPX Aacute udieresis -30 + +KPX Aacute ugrave -30 + +KPX Aacute uhungarumlaut -30 + +KPX Aacute umacron -30 + +KPX Aacute uogonek -30 + +KPX Aacute uring -30 + +KPX Aacute v -40 + +KPX Aacute w -40 + +KPX Aacute y -40 + +KPX Aacute yacute -40 + +KPX Aacute ydieresis -40 + +KPX Abreve C -30 + +KPX Abreve Cacute -30 + +KPX Abreve Ccaron -30 + +KPX Abreve Ccedilla -30 + +KPX Abreve G -30 + +KPX Abreve Gbreve -30 + +KPX Abreve Gcommaaccent -30 + +KPX Abreve O -30 + +KPX Abreve Oacute -30 + +KPX Abreve Ocircumflex -30 + +KPX Abreve Odieresis -30 + +KPX Abreve Ograve -30 + +KPX Abreve Ohungarumlaut -30 + +KPX Abreve Omacron -30 + +KPX Abreve Oslash -30 + +KPX Abreve Otilde -30 + +KPX Abreve Q -30 + +KPX Abreve T -120 + +KPX Abreve Tcaron -120 + +KPX Abreve Tcommaaccent -120 + +KPX Abreve U -50 + +KPX Abreve Uacute -50 + +KPX Abreve Ucircumflex -50 + +KPX Abreve Udieresis -50 + +KPX Abreve Ugrave -50 + +KPX Abreve Uhungarumlaut -50 + +KPX Abreve Umacron -50 + +KPX Abreve Uogonek -50 + +KPX Abreve Uring -50 + +KPX Abreve V -70 + +KPX Abreve W -50 + +KPX Abreve Y -100 + +KPX Abreve Yacute -100 + +KPX Abreve Ydieresis -100 + +KPX Abreve u -30 + +KPX Abreve uacute -30 + +KPX Abreve ucircumflex -30 + +KPX Abreve udieresis -30 + +KPX Abreve ugrave -30 + +KPX Abreve uhungarumlaut -30 + +KPX Abreve umacron -30 + +KPX Abreve uogonek -30 + +KPX Abreve uring -30 + +KPX Abreve v -40 + +KPX Abreve w -40 + +KPX Abreve y -40 + +KPX Abreve yacute -40 + +KPX Abreve ydieresis -40 + +KPX Acircumflex C -30 + +KPX Acircumflex Cacute -30 + +KPX Acircumflex Ccaron -30 + +KPX Acircumflex Ccedilla -30 + +KPX Acircumflex G -30 + +KPX Acircumflex Gbreve -30 + +KPX Acircumflex Gcommaaccent -30 + +KPX Acircumflex O -30 + +KPX Acircumflex Oacute -30 + +KPX Acircumflex Ocircumflex -30 + +KPX Acircumflex Odieresis -30 + +KPX Acircumflex Ograve -30 + +KPX Acircumflex Ohungarumlaut -30 + +KPX Acircumflex Omacron -30 + +KPX Acircumflex Oslash -30 + +KPX Acircumflex Otilde -30 + +KPX Acircumflex Q -30 + +KPX Acircumflex T -120 + +KPX Acircumflex Tcaron -120 + +KPX Acircumflex Tcommaaccent -120 + +KPX Acircumflex U -50 + +KPX Acircumflex Uacute -50 + +KPX Acircumflex Ucircumflex -50 + +KPX Acircumflex Udieresis -50 + +KPX Acircumflex Ugrave -50 + +KPX Acircumflex Uhungarumlaut -50 + +KPX Acircumflex Umacron -50 + +KPX Acircumflex Uogonek -50 + +KPX Acircumflex Uring -50 + +KPX Acircumflex V -70 + +KPX Acircumflex W -50 + +KPX Acircumflex Y -100 + +KPX Acircumflex Yacute -100 + +KPX Acircumflex Ydieresis -100 + +KPX Acircumflex u -30 + +KPX Acircumflex uacute -30 + +KPX Acircumflex ucircumflex -30 + +KPX Acircumflex udieresis -30 + +KPX Acircumflex ugrave -30 + +KPX Acircumflex uhungarumlaut -30 + +KPX Acircumflex umacron -30 + +KPX Acircumflex uogonek -30 + +KPX Acircumflex uring -30 + +KPX Acircumflex v -40 + +KPX Acircumflex w -40 + +KPX Acircumflex y -40 + +KPX Acircumflex yacute -40 + +KPX Acircumflex ydieresis -40 + +KPX Adieresis C -30 + +KPX Adieresis Cacute -30 + +KPX Adieresis Ccaron -30 + +KPX Adieresis Ccedilla -30 + +KPX Adieresis G -30 + +KPX Adieresis Gbreve -30 + +KPX Adieresis Gcommaaccent -30 + +KPX Adieresis O -30 + +KPX Adieresis Oacute -30 + +KPX Adieresis Ocircumflex -30 + +KPX Adieresis Odieresis -30 + +KPX Adieresis Ograve -30 + +KPX Adieresis Ohungarumlaut -30 + +KPX Adieresis Omacron -30 + +KPX Adieresis Oslash -30 + +KPX Adieresis Otilde -30 + +KPX Adieresis Q -30 + +KPX Adieresis T -120 + +KPX Adieresis Tcaron -120 + +KPX Adieresis Tcommaaccent -120 + +KPX Adieresis U -50 + +KPX Adieresis Uacute -50 + +KPX Adieresis Ucircumflex -50 + +KPX Adieresis Udieresis -50 + +KPX Adieresis Ugrave -50 + +KPX Adieresis Uhungarumlaut -50 + +KPX Adieresis Umacron -50 + +KPX Adieresis Uogonek -50 + +KPX Adieresis Uring -50 + +KPX Adieresis V -70 + +KPX Adieresis W -50 + +KPX Adieresis Y -100 + +KPX Adieresis Yacute -100 + +KPX Adieresis Ydieresis -100 + +KPX Adieresis u -30 + +KPX Adieresis uacute -30 + +KPX Adieresis ucircumflex -30 + +KPX Adieresis udieresis -30 + +KPX Adieresis ugrave -30 + +KPX Adieresis uhungarumlaut -30 + +KPX Adieresis umacron -30 + +KPX Adieresis uogonek -30 + +KPX Adieresis uring -30 + +KPX Adieresis v -40 + +KPX Adieresis w -40 + +KPX Adieresis y -40 + +KPX Adieresis yacute -40 + +KPX Adieresis ydieresis -40 + +KPX Agrave C -30 + +KPX Agrave Cacute -30 + +KPX Agrave Ccaron -30 + +KPX Agrave Ccedilla -30 + +KPX Agrave G -30 + +KPX Agrave Gbreve -30 + +KPX Agrave Gcommaaccent -30 + +KPX Agrave O -30 + +KPX Agrave Oacute -30 + +KPX Agrave Ocircumflex -30 + +KPX Agrave Odieresis -30 + +KPX Agrave Ograve -30 + +KPX Agrave Ohungarumlaut -30 + +KPX Agrave Omacron -30 + +KPX Agrave Oslash -30 + +KPX Agrave Otilde -30 + +KPX Agrave Q -30 + +KPX Agrave T -120 + +KPX Agrave Tcaron -120 + +KPX Agrave Tcommaaccent -120 + +KPX Agrave U -50 + +KPX Agrave Uacute -50 + +KPX Agrave Ucircumflex -50 + +KPX Agrave Udieresis -50 + +KPX Agrave Ugrave -50 + +KPX Agrave Uhungarumlaut -50 + +KPX Agrave Umacron -50 + +KPX Agrave Uogonek -50 + +KPX Agrave Uring -50 + +KPX Agrave V -70 + +KPX Agrave W -50 + +KPX Agrave Y -100 + +KPX Agrave Yacute -100 + +KPX Agrave Ydieresis -100 + +KPX Agrave u -30 + +KPX Agrave uacute -30 + +KPX Agrave ucircumflex -30 + +KPX Agrave udieresis -30 + +KPX Agrave ugrave -30 + +KPX Agrave uhungarumlaut -30 + +KPX Agrave umacron -30 + +KPX Agrave uogonek -30 + +KPX Agrave uring -30 + +KPX Agrave v -40 + +KPX Agrave w -40 + +KPX Agrave y -40 + +KPX Agrave yacute -40 + +KPX Agrave ydieresis -40 + +KPX Amacron C -30 + +KPX Amacron Cacute -30 + +KPX Amacron Ccaron -30 + +KPX Amacron Ccedilla -30 + +KPX Amacron G -30 + +KPX Amacron Gbreve -30 + +KPX Amacron Gcommaaccent -30 + +KPX Amacron O -30 + +KPX Amacron Oacute -30 + +KPX Amacron Ocircumflex -30 + +KPX Amacron Odieresis -30 + +KPX Amacron Ograve -30 + +KPX Amacron Ohungarumlaut -30 + +KPX Amacron Omacron -30 + +KPX Amacron Oslash -30 + +KPX Amacron Otilde -30 + +KPX Amacron Q -30 + +KPX Amacron T -120 + +KPX Amacron Tcaron -120 + +KPX Amacron Tcommaaccent -120 + +KPX Amacron U -50 + +KPX Amacron Uacute -50 + +KPX Amacron Ucircumflex -50 + +KPX Amacron Udieresis -50 + +KPX Amacron Ugrave -50 + +KPX Amacron Uhungarumlaut -50 + +KPX Amacron Umacron -50 + +KPX Amacron Uogonek -50 + +KPX Amacron Uring -50 + +KPX Amacron V -70 + +KPX Amacron W -50 + +KPX Amacron Y -100 + +KPX Amacron Yacute -100 + +KPX Amacron Ydieresis -100 + +KPX Amacron u -30 + +KPX Amacron uacute -30 + +KPX Amacron ucircumflex -30 + +KPX Amacron udieresis -30 + +KPX Amacron ugrave -30 + +KPX Amacron uhungarumlaut -30 + +KPX Amacron umacron -30 + +KPX Amacron uogonek -30 + +KPX Amacron uring -30 + +KPX Amacron v -40 + +KPX Amacron w -40 + +KPX Amacron y -40 + +KPX Amacron yacute -40 + +KPX Amacron ydieresis -40 + +KPX Aogonek C -30 + +KPX Aogonek Cacute -30 + +KPX Aogonek Ccaron -30 + +KPX Aogonek Ccedilla -30 + +KPX Aogonek G -30 + +KPX Aogonek Gbreve -30 + +KPX Aogonek Gcommaaccent -30 + +KPX Aogonek O -30 + +KPX Aogonek Oacute -30 + +KPX Aogonek Ocircumflex -30 + +KPX Aogonek Odieresis -30 + +KPX Aogonek Ograve -30 + +KPX Aogonek Ohungarumlaut -30 + +KPX Aogonek Omacron -30 + +KPX Aogonek Oslash -30 + +KPX Aogonek Otilde -30 + +KPX Aogonek Q -30 + +KPX Aogonek T -120 + +KPX Aogonek Tcaron -120 + +KPX Aogonek Tcommaaccent -120 + +KPX Aogonek U -50 + +KPX Aogonek Uacute -50 + +KPX Aogonek Ucircumflex -50 + +KPX Aogonek Udieresis -50 + +KPX Aogonek Ugrave -50 + +KPX Aogonek Uhungarumlaut -50 + +KPX Aogonek Umacron -50 + +KPX Aogonek Uogonek -50 + +KPX Aogonek Uring -50 + +KPX Aogonek V -70 + +KPX Aogonek W -50 + +KPX Aogonek Y -100 + +KPX Aogonek Yacute -100 + +KPX Aogonek Ydieresis -100 + +KPX Aogonek u -30 + +KPX Aogonek uacute -30 + +KPX Aogonek ucircumflex -30 + +KPX Aogonek udieresis -30 + +KPX Aogonek ugrave -30 + +KPX Aogonek uhungarumlaut -30 + +KPX Aogonek umacron -30 + +KPX Aogonek uogonek -30 + +KPX Aogonek uring -30 + +KPX Aogonek v -40 + +KPX Aogonek w -40 + +KPX Aogonek y -40 + +KPX Aogonek yacute -40 + +KPX Aogonek ydieresis -40 + +KPX Aring C -30 + +KPX Aring Cacute -30 + +KPX Aring Ccaron -30 + +KPX Aring Ccedilla -30 + +KPX Aring G -30 + +KPX Aring Gbreve -30 + +KPX Aring Gcommaaccent -30 + +KPX Aring O -30 + +KPX Aring Oacute -30 + +KPX Aring Ocircumflex -30 + +KPX Aring Odieresis -30 + +KPX Aring Ograve -30 + +KPX Aring Ohungarumlaut -30 + +KPX Aring Omacron -30 + +KPX Aring Oslash -30 + +KPX Aring Otilde -30 + +KPX Aring Q -30 + +KPX Aring T -120 + +KPX Aring Tcaron -120 + +KPX Aring Tcommaaccent -120 + +KPX Aring U -50 + +KPX Aring Uacute -50 + +KPX Aring Ucircumflex -50 + +KPX Aring Udieresis -50 + +KPX Aring Ugrave -50 + +KPX Aring Uhungarumlaut -50 + +KPX Aring Umacron -50 + +KPX Aring Uogonek -50 + +KPX Aring Uring -50 + +KPX Aring V -70 + +KPX Aring W -50 + +KPX Aring Y -100 + +KPX Aring Yacute -100 + +KPX Aring Ydieresis -100 + +KPX Aring u -30 + +KPX Aring uacute -30 + +KPX Aring ucircumflex -30 + +KPX Aring udieresis -30 + +KPX Aring ugrave -30 + +KPX Aring uhungarumlaut -30 + +KPX Aring umacron -30 + +KPX Aring uogonek -30 + +KPX Aring uring -30 + +KPX Aring v -40 + +KPX Aring w -40 + +KPX Aring y -40 + +KPX Aring yacute -40 + +KPX Aring ydieresis -40 + +KPX Atilde C -30 + +KPX Atilde Cacute -30 + +KPX Atilde Ccaron -30 + +KPX Atilde Ccedilla -30 + +KPX Atilde G -30 + +KPX Atilde Gbreve -30 + +KPX Atilde Gcommaaccent -30 + +KPX Atilde O -30 + +KPX Atilde Oacute -30 + +KPX Atilde Ocircumflex -30 + +KPX Atilde Odieresis -30 + +KPX Atilde Ograve -30 + +KPX Atilde Ohungarumlaut -30 + +KPX Atilde Omacron -30 + +KPX Atilde Oslash -30 + +KPX Atilde Otilde -30 + +KPX Atilde Q -30 + +KPX Atilde T -120 + +KPX Atilde Tcaron -120 + +KPX Atilde Tcommaaccent -120 + +KPX Atilde U -50 + +KPX Atilde Uacute -50 + +KPX Atilde Ucircumflex -50 + +KPX Atilde Udieresis -50 + +KPX Atilde Ugrave -50 + +KPX Atilde Uhungarumlaut -50 + +KPX Atilde Umacron -50 + +KPX Atilde Uogonek -50 + +KPX Atilde Uring -50 + +KPX Atilde V -70 + +KPX Atilde W -50 + +KPX Atilde Y -100 + +KPX Atilde Yacute -100 + +KPX Atilde Ydieresis -100 + +KPX Atilde u -30 + +KPX Atilde uacute -30 + +KPX Atilde ucircumflex -30 + +KPX Atilde udieresis -30 + +KPX Atilde ugrave -30 + +KPX Atilde uhungarumlaut -30 + +KPX Atilde umacron -30 + +KPX Atilde uogonek -30 + +KPX Atilde uring -30 + +KPX Atilde v -40 + +KPX Atilde w -40 + +KPX Atilde y -40 + +KPX Atilde yacute -40 + +KPX Atilde ydieresis -40 + +KPX B U -10 + +KPX B Uacute -10 + +KPX B Ucircumflex -10 + +KPX B Udieresis -10 + +KPX B Ugrave -10 + +KPX B Uhungarumlaut -10 + +KPX B Umacron -10 + +KPX B Uogonek -10 + +KPX B Uring -10 + +KPX B comma -20 + +KPX B period -20 + +KPX C comma -30 + +KPX C period -30 + +KPX Cacute comma -30 + +KPX Cacute period -30 + +KPX Ccaron comma -30 + +KPX Ccaron period -30 + +KPX Ccedilla comma -30 + +KPX Ccedilla period -30 + +KPX D A -40 + +KPX D Aacute -40 + +KPX D Abreve -40 + +KPX D Acircumflex -40 + +KPX D Adieresis -40 + +KPX D Agrave -40 + +KPX D Amacron -40 + +KPX D Aogonek -40 + +KPX D Aring -40 + +KPX D Atilde -40 + +KPX D V -70 + +KPX D W -40 + +KPX D Y -90 + +KPX D Yacute -90 + +KPX D Ydieresis -90 + +KPX D comma -70 + +KPX D period -70 + +KPX Dcaron A -40 + +KPX Dcaron Aacute -40 + +KPX Dcaron Abreve -40 + +KPX Dcaron Acircumflex -40 + +KPX Dcaron Adieresis -40 + +KPX Dcaron Agrave -40 + +KPX Dcaron Amacron -40 + +KPX Dcaron Aogonek -40 + +KPX Dcaron Aring -40 + +KPX Dcaron Atilde -40 + +KPX Dcaron V -70 + +KPX Dcaron W -40 + +KPX Dcaron Y -90 + +KPX Dcaron Yacute -90 + +KPX Dcaron Ydieresis -90 + +KPX Dcaron comma -70 + +KPX Dcaron period -70 + +KPX Dcroat A -40 + +KPX Dcroat Aacute -40 + +KPX Dcroat Abreve -40 + +KPX Dcroat Acircumflex -40 + +KPX Dcroat Adieresis -40 + +KPX Dcroat Agrave -40 + +KPX Dcroat Amacron -40 + +KPX Dcroat Aogonek -40 + +KPX Dcroat Aring -40 + +KPX Dcroat Atilde -40 + +KPX Dcroat V -70 + +KPX Dcroat W -40 + +KPX Dcroat Y -90 + +KPX Dcroat Yacute -90 + +KPX Dcroat Ydieresis -90 + +KPX Dcroat comma -70 + +KPX Dcroat period -70 + +KPX F A -80 + +KPX F Aacute -80 + +KPX F Abreve -80 + +KPX F Acircumflex -80 + +KPX F Adieresis -80 + +KPX F Agrave -80 + +KPX F Amacron -80 + +KPX F Aogonek -80 + +KPX F Aring -80 + +KPX F Atilde -80 + +KPX F a -50 + +KPX F aacute -50 + +KPX F abreve -50 + +KPX F acircumflex -50 + +KPX F adieresis -50 + +KPX F agrave -50 + +KPX F amacron -50 + +KPX F aogonek -50 + +KPX F aring -50 + +KPX F atilde -50 + +KPX F comma -150 + +KPX F e -30 + +KPX F eacute -30 + +KPX F ecaron -30 + +KPX F ecircumflex -30 + +KPX F edieresis -30 + +KPX F edotaccent -30 + +KPX F egrave -30 + +KPX F emacron -30 + +KPX F eogonek -30 + +KPX F o -30 + +KPX F oacute -30 + +KPX F ocircumflex -30 + +KPX F odieresis -30 + +KPX F ograve -30 + +KPX F ohungarumlaut -30 + +KPX F omacron -30 + +KPX F oslash -30 + +KPX F otilde -30 + +KPX F period -150 + +KPX F r -45 + +KPX F racute -45 + +KPX F rcaron -45 + +KPX F rcommaaccent -45 + +KPX J A -20 + +KPX J Aacute -20 + +KPX J Abreve -20 + +KPX J Acircumflex -20 + +KPX J Adieresis -20 + +KPX J Agrave -20 + +KPX J Amacron -20 + +KPX J Aogonek -20 + +KPX J Aring -20 + +KPX J Atilde -20 + +KPX J a -20 + +KPX J aacute -20 + +KPX J abreve -20 + +KPX J acircumflex -20 + +KPX J adieresis -20 + +KPX J agrave -20 + +KPX J amacron -20 + +KPX J aogonek -20 + +KPX J aring -20 + +KPX J atilde -20 + +KPX J comma -30 + +KPX J period -30 + +KPX J u -20 + +KPX J uacute -20 + +KPX J ucircumflex -20 + +KPX J udieresis -20 + +KPX J ugrave -20 + +KPX J uhungarumlaut -20 + +KPX J umacron -20 + +KPX J uogonek -20 + +KPX J uring -20 + +KPX K O -50 + +KPX K Oacute -50 + +KPX K Ocircumflex -50 + +KPX K Odieresis -50 + +KPX K Ograve -50 + +KPX K Ohungarumlaut -50 + +KPX K Omacron -50 + +KPX K Oslash -50 + +KPX K Otilde -50 + +KPX K e -40 + +KPX K eacute -40 + +KPX K ecaron -40 + +KPX K ecircumflex -40 + +KPX K edieresis -40 + +KPX K edotaccent -40 + +KPX K egrave -40 + +KPX K emacron -40 + +KPX K eogonek -40 + +KPX K o -40 + +KPX K oacute -40 + +KPX K ocircumflex -40 + +KPX K odieresis -40 + +KPX K ograve -40 + +KPX K ohungarumlaut -40 + +KPX K omacron -40 + +KPX K oslash -40 + +KPX K otilde -40 + +KPX K u -30 + +KPX K uacute -30 + +KPX K ucircumflex -30 + +KPX K udieresis -30 + +KPX K ugrave -30 + +KPX K uhungarumlaut -30 + +KPX K umacron -30 + +KPX K uogonek -30 + +KPX K uring -30 + +KPX K y -50 + +KPX K yacute -50 + +KPX K ydieresis -50 + +KPX Kcommaaccent O -50 + +KPX Kcommaaccent Oacute -50 + +KPX Kcommaaccent Ocircumflex -50 + +KPX Kcommaaccent Odieresis -50 + +KPX Kcommaaccent Ograve -50 + +KPX Kcommaaccent Ohungarumlaut -50 + +KPX Kcommaaccent Omacron -50 + +KPX Kcommaaccent Oslash -50 + +KPX Kcommaaccent Otilde -50 + +KPX Kcommaaccent e -40 + +KPX Kcommaaccent eacute -40 + +KPX Kcommaaccent ecaron -40 + +KPX Kcommaaccent ecircumflex -40 + +KPX Kcommaaccent edieresis -40 + +KPX Kcommaaccent edotaccent -40 + +KPX Kcommaaccent egrave -40 + +KPX Kcommaaccent emacron -40 + +KPX Kcommaaccent eogonek -40 + +KPX Kcommaaccent o -40 + +KPX Kcommaaccent oacute -40 + +KPX Kcommaaccent ocircumflex -40 + +KPX Kcommaaccent odieresis -40 + +KPX Kcommaaccent ograve -40 + +KPX Kcommaaccent ohungarumlaut -40 + +KPX Kcommaaccent omacron -40 + +KPX Kcommaaccent oslash -40 + +KPX Kcommaaccent otilde -40 + +KPX Kcommaaccent u -30 + +KPX Kcommaaccent uacute -30 + +KPX Kcommaaccent ucircumflex -30 + +KPX Kcommaaccent udieresis -30 + +KPX Kcommaaccent ugrave -30 + +KPX Kcommaaccent uhungarumlaut -30 + +KPX Kcommaaccent umacron -30 + +KPX Kcommaaccent uogonek -30 + +KPX Kcommaaccent uring -30 + +KPX Kcommaaccent y -50 + +KPX Kcommaaccent yacute -50 + +KPX Kcommaaccent ydieresis -50 + +KPX L T -110 + +KPX L Tcaron -110 + +KPX L Tcommaaccent -110 + +KPX L V -110 + +KPX L W -70 + +KPX L Y -140 + +KPX L Yacute -140 + +KPX L Ydieresis -140 + +KPX L quotedblright -140 + +KPX L quoteright -160 + +KPX L y -30 + +KPX L yacute -30 + +KPX L ydieresis -30 + +KPX Lacute T -110 + +KPX Lacute Tcaron -110 + +KPX Lacute Tcommaaccent -110 + +KPX Lacute V -110 + +KPX Lacute W -70 + +KPX Lacute Y -140 + +KPX Lacute Yacute -140 + +KPX Lacute Ydieresis -140 + +KPX Lacute quotedblright -140 + +KPX Lacute quoteright -160 + +KPX Lacute y -30 + +KPX Lacute yacute -30 + +KPX Lacute ydieresis -30 + +KPX Lcaron T -110 + +KPX Lcaron Tcaron -110 + +KPX Lcaron Tcommaaccent -110 + +KPX Lcaron V -110 + +KPX Lcaron W -70 + +KPX Lcaron Y -140 + +KPX Lcaron Yacute -140 + +KPX Lcaron Ydieresis -140 + +KPX Lcaron quotedblright -140 + +KPX Lcaron quoteright -160 + +KPX Lcaron y -30 + +KPX Lcaron yacute -30 + +KPX Lcaron ydieresis -30 + +KPX Lcommaaccent T -110 + +KPX Lcommaaccent Tcaron -110 + +KPX Lcommaaccent Tcommaaccent -110 + +KPX Lcommaaccent V -110 + +KPX Lcommaaccent W -70 + +KPX Lcommaaccent Y -140 + +KPX Lcommaaccent Yacute -140 + +KPX Lcommaaccent Ydieresis -140 + +KPX Lcommaaccent quotedblright -140 + +KPX Lcommaaccent quoteright -160 + +KPX Lcommaaccent y -30 + +KPX Lcommaaccent yacute -30 + +KPX Lcommaaccent ydieresis -30 + +KPX Lslash T -110 + +KPX Lslash Tcaron -110 + +KPX Lslash Tcommaaccent -110 + +KPX Lslash V -110 + +KPX Lslash W -70 + +KPX Lslash Y -140 + +KPX Lslash Yacute -140 + +KPX Lslash Ydieresis -140 + +KPX Lslash quotedblright -140 + +KPX Lslash quoteright -160 + +KPX Lslash y -30 + +KPX Lslash yacute -30 + +KPX Lslash ydieresis -30 + +KPX O A -20 + +KPX O Aacute -20 + +KPX O Abreve -20 + +KPX O Acircumflex -20 + +KPX O Adieresis -20 + +KPX O Agrave -20 + +KPX O Amacron -20 + +KPX O Aogonek -20 + +KPX O Aring -20 + +KPX O Atilde -20 + +KPX O T -40 + +KPX O Tcaron -40 + +KPX O Tcommaaccent -40 + +KPX O V -50 + +KPX O W -30 + +KPX O X -60 + +KPX O Y -70 + +KPX O Yacute -70 + +KPX O Ydieresis -70 + +KPX O comma -40 + +KPX O period -40 + +KPX Oacute A -20 + +KPX Oacute Aacute -20 + +KPX Oacute Abreve -20 + +KPX Oacute Acircumflex -20 + +KPX Oacute Adieresis -20 + +KPX Oacute Agrave -20 + +KPX Oacute Amacron -20 + +KPX Oacute Aogonek -20 + +KPX Oacute Aring -20 + +KPX Oacute Atilde -20 + +KPX Oacute T -40 + +KPX Oacute Tcaron -40 + +KPX Oacute Tcommaaccent -40 + +KPX Oacute V -50 + +KPX Oacute W -30 + +KPX Oacute X -60 + +KPX Oacute Y -70 + +KPX Oacute Yacute -70 + +KPX Oacute Ydieresis -70 + +KPX Oacute comma -40 + +KPX Oacute period -40 + +KPX Ocircumflex A -20 + +KPX Ocircumflex Aacute -20 + +KPX Ocircumflex Abreve -20 + +KPX Ocircumflex Acircumflex -20 + +KPX Ocircumflex Adieresis -20 + +KPX Ocircumflex Agrave -20 + +KPX Ocircumflex Amacron -20 + +KPX Ocircumflex Aogonek -20 + +KPX Ocircumflex Aring -20 + +KPX Ocircumflex Atilde -20 + +KPX Ocircumflex T -40 + +KPX Ocircumflex Tcaron -40 + +KPX Ocircumflex Tcommaaccent -40 + +KPX Ocircumflex V -50 + +KPX Ocircumflex W -30 + +KPX Ocircumflex X -60 + +KPX Ocircumflex Y -70 + +KPX Ocircumflex Yacute -70 + +KPX Ocircumflex Ydieresis -70 + +KPX Ocircumflex comma -40 + +KPX Ocircumflex period -40 + +KPX Odieresis A -20 + +KPX Odieresis Aacute -20 + +KPX Odieresis Abreve -20 + +KPX Odieresis Acircumflex -20 + +KPX Odieresis Adieresis -20 + +KPX Odieresis Agrave -20 + +KPX Odieresis Amacron -20 + +KPX Odieresis Aogonek -20 + +KPX Odieresis Aring -20 + +KPX Odieresis Atilde -20 + +KPX Odieresis T -40 + +KPX Odieresis Tcaron -40 + +KPX Odieresis Tcommaaccent -40 + +KPX Odieresis V -50 + +KPX Odieresis W -30 + +KPX Odieresis X -60 + +KPX Odieresis Y -70 + +KPX Odieresis Yacute -70 + +KPX Odieresis Ydieresis -70 + +KPX Odieresis comma -40 + +KPX Odieresis period -40 + +KPX Ograve A -20 + +KPX Ograve Aacute -20 + +KPX Ograve Abreve -20 + +KPX Ograve Acircumflex -20 + +KPX Ograve Adieresis -20 + +KPX Ograve Agrave -20 + +KPX Ograve Amacron -20 + +KPX Ograve Aogonek -20 + +KPX Ograve Aring -20 + +KPX Ograve Atilde -20 + +KPX Ograve T -40 + +KPX Ograve Tcaron -40 + +KPX Ograve Tcommaaccent -40 + +KPX Ograve V -50 + +KPX Ograve W -30 + +KPX Ograve X -60 + +KPX Ograve Y -70 + +KPX Ograve Yacute -70 + +KPX Ograve Ydieresis -70 + +KPX Ograve comma -40 + +KPX Ograve period -40 + +KPX Ohungarumlaut A -20 + +KPX Ohungarumlaut Aacute -20 + +KPX Ohungarumlaut Abreve -20 + +KPX Ohungarumlaut Acircumflex -20 + +KPX Ohungarumlaut Adieresis -20 + +KPX Ohungarumlaut Agrave -20 + +KPX Ohungarumlaut Amacron -20 + +KPX Ohungarumlaut Aogonek -20 + +KPX Ohungarumlaut Aring -20 + +KPX Ohungarumlaut Atilde -20 + +KPX Ohungarumlaut T -40 + +KPX Ohungarumlaut Tcaron -40 + +KPX Ohungarumlaut Tcommaaccent -40 + +KPX Ohungarumlaut V -50 + +KPX Ohungarumlaut W -30 + +KPX Ohungarumlaut X -60 + +KPX Ohungarumlaut Y -70 + +KPX Ohungarumlaut Yacute -70 + +KPX Ohungarumlaut Ydieresis -70 + +KPX Ohungarumlaut comma -40 + +KPX Ohungarumlaut period -40 + +KPX Omacron A -20 + +KPX Omacron Aacute -20 + +KPX Omacron Abreve -20 + +KPX Omacron Acircumflex -20 + +KPX Omacron Adieresis -20 + +KPX Omacron Agrave -20 + +KPX Omacron Amacron -20 + +KPX Omacron Aogonek -20 + +KPX Omacron Aring -20 + +KPX Omacron Atilde -20 + +KPX Omacron T -40 + +KPX Omacron Tcaron -40 + +KPX Omacron Tcommaaccent -40 + +KPX Omacron V -50 + +KPX Omacron W -30 + +KPX Omacron X -60 + +KPX Omacron Y -70 + +KPX Omacron Yacute -70 + +KPX Omacron Ydieresis -70 + +KPX Omacron comma -40 + +KPX Omacron period -40 + +KPX Oslash A -20 + +KPX Oslash Aacute -20 + +KPX Oslash Abreve -20 + +KPX Oslash Acircumflex -20 + +KPX Oslash Adieresis -20 + +KPX Oslash Agrave -20 + +KPX Oslash Amacron -20 + +KPX Oslash Aogonek -20 + +KPX Oslash Aring -20 + +KPX Oslash Atilde -20 + +KPX Oslash T -40 + +KPX Oslash Tcaron -40 + +KPX Oslash Tcommaaccent -40 + +KPX Oslash V -50 + +KPX Oslash W -30 + +KPX Oslash X -60 + +KPX Oslash Y -70 + +KPX Oslash Yacute -70 + +KPX Oslash Ydieresis -70 + +KPX Oslash comma -40 + +KPX Oslash period -40 + +KPX Otilde A -20 + +KPX Otilde Aacute -20 + +KPX Otilde Abreve -20 + +KPX Otilde Acircumflex -20 + +KPX Otilde Adieresis -20 + +KPX Otilde Agrave -20 + +KPX Otilde Amacron -20 + +KPX Otilde Aogonek -20 + +KPX Otilde Aring -20 + +KPX Otilde Atilde -20 + +KPX Otilde T -40 + +KPX Otilde Tcaron -40 + +KPX Otilde Tcommaaccent -40 + +KPX Otilde V -50 + +KPX Otilde W -30 + +KPX Otilde X -60 + +KPX Otilde Y -70 + +KPX Otilde Yacute -70 + +KPX Otilde Ydieresis -70 + +KPX Otilde comma -40 + +KPX Otilde period -40 + +KPX P A -120 + +KPX P Aacute -120 + +KPX P Abreve -120 + +KPX P Acircumflex -120 + +KPX P Adieresis -120 + +KPX P Agrave -120 + +KPX P Amacron -120 + +KPX P Aogonek -120 + +KPX P Aring -120 + +KPX P Atilde -120 + +KPX P a -40 + +KPX P aacute -40 + +KPX P abreve -40 + +KPX P acircumflex -40 + +KPX P adieresis -40 + +KPX P agrave -40 + +KPX P amacron -40 + +KPX P aogonek -40 + +KPX P aring -40 + +KPX P atilde -40 + +KPX P comma -180 + +KPX P e -50 + +KPX P eacute -50 + +KPX P ecaron -50 + +KPX P ecircumflex -50 + +KPX P edieresis -50 + +KPX P edotaccent -50 + +KPX P egrave -50 + +KPX P emacron -50 + +KPX P eogonek -50 + +KPX P o -50 + +KPX P oacute -50 + +KPX P ocircumflex -50 + +KPX P odieresis -50 + +KPX P ograve -50 + +KPX P ohungarumlaut -50 + +KPX P omacron -50 + +KPX P oslash -50 + +KPX P otilde -50 + +KPX P period -180 + +KPX Q U -10 + +KPX Q Uacute -10 + +KPX Q Ucircumflex -10 + +KPX Q Udieresis -10 + +KPX Q Ugrave -10 + +KPX Q Uhungarumlaut -10 + +KPX Q Umacron -10 + +KPX Q Uogonek -10 + +KPX Q Uring -10 + +KPX R O -20 + +KPX R Oacute -20 + +KPX R Ocircumflex -20 + +KPX R Odieresis -20 + +KPX R Ograve -20 + +KPX R Ohungarumlaut -20 + +KPX R Omacron -20 + +KPX R Oslash -20 + +KPX R Otilde -20 + +KPX R T -30 + +KPX R Tcaron -30 + +KPX R Tcommaaccent -30 + +KPX R U -40 + +KPX R Uacute -40 + +KPX R Ucircumflex -40 + +KPX R Udieresis -40 + +KPX R Ugrave -40 + +KPX R Uhungarumlaut -40 + +KPX R Umacron -40 + +KPX R Uogonek -40 + +KPX R Uring -40 + +KPX R V -50 + +KPX R W -30 + +KPX R Y -50 + +KPX R Yacute -50 + +KPX R Ydieresis -50 + +KPX Racute O -20 + +KPX Racute Oacute -20 + +KPX Racute Ocircumflex -20 + +KPX Racute Odieresis -20 + +KPX Racute Ograve -20 + +KPX Racute Ohungarumlaut -20 + +KPX Racute Omacron -20 + +KPX Racute Oslash -20 + +KPX Racute Otilde -20 + +KPX Racute T -30 + +KPX Racute Tcaron -30 + +KPX Racute Tcommaaccent -30 + +KPX Racute U -40 + +KPX Racute Uacute -40 + +KPX Racute Ucircumflex -40 + +KPX Racute Udieresis -40 + +KPX Racute Ugrave -40 + +KPX Racute Uhungarumlaut -40 + +KPX Racute Umacron -40 + +KPX Racute Uogonek -40 + +KPX Racute Uring -40 + +KPX Racute V -50 + +KPX Racute W -30 + +KPX Racute Y -50 + +KPX Racute Yacute -50 + +KPX Racute Ydieresis -50 + +KPX Rcaron O -20 + +KPX Rcaron Oacute -20 + +KPX Rcaron Ocircumflex -20 + +KPX Rcaron Odieresis -20 + +KPX Rcaron Ograve -20 + +KPX Rcaron Ohungarumlaut -20 + +KPX Rcaron Omacron -20 + +KPX Rcaron Oslash -20 + +KPX Rcaron Otilde -20 + +KPX Rcaron T -30 + +KPX Rcaron Tcaron -30 + +KPX Rcaron Tcommaaccent -30 + +KPX Rcaron U -40 + +KPX Rcaron Uacute -40 + +KPX Rcaron Ucircumflex -40 + +KPX Rcaron Udieresis -40 + +KPX Rcaron Ugrave -40 + +KPX Rcaron Uhungarumlaut -40 + +KPX Rcaron Umacron -40 + +KPX Rcaron Uogonek -40 + +KPX Rcaron Uring -40 + +KPX Rcaron V -50 + +KPX Rcaron W -30 + +KPX Rcaron Y -50 + +KPX Rcaron Yacute -50 + +KPX Rcaron Ydieresis -50 + +KPX Rcommaaccent O -20 + +KPX Rcommaaccent Oacute -20 + +KPX Rcommaaccent Ocircumflex -20 + +KPX Rcommaaccent Odieresis -20 + +KPX Rcommaaccent Ograve -20 + +KPX Rcommaaccent Ohungarumlaut -20 + +KPX Rcommaaccent Omacron -20 + +KPX Rcommaaccent Oslash -20 + +KPX Rcommaaccent Otilde -20 + +KPX Rcommaaccent T -30 + +KPX Rcommaaccent Tcaron -30 + +KPX Rcommaaccent Tcommaaccent -30 + +KPX Rcommaaccent U -40 + +KPX Rcommaaccent Uacute -40 + +KPX Rcommaaccent Ucircumflex -40 + +KPX Rcommaaccent Udieresis -40 + +KPX Rcommaaccent Ugrave -40 + +KPX Rcommaaccent Uhungarumlaut -40 + +KPX Rcommaaccent Umacron -40 + +KPX Rcommaaccent Uogonek -40 + +KPX Rcommaaccent Uring -40 + +KPX Rcommaaccent V -50 + +KPX Rcommaaccent W -30 + +KPX Rcommaaccent Y -50 + +KPX Rcommaaccent Yacute -50 + +KPX Rcommaaccent Ydieresis -50 + +KPX S comma -20 + +KPX S period -20 + +KPX Sacute comma -20 + +KPX Sacute period -20 + +KPX Scaron comma -20 + +KPX Scaron period -20 + +KPX Scedilla comma -20 + +KPX Scedilla period -20 + +KPX Scommaaccent comma -20 + +KPX Scommaaccent period -20 + +KPX T A -120 + +KPX T Aacute -120 + +KPX T Abreve -120 + +KPX T Acircumflex -120 + +KPX T Adieresis -120 + +KPX T Agrave -120 + +KPX T Amacron -120 + +KPX T Aogonek -120 + +KPX T Aring -120 + +KPX T Atilde -120 + +KPX T O -40 + +KPX T Oacute -40 + +KPX T Ocircumflex -40 + +KPX T Odieresis -40 + +KPX T Ograve -40 + +KPX T Ohungarumlaut -40 + +KPX T Omacron -40 + +KPX T Oslash -40 + +KPX T Otilde -40 + +KPX T a -120 + +KPX T aacute -120 + +KPX T abreve -60 + +KPX T acircumflex -120 + +KPX T adieresis -120 + +KPX T agrave -120 + +KPX T amacron -60 + +KPX T aogonek -120 + +KPX T aring -120 + +KPX T atilde -60 + +KPX T colon -20 + +KPX T comma -120 + +KPX T e -120 + +KPX T eacute -120 + +KPX T ecaron -120 + +KPX T ecircumflex -120 + +KPX T edieresis -120 + +KPX T edotaccent -120 + +KPX T egrave -60 + +KPX T emacron -60 + +KPX T eogonek -120 + +KPX T hyphen -140 + +KPX T o -120 + +KPX T oacute -120 + +KPX T ocircumflex -120 + +KPX T odieresis -120 + +KPX T ograve -120 + +KPX T ohungarumlaut -120 + +KPX T omacron -60 + +KPX T oslash -120 + +KPX T otilde -60 + +KPX T period -120 + +KPX T r -120 + +KPX T racute -120 + +KPX T rcaron -120 + +KPX T rcommaaccent -120 + +KPX T semicolon -20 + +KPX T u -120 + +KPX T uacute -120 + +KPX T ucircumflex -120 + +KPX T udieresis -120 + +KPX T ugrave -120 + +KPX T uhungarumlaut -120 + +KPX T umacron -60 + +KPX T uogonek -120 + +KPX T uring -120 + +KPX T w -120 + +KPX T y -120 + +KPX T yacute -120 + +KPX T ydieresis -60 + +KPX Tcaron A -120 + +KPX Tcaron Aacute -120 + +KPX Tcaron Abreve -120 + +KPX Tcaron Acircumflex -120 + +KPX Tcaron Adieresis -120 + +KPX Tcaron Agrave -120 + +KPX Tcaron Amacron -120 + +KPX Tcaron Aogonek -120 + +KPX Tcaron Aring -120 + +KPX Tcaron Atilde -120 + +KPX Tcaron O -40 + +KPX Tcaron Oacute -40 + +KPX Tcaron Ocircumflex -40 + +KPX Tcaron Odieresis -40 + +KPX Tcaron Ograve -40 + +KPX Tcaron Ohungarumlaut -40 + +KPX Tcaron Omacron -40 + +KPX Tcaron Oslash -40 + +KPX Tcaron Otilde -40 + +KPX Tcaron a -120 + +KPX Tcaron aacute -120 + +KPX Tcaron abreve -60 + +KPX Tcaron acircumflex -120 + +KPX Tcaron adieresis -120 + +KPX Tcaron agrave -120 + +KPX Tcaron amacron -60 + +KPX Tcaron aogonek -120 + +KPX Tcaron aring -120 + +KPX Tcaron atilde -60 + +KPX Tcaron colon -20 + +KPX Tcaron comma -120 + +KPX Tcaron e -120 + +KPX Tcaron eacute -120 + +KPX Tcaron ecaron -120 + +KPX Tcaron ecircumflex -120 + +KPX Tcaron edieresis -120 + +KPX Tcaron edotaccent -120 + +KPX Tcaron egrave -60 + +KPX Tcaron emacron -60 + +KPX Tcaron eogonek -120 + +KPX Tcaron hyphen -140 + +KPX Tcaron o -120 + +KPX Tcaron oacute -120 + +KPX Tcaron ocircumflex -120 + +KPX Tcaron odieresis -120 + +KPX Tcaron ograve -120 + +KPX Tcaron ohungarumlaut -120 + +KPX Tcaron omacron -60 + +KPX Tcaron oslash -120 + +KPX Tcaron otilde -60 + +KPX Tcaron period -120 + +KPX Tcaron r -120 + +KPX Tcaron racute -120 + +KPX Tcaron rcaron -120 + +KPX Tcaron rcommaaccent -120 + +KPX Tcaron semicolon -20 + +KPX Tcaron u -120 + +KPX Tcaron uacute -120 + +KPX Tcaron ucircumflex -120 + +KPX Tcaron udieresis -120 + +KPX Tcaron ugrave -120 + +KPX Tcaron uhungarumlaut -120 + +KPX Tcaron umacron -60 + +KPX Tcaron uogonek -120 + +KPX Tcaron uring -120 + +KPX Tcaron w -120 + +KPX Tcaron y -120 + +KPX Tcaron yacute -120 + +KPX Tcaron ydieresis -60 + +KPX Tcommaaccent A -120 + +KPX Tcommaaccent Aacute -120 + +KPX Tcommaaccent Abreve -120 + +KPX Tcommaaccent Acircumflex -120 + +KPX Tcommaaccent Adieresis -120 + +KPX Tcommaaccent Agrave -120 + +KPX Tcommaaccent Amacron -120 + +KPX Tcommaaccent Aogonek -120 + +KPX Tcommaaccent Aring -120 + +KPX Tcommaaccent Atilde -120 + +KPX Tcommaaccent O -40 + +KPX Tcommaaccent Oacute -40 + +KPX Tcommaaccent Ocircumflex -40 + +KPX Tcommaaccent Odieresis -40 + +KPX Tcommaaccent Ograve -40 + +KPX Tcommaaccent Ohungarumlaut -40 + +KPX Tcommaaccent Omacron -40 + +KPX Tcommaaccent Oslash -40 + +KPX Tcommaaccent Otilde -40 + +KPX Tcommaaccent a -120 + +KPX Tcommaaccent aacute -120 + +KPX Tcommaaccent abreve -60 + +KPX Tcommaaccent acircumflex -120 + +KPX Tcommaaccent adieresis -120 + +KPX Tcommaaccent agrave -120 + +KPX Tcommaaccent amacron -60 + +KPX Tcommaaccent aogonek -120 + +KPX Tcommaaccent aring -120 + +KPX Tcommaaccent atilde -60 + +KPX Tcommaaccent colon -20 + +KPX Tcommaaccent comma -120 + +KPX Tcommaaccent e -120 + +KPX Tcommaaccent eacute -120 + +KPX Tcommaaccent ecaron -120 + +KPX Tcommaaccent ecircumflex -120 + +KPX Tcommaaccent edieresis -120 + +KPX Tcommaaccent edotaccent -120 + +KPX Tcommaaccent egrave -60 + +KPX Tcommaaccent emacron -60 + +KPX Tcommaaccent eogonek -120 + +KPX Tcommaaccent hyphen -140 + +KPX Tcommaaccent o -120 + +KPX Tcommaaccent oacute -120 + +KPX Tcommaaccent ocircumflex -120 + +KPX Tcommaaccent odieresis -120 + +KPX Tcommaaccent ograve -120 + +KPX Tcommaaccent ohungarumlaut -120 + +KPX Tcommaaccent omacron -60 + +KPX Tcommaaccent oslash -120 + +KPX Tcommaaccent otilde -60 + +KPX Tcommaaccent period -120 + +KPX Tcommaaccent r -120 + +KPX Tcommaaccent racute -120 + +KPX Tcommaaccent rcaron -120 + +KPX Tcommaaccent rcommaaccent -120 + +KPX Tcommaaccent semicolon -20 + +KPX Tcommaaccent u -120 + +KPX Tcommaaccent uacute -120 + +KPX Tcommaaccent ucircumflex -120 + +KPX Tcommaaccent udieresis -120 + +KPX Tcommaaccent ugrave -120 + +KPX Tcommaaccent uhungarumlaut -120 + +KPX Tcommaaccent umacron -60 + +KPX Tcommaaccent uogonek -120 + +KPX Tcommaaccent uring -120 + +KPX Tcommaaccent w -120 + +KPX Tcommaaccent y -120 + +KPX Tcommaaccent yacute -120 + +KPX Tcommaaccent ydieresis -60 + +KPX U A -40 + +KPX U Aacute -40 + +KPX U Abreve -40 + +KPX U Acircumflex -40 + +KPX U Adieresis -40 + +KPX U Agrave -40 + +KPX U Amacron -40 + +KPX U Aogonek -40 + +KPX U Aring -40 + +KPX U Atilde -40 + +KPX U comma -40 + +KPX U period -40 + +KPX Uacute A -40 + +KPX Uacute Aacute -40 + +KPX Uacute Abreve -40 + +KPX Uacute Acircumflex -40 + +KPX Uacute Adieresis -40 + +KPX Uacute Agrave -40 + +KPX Uacute Amacron -40 + +KPX Uacute Aogonek -40 + +KPX Uacute Aring -40 + +KPX Uacute Atilde -40 + +KPX Uacute comma -40 + +KPX Uacute period -40 + +KPX Ucircumflex A -40 + +KPX Ucircumflex Aacute -40 + +KPX Ucircumflex Abreve -40 + +KPX Ucircumflex Acircumflex -40 + +KPX Ucircumflex Adieresis -40 + +KPX Ucircumflex Agrave -40 + +KPX Ucircumflex Amacron -40 + +KPX Ucircumflex Aogonek -40 + +KPX Ucircumflex Aring -40 + +KPX Ucircumflex Atilde -40 + +KPX Ucircumflex comma -40 + +KPX Ucircumflex period -40 + +KPX Udieresis A -40 + +KPX Udieresis Aacute -40 + +KPX Udieresis Abreve -40 + +KPX Udieresis Acircumflex -40 + +KPX Udieresis Adieresis -40 + +KPX Udieresis Agrave -40 + +KPX Udieresis Amacron -40 + +KPX Udieresis Aogonek -40 + +KPX Udieresis Aring -40 + +KPX Udieresis Atilde -40 + +KPX Udieresis comma -40 + +KPX Udieresis period -40 + +KPX Ugrave A -40 + +KPX Ugrave Aacute -40 + +KPX Ugrave Abreve -40 + +KPX Ugrave Acircumflex -40 + +KPX Ugrave Adieresis -40 + +KPX Ugrave Agrave -40 + +KPX Ugrave Amacron -40 + +KPX Ugrave Aogonek -40 + +KPX Ugrave Aring -40 + +KPX Ugrave Atilde -40 + +KPX Ugrave comma -40 + +KPX Ugrave period -40 + +KPX Uhungarumlaut A -40 + +KPX Uhungarumlaut Aacute -40 + +KPX Uhungarumlaut Abreve -40 + +KPX Uhungarumlaut Acircumflex -40 + +KPX Uhungarumlaut Adieresis -40 + +KPX Uhungarumlaut Agrave -40 + +KPX Uhungarumlaut Amacron -40 + +KPX Uhungarumlaut Aogonek -40 + +KPX Uhungarumlaut Aring -40 + +KPX Uhungarumlaut Atilde -40 + +KPX Uhungarumlaut comma -40 + +KPX Uhungarumlaut period -40 + +KPX Umacron A -40 + +KPX Umacron Aacute -40 + +KPX Umacron Abreve -40 + +KPX Umacron Acircumflex -40 + +KPX Umacron Adieresis -40 + +KPX Umacron Agrave -40 + +KPX Umacron Amacron -40 + +KPX Umacron Aogonek -40 + +KPX Umacron Aring -40 + +KPX Umacron Atilde -40 + +KPX Umacron comma -40 + +KPX Umacron period -40 + +KPX Uogonek A -40 + +KPX Uogonek Aacute -40 + +KPX Uogonek Abreve -40 + +KPX Uogonek Acircumflex -40 + +KPX Uogonek Adieresis -40 + +KPX Uogonek Agrave -40 + +KPX Uogonek Amacron -40 + +KPX Uogonek Aogonek -40 + +KPX Uogonek Aring -40 + +KPX Uogonek Atilde -40 + +KPX Uogonek comma -40 + +KPX Uogonek period -40 + +KPX Uring A -40 + +KPX Uring Aacute -40 + +KPX Uring Abreve -40 + +KPX Uring Acircumflex -40 + +KPX Uring Adieresis -40 + +KPX Uring Agrave -40 + +KPX Uring Amacron -40 + +KPX Uring Aogonek -40 + +KPX Uring Aring -40 + +KPX Uring Atilde -40 + +KPX Uring comma -40 + +KPX Uring period -40 + +KPX V A -80 + +KPX V Aacute -80 + +KPX V Abreve -80 + +KPX V Acircumflex -80 + +KPX V Adieresis -80 + +KPX V Agrave -80 + +KPX V Amacron -80 + +KPX V Aogonek -80 + +KPX V Aring -80 + +KPX V Atilde -80 + +KPX V G -40 + +KPX V Gbreve -40 + +KPX V Gcommaaccent -40 + +KPX V O -40 + +KPX V Oacute -40 + +KPX V Ocircumflex -40 + +KPX V Odieresis -40 + +KPX V Ograve -40 + +KPX V Ohungarumlaut -40 + +KPX V Omacron -40 + +KPX V Oslash -40 + +KPX V Otilde -40 + +KPX V a -70 + +KPX V aacute -70 + +KPX V abreve -70 + +KPX V acircumflex -70 + +KPX V adieresis -70 + +KPX V agrave -70 + +KPX V amacron -70 + +KPX V aogonek -70 + +KPX V aring -70 + +KPX V atilde -70 + +KPX V colon -40 + +KPX V comma -125 + +KPX V e -80 + +KPX V eacute -80 + +KPX V ecaron -80 + +KPX V ecircumflex -80 + +KPX V edieresis -80 + +KPX V edotaccent -80 + +KPX V egrave -80 + +KPX V emacron -80 + +KPX V eogonek -80 + +KPX V hyphen -80 + +KPX V o -80 + +KPX V oacute -80 + +KPX V ocircumflex -80 + +KPX V odieresis -80 + +KPX V ograve -80 + +KPX V ohungarumlaut -80 + +KPX V omacron -80 + +KPX V oslash -80 + +KPX V otilde -80 + +KPX V period -125 + +KPX V semicolon -40 + +KPX V u -70 + +KPX V uacute -70 + +KPX V ucircumflex -70 + +KPX V udieresis -70 + +KPX V ugrave -70 + +KPX V uhungarumlaut -70 + +KPX V umacron -70 + +KPX V uogonek -70 + +KPX V uring -70 + +KPX W A -50 + +KPX W Aacute -50 + +KPX W Abreve -50 + +KPX W Acircumflex -50 + +KPX W Adieresis -50 + +KPX W Agrave -50 + +KPX W Amacron -50 + +KPX W Aogonek -50 + +KPX W Aring -50 + +KPX W Atilde -50 + +KPX W O -20 + +KPX W Oacute -20 + +KPX W Ocircumflex -20 + +KPX W Odieresis -20 + +KPX W Ograve -20 + +KPX W Ohungarumlaut -20 + +KPX W Omacron -20 + +KPX W Oslash -20 + +KPX W Otilde -20 + +KPX W a -40 + +KPX W aacute -40 + +KPX W abreve -40 + +KPX W acircumflex -40 + +KPX W adieresis -40 + +KPX W agrave -40 + +KPX W amacron -40 + +KPX W aogonek -40 + +KPX W aring -40 + +KPX W atilde -40 + +KPX W comma -80 + +KPX W e -30 + +KPX W eacute -30 + +KPX W ecaron -30 + +KPX W ecircumflex -30 + +KPX W edieresis -30 + +KPX W edotaccent -30 + +KPX W egrave -30 + +KPX W emacron -30 + +KPX W eogonek -30 + +KPX W hyphen -40 + +KPX W o -30 + +KPX W oacute -30 + +KPX W ocircumflex -30 + +KPX W odieresis -30 + +KPX W ograve -30 + +KPX W ohungarumlaut -30 + +KPX W omacron -30 + +KPX W oslash -30 + +KPX W otilde -30 + +KPX W period -80 + +KPX W u -30 + +KPX W uacute -30 + +KPX W ucircumflex -30 + +KPX W udieresis -30 + +KPX W ugrave -30 + +KPX W uhungarumlaut -30 + +KPX W umacron -30 + +KPX W uogonek -30 + +KPX W uring -30 + +KPX W y -20 + +KPX W yacute -20 + +KPX W ydieresis -20 + +KPX Y A -110 + +KPX Y Aacute -110 + +KPX Y Abreve -110 + +KPX Y Acircumflex -110 + +KPX Y Adieresis -110 + +KPX Y Agrave -110 + +KPX Y Amacron -110 + +KPX Y Aogonek -110 + +KPX Y Aring -110 + +KPX Y Atilde -110 + +KPX Y O -85 + +KPX Y Oacute -85 + +KPX Y Ocircumflex -85 + +KPX Y Odieresis -85 + +KPX Y Ograve -85 + +KPX Y Ohungarumlaut -85 + +KPX Y Omacron -85 + +KPX Y Oslash -85 + +KPX Y Otilde -85 + +KPX Y a -140 + +KPX Y aacute -140 + +KPX Y abreve -70 + +KPX Y acircumflex -140 + +KPX Y adieresis -140 + +KPX Y agrave -140 + +KPX Y amacron -70 + +KPX Y aogonek -140 + +KPX Y aring -140 + +KPX Y atilde -140 + +KPX Y colon -60 + +KPX Y comma -140 + +KPX Y e -140 + +KPX Y eacute -140 + +KPX Y ecaron -140 + +KPX Y ecircumflex -140 + +KPX Y edieresis -140 + +KPX Y edotaccent -140 + +KPX Y egrave -140 + +KPX Y emacron -70 + +KPX Y eogonek -140 + +KPX Y hyphen -140 + +KPX Y i -20 + +KPX Y iacute -20 + +KPX Y iogonek -20 + +KPX Y o -140 + +KPX Y oacute -140 + +KPX Y ocircumflex -140 + +KPX Y odieresis -140 + +KPX Y ograve -140 + +KPX Y ohungarumlaut -140 + +KPX Y omacron -140 + +KPX Y oslash -140 + +KPX Y otilde -140 + +KPX Y period -140 + +KPX Y semicolon -60 + +KPX Y u -110 + +KPX Y uacute -110 + +KPX Y ucircumflex -110 + +KPX Y udieresis -110 + +KPX Y ugrave -110 + +KPX Y uhungarumlaut -110 + +KPX Y umacron -110 + +KPX Y uogonek -110 + +KPX Y uring -110 + +KPX Yacute A -110 + +KPX Yacute Aacute -110 + +KPX Yacute Abreve -110 + +KPX Yacute Acircumflex -110 + +KPX Yacute Adieresis -110 + +KPX Yacute Agrave -110 + +KPX Yacute Amacron -110 + +KPX Yacute Aogonek -110 + +KPX Yacute Aring -110 + +KPX Yacute Atilde -110 + +KPX Yacute O -85 + +KPX Yacute Oacute -85 + +KPX Yacute Ocircumflex -85 + +KPX Yacute Odieresis -85 + +KPX Yacute Ograve -85 + +KPX Yacute Ohungarumlaut -85 + +KPX Yacute Omacron -85 + +KPX Yacute Oslash -85 + +KPX Yacute Otilde -85 + +KPX Yacute a -140 + +KPX Yacute aacute -140 + +KPX Yacute abreve -70 + +KPX Yacute acircumflex -140 + +KPX Yacute adieresis -140 + +KPX Yacute agrave -140 + +KPX Yacute amacron -70 + +KPX Yacute aogonek -140 + +KPX Yacute aring -140 + +KPX Yacute atilde -70 + +KPX Yacute colon -60 + +KPX Yacute comma -140 + +KPX Yacute e -140 + +KPX Yacute eacute -140 + +KPX Yacute ecaron -140 + +KPX Yacute ecircumflex -140 + +KPX Yacute edieresis -140 + +KPX Yacute edotaccent -140 + +KPX Yacute egrave -140 + +KPX Yacute emacron -70 + +KPX Yacute eogonek -140 + +KPX Yacute hyphen -140 + +KPX Yacute i -20 + +KPX Yacute iacute -20 + +KPX Yacute iogonek -20 + +KPX Yacute o -140 + +KPX Yacute oacute -140 + +KPX Yacute ocircumflex -140 + +KPX Yacute odieresis -140 + +KPX Yacute ograve -140 + +KPX Yacute ohungarumlaut -140 + +KPX Yacute omacron -70 + +KPX Yacute oslash -140 + +KPX Yacute otilde -140 + +KPX Yacute period -140 + +KPX Yacute semicolon -60 + +KPX Yacute u -110 + +KPX Yacute uacute -110 + +KPX Yacute ucircumflex -110 + +KPX Yacute udieresis -110 + +KPX Yacute ugrave -110 + +KPX Yacute uhungarumlaut -110 + +KPX Yacute umacron -110 + +KPX Yacute uogonek -110 + +KPX Yacute uring -110 + +KPX Ydieresis A -110 + +KPX Ydieresis Aacute -110 + +KPX Ydieresis Abreve -110 + +KPX Ydieresis Acircumflex -110 + +KPX Ydieresis Adieresis -110 + +KPX Ydieresis Agrave -110 + +KPX Ydieresis Amacron -110 + +KPX Ydieresis Aogonek -110 + +KPX Ydieresis Aring -110 + +KPX Ydieresis Atilde -110 + +KPX Ydieresis O -85 + +KPX Ydieresis Oacute -85 + +KPX Ydieresis Ocircumflex -85 + +KPX Ydieresis Odieresis -85 + +KPX Ydieresis Ograve -85 + +KPX Ydieresis Ohungarumlaut -85 + +KPX Ydieresis Omacron -85 + +KPX Ydieresis Oslash -85 + +KPX Ydieresis Otilde -85 + +KPX Ydieresis a -140 + +KPX Ydieresis aacute -140 + +KPX Ydieresis abreve -70 + +KPX Ydieresis acircumflex -140 + +KPX Ydieresis adieresis -140 + +KPX Ydieresis agrave -140 + +KPX Ydieresis amacron -70 + +KPX Ydieresis aogonek -140 + +KPX Ydieresis aring -140 + +KPX Ydieresis atilde -70 + +KPX Ydieresis colon -60 + +KPX Ydieresis comma -140 + +KPX Ydieresis e -140 + +KPX Ydieresis eacute -140 + +KPX Ydieresis ecaron -140 + +KPX Ydieresis ecircumflex -140 + +KPX Ydieresis edieresis -140 + +KPX Ydieresis edotaccent -140 + +KPX Ydieresis egrave -140 + +KPX Ydieresis emacron -70 + +KPX Ydieresis eogonek -140 + +KPX Ydieresis hyphen -140 + +KPX Ydieresis i -20 + +KPX Ydieresis iacute -20 + +KPX Ydieresis iogonek -20 + +KPX Ydieresis o -140 + +KPX Ydieresis oacute -140 + +KPX Ydieresis ocircumflex -140 + +KPX Ydieresis odieresis -140 + +KPX Ydieresis ograve -140 + +KPX Ydieresis ohungarumlaut -140 + +KPX Ydieresis omacron -140 + +KPX Ydieresis oslash -140 + +KPX Ydieresis otilde -140 + +KPX Ydieresis period -140 + +KPX Ydieresis semicolon -60 + +KPX Ydieresis u -110 + +KPX Ydieresis uacute -110 + +KPX Ydieresis ucircumflex -110 + +KPX Ydieresis udieresis -110 + +KPX Ydieresis ugrave -110 + +KPX Ydieresis uhungarumlaut -110 + +KPX Ydieresis umacron -110 + +KPX Ydieresis uogonek -110 + +KPX Ydieresis uring -110 + +KPX a v -20 + +KPX a w -20 + +KPX a y -30 + +KPX a yacute -30 + +KPX a ydieresis -30 + +KPX aacute v -20 + +KPX aacute w -20 + +KPX aacute y -30 + +KPX aacute yacute -30 + +KPX aacute ydieresis -30 + +KPX abreve v -20 + +KPX abreve w -20 + +KPX abreve y -30 + +KPX abreve yacute -30 + +KPX abreve ydieresis -30 + +KPX acircumflex v -20 + +KPX acircumflex w -20 + +KPX acircumflex y -30 + +KPX acircumflex yacute -30 + +KPX acircumflex ydieresis -30 + +KPX adieresis v -20 + +KPX adieresis w -20 + +KPX adieresis y -30 + +KPX adieresis yacute -30 + +KPX adieresis ydieresis -30 + +KPX agrave v -20 + +KPX agrave w -20 + +KPX agrave y -30 + +KPX agrave yacute -30 + +KPX agrave ydieresis -30 + +KPX amacron v -20 + +KPX amacron w -20 + +KPX amacron y -30 + +KPX amacron yacute -30 + +KPX amacron ydieresis -30 + +KPX aogonek v -20 + +KPX aogonek w -20 + +KPX aogonek y -30 + +KPX aogonek yacute -30 + +KPX aogonek ydieresis -30 + +KPX aring v -20 + +KPX aring w -20 + +KPX aring y -30 + +KPX aring yacute -30 + +KPX aring ydieresis -30 + +KPX atilde v -20 + +KPX atilde w -20 + +KPX atilde y -30 + +KPX atilde yacute -30 + +KPX atilde ydieresis -30 + +KPX b b -10 + +KPX b comma -40 + +KPX b l -20 + +KPX b lacute -20 + +KPX b lcommaaccent -20 + +KPX b lslash -20 + +KPX b period -40 + +KPX b u -20 + +KPX b uacute -20 + +KPX b ucircumflex -20 + +KPX b udieresis -20 + +KPX b ugrave -20 + +KPX b uhungarumlaut -20 + +KPX b umacron -20 + +KPX b uogonek -20 + +KPX b uring -20 + +KPX b v -20 + +KPX b y -20 + +KPX b yacute -20 + +KPX b ydieresis -20 + +KPX c comma -15 + +KPX c k -20 + +KPX c kcommaaccent -20 + +KPX cacute comma -15 + +KPX cacute k -20 + +KPX cacute kcommaaccent -20 + +KPX ccaron comma -15 + +KPX ccaron k -20 + +KPX ccaron kcommaaccent -20 + +KPX ccedilla comma -15 + +KPX ccedilla k -20 + +KPX ccedilla kcommaaccent -20 + +KPX colon space -50 + +KPX comma quotedblright -100 + +KPX comma quoteright -100 + +KPX e comma -15 + +KPX e period -15 + +KPX e v -30 + +KPX e w -20 + +KPX e x -30 + +KPX e y -20 + +KPX e yacute -20 + +KPX e ydieresis -20 + +KPX eacute comma -15 + +KPX eacute period -15 + +KPX eacute v -30 + +KPX eacute w -20 + +KPX eacute x -30 + +KPX eacute y -20 + +KPX eacute yacute -20 + +KPX eacute ydieresis -20 + +KPX ecaron comma -15 + +KPX ecaron period -15 + +KPX ecaron v -30 + +KPX ecaron w -20 + +KPX ecaron x -30 + +KPX ecaron y -20 + +KPX ecaron yacute -20 + +KPX ecaron ydieresis -20 + +KPX ecircumflex comma -15 + +KPX ecircumflex period -15 + +KPX ecircumflex v -30 + +KPX ecircumflex w -20 + +KPX ecircumflex x -30 + +KPX ecircumflex y -20 + +KPX ecircumflex yacute -20 + +KPX ecircumflex ydieresis -20 + +KPX edieresis comma -15 + +KPX edieresis period -15 + +KPX edieresis v -30 + +KPX edieresis w -20 + +KPX edieresis x -30 + +KPX edieresis y -20 + +KPX edieresis yacute -20 + +KPX edieresis ydieresis -20 + +KPX edotaccent comma -15 + +KPX edotaccent period -15 + +KPX edotaccent v -30 + +KPX edotaccent w -20 + +KPX edotaccent x -30 + +KPX edotaccent y -20 + +KPX edotaccent yacute -20 + +KPX edotaccent ydieresis -20 + +KPX egrave comma -15 + +KPX egrave period -15 + +KPX egrave v -30 + +KPX egrave w -20 + +KPX egrave x -30 + +KPX egrave y -20 + +KPX egrave yacute -20 + +KPX egrave ydieresis -20 + +KPX emacron comma -15 + +KPX emacron period -15 + +KPX emacron v -30 + +KPX emacron w -20 + +KPX emacron x -30 + +KPX emacron y -20 + +KPX emacron yacute -20 + +KPX emacron ydieresis -20 + +KPX eogonek comma -15 + +KPX eogonek period -15 + +KPX eogonek v -30 + +KPX eogonek w -20 + +KPX eogonek x -30 + +KPX eogonek y -20 + +KPX eogonek yacute -20 + +KPX eogonek ydieresis -20 + +KPX f a -30 + +KPX f aacute -30 + +KPX f abreve -30 + +KPX f acircumflex -30 + +KPX f adieresis -30 + +KPX f agrave -30 + +KPX f amacron -30 + +KPX f aogonek -30 + +KPX f aring -30 + +KPX f atilde -30 + +KPX f comma -30 + +KPX f dotlessi -28 + +KPX f e -30 + +KPX f eacute -30 + +KPX f ecaron -30 + +KPX f ecircumflex -30 + +KPX f edieresis -30 + +KPX f edotaccent -30 + +KPX f egrave -30 + +KPX f emacron -30 + +KPX f eogonek -30 + +KPX f o -30 + +KPX f oacute -30 + +KPX f ocircumflex -30 + +KPX f odieresis -30 + +KPX f ograve -30 + +KPX f ohungarumlaut -30 + +KPX f omacron -30 + +KPX f oslash -30 + +KPX f otilde -30 + +KPX f period -30 + +KPX f quotedblright 60 + +KPX f quoteright 50 + +KPX g r -10 + +KPX g racute -10 + +KPX g rcaron -10 + +KPX g rcommaaccent -10 + +KPX gbreve r -10 + +KPX gbreve racute -10 + +KPX gbreve rcaron -10 + +KPX gbreve rcommaaccent -10 + +KPX gcommaaccent r -10 + +KPX gcommaaccent racute -10 + +KPX gcommaaccent rcaron -10 + +KPX gcommaaccent rcommaaccent -10 + +KPX h y -30 + +KPX h yacute -30 + +KPX h ydieresis -30 + +KPX k e -20 + +KPX k eacute -20 + +KPX k ecaron -20 + +KPX k ecircumflex -20 + +KPX k edieresis -20 + +KPX k edotaccent -20 + +KPX k egrave -20 + +KPX k emacron -20 + +KPX k eogonek -20 + +KPX k o -20 + +KPX k oacute -20 + +KPX k ocircumflex -20 + +KPX k odieresis -20 + +KPX k ograve -20 + +KPX k ohungarumlaut -20 + +KPX k omacron -20 + +KPX k oslash -20 + +KPX k otilde -20 + +KPX kcommaaccent e -20 + +KPX kcommaaccent eacute -20 + +KPX kcommaaccent ecaron -20 + +KPX kcommaaccent ecircumflex -20 + +KPX kcommaaccent edieresis -20 + +KPX kcommaaccent edotaccent -20 + +KPX kcommaaccent egrave -20 + +KPX kcommaaccent emacron -20 + +KPX kcommaaccent eogonek -20 + +KPX kcommaaccent o -20 + +KPX kcommaaccent oacute -20 + +KPX kcommaaccent ocircumflex -20 + +KPX kcommaaccent odieresis -20 + +KPX kcommaaccent ograve -20 + +KPX kcommaaccent ohungarumlaut -20 + +KPX kcommaaccent omacron -20 + +KPX kcommaaccent oslash -20 + +KPX kcommaaccent otilde -20 + +KPX m u -10 + +KPX m uacute -10 + +KPX m ucircumflex -10 + +KPX m udieresis -10 + +KPX m ugrave -10 + +KPX m uhungarumlaut -10 + +KPX m umacron -10 + +KPX m uogonek -10 + +KPX m uring -10 + +KPX m y -15 + +KPX m yacute -15 + +KPX m ydieresis -15 + +KPX n u -10 + +KPX n uacute -10 + +KPX n ucircumflex -10 + +KPX n udieresis -10 + +KPX n ugrave -10 + +KPX n uhungarumlaut -10 + +KPX n umacron -10 + +KPX n uogonek -10 + +KPX n uring -10 + +KPX n v -20 + +KPX n y -15 + +KPX n yacute -15 + +KPX n ydieresis -15 + +KPX nacute u -10 + +KPX nacute uacute -10 + +KPX nacute ucircumflex -10 + +KPX nacute udieresis -10 + +KPX nacute ugrave -10 + +KPX nacute uhungarumlaut -10 + +KPX nacute umacron -10 + +KPX nacute uogonek -10 + +KPX nacute uring -10 + +KPX nacute v -20 + +KPX nacute y -15 + +KPX nacute yacute -15 + +KPX nacute ydieresis -15 + +KPX ncaron u -10 + +KPX ncaron uacute -10 + +KPX ncaron ucircumflex -10 + +KPX ncaron udieresis -10 + +KPX ncaron ugrave -10 + +KPX ncaron uhungarumlaut -10 + +KPX ncaron umacron -10 + +KPX ncaron uogonek -10 + +KPX ncaron uring -10 + +KPX ncaron v -20 + +KPX ncaron y -15 + +KPX ncaron yacute -15 + +KPX ncaron ydieresis -15 + +KPX ncommaaccent u -10 + +KPX ncommaaccent uacute -10 + +KPX ncommaaccent ucircumflex -10 + +KPX ncommaaccent udieresis -10 + +KPX ncommaaccent ugrave -10 + +KPX ncommaaccent uhungarumlaut -10 + +KPX ncommaaccent umacron -10 + +KPX ncommaaccent uogonek -10 + +KPX ncommaaccent uring -10 + +KPX ncommaaccent v -20 + +KPX ncommaaccent y -15 + +KPX ncommaaccent yacute -15 + +KPX ncommaaccent ydieresis -15 + +KPX ntilde u -10 + +KPX ntilde uacute -10 + +KPX ntilde ucircumflex -10 + +KPX ntilde udieresis -10 + +KPX ntilde ugrave -10 + +KPX ntilde uhungarumlaut -10 + +KPX ntilde umacron -10 + +KPX ntilde uogonek -10 + +KPX ntilde uring -10 + +KPX ntilde v -20 + +KPX ntilde y -15 + +KPX ntilde yacute -15 + +KPX ntilde ydieresis -15 + +KPX o comma -40 + +KPX o period -40 + +KPX o v -15 + +KPX o w -15 + +KPX o x -30 + +KPX o y -30 + +KPX o yacute -30 + +KPX o ydieresis -30 + +KPX oacute comma -40 + +KPX oacute period -40 + +KPX oacute v -15 + +KPX oacute w -15 + +KPX oacute x -30 + +KPX oacute y -30 + +KPX oacute yacute -30 + +KPX oacute ydieresis -30 + +KPX ocircumflex comma -40 + +KPX ocircumflex period -40 + +KPX ocircumflex v -15 + +KPX ocircumflex w -15 + +KPX ocircumflex x -30 + +KPX ocircumflex y -30 + +KPX ocircumflex yacute -30 + +KPX ocircumflex ydieresis -30 + +KPX odieresis comma -40 + +KPX odieresis period -40 + +KPX odieresis v -15 + +KPX odieresis w -15 + +KPX odieresis x -30 + +KPX odieresis y -30 + +KPX odieresis yacute -30 + +KPX odieresis ydieresis -30 + +KPX ograve comma -40 + +KPX ograve period -40 + +KPX ograve v -15 + +KPX ograve w -15 + +KPX ograve x -30 + +KPX ograve y -30 + +KPX ograve yacute -30 + +KPX ograve ydieresis -30 + +KPX ohungarumlaut comma -40 + +KPX ohungarumlaut period -40 + +KPX ohungarumlaut v -15 + +KPX ohungarumlaut w -15 + +KPX ohungarumlaut x -30 + +KPX ohungarumlaut y -30 + +KPX ohungarumlaut yacute -30 + +KPX ohungarumlaut ydieresis -30 + +KPX omacron comma -40 + +KPX omacron period -40 + +KPX omacron v -15 + +KPX omacron w -15 + +KPX omacron x -30 + +KPX omacron y -30 + +KPX omacron yacute -30 + +KPX omacron ydieresis -30 + +KPX oslash a -55 + +KPX oslash aacute -55 + +KPX oslash abreve -55 + +KPX oslash acircumflex -55 + +KPX oslash adieresis -55 + +KPX oslash agrave -55 + +KPX oslash amacron -55 + +KPX oslash aogonek -55 + +KPX oslash aring -55 + +KPX oslash atilde -55 + +KPX oslash b -55 + +KPX oslash c -55 + +KPX oslash cacute -55 + +KPX oslash ccaron -55 + +KPX oslash ccedilla -55 + +KPX oslash comma -95 + +KPX oslash d -55 + +KPX oslash dcroat -55 + +KPX oslash e -55 + +KPX oslash eacute -55 + +KPX oslash ecaron -55 + +KPX oslash ecircumflex -55 + +KPX oslash edieresis -55 + +KPX oslash edotaccent -55 + +KPX oslash egrave -55 + +KPX oslash emacron -55 + +KPX oslash eogonek -55 + +KPX oslash f -55 + +KPX oslash g -55 + +KPX oslash gbreve -55 + +KPX oslash gcommaaccent -55 + +KPX oslash h -55 + +KPX oslash i -55 + +KPX oslash iacute -55 + +KPX oslash icircumflex -55 + +KPX oslash idieresis -55 + +KPX oslash igrave -55 + +KPX oslash imacron -55 + +KPX oslash iogonek -55 + +KPX oslash j -55 + +KPX oslash k -55 + +KPX oslash kcommaaccent -55 + +KPX oslash l -55 + +KPX oslash lacute -55 + +KPX oslash lcommaaccent -55 + +KPX oslash lslash -55 + +KPX oslash m -55 + +KPX oslash n -55 + +KPX oslash nacute -55 + +KPX oslash ncaron -55 + +KPX oslash ncommaaccent -55 + +KPX oslash ntilde -55 + +KPX oslash o -55 + +KPX oslash oacute -55 + +KPX oslash ocircumflex -55 + +KPX oslash odieresis -55 + +KPX oslash ograve -55 + +KPX oslash ohungarumlaut -55 + +KPX oslash omacron -55 + +KPX oslash oslash -55 + +KPX oslash otilde -55 + +KPX oslash p -55 + +KPX oslash period -95 + +KPX oslash q -55 + +KPX oslash r -55 + +KPX oslash racute -55 + +KPX oslash rcaron -55 + +KPX oslash rcommaaccent -55 + +KPX oslash s -55 + +KPX oslash sacute -55 + +KPX oslash scaron -55 + +KPX oslash scedilla -55 + +KPX oslash scommaaccent -55 + +KPX oslash t -55 + +KPX oslash tcommaaccent -55 + +KPX oslash u -55 + +KPX oslash uacute -55 + +KPX oslash ucircumflex -55 + +KPX oslash udieresis -55 + +KPX oslash ugrave -55 + +KPX oslash uhungarumlaut -55 + +KPX oslash umacron -55 + +KPX oslash uogonek -55 + +KPX oslash uring -55 + +KPX oslash v -70 + +KPX oslash w -70 + +KPX oslash x -85 + +KPX oslash y -70 + +KPX oslash yacute -70 + +KPX oslash ydieresis -70 + +KPX oslash z -55 + +KPX oslash zacute -55 + +KPX oslash zcaron -55 + +KPX oslash zdotaccent -55 + +KPX otilde comma -40 + +KPX otilde period -40 + +KPX otilde v -15 + +KPX otilde w -15 + +KPX otilde x -30 + +KPX otilde y -30 + +KPX otilde yacute -30 + +KPX otilde ydieresis -30 + +KPX p comma -35 + +KPX p period -35 + +KPX p y -30 + +KPX p yacute -30 + +KPX p ydieresis -30 + +KPX period quotedblright -100 + +KPX period quoteright -100 + +KPX period space -60 + +KPX quotedblright space -40 + +KPX quoteleft quoteleft -57 + +KPX quoteright d -50 + +KPX quoteright dcroat -50 + +KPX quoteright quoteright -57 + +KPX quoteright r -50 + +KPX quoteright racute -50 + +KPX quoteright rcaron -50 + +KPX quoteright rcommaaccent -50 + +KPX quoteright s -50 + +KPX quoteright sacute -50 + +KPX quoteright scaron -50 + +KPX quoteright scedilla -50 + +KPX quoteright scommaaccent -50 + +KPX quoteright space -70 + +KPX r a -10 + +KPX r aacute -10 + +KPX r abreve -10 + +KPX r acircumflex -10 + +KPX r adieresis -10 + +KPX r agrave -10 + +KPX r amacron -10 + +KPX r aogonek -10 + +KPX r aring -10 + +KPX r atilde -10 + +KPX r colon 30 + +KPX r comma -50 + +KPX r i 15 + +KPX r iacute 15 + +KPX r icircumflex 15 + +KPX r idieresis 15 + +KPX r igrave 15 + +KPX r imacron 15 + +KPX r iogonek 15 + +KPX r k 15 + +KPX r kcommaaccent 15 + +KPX r l 15 + +KPX r lacute 15 + +KPX r lcommaaccent 15 + +KPX r lslash 15 + +KPX r m 25 + +KPX r n 25 + +KPX r nacute 25 + +KPX r ncaron 25 + +KPX r ncommaaccent 25 + +KPX r ntilde 25 + +KPX r p 30 + +KPX r period -50 + +KPX r semicolon 30 + +KPX r t 40 + +KPX r tcommaaccent 40 + +KPX r u 15 + +KPX r uacute 15 + +KPX r ucircumflex 15 + +KPX r udieresis 15 + +KPX r ugrave 15 + +KPX r uhungarumlaut 15 + +KPX r umacron 15 + +KPX r uogonek 15 + +KPX r uring 15 + +KPX r v 30 + +KPX r y 30 + +KPX r yacute 30 + +KPX r ydieresis 30 + +KPX racute a -10 + +KPX racute aacute -10 + +KPX racute abreve -10 + +KPX racute acircumflex -10 + +KPX racute adieresis -10 + +KPX racute agrave -10 + +KPX racute amacron -10 + +KPX racute aogonek -10 + +KPX racute aring -10 + +KPX racute atilde -10 + +KPX racute colon 30 + +KPX racute comma -50 + +KPX racute i 15 + +KPX racute iacute 15 + +KPX racute icircumflex 15 + +KPX racute idieresis 15 + +KPX racute igrave 15 + +KPX racute imacron 15 + +KPX racute iogonek 15 + +KPX racute k 15 + +KPX racute kcommaaccent 15 + +KPX racute l 15 + +KPX racute lacute 15 + +KPX racute lcommaaccent 15 + +KPX racute lslash 15 + +KPX racute m 25 + +KPX racute n 25 + +KPX racute nacute 25 + +KPX racute ncaron 25 + +KPX racute ncommaaccent 25 + +KPX racute ntilde 25 + +KPX racute p 30 + +KPX racute period -50 + +KPX racute semicolon 30 + +KPX racute t 40 + +KPX racute tcommaaccent 40 + +KPX racute u 15 + +KPX racute uacute 15 + +KPX racute ucircumflex 15 + +KPX racute udieresis 15 + +KPX racute ugrave 15 + +KPX racute uhungarumlaut 15 + +KPX racute umacron 15 + +KPX racute uogonek 15 + +KPX racute uring 15 + +KPX racute v 30 + +KPX racute y 30 + +KPX racute yacute 30 + +KPX racute ydieresis 30 + +KPX rcaron a -10 + +KPX rcaron aacute -10 + +KPX rcaron abreve -10 + +KPX rcaron acircumflex -10 + +KPX rcaron adieresis -10 + +KPX rcaron agrave -10 + +KPX rcaron amacron -10 + +KPX rcaron aogonek -10 + +KPX rcaron aring -10 + +KPX rcaron atilde -10 + +KPX rcaron colon 30 + +KPX rcaron comma -50 + +KPX rcaron i 15 + +KPX rcaron iacute 15 + +KPX rcaron icircumflex 15 + +KPX rcaron idieresis 15 + +KPX rcaron igrave 15 + +KPX rcaron imacron 15 + +KPX rcaron iogonek 15 + +KPX rcaron k 15 + +KPX rcaron kcommaaccent 15 + +KPX rcaron l 15 + +KPX rcaron lacute 15 + +KPX rcaron lcommaaccent 15 + +KPX rcaron lslash 15 + +KPX rcaron m 25 + +KPX rcaron n 25 + +KPX rcaron nacute 25 + +KPX rcaron ncaron 25 + +KPX rcaron ncommaaccent 25 + +KPX rcaron ntilde 25 + +KPX rcaron p 30 + +KPX rcaron period -50 + +KPX rcaron semicolon 30 + +KPX rcaron t 40 + +KPX rcaron tcommaaccent 40 + +KPX rcaron u 15 + +KPX rcaron uacute 15 + +KPX rcaron ucircumflex 15 + +KPX rcaron udieresis 15 + +KPX rcaron ugrave 15 + +KPX rcaron uhungarumlaut 15 + +KPX rcaron umacron 15 + +KPX rcaron uogonek 15 + +KPX rcaron uring 15 + +KPX rcaron v 30 + +KPX rcaron y 30 + +KPX rcaron yacute 30 + +KPX rcaron ydieresis 30 + +KPX rcommaaccent a -10 + +KPX rcommaaccent aacute -10 + +KPX rcommaaccent abreve -10 + +KPX rcommaaccent acircumflex -10 + +KPX rcommaaccent adieresis -10 + +KPX rcommaaccent agrave -10 + +KPX rcommaaccent amacron -10 + +KPX rcommaaccent aogonek -10 + +KPX rcommaaccent aring -10 + +KPX rcommaaccent atilde -10 + +KPX rcommaaccent colon 30 + +KPX rcommaaccent comma -50 + +KPX rcommaaccent i 15 + +KPX rcommaaccent iacute 15 + +KPX rcommaaccent icircumflex 15 + +KPX rcommaaccent idieresis 15 + +KPX rcommaaccent igrave 15 + +KPX rcommaaccent imacron 15 + +KPX rcommaaccent iogonek 15 + +KPX rcommaaccent k 15 + +KPX rcommaaccent kcommaaccent 15 + +KPX rcommaaccent l 15 + +KPX rcommaaccent lacute 15 + +KPX rcommaaccent lcommaaccent 15 + +KPX rcommaaccent lslash 15 + +KPX rcommaaccent m 25 + +KPX rcommaaccent n 25 + +KPX rcommaaccent nacute 25 + +KPX rcommaaccent ncaron 25 + +KPX rcommaaccent ncommaaccent 25 + +KPX rcommaaccent ntilde 25 + +KPX rcommaaccent p 30 + +KPX rcommaaccent period -50 + +KPX rcommaaccent semicolon 30 + +KPX rcommaaccent t 40 + +KPX rcommaaccent tcommaaccent 40 + +KPX rcommaaccent u 15 + +KPX rcommaaccent uacute 15 + +KPX rcommaaccent ucircumflex 15 + +KPX rcommaaccent udieresis 15 + +KPX rcommaaccent ugrave 15 + +KPX rcommaaccent uhungarumlaut 15 + +KPX rcommaaccent umacron 15 + +KPX rcommaaccent uogonek 15 + +KPX rcommaaccent uring 15 + +KPX rcommaaccent v 30 + +KPX rcommaaccent y 30 + +KPX rcommaaccent yacute 30 + +KPX rcommaaccent ydieresis 30 + +KPX s comma -15 + +KPX s period -15 + +KPX s w -30 + +KPX sacute comma -15 + +KPX sacute period -15 + +KPX sacute w -30 + +KPX scaron comma -15 + +KPX scaron period -15 + +KPX scaron w -30 + +KPX scedilla comma -15 + +KPX scedilla period -15 + +KPX scedilla w -30 + +KPX scommaaccent comma -15 + +KPX scommaaccent period -15 + +KPX scommaaccent w -30 + +KPX semicolon space -50 + +KPX space T -50 + +KPX space Tcaron -50 + +KPX space Tcommaaccent -50 + +KPX space V -50 + +KPX space W -40 + +KPX space Y -90 + +KPX space Yacute -90 + +KPX space Ydieresis -90 + +KPX space quotedblleft -30 + +KPX space quoteleft -60 + +KPX v a -25 + +KPX v aacute -25 + +KPX v abreve -25 + +KPX v acircumflex -25 + +KPX v adieresis -25 + +KPX v agrave -25 + +KPX v amacron -25 + +KPX v aogonek -25 + +KPX v aring -25 + +KPX v atilde -25 + +KPX v comma -80 + +KPX v e -25 + +KPX v eacute -25 + +KPX v ecaron -25 + +KPX v ecircumflex -25 + +KPX v edieresis -25 + +KPX v edotaccent -25 + +KPX v egrave -25 + +KPX v emacron -25 + +KPX v eogonek -25 + +KPX v o -25 + +KPX v oacute -25 + +KPX v ocircumflex -25 + +KPX v odieresis -25 + +KPX v ograve -25 + +KPX v ohungarumlaut -25 + +KPX v omacron -25 + +KPX v oslash -25 + +KPX v otilde -25 + +KPX v period -80 + +KPX w a -15 + +KPX w aacute -15 + +KPX w abreve -15 + +KPX w acircumflex -15 + +KPX w adieresis -15 + +KPX w agrave -15 + +KPX w amacron -15 + +KPX w aogonek -15 + +KPX w aring -15 + +KPX w atilde -15 + +KPX w comma -60 + +KPX w e -10 + +KPX w eacute -10 + +KPX w ecaron -10 + +KPX w ecircumflex -10 + +KPX w edieresis -10 + +KPX w edotaccent -10 + +KPX w egrave -10 + +KPX w emacron -10 + +KPX w eogonek -10 + +KPX w o -10 + +KPX w oacute -10 + +KPX w ocircumflex -10 + +KPX w odieresis -10 + +KPX w ograve -10 + +KPX w ohungarumlaut -10 + +KPX w omacron -10 + +KPX w oslash -10 + +KPX w otilde -10 + +KPX w period -60 + +KPX x e -30 + +KPX x eacute -30 + +KPX x ecaron -30 + +KPX x ecircumflex -30 + +KPX x edieresis -30 + +KPX x edotaccent -30 + +KPX x egrave -30 + +KPX x emacron -30 + +KPX x eogonek -30 + +KPX y a -20 + +KPX y aacute -20 + +KPX y abreve -20 + +KPX y acircumflex -20 + +KPX y adieresis -20 + +KPX y agrave -20 + +KPX y amacron -20 + +KPX y aogonek -20 + +KPX y aring -20 + +KPX y atilde -20 + +KPX y comma -100 + +KPX y e -20 + +KPX y eacute -20 + +KPX y ecaron -20 + +KPX y ecircumflex -20 + +KPX y edieresis -20 + +KPX y edotaccent -20 + +KPX y egrave -20 + +KPX y emacron -20 + +KPX y eogonek -20 + +KPX y o -20 + +KPX y oacute -20 + +KPX y ocircumflex -20 + +KPX y odieresis -20 + +KPX y ograve -20 + +KPX y ohungarumlaut -20 + +KPX y omacron -20 + +KPX y oslash -20 + +KPX y otilde -20 + +KPX y period -100 + +KPX yacute a -20 + +KPX yacute aacute -20 + +KPX yacute abreve -20 + +KPX yacute acircumflex -20 + +KPX yacute adieresis -20 + +KPX yacute agrave -20 + +KPX yacute amacron -20 + +KPX yacute aogonek -20 + +KPX yacute aring -20 + +KPX yacute atilde -20 + +KPX yacute comma -100 + +KPX yacute e -20 + +KPX yacute eacute -20 + +KPX yacute ecaron -20 + +KPX yacute ecircumflex -20 + +KPX yacute edieresis -20 + +KPX yacute edotaccent -20 + +KPX yacute egrave -20 + +KPX yacute emacron -20 + +KPX yacute eogonek -20 + +KPX yacute o -20 + +KPX yacute oacute -20 + +KPX yacute ocircumflex -20 + +KPX yacute odieresis -20 + +KPX yacute ograve -20 + +KPX yacute ohungarumlaut -20 + +KPX yacute omacron -20 + +KPX yacute oslash -20 + +KPX yacute otilde -20 + +KPX yacute period -100 + +KPX ydieresis a -20 + +KPX ydieresis aacute -20 + +KPX ydieresis abreve -20 + +KPX ydieresis acircumflex -20 + +KPX ydieresis adieresis -20 + +KPX ydieresis agrave -20 + +KPX ydieresis amacron -20 + +KPX ydieresis aogonek -20 + +KPX ydieresis aring -20 + +KPX ydieresis atilde -20 + +KPX ydieresis comma -100 + +KPX ydieresis e -20 + +KPX ydieresis eacute -20 + +KPX ydieresis ecaron -20 + +KPX ydieresis ecircumflex -20 + +KPX ydieresis edieresis -20 + +KPX ydieresis edotaccent -20 + +KPX ydieresis egrave -20 + +KPX ydieresis emacron -20 + +KPX ydieresis eogonek -20 + +KPX ydieresis o -20 + +KPX ydieresis oacute -20 + +KPX ydieresis ocircumflex -20 + +KPX ydieresis odieresis -20 + +KPX ydieresis ograve -20 + +KPX ydieresis ohungarumlaut -20 + +KPX ydieresis omacron -20 + +KPX ydieresis oslash -20 + +KPX ydieresis otilde -20 + +KPX ydieresis period -100 + +KPX z e -15 + +KPX z eacute -15 + +KPX z ecaron -15 + +KPX z ecircumflex -15 + +KPX z edieresis -15 + +KPX z edotaccent -15 + +KPX z egrave -15 + +KPX z emacron -15 + +KPX z eogonek -15 + +KPX z o -15 + +KPX z oacute -15 + +KPX z ocircumflex -15 + +KPX z odieresis -15 + +KPX z ograve -15 + +KPX z ohungarumlaut -15 + +KPX z omacron -15 + +KPX z oslash -15 + +KPX z otilde -15 + +KPX zacute e -15 + +KPX zacute eacute -15 + +KPX zacute ecaron -15 + +KPX zacute ecircumflex -15 + +KPX zacute edieresis -15 + +KPX zacute edotaccent -15 + +KPX zacute egrave -15 + +KPX zacute emacron -15 + +KPX zacute eogonek -15 + +KPX zacute o -15 + +KPX zacute oacute -15 + +KPX zacute ocircumflex -15 + +KPX zacute odieresis -15 + +KPX zacute ograve -15 + +KPX zacute ohungarumlaut -15 + +KPX zacute omacron -15 + +KPX zacute oslash -15 + +KPX zacute otilde -15 + +KPX zcaron e -15 + +KPX zcaron eacute -15 + +KPX zcaron ecaron -15 + +KPX zcaron ecircumflex -15 + +KPX zcaron edieresis -15 + +KPX zcaron edotaccent -15 + +KPX zcaron egrave -15 + +KPX zcaron emacron -15 + +KPX zcaron eogonek -15 + +KPX zcaron o -15 + +KPX zcaron oacute -15 + +KPX zcaron ocircumflex -15 + +KPX zcaron odieresis -15 + +KPX zcaron ograve -15 + +KPX zcaron ohungarumlaut -15 + +KPX zcaron omacron -15 + +KPX zcaron oslash -15 + +KPX zcaron otilde -15 + +KPX zdotaccent e -15 + +KPX zdotaccent eacute -15 + +KPX zdotaccent ecaron -15 + +KPX zdotaccent ecircumflex -15 + +KPX zdotaccent edieresis -15 + +KPX zdotaccent edotaccent -15 + +KPX zdotaccent egrave -15 + +KPX zdotaccent emacron -15 + +KPX zdotaccent eogonek -15 + +KPX zdotaccent o -15 + +KPX zdotaccent oacute -15 + +KPX zdotaccent ocircumflex -15 + +KPX zdotaccent odieresis -15 + +KPX zdotaccent ograve -15 + +KPX zdotaccent ohungarumlaut -15 + +KPX zdotaccent omacron -15 + +KPX zdotaccent oslash -15 + +KPX zdotaccent otilde -15 + +EndKernPairs + +EndKernData + +EndFontMetrics + diff --git a/src/Broadside/Fonts/Data/Afm/MustRead.html b/src/Broadside/Fonts/Data/Afm/MustRead.html new file mode 100644 index 00000000..6dada97b --- /dev/null +++ b/src/Broadside/Fonts/Data/Afm/MustRead.html @@ -0,0 +1,19 @@ + + + + + + Core 14 AFM Files - ReadMe + + + + or + + + + + +
This file and the 14 PostScript(R) AFM files it accompanies may be used, copied, and distributed for any purpose and without charge, with or without modification, provided that all copyright notices are retained; that the AFM files are not distributed without this file; that all modifications to this file or any of the AFM files are prominently noted in the modified file(s); and that this paragraph is not modified. Adobe Systems has no responsibility or obligation to support the use of the AFM files. Col
+ + + diff --git a/src/Broadside/Fonts/Data/Afm/Symbol.afm b/src/Broadside/Fonts/Data/Afm/Symbol.afm new file mode 100644 index 00000000..dd8bf918 --- /dev/null +++ b/src/Broadside/Fonts/Data/Afm/Symbol.afm @@ -0,0 +1,426 @@ +StartFontMetrics 4.1 + +Comment Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All rights reserved. + +Comment Creation Date: Thu May 1 15:12:25 1997 + +Comment UniqueID 43064 + +Comment VMusage 30820 39997 + +FontName Symbol + +FullName Symbol + +FamilyName Symbol + +Weight Medium + +ItalicAngle 0 + +IsFixedPitch false + +CharacterSet Special + +FontBBox -180 -293 1090 1010 + +UnderlinePosition -100 + +UnderlineThickness 50 + +Version 001.008 + +Notice Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All rights reserved. + +EncodingScheme FontSpecific + +StdHW 92 + +StdVW 85 + +StartCharMetrics 190 + +C 32 ; WX 250 ; N space ; B 0 0 0 0 ; + +C 33 ; WX 333 ; N exclam ; B 128 -17 240 672 ; + +C 34 ; WX 713 ; N universal ; B 31 0 681 705 ; + +C 35 ; WX 500 ; N numbersign ; B 20 -16 481 673 ; + +C 36 ; WX 549 ; N existential ; B 25 0 478 707 ; + +C 37 ; WX 833 ; N percent ; B 63 -36 771 655 ; + +C 38 ; WX 778 ; N ampersand ; B 41 -18 750 661 ; + +C 39 ; WX 439 ; N suchthat ; B 48 -17 414 500 ; + +C 40 ; WX 333 ; N parenleft ; B 53 -191 300 673 ; + +C 41 ; WX 333 ; N parenright ; B 30 -191 277 673 ; + +C 42 ; WX 500 ; N asteriskmath ; B 65 134 427 551 ; + +C 43 ; WX 549 ; N plus ; B 10 0 539 533 ; + +C 44 ; WX 250 ; N comma ; B 56 -152 194 104 ; + +C 45 ; WX 549 ; N minus ; B 11 233 535 288 ; + +C 46 ; WX 250 ; N period ; B 69 -17 181 95 ; + +C 47 ; WX 278 ; N slash ; B 0 -18 254 646 ; + +C 48 ; WX 500 ; N zero ; B 24 -14 476 685 ; + +C 49 ; WX 500 ; N one ; B 117 0 390 673 ; + +C 50 ; WX 500 ; N two ; B 25 0 475 685 ; + +C 51 ; WX 500 ; N three ; B 43 -14 435 685 ; + +C 52 ; WX 500 ; N four ; B 15 0 469 685 ; + +C 53 ; WX 500 ; N five ; B 32 -14 445 690 ; + +C 54 ; WX 500 ; N six ; B 34 -14 468 685 ; + +C 55 ; WX 500 ; N seven ; B 24 -16 448 673 ; + +C 56 ; WX 500 ; N eight ; B 56 -14 445 685 ; + +C 57 ; WX 500 ; N nine ; B 30 -18 459 685 ; + +C 58 ; WX 278 ; N colon ; B 81 -17 193 460 ; + +C 59 ; WX 278 ; N semicolon ; B 83 -152 221 460 ; + +C 60 ; WX 549 ; N less ; B 26 0 523 522 ; + +C 61 ; WX 549 ; N equal ; B 11 141 537 390 ; + +C 62 ; WX 549 ; N greater ; B 26 0 523 522 ; + +C 63 ; WX 444 ; N question ; B 70 -17 412 686 ; + +C 64 ; WX 549 ; N congruent ; B 11 0 537 475 ; + +C 65 ; WX 722 ; N Alpha ; B 4 0 684 673 ; + +C 66 ; WX 667 ; N Beta ; B 29 0 592 673 ; + +C 67 ; WX 722 ; N Chi ; B -9 0 704 673 ; + +C 68 ; WX 612 ; N Delta ; B 6 0 608 688 ; + +C 69 ; WX 611 ; N Epsilon ; B 32 0 617 673 ; + +C 70 ; WX 763 ; N Phi ; B 26 0 741 673 ; + +C 71 ; WX 603 ; N Gamma ; B 24 0 609 673 ; + +C 72 ; WX 722 ; N Eta ; B 39 0 729 673 ; + +C 73 ; WX 333 ; N Iota ; B 32 0 316 673 ; + +C 74 ; WX 631 ; N theta1 ; B 18 -18 623 689 ; + +C 75 ; WX 722 ; N Kappa ; B 35 0 722 673 ; + +C 76 ; WX 686 ; N Lambda ; B 6 0 680 688 ; + +C 77 ; WX 889 ; N Mu ; B 28 0 887 673 ; + +C 78 ; WX 722 ; N Nu ; B 29 -8 720 673 ; + +C 79 ; WX 722 ; N Omicron ; B 41 -17 715 685 ; + +C 80 ; WX 768 ; N Pi ; B 25 0 745 673 ; + +C 81 ; WX 741 ; N Theta ; B 41 -17 715 685 ; + +C 82 ; WX 556 ; N Rho ; B 28 0 563 673 ; + +C 83 ; WX 592 ; N Sigma ; B 5 0 589 673 ; + +C 84 ; WX 611 ; N Tau ; B 33 0 607 673 ; + +C 85 ; WX 690 ; N Upsilon ; B -8 0 694 673 ; + +C 86 ; WX 439 ; N sigma1 ; B 40 -233 436 500 ; + +C 87 ; WX 768 ; N Omega ; B 34 0 736 688 ; + +C 88 ; WX 645 ; N Xi ; B 40 0 599 673 ; + +C 89 ; WX 795 ; N Psi ; B 15 0 781 684 ; + +C 90 ; WX 611 ; N Zeta ; B 44 0 636 673 ; + +C 91 ; WX 333 ; N bracketleft ; B 86 -155 299 674 ; + +C 92 ; WX 863 ; N therefore ; B 163 0 701 487 ; + +C 93 ; WX 333 ; N bracketright ; B 33 -155 246 674 ; + +C 94 ; WX 658 ; N perpendicular ; B 15 0 652 674 ; + +C 95 ; WX 500 ; N underscore ; B -2 -125 502 -75 ; + +C 96 ; WX 500 ; N radicalex ; B 480 881 1090 917 ; + +C 97 ; WX 631 ; N alpha ; B 41 -18 622 500 ; + +C 98 ; WX 549 ; N beta ; B 61 -223 515 741 ; + +C 99 ; WX 549 ; N chi ; B 12 -231 522 499 ; + +C 100 ; WX 494 ; N delta ; B 40 -19 481 740 ; + +C 101 ; WX 439 ; N epsilon ; B 22 -19 427 502 ; + +C 102 ; WX 521 ; N phi ; B 28 -224 492 673 ; + +C 103 ; WX 411 ; N gamma ; B 5 -225 484 499 ; + +C 104 ; WX 603 ; N eta ; B 0 -202 527 514 ; + +C 105 ; WX 329 ; N iota ; B 0 -17 301 503 ; + +C 106 ; WX 603 ; N phi1 ; B 36 -224 587 499 ; + +C 107 ; WX 549 ; N kappa ; B 33 0 558 501 ; + +C 108 ; WX 549 ; N lambda ; B 24 -17 548 739 ; + +C 109 ; WX 576 ; N mu ; B 33 -223 567 500 ; + +C 110 ; WX 521 ; N nu ; B -9 -16 475 507 ; + +C 111 ; WX 549 ; N omicron ; B 35 -19 501 499 ; + +C 112 ; WX 549 ; N pi ; B 10 -19 530 487 ; + +C 113 ; WX 521 ; N theta ; B 43 -17 485 690 ; + +C 114 ; WX 549 ; N rho ; B 50 -230 490 499 ; + +C 115 ; WX 603 ; N sigma ; B 30 -21 588 500 ; + +C 116 ; WX 439 ; N tau ; B 10 -19 418 500 ; + +C 117 ; WX 576 ; N upsilon ; B 7 -18 535 507 ; + +C 118 ; WX 713 ; N omega1 ; B 12 -18 671 583 ; + +C 119 ; WX 686 ; N omega ; B 42 -17 684 500 ; + +C 120 ; WX 493 ; N xi ; B 27 -224 469 766 ; + +C 121 ; WX 686 ; N psi ; B 12 -228 701 500 ; + +C 122 ; WX 494 ; N zeta ; B 60 -225 467 756 ; + +C 123 ; WX 480 ; N braceleft ; B 58 -183 397 673 ; + +C 124 ; WX 200 ; N bar ; B 65 -293 135 707 ; + +C 125 ; WX 480 ; N braceright ; B 79 -183 418 673 ; + +C 126 ; WX 549 ; N similar ; B 17 203 529 307 ; + +C 160 ; WX 750 ; N Euro ; B 20 -12 714 685 ; + +C 161 ; WX 620 ; N Upsilon1 ; B -2 0 610 685 ; + +C 162 ; WX 247 ; N minute ; B 27 459 228 735 ; + +C 163 ; WX 549 ; N lessequal ; B 29 0 526 639 ; + +C 164 ; WX 167 ; N fraction ; B -180 -12 340 677 ; + +C 165 ; WX 713 ; N infinity ; B 26 124 688 404 ; + +C 166 ; WX 500 ; N florin ; B 2 -193 494 686 ; + +C 167 ; WX 753 ; N club ; B 86 -26 660 533 ; + +C 168 ; WX 753 ; N diamond ; B 142 -36 600 550 ; + +C 169 ; WX 753 ; N heart ; B 117 -33 631 532 ; + +C 170 ; WX 753 ; N spade ; B 113 -36 629 548 ; + +C 171 ; WX 1042 ; N arrowboth ; B 24 -15 1024 511 ; + +C 172 ; WX 987 ; N arrowleft ; B 32 -15 942 511 ; + +C 173 ; WX 603 ; N arrowup ; B 45 0 571 910 ; + +C 174 ; WX 987 ; N arrowright ; B 49 -15 959 511 ; + +C 175 ; WX 603 ; N arrowdown ; B 45 -22 571 888 ; + +C 176 ; WX 400 ; N degree ; B 50 385 350 685 ; + +C 177 ; WX 549 ; N plusminus ; B 10 0 539 645 ; + +C 178 ; WX 411 ; N second ; B 20 459 413 737 ; + +C 179 ; WX 549 ; N greaterequal ; B 29 0 526 639 ; + +C 180 ; WX 549 ; N multiply ; B 17 8 533 524 ; + +C 181 ; WX 713 ; N proportional ; B 27 123 639 404 ; + +C 182 ; WX 494 ; N partialdiff ; B 26 -20 462 746 ; + +C 183 ; WX 460 ; N bullet ; B 50 113 410 473 ; + +C 184 ; WX 549 ; N divide ; B 10 71 536 456 ; + +C 185 ; WX 549 ; N notequal ; B 15 -25 540 549 ; + +C 186 ; WX 549 ; N equivalence ; B 14 82 538 443 ; + +C 187 ; WX 549 ; N approxequal ; B 14 135 527 394 ; + +C 188 ; WX 1000 ; N ellipsis ; B 111 -17 889 95 ; + +C 189 ; WX 603 ; N arrowvertex ; B 280 -120 336 1010 ; + +C 190 ; WX 1000 ; N arrowhorizex ; B -60 220 1050 276 ; + +C 191 ; WX 658 ; N carriagereturn ; B 15 -16 602 629 ; + +C 192 ; WX 823 ; N aleph ; B 175 -18 661 658 ; + +C 193 ; WX 686 ; N Ifraktur ; B 10 -53 578 740 ; + +C 194 ; WX 795 ; N Rfraktur ; B 26 -15 759 734 ; + +C 195 ; WX 987 ; N weierstrass ; B 159 -211 870 573 ; + +C 196 ; WX 768 ; N circlemultiply ; B 43 -17 733 673 ; + +C 197 ; WX 768 ; N circleplus ; B 43 -15 733 675 ; + +C 198 ; WX 823 ; N emptyset ; B 39 -24 781 719 ; + +C 199 ; WX 768 ; N intersection ; B 40 0 732 509 ; + +C 200 ; WX 768 ; N union ; B 40 -17 732 492 ; + +C 201 ; WX 713 ; N propersuperset ; B 20 0 673 470 ; + +C 202 ; WX 713 ; N reflexsuperset ; B 20 -125 673 470 ; + +C 203 ; WX 713 ; N notsubset ; B 36 -70 690 540 ; + +C 204 ; WX 713 ; N propersubset ; B 37 0 690 470 ; + +C 205 ; WX 713 ; N reflexsubset ; B 37 -125 690 470 ; + +C 206 ; WX 713 ; N element ; B 45 0 505 468 ; + +C 207 ; WX 713 ; N notelement ; B 45 -58 505 555 ; + +C 208 ; WX 768 ; N angle ; B 26 0 738 673 ; + +C 209 ; WX 713 ; N gradient ; B 36 -19 681 718 ; + +C 210 ; WX 790 ; N registerserif ; B 50 -17 740 673 ; + +C 211 ; WX 790 ; N copyrightserif ; B 51 -15 741 675 ; + +C 212 ; WX 890 ; N trademarkserif ; B 18 293 855 673 ; + +C 213 ; WX 823 ; N product ; B 25 -101 803 751 ; + +C 214 ; WX 549 ; N radical ; B 10 -38 515 917 ; + +C 215 ; WX 250 ; N dotmath ; B 69 210 169 310 ; + +C 216 ; WX 713 ; N logicalnot ; B 15 0 680 288 ; + +C 217 ; WX 603 ; N logicaland ; B 23 0 583 454 ; + +C 218 ; WX 603 ; N logicalor ; B 30 0 578 477 ; + +C 219 ; WX 1042 ; N arrowdblboth ; B 27 -20 1023 510 ; + +C 220 ; WX 987 ; N arrowdblleft ; B 30 -15 939 513 ; + +C 221 ; WX 603 ; N arrowdblup ; B 39 2 567 911 ; + +C 222 ; WX 987 ; N arrowdblright ; B 45 -20 954 508 ; + +C 223 ; WX 603 ; N arrowdbldown ; B 44 -19 572 890 ; + +C 224 ; WX 494 ; N lozenge ; B 18 0 466 745 ; + +C 225 ; WX 329 ; N angleleft ; B 25 -198 306 746 ; + +C 226 ; WX 790 ; N registersans ; B 50 -20 740 670 ; + +C 227 ; WX 790 ; N copyrightsans ; B 49 -15 739 675 ; + +C 228 ; WX 786 ; N trademarksans ; B 5 293 725 673 ; + +C 229 ; WX 713 ; N summation ; B 14 -108 695 752 ; + +C 230 ; WX 384 ; N parenlefttp ; B 24 -293 436 926 ; + +C 231 ; WX 384 ; N parenleftex ; B 24 -85 108 925 ; + +C 232 ; WX 384 ; N parenleftbt ; B 24 -293 436 926 ; + +C 233 ; WX 384 ; N bracketlefttp ; B 0 -80 349 926 ; + +C 234 ; WX 384 ; N bracketleftex ; B 0 -79 77 925 ; + +C 235 ; WX 384 ; N bracketleftbt ; B 0 -80 349 926 ; + +C 236 ; WX 494 ; N bracelefttp ; B 209 -85 445 925 ; + +C 237 ; WX 494 ; N braceleftmid ; B 20 -85 284 935 ; + +C 238 ; WX 494 ; N braceleftbt ; B 209 -75 445 935 ; + +C 239 ; WX 494 ; N braceex ; B 209 -85 284 935 ; + +C 241 ; WX 329 ; N angleright ; B 21 -198 302 746 ; + +C 242 ; WX 274 ; N integral ; B 2 -107 291 916 ; + +C 243 ; WX 686 ; N integraltp ; B 308 -88 675 920 ; + +C 244 ; WX 686 ; N integralex ; B 308 -88 378 975 ; + +C 245 ; WX 686 ; N integralbt ; B 11 -87 378 921 ; + +C 246 ; WX 384 ; N parenrighttp ; B 54 -293 466 926 ; + +C 247 ; WX 384 ; N parenrightex ; B 382 -85 466 925 ; + +C 248 ; WX 384 ; N parenrightbt ; B 54 -293 466 926 ; + +C 249 ; WX 384 ; N bracketrighttp ; B 22 -80 371 926 ; + +C 250 ; WX 384 ; N bracketrightex ; B 294 -79 371 925 ; + +C 251 ; WX 384 ; N bracketrightbt ; B 22 -80 371 926 ; + +C 252 ; WX 494 ; N bracerighttp ; B 48 -85 284 925 ; + +C 253 ; WX 494 ; N bracerightmid ; B 209 -85 473 935 ; + +C 254 ; WX 494 ; N bracerightbt ; B 48 -75 284 935 ; + +C -1 ; WX 790 ; N apple ; B 56 -3 733 808 ; + +EndCharMetrics + +EndFontMetrics + diff --git a/src/Broadside/Fonts/Data/Afm/Times-Bold.afm b/src/Broadside/Fonts/Data/Afm/Times-Bold.afm new file mode 100644 index 00000000..eb1919b3 --- /dev/null +++ b/src/Broadside/Fonts/Data/Afm/Times-Bold.afm @@ -0,0 +1,5176 @@ +StartFontMetrics 4.1 + +Comment Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. + +Comment Creation Date: Thu May 1 12:52:56 1997 + +Comment UniqueID 43065 + +Comment VMusage 41636 52661 + +FontName Times-Bold + +FullName Times Bold + +FamilyName Times + +Weight Bold + +ItalicAngle 0 + +IsFixedPitch false + +CharacterSet ExtendedRoman + +FontBBox -168 -218 1000 935 + +UnderlinePosition -100 + +UnderlineThickness 50 + +Version 002.000 + +Notice Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.Times is a trademark of Linotype-Hell AG and/or its subsidiaries. + +EncodingScheme AdobeStandardEncoding + +CapHeight 676 + +XHeight 461 + +Ascender 683 + +Descender -217 + +StdHW 44 + +StdVW 139 + +StartCharMetrics 315 + +C 32 ; WX 250 ; N space ; B 0 0 0 0 ; + +C 33 ; WX 333 ; N exclam ; B 81 -13 251 691 ; + +C 34 ; WX 555 ; N quotedbl ; B 83 404 472 691 ; + +C 35 ; WX 500 ; N numbersign ; B 4 0 496 700 ; + +C 36 ; WX 500 ; N dollar ; B 29 -99 472 750 ; + +C 37 ; WX 1000 ; N percent ; B 124 -14 877 692 ; + +C 38 ; WX 833 ; N ampersand ; B 62 -16 787 691 ; + +C 39 ; WX 333 ; N quoteright ; B 79 356 263 691 ; + +C 40 ; WX 333 ; N parenleft ; B 46 -168 306 694 ; + +C 41 ; WX 333 ; N parenright ; B 27 -168 287 694 ; + +C 42 ; WX 500 ; N asterisk ; B 56 255 447 691 ; + +C 43 ; WX 570 ; N plus ; B 33 0 537 506 ; + +C 44 ; WX 250 ; N comma ; B 39 -180 223 155 ; + +C 45 ; WX 333 ; N hyphen ; B 44 171 287 287 ; + +C 46 ; WX 250 ; N period ; B 41 -13 210 156 ; + +C 47 ; WX 278 ; N slash ; B -24 -19 302 691 ; + +C 48 ; WX 500 ; N zero ; B 24 -13 476 688 ; + +C 49 ; WX 500 ; N one ; B 65 0 442 688 ; + +C 50 ; WX 500 ; N two ; B 17 0 478 688 ; + +C 51 ; WX 500 ; N three ; B 16 -14 468 688 ; + +C 52 ; WX 500 ; N four ; B 19 0 475 688 ; + +C 53 ; WX 500 ; N five ; B 22 -8 470 676 ; + +C 54 ; WX 500 ; N six ; B 28 -13 475 688 ; + +C 55 ; WX 500 ; N seven ; B 17 0 477 676 ; + +C 56 ; WX 500 ; N eight ; B 28 -13 472 688 ; + +C 57 ; WX 500 ; N nine ; B 26 -13 473 688 ; + +C 58 ; WX 333 ; N colon ; B 82 -13 251 472 ; + +C 59 ; WX 333 ; N semicolon ; B 82 -180 266 472 ; + +C 60 ; WX 570 ; N less ; B 31 -8 539 514 ; + +C 61 ; WX 570 ; N equal ; B 33 107 537 399 ; + +C 62 ; WX 570 ; N greater ; B 31 -8 539 514 ; + +C 63 ; WX 500 ; N question ; B 57 -13 445 689 ; + +C 64 ; WX 930 ; N at ; B 108 -19 822 691 ; + +C 65 ; WX 722 ; N A ; B 9 0 689 690 ; + +C 66 ; WX 667 ; N B ; B 16 0 619 676 ; + +C 67 ; WX 722 ; N C ; B 49 -19 687 691 ; + +C 68 ; WX 722 ; N D ; B 14 0 690 676 ; + +C 69 ; WX 667 ; N E ; B 16 0 641 676 ; + +C 70 ; WX 611 ; N F ; B 16 0 583 676 ; + +C 71 ; WX 778 ; N G ; B 37 -19 755 691 ; + +C 72 ; WX 778 ; N H ; B 21 0 759 676 ; + +C 73 ; WX 389 ; N I ; B 20 0 370 676 ; + +C 74 ; WX 500 ; N J ; B 3 -96 479 676 ; + +C 75 ; WX 778 ; N K ; B 30 0 769 676 ; + +C 76 ; WX 667 ; N L ; B 19 0 638 676 ; + +C 77 ; WX 944 ; N M ; B 14 0 921 676 ; + +C 78 ; WX 722 ; N N ; B 16 -18 701 676 ; + +C 79 ; WX 778 ; N O ; B 35 -19 743 691 ; + +C 80 ; WX 611 ; N P ; B 16 0 600 676 ; + +C 81 ; WX 778 ; N Q ; B 35 -176 743 691 ; + +C 82 ; WX 722 ; N R ; B 26 0 715 676 ; + +C 83 ; WX 556 ; N S ; B 35 -19 513 692 ; + +C 84 ; WX 667 ; N T ; B 31 0 636 676 ; + +C 85 ; WX 722 ; N U ; B 16 -19 701 676 ; + +C 86 ; WX 722 ; N V ; B 16 -18 701 676 ; + +C 87 ; WX 1000 ; N W ; B 19 -15 981 676 ; + +C 88 ; WX 722 ; N X ; B 16 0 699 676 ; + +C 89 ; WX 722 ; N Y ; B 15 0 699 676 ; + +C 90 ; WX 667 ; N Z ; B 28 0 634 676 ; + +C 91 ; WX 333 ; N bracketleft ; B 67 -149 301 678 ; + +C 92 ; WX 278 ; N backslash ; B -25 -19 303 691 ; + +C 93 ; WX 333 ; N bracketright ; B 32 -149 266 678 ; + +C 94 ; WX 581 ; N asciicircum ; B 73 311 509 676 ; + +C 95 ; WX 500 ; N underscore ; B 0 -125 500 -75 ; + +C 96 ; WX 333 ; N quoteleft ; B 70 356 254 691 ; + +C 97 ; WX 500 ; N a ; B 25 -14 488 473 ; + +C 98 ; WX 556 ; N b ; B 17 -14 521 676 ; + +C 99 ; WX 444 ; N c ; B 25 -14 430 473 ; + +C 100 ; WX 556 ; N d ; B 25 -14 534 676 ; + +C 101 ; WX 444 ; N e ; B 25 -14 426 473 ; + +C 102 ; WX 333 ; N f ; B 14 0 389 691 ; L i fi ; L l fl ; + +C 103 ; WX 500 ; N g ; B 28 -206 483 473 ; + +C 104 ; WX 556 ; N h ; B 16 0 534 676 ; + +C 105 ; WX 278 ; N i ; B 16 0 255 691 ; + +C 106 ; WX 333 ; N j ; B -57 -203 263 691 ; + +C 107 ; WX 556 ; N k ; B 22 0 543 676 ; + +C 108 ; WX 278 ; N l ; B 16 0 255 676 ; + +C 109 ; WX 833 ; N m ; B 16 0 814 473 ; + +C 110 ; WX 556 ; N n ; B 21 0 539 473 ; + +C 111 ; WX 500 ; N o ; B 25 -14 476 473 ; + +C 112 ; WX 556 ; N p ; B 19 -205 524 473 ; + +C 113 ; WX 556 ; N q ; B 34 -205 536 473 ; + +C 114 ; WX 444 ; N r ; B 29 0 434 473 ; + +C 115 ; WX 389 ; N s ; B 25 -14 361 473 ; + +C 116 ; WX 333 ; N t ; B 20 -12 332 630 ; + +C 117 ; WX 556 ; N u ; B 16 -14 537 461 ; + +C 118 ; WX 500 ; N v ; B 21 -14 485 461 ; + +C 119 ; WX 722 ; N w ; B 23 -14 707 461 ; + +C 120 ; WX 500 ; N x ; B 12 0 484 461 ; + +C 121 ; WX 500 ; N y ; B 16 -205 480 461 ; + +C 122 ; WX 444 ; N z ; B 21 0 420 461 ; + +C 123 ; WX 394 ; N braceleft ; B 22 -175 340 698 ; + +C 124 ; WX 220 ; N bar ; B 66 -218 154 782 ; + +C 125 ; WX 394 ; N braceright ; B 54 -175 372 698 ; + +C 126 ; WX 520 ; N asciitilde ; B 29 173 491 333 ; + +C 161 ; WX 333 ; N exclamdown ; B 82 -203 252 501 ; + +C 162 ; WX 500 ; N cent ; B 53 -140 458 588 ; + +C 163 ; WX 500 ; N sterling ; B 21 -14 477 684 ; + +C 164 ; WX 167 ; N fraction ; B -168 -12 329 688 ; + +C 165 ; WX 500 ; N yen ; B -64 0 547 676 ; + +C 166 ; WX 500 ; N florin ; B 0 -155 498 706 ; + +C 167 ; WX 500 ; N section ; B 57 -132 443 691 ; + +C 168 ; WX 500 ; N currency ; B -26 61 526 613 ; + +C 169 ; WX 278 ; N quotesingle ; B 75 404 204 691 ; + +C 170 ; WX 500 ; N quotedblleft ; B 32 356 486 691 ; + +C 171 ; WX 500 ; N guillemotleft ; B 23 36 473 415 ; + +C 172 ; WX 333 ; N guilsinglleft ; B 51 36 305 415 ; + +C 173 ; WX 333 ; N guilsinglright ; B 28 36 282 415 ; + +C 174 ; WX 556 ; N fi ; B 14 0 536 691 ; + +C 175 ; WX 556 ; N fl ; B 14 0 536 691 ; + +C 177 ; WX 500 ; N endash ; B 0 181 500 271 ; + +C 178 ; WX 500 ; N dagger ; B 47 -134 453 691 ; + +C 179 ; WX 500 ; N daggerdbl ; B 45 -132 456 691 ; + +C 180 ; WX 250 ; N periodcentered ; B 41 248 210 417 ; + +C 182 ; WX 540 ; N paragraph ; B 0 -186 519 676 ; + +C 183 ; WX 350 ; N bullet ; B 35 198 315 478 ; + +C 184 ; WX 333 ; N quotesinglbase ; B 79 -180 263 155 ; + +C 185 ; WX 500 ; N quotedblbase ; B 14 -180 468 155 ; + +C 186 ; WX 500 ; N quotedblright ; B 14 356 468 691 ; + +C 187 ; WX 500 ; N guillemotright ; B 27 36 477 415 ; + +C 188 ; WX 1000 ; N ellipsis ; B 82 -13 917 156 ; + +C 189 ; WX 1000 ; N perthousand ; B 7 -29 995 706 ; + +C 191 ; WX 500 ; N questiondown ; B 55 -201 443 501 ; + +C 193 ; WX 333 ; N grave ; B 8 528 246 713 ; + +C 194 ; WX 333 ; N acute ; B 86 528 324 713 ; + +C 195 ; WX 333 ; N circumflex ; B -2 528 335 704 ; + +C 196 ; WX 333 ; N tilde ; B -16 547 349 674 ; + +C 197 ; WX 333 ; N macron ; B 1 565 331 637 ; + +C 198 ; WX 333 ; N breve ; B 15 528 318 691 ; + +C 199 ; WX 333 ; N dotaccent ; B 103 536 258 691 ; + +C 200 ; WX 333 ; N dieresis ; B -2 537 335 667 ; + +C 202 ; WX 333 ; N ring ; B 60 527 273 740 ; + +C 203 ; WX 333 ; N cedilla ; B 68 -218 294 0 ; + +C 205 ; WX 333 ; N hungarumlaut ; B -13 528 425 713 ; + +C 206 ; WX 333 ; N ogonek ; B 90 -193 319 24 ; + +C 207 ; WX 333 ; N caron ; B -2 528 335 704 ; + +C 208 ; WX 1000 ; N emdash ; B 0 181 1000 271 ; + +C 225 ; WX 1000 ; N AE ; B 4 0 951 676 ; + +C 227 ; WX 300 ; N ordfeminine ; B -1 397 301 688 ; + +C 232 ; WX 667 ; N Lslash ; B 19 0 638 676 ; + +C 233 ; WX 778 ; N Oslash ; B 35 -74 743 737 ; + +C 234 ; WX 1000 ; N OE ; B 22 -5 981 684 ; + +C 235 ; WX 330 ; N ordmasculine ; B 18 397 312 688 ; + +C 241 ; WX 722 ; N ae ; B 33 -14 693 473 ; + +C 245 ; WX 278 ; N dotlessi ; B 16 0 255 461 ; + +C 248 ; WX 278 ; N lslash ; B -22 0 303 676 ; + +C 249 ; WX 500 ; N oslash ; B 25 -92 476 549 ; + +C 250 ; WX 722 ; N oe ; B 22 -14 696 473 ; + +C 251 ; WX 556 ; N germandbls ; B 19 -12 517 691 ; + +C -1 ; WX 389 ; N Idieresis ; B 20 0 370 877 ; + +C -1 ; WX 444 ; N eacute ; B 25 -14 426 713 ; + +C -1 ; WX 500 ; N abreve ; B 25 -14 488 691 ; + +C -1 ; WX 556 ; N uhungarumlaut ; B 16 -14 557 713 ; + +C -1 ; WX 444 ; N ecaron ; B 25 -14 426 704 ; + +C -1 ; WX 722 ; N Ydieresis ; B 15 0 699 877 ; + +C -1 ; WX 570 ; N divide ; B 33 -31 537 537 ; + +C -1 ; WX 722 ; N Yacute ; B 15 0 699 923 ; + +C -1 ; WX 722 ; N Acircumflex ; B 9 0 689 914 ; + +C -1 ; WX 500 ; N aacute ; B 25 -14 488 713 ; + +C -1 ; WX 722 ; N Ucircumflex ; B 16 -19 701 914 ; + +C -1 ; WX 500 ; N yacute ; B 16 -205 480 713 ; + +C -1 ; WX 389 ; N scommaaccent ; B 25 -218 361 473 ; + +C -1 ; WX 444 ; N ecircumflex ; B 25 -14 426 704 ; + +C -1 ; WX 722 ; N Uring ; B 16 -19 701 935 ; + +C -1 ; WX 722 ; N Udieresis ; B 16 -19 701 877 ; + +C -1 ; WX 500 ; N aogonek ; B 25 -193 504 473 ; + +C -1 ; WX 722 ; N Uacute ; B 16 -19 701 923 ; + +C -1 ; WX 556 ; N uogonek ; B 16 -193 539 461 ; + +C -1 ; WX 667 ; N Edieresis ; B 16 0 641 877 ; + +C -1 ; WX 722 ; N Dcroat ; B 6 0 690 676 ; + +C -1 ; WX 250 ; N commaaccent ; B 47 -218 203 -50 ; + +C -1 ; WX 747 ; N copyright ; B 26 -19 721 691 ; + +C -1 ; WX 667 ; N Emacron ; B 16 0 641 847 ; + +C -1 ; WX 444 ; N ccaron ; B 25 -14 430 704 ; + +C -1 ; WX 500 ; N aring ; B 25 -14 488 740 ; + +C -1 ; WX 722 ; N Ncommaaccent ; B 16 -188 701 676 ; + +C -1 ; WX 278 ; N lacute ; B 16 0 297 923 ; + +C -1 ; WX 500 ; N agrave ; B 25 -14 488 713 ; + +C -1 ; WX 667 ; N Tcommaaccent ; B 31 -218 636 676 ; + +C -1 ; WX 722 ; N Cacute ; B 49 -19 687 923 ; + +C -1 ; WX 500 ; N atilde ; B 25 -14 488 674 ; + +C -1 ; WX 667 ; N Edotaccent ; B 16 0 641 901 ; + +C -1 ; WX 389 ; N scaron ; B 25 -14 363 704 ; + +C -1 ; WX 389 ; N scedilla ; B 25 -218 361 473 ; + +C -1 ; WX 278 ; N iacute ; B 16 0 289 713 ; + +C -1 ; WX 494 ; N lozenge ; B 10 0 484 745 ; + +C -1 ; WX 722 ; N Rcaron ; B 26 0 715 914 ; + +C -1 ; WX 778 ; N Gcommaaccent ; B 37 -218 755 691 ; + +C -1 ; WX 556 ; N ucircumflex ; B 16 -14 537 704 ; + +C -1 ; WX 500 ; N acircumflex ; B 25 -14 488 704 ; + +C -1 ; WX 722 ; N Amacron ; B 9 0 689 847 ; + +C -1 ; WX 444 ; N rcaron ; B 29 0 434 704 ; + +C -1 ; WX 444 ; N ccedilla ; B 25 -218 430 473 ; + +C -1 ; WX 667 ; N Zdotaccent ; B 28 0 634 901 ; + +C -1 ; WX 611 ; N Thorn ; B 16 0 600 676 ; + +C -1 ; WX 778 ; N Omacron ; B 35 -19 743 847 ; + +C -1 ; WX 722 ; N Racute ; B 26 0 715 923 ; + +C -1 ; WX 556 ; N Sacute ; B 35 -19 513 923 ; + +C -1 ; WX 672 ; N dcaron ; B 25 -14 681 682 ; + +C -1 ; WX 722 ; N Umacron ; B 16 -19 701 847 ; + +C -1 ; WX 556 ; N uring ; B 16 -14 537 740 ; + +C -1 ; WX 300 ; N threesuperior ; B 3 268 297 688 ; + +C -1 ; WX 778 ; N Ograve ; B 35 -19 743 923 ; + +C -1 ; WX 722 ; N Agrave ; B 9 0 689 923 ; + +C -1 ; WX 722 ; N Abreve ; B 9 0 689 901 ; + +C -1 ; WX 570 ; N multiply ; B 48 16 522 490 ; + +C -1 ; WX 556 ; N uacute ; B 16 -14 537 713 ; + +C -1 ; WX 667 ; N Tcaron ; B 31 0 636 914 ; + +C -1 ; WX 494 ; N partialdiff ; B 11 -21 494 750 ; + +C -1 ; WX 500 ; N ydieresis ; B 16 -205 480 667 ; + +C -1 ; WX 722 ; N Nacute ; B 16 -18 701 923 ; + +C -1 ; WX 278 ; N icircumflex ; B -37 0 300 704 ; + +C -1 ; WX 667 ; N Ecircumflex ; B 16 0 641 914 ; + +C -1 ; WX 500 ; N adieresis ; B 25 -14 488 667 ; + +C -1 ; WX 444 ; N edieresis ; B 25 -14 426 667 ; + +C -1 ; WX 444 ; N cacute ; B 25 -14 430 713 ; + +C -1 ; WX 556 ; N nacute ; B 21 0 539 713 ; + +C -1 ; WX 556 ; N umacron ; B 16 -14 537 637 ; + +C -1 ; WX 722 ; N Ncaron ; B 16 -18 701 914 ; + +C -1 ; WX 389 ; N Iacute ; B 20 0 370 923 ; + +C -1 ; WX 570 ; N plusminus ; B 33 0 537 506 ; + +C -1 ; WX 220 ; N brokenbar ; B 66 -143 154 707 ; + +C -1 ; WX 747 ; N registered ; B 26 -19 721 691 ; + +C -1 ; WX 778 ; N Gbreve ; B 37 -19 755 901 ; + +C -1 ; WX 389 ; N Idotaccent ; B 20 0 370 901 ; + +C -1 ; WX 600 ; N summation ; B 14 -10 585 706 ; + +C -1 ; WX 667 ; N Egrave ; B 16 0 641 923 ; + +C -1 ; WX 444 ; N racute ; B 29 0 434 713 ; + +C -1 ; WX 500 ; N omacron ; B 25 -14 476 637 ; + +C -1 ; WX 667 ; N Zacute ; B 28 0 634 923 ; + +C -1 ; WX 667 ; N Zcaron ; B 28 0 634 914 ; + +C -1 ; WX 549 ; N greaterequal ; B 26 0 523 704 ; + +C -1 ; WX 722 ; N Eth ; B 6 0 690 676 ; + +C -1 ; WX 722 ; N Ccedilla ; B 49 -218 687 691 ; + +C -1 ; WX 278 ; N lcommaaccent ; B 16 -218 255 676 ; + +C -1 ; WX 416 ; N tcaron ; B 20 -12 425 815 ; + +C -1 ; WX 444 ; N eogonek ; B 25 -193 426 473 ; + +C -1 ; WX 722 ; N Uogonek ; B 16 -193 701 676 ; + +C -1 ; WX 722 ; N Aacute ; B 9 0 689 923 ; + +C -1 ; WX 722 ; N Adieresis ; B 9 0 689 877 ; + +C -1 ; WX 444 ; N egrave ; B 25 -14 426 713 ; + +C -1 ; WX 444 ; N zacute ; B 21 0 420 713 ; + +C -1 ; WX 278 ; N iogonek ; B 16 -193 274 691 ; + +C -1 ; WX 778 ; N Oacute ; B 35 -19 743 923 ; + +C -1 ; WX 500 ; N oacute ; B 25 -14 476 713 ; + +C -1 ; WX 500 ; N amacron ; B 25 -14 488 637 ; + +C -1 ; WX 389 ; N sacute ; B 25 -14 361 713 ; + +C -1 ; WX 278 ; N idieresis ; B -37 0 300 667 ; + +C -1 ; WX 778 ; N Ocircumflex ; B 35 -19 743 914 ; + +C -1 ; WX 722 ; N Ugrave ; B 16 -19 701 923 ; + +C -1 ; WX 612 ; N Delta ; B 6 0 608 688 ; + +C -1 ; WX 556 ; N thorn ; B 19 -205 524 676 ; + +C -1 ; WX 300 ; N twosuperior ; B 0 275 300 688 ; + +C -1 ; WX 778 ; N Odieresis ; B 35 -19 743 877 ; + +C -1 ; WX 556 ; N mu ; B 33 -206 536 461 ; + +C -1 ; WX 278 ; N igrave ; B -27 0 255 713 ; + +C -1 ; WX 500 ; N ohungarumlaut ; B 25 -14 529 713 ; + +C -1 ; WX 667 ; N Eogonek ; B 16 -193 644 676 ; + +C -1 ; WX 556 ; N dcroat ; B 25 -14 534 676 ; + +C -1 ; WX 750 ; N threequarters ; B 23 -12 733 688 ; + +C -1 ; WX 556 ; N Scedilla ; B 35 -218 513 692 ; + +C -1 ; WX 394 ; N lcaron ; B 16 0 412 682 ; + +C -1 ; WX 778 ; N Kcommaaccent ; B 30 -218 769 676 ; + +C -1 ; WX 667 ; N Lacute ; B 19 0 638 923 ; + +C -1 ; WX 1000 ; N trademark ; B 24 271 977 676 ; + +C -1 ; WX 444 ; N edotaccent ; B 25 -14 426 691 ; + +C -1 ; WX 389 ; N Igrave ; B 20 0 370 923 ; + +C -1 ; WX 389 ; N Imacron ; B 20 0 370 847 ; + +C -1 ; WX 667 ; N Lcaron ; B 19 0 652 682 ; + +C -1 ; WX 750 ; N onehalf ; B -7 -12 775 688 ; + +C -1 ; WX 549 ; N lessequal ; B 29 0 526 704 ; + +C -1 ; WX 500 ; N ocircumflex ; B 25 -14 476 704 ; + +C -1 ; WX 556 ; N ntilde ; B 21 0 539 674 ; + +C -1 ; WX 722 ; N Uhungarumlaut ; B 16 -19 701 923 ; + +C -1 ; WX 667 ; N Eacute ; B 16 0 641 923 ; + +C -1 ; WX 444 ; N emacron ; B 25 -14 426 637 ; + +C -1 ; WX 500 ; N gbreve ; B 28 -206 483 691 ; + +C -1 ; WX 750 ; N onequarter ; B 28 -12 743 688 ; + +C -1 ; WX 556 ; N Scaron ; B 35 -19 513 914 ; + +C -1 ; WX 556 ; N Scommaaccent ; B 35 -218 513 692 ; + +C -1 ; WX 778 ; N Ohungarumlaut ; B 35 -19 743 923 ; + +C -1 ; WX 400 ; N degree ; B 57 402 343 688 ; + +C -1 ; WX 500 ; N ograve ; B 25 -14 476 713 ; + +C -1 ; WX 722 ; N Ccaron ; B 49 -19 687 914 ; + +C -1 ; WX 556 ; N ugrave ; B 16 -14 537 713 ; + +C -1 ; WX 549 ; N radical ; B 10 -46 512 850 ; + +C -1 ; WX 722 ; N Dcaron ; B 14 0 690 914 ; + +C -1 ; WX 444 ; N rcommaaccent ; B 29 -218 434 473 ; + +C -1 ; WX 722 ; N Ntilde ; B 16 -18 701 884 ; + +C -1 ; WX 500 ; N otilde ; B 25 -14 476 674 ; + +C -1 ; WX 722 ; N Rcommaaccent ; B 26 -218 715 676 ; + +C -1 ; WX 667 ; N Lcommaaccent ; B 19 -218 638 676 ; + +C -1 ; WX 722 ; N Atilde ; B 9 0 689 884 ; + +C -1 ; WX 722 ; N Aogonek ; B 9 -193 699 690 ; + +C -1 ; WX 722 ; N Aring ; B 9 0 689 935 ; + +C -1 ; WX 778 ; N Otilde ; B 35 -19 743 884 ; + +C -1 ; WX 444 ; N zdotaccent ; B 21 0 420 691 ; + +C -1 ; WX 667 ; N Ecaron ; B 16 0 641 914 ; + +C -1 ; WX 389 ; N Iogonek ; B 20 -193 370 676 ; + +C -1 ; WX 556 ; N kcommaaccent ; B 22 -218 543 676 ; + +C -1 ; WX 570 ; N minus ; B 33 209 537 297 ; + +C -1 ; WX 389 ; N Icircumflex ; B 20 0 370 914 ; + +C -1 ; WX 556 ; N ncaron ; B 21 0 539 704 ; + +C -1 ; WX 333 ; N tcommaaccent ; B 20 -218 332 630 ; + +C -1 ; WX 570 ; N logicalnot ; B 33 108 537 399 ; + +C -1 ; WX 500 ; N odieresis ; B 25 -14 476 667 ; + +C -1 ; WX 556 ; N udieresis ; B 16 -14 537 667 ; + +C -1 ; WX 549 ; N notequal ; B 15 -49 540 570 ; + +C -1 ; WX 500 ; N gcommaaccent ; B 28 -206 483 829 ; + +C -1 ; WX 500 ; N eth ; B 25 -14 476 691 ; + +C -1 ; WX 444 ; N zcaron ; B 21 0 420 704 ; + +C -1 ; WX 556 ; N ncommaaccent ; B 21 -218 539 473 ; + +C -1 ; WX 300 ; N onesuperior ; B 28 275 273 688 ; + +C -1 ; WX 278 ; N imacron ; B -8 0 272 637 ; + +C -1 ; WX 500 ; N Euro ; B 0 0 0 0 ; + +EndCharMetrics + +StartKernData + +StartKernPairs 2242 + +KPX A C -55 + +KPX A Cacute -55 + +KPX A Ccaron -55 + +KPX A Ccedilla -55 + +KPX A G -55 + +KPX A Gbreve -55 + +KPX A Gcommaaccent -55 + +KPX A O -45 + +KPX A Oacute -45 + +KPX A Ocircumflex -45 + +KPX A Odieresis -45 + +KPX A Ograve -45 + +KPX A Ohungarumlaut -45 + +KPX A Omacron -45 + +KPX A Oslash -45 + +KPX A Otilde -45 + +KPX A Q -45 + +KPX A T -95 + +KPX A Tcaron -95 + +KPX A Tcommaaccent -95 + +KPX A U -50 + +KPX A Uacute -50 + +KPX A Ucircumflex -50 + +KPX A Udieresis -50 + +KPX A Ugrave -50 + +KPX A Uhungarumlaut -50 + +KPX A Umacron -50 + +KPX A Uogonek -50 + +KPX A Uring -50 + +KPX A V -145 + +KPX A W -130 + +KPX A Y -100 + +KPX A Yacute -100 + +KPX A Ydieresis -100 + +KPX A p -25 + +KPX A quoteright -74 + +KPX A u -50 + +KPX A uacute -50 + +KPX A ucircumflex -50 + +KPX A udieresis -50 + +KPX A ugrave -50 + +KPX A uhungarumlaut -50 + +KPX A umacron -50 + +KPX A uogonek -50 + +KPX A uring -50 + +KPX A v -100 + +KPX A w -90 + +KPX A y -74 + +KPX A yacute -74 + +KPX A ydieresis -74 + +KPX Aacute C -55 + +KPX Aacute Cacute -55 + +KPX Aacute Ccaron -55 + +KPX Aacute Ccedilla -55 + +KPX Aacute G -55 + +KPX Aacute Gbreve -55 + +KPX Aacute Gcommaaccent -55 + +KPX Aacute O -45 + +KPX Aacute Oacute -45 + +KPX Aacute Ocircumflex -45 + +KPX Aacute Odieresis -45 + +KPX Aacute Ograve -45 + +KPX Aacute Ohungarumlaut -45 + +KPX Aacute Omacron -45 + +KPX Aacute Oslash -45 + +KPX Aacute Otilde -45 + +KPX Aacute Q -45 + +KPX Aacute T -95 + +KPX Aacute Tcaron -95 + +KPX Aacute Tcommaaccent -95 + +KPX Aacute U -50 + +KPX Aacute Uacute -50 + +KPX Aacute Ucircumflex -50 + +KPX Aacute Udieresis -50 + +KPX Aacute Ugrave -50 + +KPX Aacute Uhungarumlaut -50 + +KPX Aacute Umacron -50 + +KPX Aacute Uogonek -50 + +KPX Aacute Uring -50 + +KPX Aacute V -145 + +KPX Aacute W -130 + +KPX Aacute Y -100 + +KPX Aacute Yacute -100 + +KPX Aacute Ydieresis -100 + +KPX Aacute p -25 + +KPX Aacute quoteright -74 + +KPX Aacute u -50 + +KPX Aacute uacute -50 + +KPX Aacute ucircumflex -50 + +KPX Aacute udieresis -50 + +KPX Aacute ugrave -50 + +KPX Aacute uhungarumlaut -50 + +KPX Aacute umacron -50 + +KPX Aacute uogonek -50 + +KPX Aacute uring -50 + +KPX Aacute v -100 + +KPX Aacute w -90 + +KPX Aacute y -74 + +KPX Aacute yacute -74 + +KPX Aacute ydieresis -74 + +KPX Abreve C -55 + +KPX Abreve Cacute -55 + +KPX Abreve Ccaron -55 + +KPX Abreve Ccedilla -55 + +KPX Abreve G -55 + +KPX Abreve Gbreve -55 + +KPX Abreve Gcommaaccent -55 + +KPX Abreve O -45 + +KPX Abreve Oacute -45 + +KPX Abreve Ocircumflex -45 + +KPX Abreve Odieresis -45 + +KPX Abreve Ograve -45 + +KPX Abreve Ohungarumlaut -45 + +KPX Abreve Omacron -45 + +KPX Abreve Oslash -45 + +KPX Abreve Otilde -45 + +KPX Abreve Q -45 + +KPX Abreve T -95 + +KPX Abreve Tcaron -95 + +KPX Abreve Tcommaaccent -95 + +KPX Abreve U -50 + +KPX Abreve Uacute -50 + +KPX Abreve Ucircumflex -50 + +KPX Abreve Udieresis -50 + +KPX Abreve Ugrave -50 + +KPX Abreve Uhungarumlaut -50 + +KPX Abreve Umacron -50 + +KPX Abreve Uogonek -50 + +KPX Abreve Uring -50 + +KPX Abreve V -145 + +KPX Abreve W -130 + +KPX Abreve Y -100 + +KPX Abreve Yacute -100 + +KPX Abreve Ydieresis -100 + +KPX Abreve p -25 + +KPX Abreve quoteright -74 + +KPX Abreve u -50 + +KPX Abreve uacute -50 + +KPX Abreve ucircumflex -50 + +KPX Abreve udieresis -50 + +KPX Abreve ugrave -50 + +KPX Abreve uhungarumlaut -50 + +KPX Abreve umacron -50 + +KPX Abreve uogonek -50 + +KPX Abreve uring -50 + +KPX Abreve v -100 + +KPX Abreve w -90 + +KPX Abreve y -74 + +KPX Abreve yacute -74 + +KPX Abreve ydieresis -74 + +KPX Acircumflex C -55 + +KPX Acircumflex Cacute -55 + +KPX Acircumflex Ccaron -55 + +KPX Acircumflex Ccedilla -55 + +KPX Acircumflex G -55 + +KPX Acircumflex Gbreve -55 + +KPX Acircumflex Gcommaaccent -55 + +KPX Acircumflex O -45 + +KPX Acircumflex Oacute -45 + +KPX Acircumflex Ocircumflex -45 + +KPX Acircumflex Odieresis -45 + +KPX Acircumflex Ograve -45 + +KPX Acircumflex Ohungarumlaut -45 + +KPX Acircumflex Omacron -45 + +KPX Acircumflex Oslash -45 + +KPX Acircumflex Otilde -45 + +KPX Acircumflex Q -45 + +KPX Acircumflex T -95 + +KPX Acircumflex Tcaron -95 + +KPX Acircumflex Tcommaaccent -95 + +KPX Acircumflex U -50 + +KPX Acircumflex Uacute -50 + +KPX Acircumflex Ucircumflex -50 + +KPX Acircumflex Udieresis -50 + +KPX Acircumflex Ugrave -50 + +KPX Acircumflex Uhungarumlaut -50 + +KPX Acircumflex Umacron -50 + +KPX Acircumflex Uogonek -50 + +KPX Acircumflex Uring -50 + +KPX Acircumflex V -145 + +KPX Acircumflex W -130 + +KPX Acircumflex Y -100 + +KPX Acircumflex Yacute -100 + +KPX Acircumflex Ydieresis -100 + +KPX Acircumflex p -25 + +KPX Acircumflex quoteright -74 + +KPX Acircumflex u -50 + +KPX Acircumflex uacute -50 + +KPX Acircumflex ucircumflex -50 + +KPX Acircumflex udieresis -50 + +KPX Acircumflex ugrave -50 + +KPX Acircumflex uhungarumlaut -50 + +KPX Acircumflex umacron -50 + +KPX Acircumflex uogonek -50 + +KPX Acircumflex uring -50 + +KPX Acircumflex v -100 + +KPX Acircumflex w -90 + +KPX Acircumflex y -74 + +KPX Acircumflex yacute -74 + +KPX Acircumflex ydieresis -74 + +KPX Adieresis C -55 + +KPX Adieresis Cacute -55 + +KPX Adieresis Ccaron -55 + +KPX Adieresis Ccedilla -55 + +KPX Adieresis G -55 + +KPX Adieresis Gbreve -55 + +KPX Adieresis Gcommaaccent -55 + +KPX Adieresis O -45 + +KPX Adieresis Oacute -45 + +KPX Adieresis Ocircumflex -45 + +KPX Adieresis Odieresis -45 + +KPX Adieresis Ograve -45 + +KPX Adieresis Ohungarumlaut -45 + +KPX Adieresis Omacron -45 + +KPX Adieresis Oslash -45 + +KPX Adieresis Otilde -45 + +KPX Adieresis Q -45 + +KPX Adieresis T -95 + +KPX Adieresis Tcaron -95 + +KPX Adieresis Tcommaaccent -95 + +KPX Adieresis U -50 + +KPX Adieresis Uacute -50 + +KPX Adieresis Ucircumflex -50 + +KPX Adieresis Udieresis -50 + +KPX Adieresis Ugrave -50 + +KPX Adieresis Uhungarumlaut -50 + +KPX Adieresis Umacron -50 + +KPX Adieresis Uogonek -50 + +KPX Adieresis Uring -50 + +KPX Adieresis V -145 + +KPX Adieresis W -130 + +KPX Adieresis Y -100 + +KPX Adieresis Yacute -100 + +KPX Adieresis Ydieresis -100 + +KPX Adieresis p -25 + +KPX Adieresis quoteright -74 + +KPX Adieresis u -50 + +KPX Adieresis uacute -50 + +KPX Adieresis ucircumflex -50 + +KPX Adieresis udieresis -50 + +KPX Adieresis ugrave -50 + +KPX Adieresis uhungarumlaut -50 + +KPX Adieresis umacron -50 + +KPX Adieresis uogonek -50 + +KPX Adieresis uring -50 + +KPX Adieresis v -100 + +KPX Adieresis w -90 + +KPX Adieresis y -74 + +KPX Adieresis yacute -74 + +KPX Adieresis ydieresis -74 + +KPX Agrave C -55 + +KPX Agrave Cacute -55 + +KPX Agrave Ccaron -55 + +KPX Agrave Ccedilla -55 + +KPX Agrave G -55 + +KPX Agrave Gbreve -55 + +KPX Agrave Gcommaaccent -55 + +KPX Agrave O -45 + +KPX Agrave Oacute -45 + +KPX Agrave Ocircumflex -45 + +KPX Agrave Odieresis -45 + +KPX Agrave Ograve -45 + +KPX Agrave Ohungarumlaut -45 + +KPX Agrave Omacron -45 + +KPX Agrave Oslash -45 + +KPX Agrave Otilde -45 + +KPX Agrave Q -45 + +KPX Agrave T -95 + +KPX Agrave Tcaron -95 + +KPX Agrave Tcommaaccent -95 + +KPX Agrave U -50 + +KPX Agrave Uacute -50 + +KPX Agrave Ucircumflex -50 + +KPX Agrave Udieresis -50 + +KPX Agrave Ugrave -50 + +KPX Agrave Uhungarumlaut -50 + +KPX Agrave Umacron -50 + +KPX Agrave Uogonek -50 + +KPX Agrave Uring -50 + +KPX Agrave V -145 + +KPX Agrave W -130 + +KPX Agrave Y -100 + +KPX Agrave Yacute -100 + +KPX Agrave Ydieresis -100 + +KPX Agrave p -25 + +KPX Agrave quoteright -74 + +KPX Agrave u -50 + +KPX Agrave uacute -50 + +KPX Agrave ucircumflex -50 + +KPX Agrave udieresis -50 + +KPX Agrave ugrave -50 + +KPX Agrave uhungarumlaut -50 + +KPX Agrave umacron -50 + +KPX Agrave uogonek -50 + +KPX Agrave uring -50 + +KPX Agrave v -100 + +KPX Agrave w -90 + +KPX Agrave y -74 + +KPX Agrave yacute -74 + +KPX Agrave ydieresis -74 + +KPX Amacron C -55 + +KPX Amacron Cacute -55 + +KPX Amacron Ccaron -55 + +KPX Amacron Ccedilla -55 + +KPX Amacron G -55 + +KPX Amacron Gbreve -55 + +KPX Amacron Gcommaaccent -55 + +KPX Amacron O -45 + +KPX Amacron Oacute -45 + +KPX Amacron Ocircumflex -45 + +KPX Amacron Odieresis -45 + +KPX Amacron Ograve -45 + +KPX Amacron Ohungarumlaut -45 + +KPX Amacron Omacron -45 + +KPX Amacron Oslash -45 + +KPX Amacron Otilde -45 + +KPX Amacron Q -45 + +KPX Amacron T -95 + +KPX Amacron Tcaron -95 + +KPX Amacron Tcommaaccent -95 + +KPX Amacron U -50 + +KPX Amacron Uacute -50 + +KPX Amacron Ucircumflex -50 + +KPX Amacron Udieresis -50 + +KPX Amacron Ugrave -50 + +KPX Amacron Uhungarumlaut -50 + +KPX Amacron Umacron -50 + +KPX Amacron Uogonek -50 + +KPX Amacron Uring -50 + +KPX Amacron V -145 + +KPX Amacron W -130 + +KPX Amacron Y -100 + +KPX Amacron Yacute -100 + +KPX Amacron Ydieresis -100 + +KPX Amacron p -25 + +KPX Amacron quoteright -74 + +KPX Amacron u -50 + +KPX Amacron uacute -50 + +KPX Amacron ucircumflex -50 + +KPX Amacron udieresis -50 + +KPX Amacron ugrave -50 + +KPX Amacron uhungarumlaut -50 + +KPX Amacron umacron -50 + +KPX Amacron uogonek -50 + +KPX Amacron uring -50 + +KPX Amacron v -100 + +KPX Amacron w -90 + +KPX Amacron y -74 + +KPX Amacron yacute -74 + +KPX Amacron ydieresis -74 + +KPX Aogonek C -55 + +KPX Aogonek Cacute -55 + +KPX Aogonek Ccaron -55 + +KPX Aogonek Ccedilla -55 + +KPX Aogonek G -55 + +KPX Aogonek Gbreve -55 + +KPX Aogonek Gcommaaccent -55 + +KPX Aogonek O -45 + +KPX Aogonek Oacute -45 + +KPX Aogonek Ocircumflex -45 + +KPX Aogonek Odieresis -45 + +KPX Aogonek Ograve -45 + +KPX Aogonek Ohungarumlaut -45 + +KPX Aogonek Omacron -45 + +KPX Aogonek Oslash -45 + +KPX Aogonek Otilde -45 + +KPX Aogonek Q -45 + +KPX Aogonek T -95 + +KPX Aogonek Tcaron -95 + +KPX Aogonek Tcommaaccent -95 + +KPX Aogonek U -50 + +KPX Aogonek Uacute -50 + +KPX Aogonek Ucircumflex -50 + +KPX Aogonek Udieresis -50 + +KPX Aogonek Ugrave -50 + +KPX Aogonek Uhungarumlaut -50 + +KPX Aogonek Umacron -50 + +KPX Aogonek Uogonek -50 + +KPX Aogonek Uring -50 + +KPX Aogonek V -145 + +KPX Aogonek W -130 + +KPX Aogonek Y -100 + +KPX Aogonek Yacute -100 + +KPX Aogonek Ydieresis -100 + +KPX Aogonek p -25 + +KPX Aogonek quoteright -74 + +KPX Aogonek u -50 + +KPX Aogonek uacute -50 + +KPX Aogonek ucircumflex -50 + +KPX Aogonek udieresis -50 + +KPX Aogonek ugrave -50 + +KPX Aogonek uhungarumlaut -50 + +KPX Aogonek umacron -50 + +KPX Aogonek uogonek -50 + +KPX Aogonek uring -50 + +KPX Aogonek v -100 + +KPX Aogonek w -90 + +KPX Aogonek y -34 + +KPX Aogonek yacute -34 + +KPX Aogonek ydieresis -34 + +KPX Aring C -55 + +KPX Aring Cacute -55 + +KPX Aring Ccaron -55 + +KPX Aring Ccedilla -55 + +KPX Aring G -55 + +KPX Aring Gbreve -55 + +KPX Aring Gcommaaccent -55 + +KPX Aring O -45 + +KPX Aring Oacute -45 + +KPX Aring Ocircumflex -45 + +KPX Aring Odieresis -45 + +KPX Aring Ograve -45 + +KPX Aring Ohungarumlaut -45 + +KPX Aring Omacron -45 + +KPX Aring Oslash -45 + +KPX Aring Otilde -45 + +KPX Aring Q -45 + +KPX Aring T -95 + +KPX Aring Tcaron -95 + +KPX Aring Tcommaaccent -95 + +KPX Aring U -50 + +KPX Aring Uacute -50 + +KPX Aring Ucircumflex -50 + +KPX Aring Udieresis -50 + +KPX Aring Ugrave -50 + +KPX Aring Uhungarumlaut -50 + +KPX Aring Umacron -50 + +KPX Aring Uogonek -50 + +KPX Aring Uring -50 + +KPX Aring V -145 + +KPX Aring W -130 + +KPX Aring Y -100 + +KPX Aring Yacute -100 + +KPX Aring Ydieresis -100 + +KPX Aring p -25 + +KPX Aring quoteright -74 + +KPX Aring u -50 + +KPX Aring uacute -50 + +KPX Aring ucircumflex -50 + +KPX Aring udieresis -50 + +KPX Aring ugrave -50 + +KPX Aring uhungarumlaut -50 + +KPX Aring umacron -50 + +KPX Aring uogonek -50 + +KPX Aring uring -50 + +KPX Aring v -100 + +KPX Aring w -90 + +KPX Aring y -74 + +KPX Aring yacute -74 + +KPX Aring ydieresis -74 + +KPX Atilde C -55 + +KPX Atilde Cacute -55 + +KPX Atilde Ccaron -55 + +KPX Atilde Ccedilla -55 + +KPX Atilde G -55 + +KPX Atilde Gbreve -55 + +KPX Atilde Gcommaaccent -55 + +KPX Atilde O -45 + +KPX Atilde Oacute -45 + +KPX Atilde Ocircumflex -45 + +KPX Atilde Odieresis -45 + +KPX Atilde Ograve -45 + +KPX Atilde Ohungarumlaut -45 + +KPX Atilde Omacron -45 + +KPX Atilde Oslash -45 + +KPX Atilde Otilde -45 + +KPX Atilde Q -45 + +KPX Atilde T -95 + +KPX Atilde Tcaron -95 + +KPX Atilde Tcommaaccent -95 + +KPX Atilde U -50 + +KPX Atilde Uacute -50 + +KPX Atilde Ucircumflex -50 + +KPX Atilde Udieresis -50 + +KPX Atilde Ugrave -50 + +KPX Atilde Uhungarumlaut -50 + +KPX Atilde Umacron -50 + +KPX Atilde Uogonek -50 + +KPX Atilde Uring -50 + +KPX Atilde V -145 + +KPX Atilde W -130 + +KPX Atilde Y -100 + +KPX Atilde Yacute -100 + +KPX Atilde Ydieresis -100 + +KPX Atilde p -25 + +KPX Atilde quoteright -74 + +KPX Atilde u -50 + +KPX Atilde uacute -50 + +KPX Atilde ucircumflex -50 + +KPX Atilde udieresis -50 + +KPX Atilde ugrave -50 + +KPX Atilde uhungarumlaut -50 + +KPX Atilde umacron -50 + +KPX Atilde uogonek -50 + +KPX Atilde uring -50 + +KPX Atilde v -100 + +KPX Atilde w -90 + +KPX Atilde y -74 + +KPX Atilde yacute -74 + +KPX Atilde ydieresis -74 + +KPX B A -30 + +KPX B Aacute -30 + +KPX B Abreve -30 + +KPX B Acircumflex -30 + +KPX B Adieresis -30 + +KPX B Agrave -30 + +KPX B Amacron -30 + +KPX B Aogonek -30 + +KPX B Aring -30 + +KPX B Atilde -30 + +KPX B U -10 + +KPX B Uacute -10 + +KPX B Ucircumflex -10 + +KPX B Udieresis -10 + +KPX B Ugrave -10 + +KPX B Uhungarumlaut -10 + +KPX B Umacron -10 + +KPX B Uogonek -10 + +KPX B Uring -10 + +KPX D A -35 + +KPX D Aacute -35 + +KPX D Abreve -35 + +KPX D Acircumflex -35 + +KPX D Adieresis -35 + +KPX D Agrave -35 + +KPX D Amacron -35 + +KPX D Aogonek -35 + +KPX D Aring -35 + +KPX D Atilde -35 + +KPX D V -40 + +KPX D W -40 + +KPX D Y -40 + +KPX D Yacute -40 + +KPX D Ydieresis -40 + +KPX D period -20 + +KPX Dcaron A -35 + +KPX Dcaron Aacute -35 + +KPX Dcaron Abreve -35 + +KPX Dcaron Acircumflex -35 + +KPX Dcaron Adieresis -35 + +KPX Dcaron Agrave -35 + +KPX Dcaron Amacron -35 + +KPX Dcaron Aogonek -35 + +KPX Dcaron Aring -35 + +KPX Dcaron Atilde -35 + +KPX Dcaron V -40 + +KPX Dcaron W -40 + +KPX Dcaron Y -40 + +KPX Dcaron Yacute -40 + +KPX Dcaron Ydieresis -40 + +KPX Dcaron period -20 + +KPX Dcroat A -35 + +KPX Dcroat Aacute -35 + +KPX Dcroat Abreve -35 + +KPX Dcroat Acircumflex -35 + +KPX Dcroat Adieresis -35 + +KPX Dcroat Agrave -35 + +KPX Dcroat Amacron -35 + +KPX Dcroat Aogonek -35 + +KPX Dcroat Aring -35 + +KPX Dcroat Atilde -35 + +KPX Dcroat V -40 + +KPX Dcroat W -40 + +KPX Dcroat Y -40 + +KPX Dcroat Yacute -40 + +KPX Dcroat Ydieresis -40 + +KPX Dcroat period -20 + +KPX F A -90 + +KPX F Aacute -90 + +KPX F Abreve -90 + +KPX F Acircumflex -90 + +KPX F Adieresis -90 + +KPX F Agrave -90 + +KPX F Amacron -90 + +KPX F Aogonek -90 + +KPX F Aring -90 + +KPX F Atilde -90 + +KPX F a -25 + +KPX F aacute -25 + +KPX F abreve -25 + +KPX F acircumflex -25 + +KPX F adieresis -25 + +KPX F agrave -25 + +KPX F amacron -25 + +KPX F aogonek -25 + +KPX F aring -25 + +KPX F atilde -25 + +KPX F comma -92 + +KPX F e -25 + +KPX F eacute -25 + +KPX F ecaron -25 + +KPX F ecircumflex -25 + +KPX F edieresis -25 + +KPX F edotaccent -25 + +KPX F egrave -25 + +KPX F emacron -25 + +KPX F eogonek -25 + +KPX F o -25 + +KPX F oacute -25 + +KPX F ocircumflex -25 + +KPX F odieresis -25 + +KPX F ograve -25 + +KPX F ohungarumlaut -25 + +KPX F omacron -25 + +KPX F oslash -25 + +KPX F otilde -25 + +KPX F period -110 + +KPX J A -30 + +KPX J Aacute -30 + +KPX J Abreve -30 + +KPX J Acircumflex -30 + +KPX J Adieresis -30 + +KPX J Agrave -30 + +KPX J Amacron -30 + +KPX J Aogonek -30 + +KPX J Aring -30 + +KPX J Atilde -30 + +KPX J a -15 + +KPX J aacute -15 + +KPX J abreve -15 + +KPX J acircumflex -15 + +KPX J adieresis -15 + +KPX J agrave -15 + +KPX J amacron -15 + +KPX J aogonek -15 + +KPX J aring -15 + +KPX J atilde -15 + +KPX J e -15 + +KPX J eacute -15 + +KPX J ecaron -15 + +KPX J ecircumflex -15 + +KPX J edieresis -15 + +KPX J edotaccent -15 + +KPX J egrave -15 + +KPX J emacron -15 + +KPX J eogonek -15 + +KPX J o -15 + +KPX J oacute -15 + +KPX J ocircumflex -15 + +KPX J odieresis -15 + +KPX J ograve -15 + +KPX J ohungarumlaut -15 + +KPX J omacron -15 + +KPX J oslash -15 + +KPX J otilde -15 + +KPX J period -20 + +KPX J u -15 + +KPX J uacute -15 + +KPX J ucircumflex -15 + +KPX J udieresis -15 + +KPX J ugrave -15 + +KPX J uhungarumlaut -15 + +KPX J umacron -15 + +KPX J uogonek -15 + +KPX J uring -15 + +KPX K O -30 + +KPX K Oacute -30 + +KPX K Ocircumflex -30 + +KPX K Odieresis -30 + +KPX K Ograve -30 + +KPX K Ohungarumlaut -30 + +KPX K Omacron -30 + +KPX K Oslash -30 + +KPX K Otilde -30 + +KPX K e -25 + +KPX K eacute -25 + +KPX K ecaron -25 + +KPX K ecircumflex -25 + +KPX K edieresis -25 + +KPX K edotaccent -25 + +KPX K egrave -25 + +KPX K emacron -25 + +KPX K eogonek -25 + +KPX K o -25 + +KPX K oacute -25 + +KPX K ocircumflex -25 + +KPX K odieresis -25 + +KPX K ograve -25 + +KPX K ohungarumlaut -25 + +KPX K omacron -25 + +KPX K oslash -25 + +KPX K otilde -25 + +KPX K u -15 + +KPX K uacute -15 + +KPX K ucircumflex -15 + +KPX K udieresis -15 + +KPX K ugrave -15 + +KPX K uhungarumlaut -15 + +KPX K umacron -15 + +KPX K uogonek -15 + +KPX K uring -15 + +KPX K y -45 + +KPX K yacute -45 + +KPX K ydieresis -45 + +KPX Kcommaaccent O -30 + +KPX Kcommaaccent Oacute -30 + +KPX Kcommaaccent Ocircumflex -30 + +KPX Kcommaaccent Odieresis -30 + +KPX Kcommaaccent Ograve -30 + +KPX Kcommaaccent Ohungarumlaut -30 + +KPX Kcommaaccent Omacron -30 + +KPX Kcommaaccent Oslash -30 + +KPX Kcommaaccent Otilde -30 + +KPX Kcommaaccent e -25 + +KPX Kcommaaccent eacute -25 + +KPX Kcommaaccent ecaron -25 + +KPX Kcommaaccent ecircumflex -25 + +KPX Kcommaaccent edieresis -25 + +KPX Kcommaaccent edotaccent -25 + +KPX Kcommaaccent egrave -25 + +KPX Kcommaaccent emacron -25 + +KPX Kcommaaccent eogonek -25 + +KPX Kcommaaccent o -25 + +KPX Kcommaaccent oacute -25 + +KPX Kcommaaccent ocircumflex -25 + +KPX Kcommaaccent odieresis -25 + +KPX Kcommaaccent ograve -25 + +KPX Kcommaaccent ohungarumlaut -25 + +KPX Kcommaaccent omacron -25 + +KPX Kcommaaccent oslash -25 + +KPX Kcommaaccent otilde -25 + +KPX Kcommaaccent u -15 + +KPX Kcommaaccent uacute -15 + +KPX Kcommaaccent ucircumflex -15 + +KPX Kcommaaccent udieresis -15 + +KPX Kcommaaccent ugrave -15 + +KPX Kcommaaccent uhungarumlaut -15 + +KPX Kcommaaccent umacron -15 + +KPX Kcommaaccent uogonek -15 + +KPX Kcommaaccent uring -15 + +KPX Kcommaaccent y -45 + +KPX Kcommaaccent yacute -45 + +KPX Kcommaaccent ydieresis -45 + +KPX L T -92 + +KPX L Tcaron -92 + +KPX L Tcommaaccent -92 + +KPX L V -92 + +KPX L W -92 + +KPX L Y -92 + +KPX L Yacute -92 + +KPX L Ydieresis -92 + +KPX L quotedblright -20 + +KPX L quoteright -110 + +KPX L y -55 + +KPX L yacute -55 + +KPX L ydieresis -55 + +KPX Lacute T -92 + +KPX Lacute Tcaron -92 + +KPX Lacute Tcommaaccent -92 + +KPX Lacute V -92 + +KPX Lacute W -92 + +KPX Lacute Y -92 + +KPX Lacute Yacute -92 + +KPX Lacute Ydieresis -92 + +KPX Lacute quotedblright -20 + +KPX Lacute quoteright -110 + +KPX Lacute y -55 + +KPX Lacute yacute -55 + +KPX Lacute ydieresis -55 + +KPX Lcommaaccent T -92 + +KPX Lcommaaccent Tcaron -92 + +KPX Lcommaaccent Tcommaaccent -92 + +KPX Lcommaaccent V -92 + +KPX Lcommaaccent W -92 + +KPX Lcommaaccent Y -92 + +KPX Lcommaaccent Yacute -92 + +KPX Lcommaaccent Ydieresis -92 + +KPX Lcommaaccent quotedblright -20 + +KPX Lcommaaccent quoteright -110 + +KPX Lcommaaccent y -55 + +KPX Lcommaaccent yacute -55 + +KPX Lcommaaccent ydieresis -55 + +KPX Lslash T -92 + +KPX Lslash Tcaron -92 + +KPX Lslash Tcommaaccent -92 + +KPX Lslash V -92 + +KPX Lslash W -92 + +KPX Lslash Y -92 + +KPX Lslash Yacute -92 + +KPX Lslash Ydieresis -92 + +KPX Lslash quotedblright -20 + +KPX Lslash quoteright -110 + +KPX Lslash y -55 + +KPX Lslash yacute -55 + +KPX Lslash ydieresis -55 + +KPX N A -20 + +KPX N Aacute -20 + +KPX N Abreve -20 + +KPX N Acircumflex -20 + +KPX N Adieresis -20 + +KPX N Agrave -20 + +KPX N Amacron -20 + +KPX N Aogonek -20 + +KPX N Aring -20 + +KPX N Atilde -20 + +KPX Nacute A -20 + +KPX Nacute Aacute -20 + +KPX Nacute Abreve -20 + +KPX Nacute Acircumflex -20 + +KPX Nacute Adieresis -20 + +KPX Nacute Agrave -20 + +KPX Nacute Amacron -20 + +KPX Nacute Aogonek -20 + +KPX Nacute Aring -20 + +KPX Nacute Atilde -20 + +KPX Ncaron A -20 + +KPX Ncaron Aacute -20 + +KPX Ncaron Abreve -20 + +KPX Ncaron Acircumflex -20 + +KPX Ncaron Adieresis -20 + +KPX Ncaron Agrave -20 + +KPX Ncaron Amacron -20 + +KPX Ncaron Aogonek -20 + +KPX Ncaron Aring -20 + +KPX Ncaron Atilde -20 + +KPX Ncommaaccent A -20 + +KPX Ncommaaccent Aacute -20 + +KPX Ncommaaccent Abreve -20 + +KPX Ncommaaccent Acircumflex -20 + +KPX Ncommaaccent Adieresis -20 + +KPX Ncommaaccent Agrave -20 + +KPX Ncommaaccent Amacron -20 + +KPX Ncommaaccent Aogonek -20 + +KPX Ncommaaccent Aring -20 + +KPX Ncommaaccent Atilde -20 + +KPX Ntilde A -20 + +KPX Ntilde Aacute -20 + +KPX Ntilde Abreve -20 + +KPX Ntilde Acircumflex -20 + +KPX Ntilde Adieresis -20 + +KPX Ntilde Agrave -20 + +KPX Ntilde Amacron -20 + +KPX Ntilde Aogonek -20 + +KPX Ntilde Aring -20 + +KPX Ntilde Atilde -20 + +KPX O A -40 + +KPX O Aacute -40 + +KPX O Abreve -40 + +KPX O Acircumflex -40 + +KPX O Adieresis -40 + +KPX O Agrave -40 + +KPX O Amacron -40 + +KPX O Aogonek -40 + +KPX O Aring -40 + +KPX O Atilde -40 + +KPX O T -40 + +KPX O Tcaron -40 + +KPX O Tcommaaccent -40 + +KPX O V -50 + +KPX O W -50 + +KPX O X -40 + +KPX O Y -50 + +KPX O Yacute -50 + +KPX O Ydieresis -50 + +KPX Oacute A -40 + +KPX Oacute Aacute -40 + +KPX Oacute Abreve -40 + +KPX Oacute Acircumflex -40 + +KPX Oacute Adieresis -40 + +KPX Oacute Agrave -40 + +KPX Oacute Amacron -40 + +KPX Oacute Aogonek -40 + +KPX Oacute Aring -40 + +KPX Oacute Atilde -40 + +KPX Oacute T -40 + +KPX Oacute Tcaron -40 + +KPX Oacute Tcommaaccent -40 + +KPX Oacute V -50 + +KPX Oacute W -50 + +KPX Oacute X -40 + +KPX Oacute Y -50 + +KPX Oacute Yacute -50 + +KPX Oacute Ydieresis -50 + +KPX Ocircumflex A -40 + +KPX Ocircumflex Aacute -40 + +KPX Ocircumflex Abreve -40 + +KPX Ocircumflex Acircumflex -40 + +KPX Ocircumflex Adieresis -40 + +KPX Ocircumflex Agrave -40 + +KPX Ocircumflex Amacron -40 + +KPX Ocircumflex Aogonek -40 + +KPX Ocircumflex Aring -40 + +KPX Ocircumflex Atilde -40 + +KPX Ocircumflex T -40 + +KPX Ocircumflex Tcaron -40 + +KPX Ocircumflex Tcommaaccent -40 + +KPX Ocircumflex V -50 + +KPX Ocircumflex W -50 + +KPX Ocircumflex X -40 + +KPX Ocircumflex Y -50 + +KPX Ocircumflex Yacute -50 + +KPX Ocircumflex Ydieresis -50 + +KPX Odieresis A -40 + +KPX Odieresis Aacute -40 + +KPX Odieresis Abreve -40 + +KPX Odieresis Acircumflex -40 + +KPX Odieresis Adieresis -40 + +KPX Odieresis Agrave -40 + +KPX Odieresis Amacron -40 + +KPX Odieresis Aogonek -40 + +KPX Odieresis Aring -40 + +KPX Odieresis Atilde -40 + +KPX Odieresis T -40 + +KPX Odieresis Tcaron -40 + +KPX Odieresis Tcommaaccent -40 + +KPX Odieresis V -50 + +KPX Odieresis W -50 + +KPX Odieresis X -40 + +KPX Odieresis Y -50 + +KPX Odieresis Yacute -50 + +KPX Odieresis Ydieresis -50 + +KPX Ograve A -40 + +KPX Ograve Aacute -40 + +KPX Ograve Abreve -40 + +KPX Ograve Acircumflex -40 + +KPX Ograve Adieresis -40 + +KPX Ograve Agrave -40 + +KPX Ograve Amacron -40 + +KPX Ograve Aogonek -40 + +KPX Ograve Aring -40 + +KPX Ograve Atilde -40 + +KPX Ograve T -40 + +KPX Ograve Tcaron -40 + +KPX Ograve Tcommaaccent -40 + +KPX Ograve V -50 + +KPX Ograve W -50 + +KPX Ograve X -40 + +KPX Ograve Y -50 + +KPX Ograve Yacute -50 + +KPX Ograve Ydieresis -50 + +KPX Ohungarumlaut A -40 + +KPX Ohungarumlaut Aacute -40 + +KPX Ohungarumlaut Abreve -40 + +KPX Ohungarumlaut Acircumflex -40 + +KPX Ohungarumlaut Adieresis -40 + +KPX Ohungarumlaut Agrave -40 + +KPX Ohungarumlaut Amacron -40 + +KPX Ohungarumlaut Aogonek -40 + +KPX Ohungarumlaut Aring -40 + +KPX Ohungarumlaut Atilde -40 + +KPX Ohungarumlaut T -40 + +KPX Ohungarumlaut Tcaron -40 + +KPX Ohungarumlaut Tcommaaccent -40 + +KPX Ohungarumlaut V -50 + +KPX Ohungarumlaut W -50 + +KPX Ohungarumlaut X -40 + +KPX Ohungarumlaut Y -50 + +KPX Ohungarumlaut Yacute -50 + +KPX Ohungarumlaut Ydieresis -50 + +KPX Omacron A -40 + +KPX Omacron Aacute -40 + +KPX Omacron Abreve -40 + +KPX Omacron Acircumflex -40 + +KPX Omacron Adieresis -40 + +KPX Omacron Agrave -40 + +KPX Omacron Amacron -40 + +KPX Omacron Aogonek -40 + +KPX Omacron Aring -40 + +KPX Omacron Atilde -40 + +KPX Omacron T -40 + +KPX Omacron Tcaron -40 + +KPX Omacron Tcommaaccent -40 + +KPX Omacron V -50 + +KPX Omacron W -50 + +KPX Omacron X -40 + +KPX Omacron Y -50 + +KPX Omacron Yacute -50 + +KPX Omacron Ydieresis -50 + +KPX Oslash A -40 + +KPX Oslash Aacute -40 + +KPX Oslash Abreve -40 + +KPX Oslash Acircumflex -40 + +KPX Oslash Adieresis -40 + +KPX Oslash Agrave -40 + +KPX Oslash Amacron -40 + +KPX Oslash Aogonek -40 + +KPX Oslash Aring -40 + +KPX Oslash Atilde -40 + +KPX Oslash T -40 + +KPX Oslash Tcaron -40 + +KPX Oslash Tcommaaccent -40 + +KPX Oslash V -50 + +KPX Oslash W -50 + +KPX Oslash X -40 + +KPX Oslash Y -50 + +KPX Oslash Yacute -50 + +KPX Oslash Ydieresis -50 + +KPX Otilde A -40 + +KPX Otilde Aacute -40 + +KPX Otilde Abreve -40 + +KPX Otilde Acircumflex -40 + +KPX Otilde Adieresis -40 + +KPX Otilde Agrave -40 + +KPX Otilde Amacron -40 + +KPX Otilde Aogonek -40 + +KPX Otilde Aring -40 + +KPX Otilde Atilde -40 + +KPX Otilde T -40 + +KPX Otilde Tcaron -40 + +KPX Otilde Tcommaaccent -40 + +KPX Otilde V -50 + +KPX Otilde W -50 + +KPX Otilde X -40 + +KPX Otilde Y -50 + +KPX Otilde Yacute -50 + +KPX Otilde Ydieresis -50 + +KPX P A -74 + +KPX P Aacute -74 + +KPX P Abreve -74 + +KPX P Acircumflex -74 + +KPX P Adieresis -74 + +KPX P Agrave -74 + +KPX P Amacron -74 + +KPX P Aogonek -74 + +KPX P Aring -74 + +KPX P Atilde -74 + +KPX P a -10 + +KPX P aacute -10 + +KPX P abreve -10 + +KPX P acircumflex -10 + +KPX P adieresis -10 + +KPX P agrave -10 + +KPX P amacron -10 + +KPX P aogonek -10 + +KPX P aring -10 + +KPX P atilde -10 + +KPX P comma -92 + +KPX P e -20 + +KPX P eacute -20 + +KPX P ecaron -20 + +KPX P ecircumflex -20 + +KPX P edieresis -20 + +KPX P edotaccent -20 + +KPX P egrave -20 + +KPX P emacron -20 + +KPX P eogonek -20 + +KPX P o -20 + +KPX P oacute -20 + +KPX P ocircumflex -20 + +KPX P odieresis -20 + +KPX P ograve -20 + +KPX P ohungarumlaut -20 + +KPX P omacron -20 + +KPX P oslash -20 + +KPX P otilde -20 + +KPX P period -110 + +KPX Q U -10 + +KPX Q Uacute -10 + +KPX Q Ucircumflex -10 + +KPX Q Udieresis -10 + +KPX Q Ugrave -10 + +KPX Q Uhungarumlaut -10 + +KPX Q Umacron -10 + +KPX Q Uogonek -10 + +KPX Q Uring -10 + +KPX Q period -20 + +KPX R O -30 + +KPX R Oacute -30 + +KPX R Ocircumflex -30 + +KPX R Odieresis -30 + +KPX R Ograve -30 + +KPX R Ohungarumlaut -30 + +KPX R Omacron -30 + +KPX R Oslash -30 + +KPX R Otilde -30 + +KPX R T -40 + +KPX R Tcaron -40 + +KPX R Tcommaaccent -40 + +KPX R U -30 + +KPX R Uacute -30 + +KPX R Ucircumflex -30 + +KPX R Udieresis -30 + +KPX R Ugrave -30 + +KPX R Uhungarumlaut -30 + +KPX R Umacron -30 + +KPX R Uogonek -30 + +KPX R Uring -30 + +KPX R V -55 + +KPX R W -35 + +KPX R Y -35 + +KPX R Yacute -35 + +KPX R Ydieresis -35 + +KPX Racute O -30 + +KPX Racute Oacute -30 + +KPX Racute Ocircumflex -30 + +KPX Racute Odieresis -30 + +KPX Racute Ograve -30 + +KPX Racute Ohungarumlaut -30 + +KPX Racute Omacron -30 + +KPX Racute Oslash -30 + +KPX Racute Otilde -30 + +KPX Racute T -40 + +KPX Racute Tcaron -40 + +KPX Racute Tcommaaccent -40 + +KPX Racute U -30 + +KPX Racute Uacute -30 + +KPX Racute Ucircumflex -30 + +KPX Racute Udieresis -30 + +KPX Racute Ugrave -30 + +KPX Racute Uhungarumlaut -30 + +KPX Racute Umacron -30 + +KPX Racute Uogonek -30 + +KPX Racute Uring -30 + +KPX Racute V -55 + +KPX Racute W -35 + +KPX Racute Y -35 + +KPX Racute Yacute -35 + +KPX Racute Ydieresis -35 + +KPX Rcaron O -30 + +KPX Rcaron Oacute -30 + +KPX Rcaron Ocircumflex -30 + +KPX Rcaron Odieresis -30 + +KPX Rcaron Ograve -30 + +KPX Rcaron Ohungarumlaut -30 + +KPX Rcaron Omacron -30 + +KPX Rcaron Oslash -30 + +KPX Rcaron Otilde -30 + +KPX Rcaron T -40 + +KPX Rcaron Tcaron -40 + +KPX Rcaron Tcommaaccent -40 + +KPX Rcaron U -30 + +KPX Rcaron Uacute -30 + +KPX Rcaron Ucircumflex -30 + +KPX Rcaron Udieresis -30 + +KPX Rcaron Ugrave -30 + +KPX Rcaron Uhungarumlaut -30 + +KPX Rcaron Umacron -30 + +KPX Rcaron Uogonek -30 + +KPX Rcaron Uring -30 + +KPX Rcaron V -55 + +KPX Rcaron W -35 + +KPX Rcaron Y -35 + +KPX Rcaron Yacute -35 + +KPX Rcaron Ydieresis -35 + +KPX Rcommaaccent O -30 + +KPX Rcommaaccent Oacute -30 + +KPX Rcommaaccent Ocircumflex -30 + +KPX Rcommaaccent Odieresis -30 + +KPX Rcommaaccent Ograve -30 + +KPX Rcommaaccent Ohungarumlaut -30 + +KPX Rcommaaccent Omacron -30 + +KPX Rcommaaccent Oslash -30 + +KPX Rcommaaccent Otilde -30 + +KPX Rcommaaccent T -40 + +KPX Rcommaaccent Tcaron -40 + +KPX Rcommaaccent Tcommaaccent -40 + +KPX Rcommaaccent U -30 + +KPX Rcommaaccent Uacute -30 + +KPX Rcommaaccent Ucircumflex -30 + +KPX Rcommaaccent Udieresis -30 + +KPX Rcommaaccent Ugrave -30 + +KPX Rcommaaccent Uhungarumlaut -30 + +KPX Rcommaaccent Umacron -30 + +KPX Rcommaaccent Uogonek -30 + +KPX Rcommaaccent Uring -30 + +KPX Rcommaaccent V -55 + +KPX Rcommaaccent W -35 + +KPX Rcommaaccent Y -35 + +KPX Rcommaaccent Yacute -35 + +KPX Rcommaaccent Ydieresis -35 + +KPX T A -90 + +KPX T Aacute -90 + +KPX T Abreve -90 + +KPX T Acircumflex -90 + +KPX T Adieresis -90 + +KPX T Agrave -90 + +KPX T Amacron -90 + +KPX T Aogonek -90 + +KPX T Aring -90 + +KPX T Atilde -90 + +KPX T O -18 + +KPX T Oacute -18 + +KPX T Ocircumflex -18 + +KPX T Odieresis -18 + +KPX T Ograve -18 + +KPX T Ohungarumlaut -18 + +KPX T Omacron -18 + +KPX T Oslash -18 + +KPX T Otilde -18 + +KPX T a -92 + +KPX T aacute -92 + +KPX T abreve -52 + +KPX T acircumflex -52 + +KPX T adieresis -52 + +KPX T agrave -52 + +KPX T amacron -52 + +KPX T aogonek -92 + +KPX T aring -92 + +KPX T atilde -52 + +KPX T colon -74 + +KPX T comma -74 + +KPX T e -92 + +KPX T eacute -92 + +KPX T ecaron -92 + +KPX T ecircumflex -92 + +KPX T edieresis -52 + +KPX T edotaccent -92 + +KPX T egrave -52 + +KPX T emacron -52 + +KPX T eogonek -92 + +KPX T hyphen -92 + +KPX T i -18 + +KPX T iacute -18 + +KPX T iogonek -18 + +KPX T o -92 + +KPX T oacute -92 + +KPX T ocircumflex -92 + +KPX T odieresis -92 + +KPX T ograve -92 + +KPX T ohungarumlaut -92 + +KPX T omacron -92 + +KPX T oslash -92 + +KPX T otilde -92 + +KPX T period -90 + +KPX T r -74 + +KPX T racute -74 + +KPX T rcaron -74 + +KPX T rcommaaccent -74 + +KPX T semicolon -74 + +KPX T u -92 + +KPX T uacute -92 + +KPX T ucircumflex -92 + +KPX T udieresis -92 + +KPX T ugrave -92 + +KPX T uhungarumlaut -92 + +KPX T umacron -92 + +KPX T uogonek -92 + +KPX T uring -92 + +KPX T w -74 + +KPX T y -34 + +KPX T yacute -34 + +KPX T ydieresis -34 + +KPX Tcaron A -90 + +KPX Tcaron Aacute -90 + +KPX Tcaron Abreve -90 + +KPX Tcaron Acircumflex -90 + +KPX Tcaron Adieresis -90 + +KPX Tcaron Agrave -90 + +KPX Tcaron Amacron -90 + +KPX Tcaron Aogonek -90 + +KPX Tcaron Aring -90 + +KPX Tcaron Atilde -90 + +KPX Tcaron O -18 + +KPX Tcaron Oacute -18 + +KPX Tcaron Ocircumflex -18 + +KPX Tcaron Odieresis -18 + +KPX Tcaron Ograve -18 + +KPX Tcaron Ohungarumlaut -18 + +KPX Tcaron Omacron -18 + +KPX Tcaron Oslash -18 + +KPX Tcaron Otilde -18 + +KPX Tcaron a -92 + +KPX Tcaron aacute -92 + +KPX Tcaron abreve -52 + +KPX Tcaron acircumflex -52 + +KPX Tcaron adieresis -52 + +KPX Tcaron agrave -52 + +KPX Tcaron amacron -52 + +KPX Tcaron aogonek -92 + +KPX Tcaron aring -92 + +KPX Tcaron atilde -52 + +KPX Tcaron colon -74 + +KPX Tcaron comma -74 + +KPX Tcaron e -92 + +KPX Tcaron eacute -92 + +KPX Tcaron ecaron -92 + +KPX Tcaron ecircumflex -92 + +KPX Tcaron edieresis -52 + +KPX Tcaron edotaccent -92 + +KPX Tcaron egrave -52 + +KPX Tcaron emacron -52 + +KPX Tcaron eogonek -92 + +KPX Tcaron hyphen -92 + +KPX Tcaron i -18 + +KPX Tcaron iacute -18 + +KPX Tcaron iogonek -18 + +KPX Tcaron o -92 + +KPX Tcaron oacute -92 + +KPX Tcaron ocircumflex -92 + +KPX Tcaron odieresis -92 + +KPX Tcaron ograve -92 + +KPX Tcaron ohungarumlaut -92 + +KPX Tcaron omacron -92 + +KPX Tcaron oslash -92 + +KPX Tcaron otilde -92 + +KPX Tcaron period -90 + +KPX Tcaron r -74 + +KPX Tcaron racute -74 + +KPX Tcaron rcaron -74 + +KPX Tcaron rcommaaccent -74 + +KPX Tcaron semicolon -74 + +KPX Tcaron u -92 + +KPX Tcaron uacute -92 + +KPX Tcaron ucircumflex -92 + +KPX Tcaron udieresis -92 + +KPX Tcaron ugrave -92 + +KPX Tcaron uhungarumlaut -92 + +KPX Tcaron umacron -92 + +KPX Tcaron uogonek -92 + +KPX Tcaron uring -92 + +KPX Tcaron w -74 + +KPX Tcaron y -34 + +KPX Tcaron yacute -34 + +KPX Tcaron ydieresis -34 + +KPX Tcommaaccent A -90 + +KPX Tcommaaccent Aacute -90 + +KPX Tcommaaccent Abreve -90 + +KPX Tcommaaccent Acircumflex -90 + +KPX Tcommaaccent Adieresis -90 + +KPX Tcommaaccent Agrave -90 + +KPX Tcommaaccent Amacron -90 + +KPX Tcommaaccent Aogonek -90 + +KPX Tcommaaccent Aring -90 + +KPX Tcommaaccent Atilde -90 + +KPX Tcommaaccent O -18 + +KPX Tcommaaccent Oacute -18 + +KPX Tcommaaccent Ocircumflex -18 + +KPX Tcommaaccent Odieresis -18 + +KPX Tcommaaccent Ograve -18 + +KPX Tcommaaccent Ohungarumlaut -18 + +KPX Tcommaaccent Omacron -18 + +KPX Tcommaaccent Oslash -18 + +KPX Tcommaaccent Otilde -18 + +KPX Tcommaaccent a -92 + +KPX Tcommaaccent aacute -92 + +KPX Tcommaaccent abreve -52 + +KPX Tcommaaccent acircumflex -52 + +KPX Tcommaaccent adieresis -52 + +KPX Tcommaaccent agrave -52 + +KPX Tcommaaccent amacron -52 + +KPX Tcommaaccent aogonek -92 + +KPX Tcommaaccent aring -92 + +KPX Tcommaaccent atilde -52 + +KPX Tcommaaccent colon -74 + +KPX Tcommaaccent comma -74 + +KPX Tcommaaccent e -92 + +KPX Tcommaaccent eacute -92 + +KPX Tcommaaccent ecaron -92 + +KPX Tcommaaccent ecircumflex -92 + +KPX Tcommaaccent edieresis -52 + +KPX Tcommaaccent edotaccent -92 + +KPX Tcommaaccent egrave -52 + +KPX Tcommaaccent emacron -52 + +KPX Tcommaaccent eogonek -92 + +KPX Tcommaaccent hyphen -92 + +KPX Tcommaaccent i -18 + +KPX Tcommaaccent iacute -18 + +KPX Tcommaaccent iogonek -18 + +KPX Tcommaaccent o -92 + +KPX Tcommaaccent oacute -92 + +KPX Tcommaaccent ocircumflex -92 + +KPX Tcommaaccent odieresis -92 + +KPX Tcommaaccent ograve -92 + +KPX Tcommaaccent ohungarumlaut -92 + +KPX Tcommaaccent omacron -92 + +KPX Tcommaaccent oslash -92 + +KPX Tcommaaccent otilde -92 + +KPX Tcommaaccent period -90 + +KPX Tcommaaccent r -74 + +KPX Tcommaaccent racute -74 + +KPX Tcommaaccent rcaron -74 + +KPX Tcommaaccent rcommaaccent -74 + +KPX Tcommaaccent semicolon -74 + +KPX Tcommaaccent u -92 + +KPX Tcommaaccent uacute -92 + +KPX Tcommaaccent ucircumflex -92 + +KPX Tcommaaccent udieresis -92 + +KPX Tcommaaccent ugrave -92 + +KPX Tcommaaccent uhungarumlaut -92 + +KPX Tcommaaccent umacron -92 + +KPX Tcommaaccent uogonek -92 + +KPX Tcommaaccent uring -92 + +KPX Tcommaaccent w -74 + +KPX Tcommaaccent y -34 + +KPX Tcommaaccent yacute -34 + +KPX Tcommaaccent ydieresis -34 + +KPX U A -60 + +KPX U Aacute -60 + +KPX U Abreve -60 + +KPX U Acircumflex -60 + +KPX U Adieresis -60 + +KPX U Agrave -60 + +KPX U Amacron -60 + +KPX U Aogonek -60 + +KPX U Aring -60 + +KPX U Atilde -60 + +KPX U comma -50 + +KPX U period -50 + +KPX Uacute A -60 + +KPX Uacute Aacute -60 + +KPX Uacute Abreve -60 + +KPX Uacute Acircumflex -60 + +KPX Uacute Adieresis -60 + +KPX Uacute Agrave -60 + +KPX Uacute Amacron -60 + +KPX Uacute Aogonek -60 + +KPX Uacute Aring -60 + +KPX Uacute Atilde -60 + +KPX Uacute comma -50 + +KPX Uacute period -50 + +KPX Ucircumflex A -60 + +KPX Ucircumflex Aacute -60 + +KPX Ucircumflex Abreve -60 + +KPX Ucircumflex Acircumflex -60 + +KPX Ucircumflex Adieresis -60 + +KPX Ucircumflex Agrave -60 + +KPX Ucircumflex Amacron -60 + +KPX Ucircumflex Aogonek -60 + +KPX Ucircumflex Aring -60 + +KPX Ucircumflex Atilde -60 + +KPX Ucircumflex comma -50 + +KPX Ucircumflex period -50 + +KPX Udieresis A -60 + +KPX Udieresis Aacute -60 + +KPX Udieresis Abreve -60 + +KPX Udieresis Acircumflex -60 + +KPX Udieresis Adieresis -60 + +KPX Udieresis Agrave -60 + +KPX Udieresis Amacron -60 + +KPX Udieresis Aogonek -60 + +KPX Udieresis Aring -60 + +KPX Udieresis Atilde -60 + +KPX Udieresis comma -50 + +KPX Udieresis period -50 + +KPX Ugrave A -60 + +KPX Ugrave Aacute -60 + +KPX Ugrave Abreve -60 + +KPX Ugrave Acircumflex -60 + +KPX Ugrave Adieresis -60 + +KPX Ugrave Agrave -60 + +KPX Ugrave Amacron -60 + +KPX Ugrave Aogonek -60 + +KPX Ugrave Aring -60 + +KPX Ugrave Atilde -60 + +KPX Ugrave comma -50 + +KPX Ugrave period -50 + +KPX Uhungarumlaut A -60 + +KPX Uhungarumlaut Aacute -60 + +KPX Uhungarumlaut Abreve -60 + +KPX Uhungarumlaut Acircumflex -60 + +KPX Uhungarumlaut Adieresis -60 + +KPX Uhungarumlaut Agrave -60 + +KPX Uhungarumlaut Amacron -60 + +KPX Uhungarumlaut Aogonek -60 + +KPX Uhungarumlaut Aring -60 + +KPX Uhungarumlaut Atilde -60 + +KPX Uhungarumlaut comma -50 + +KPX Uhungarumlaut period -50 + +KPX Umacron A -60 + +KPX Umacron Aacute -60 + +KPX Umacron Abreve -60 + +KPX Umacron Acircumflex -60 + +KPX Umacron Adieresis -60 + +KPX Umacron Agrave -60 + +KPX Umacron Amacron -60 + +KPX Umacron Aogonek -60 + +KPX Umacron Aring -60 + +KPX Umacron Atilde -60 + +KPX Umacron comma -50 + +KPX Umacron period -50 + +KPX Uogonek A -60 + +KPX Uogonek Aacute -60 + +KPX Uogonek Abreve -60 + +KPX Uogonek Acircumflex -60 + +KPX Uogonek Adieresis -60 + +KPX Uogonek Agrave -60 + +KPX Uogonek Amacron -60 + +KPX Uogonek Aogonek -60 + +KPX Uogonek Aring -60 + +KPX Uogonek Atilde -60 + +KPX Uogonek comma -50 + +KPX Uogonek period -50 + +KPX Uring A -60 + +KPX Uring Aacute -60 + +KPX Uring Abreve -60 + +KPX Uring Acircumflex -60 + +KPX Uring Adieresis -60 + +KPX Uring Agrave -60 + +KPX Uring Amacron -60 + +KPX Uring Aogonek -60 + +KPX Uring Aring -60 + +KPX Uring Atilde -60 + +KPX Uring comma -50 + +KPX Uring period -50 + +KPX V A -135 + +KPX V Aacute -135 + +KPX V Abreve -135 + +KPX V Acircumflex -135 + +KPX V Adieresis -135 + +KPX V Agrave -135 + +KPX V Amacron -135 + +KPX V Aogonek -135 + +KPX V Aring -135 + +KPX V Atilde -135 + +KPX V G -30 + +KPX V Gbreve -30 + +KPX V Gcommaaccent -30 + +KPX V O -45 + +KPX V Oacute -45 + +KPX V Ocircumflex -45 + +KPX V Odieresis -45 + +KPX V Ograve -45 + +KPX V Ohungarumlaut -45 + +KPX V Omacron -45 + +KPX V Oslash -45 + +KPX V Otilde -45 + +KPX V a -92 + +KPX V aacute -92 + +KPX V abreve -92 + +KPX V acircumflex -92 + +KPX V adieresis -92 + +KPX V agrave -92 + +KPX V amacron -92 + +KPX V aogonek -92 + +KPX V aring -92 + +KPX V atilde -92 + +KPX V colon -92 + +KPX V comma -129 + +KPX V e -100 + +KPX V eacute -100 + +KPX V ecaron -100 + +KPX V ecircumflex -100 + +KPX V edieresis -100 + +KPX V edotaccent -100 + +KPX V egrave -100 + +KPX V emacron -100 + +KPX V eogonek -100 + +KPX V hyphen -74 + +KPX V i -37 + +KPX V iacute -37 + +KPX V icircumflex -37 + +KPX V idieresis -37 + +KPX V igrave -37 + +KPX V imacron -37 + +KPX V iogonek -37 + +KPX V o -100 + +KPX V oacute -100 + +KPX V ocircumflex -100 + +KPX V odieresis -100 + +KPX V ograve -100 + +KPX V ohungarumlaut -100 + +KPX V omacron -100 + +KPX V oslash -100 + +KPX V otilde -100 + +KPX V period -145 + +KPX V semicolon -92 + +KPX V u -92 + +KPX V uacute -92 + +KPX V ucircumflex -92 + +KPX V udieresis -92 + +KPX V ugrave -92 + +KPX V uhungarumlaut -92 + +KPX V umacron -92 + +KPX V uogonek -92 + +KPX V uring -92 + +KPX W A -120 + +KPX W Aacute -120 + +KPX W Abreve -120 + +KPX W Acircumflex -120 + +KPX W Adieresis -120 + +KPX W Agrave -120 + +KPX W Amacron -120 + +KPX W Aogonek -120 + +KPX W Aring -120 + +KPX W Atilde -120 + +KPX W O -10 + +KPX W Oacute -10 + +KPX W Ocircumflex -10 + +KPX W Odieresis -10 + +KPX W Ograve -10 + +KPX W Ohungarumlaut -10 + +KPX W Omacron -10 + +KPX W Oslash -10 + +KPX W Otilde -10 + +KPX W a -65 + +KPX W aacute -65 + +KPX W abreve -65 + +KPX W acircumflex -65 + +KPX W adieresis -65 + +KPX W agrave -65 + +KPX W amacron -65 + +KPX W aogonek -65 + +KPX W aring -65 + +KPX W atilde -65 + +KPX W colon -55 + +KPX W comma -92 + +KPX W e -65 + +KPX W eacute -65 + +KPX W ecaron -65 + +KPX W ecircumflex -65 + +KPX W edieresis -65 + +KPX W edotaccent -65 + +KPX W egrave -65 + +KPX W emacron -65 + +KPX W eogonek -65 + +KPX W hyphen -37 + +KPX W i -18 + +KPX W iacute -18 + +KPX W iogonek -18 + +KPX W o -75 + +KPX W oacute -75 + +KPX W ocircumflex -75 + +KPX W odieresis -75 + +KPX W ograve -75 + +KPX W ohungarumlaut -75 + +KPX W omacron -75 + +KPX W oslash -75 + +KPX W otilde -75 + +KPX W period -92 + +KPX W semicolon -55 + +KPX W u -50 + +KPX W uacute -50 + +KPX W ucircumflex -50 + +KPX W udieresis -50 + +KPX W ugrave -50 + +KPX W uhungarumlaut -50 + +KPX W umacron -50 + +KPX W uogonek -50 + +KPX W uring -50 + +KPX W y -60 + +KPX W yacute -60 + +KPX W ydieresis -60 + +KPX Y A -110 + +KPX Y Aacute -110 + +KPX Y Abreve -110 + +KPX Y Acircumflex -110 + +KPX Y Adieresis -110 + +KPX Y Agrave -110 + +KPX Y Amacron -110 + +KPX Y Aogonek -110 + +KPX Y Aring -110 + +KPX Y Atilde -110 + +KPX Y O -35 + +KPX Y Oacute -35 + +KPX Y Ocircumflex -35 + +KPX Y Odieresis -35 + +KPX Y Ograve -35 + +KPX Y Ohungarumlaut -35 + +KPX Y Omacron -35 + +KPX Y Oslash -35 + +KPX Y Otilde -35 + +KPX Y a -85 + +KPX Y aacute -85 + +KPX Y abreve -85 + +KPX Y acircumflex -85 + +KPX Y adieresis -85 + +KPX Y agrave -85 + +KPX Y amacron -85 + +KPX Y aogonek -85 + +KPX Y aring -85 + +KPX Y atilde -85 + +KPX Y colon -92 + +KPX Y comma -92 + +KPX Y e -111 + +KPX Y eacute -111 + +KPX Y ecaron -111 + +KPX Y ecircumflex -111 + +KPX Y edieresis -71 + +KPX Y edotaccent -111 + +KPX Y egrave -71 + +KPX Y emacron -71 + +KPX Y eogonek -111 + +KPX Y hyphen -92 + +KPX Y i -37 + +KPX Y iacute -37 + +KPX Y iogonek -37 + +KPX Y o -111 + +KPX Y oacute -111 + +KPX Y ocircumflex -111 + +KPX Y odieresis -111 + +KPX Y ograve -111 + +KPX Y ohungarumlaut -111 + +KPX Y omacron -111 + +KPX Y oslash -111 + +KPX Y otilde -111 + +KPX Y period -92 + +KPX Y semicolon -92 + +KPX Y u -92 + +KPX Y uacute -92 + +KPX Y ucircumflex -92 + +KPX Y udieresis -92 + +KPX Y ugrave -92 + +KPX Y uhungarumlaut -92 + +KPX Y umacron -92 + +KPX Y uogonek -92 + +KPX Y uring -92 + +KPX Yacute A -110 + +KPX Yacute Aacute -110 + +KPX Yacute Abreve -110 + +KPX Yacute Acircumflex -110 + +KPX Yacute Adieresis -110 + +KPX Yacute Agrave -110 + +KPX Yacute Amacron -110 + +KPX Yacute Aogonek -110 + +KPX Yacute Aring -110 + +KPX Yacute Atilde -110 + +KPX Yacute O -35 + +KPX Yacute Oacute -35 + +KPX Yacute Ocircumflex -35 + +KPX Yacute Odieresis -35 + +KPX Yacute Ograve -35 + +KPX Yacute Ohungarumlaut -35 + +KPX Yacute Omacron -35 + +KPX Yacute Oslash -35 + +KPX Yacute Otilde -35 + +KPX Yacute a -85 + +KPX Yacute aacute -85 + +KPX Yacute abreve -85 + +KPX Yacute acircumflex -85 + +KPX Yacute adieresis -85 + +KPX Yacute agrave -85 + +KPX Yacute amacron -85 + +KPX Yacute aogonek -85 + +KPX Yacute aring -85 + +KPX Yacute atilde -85 + +KPX Yacute colon -92 + +KPX Yacute comma -92 + +KPX Yacute e -111 + +KPX Yacute eacute -111 + +KPX Yacute ecaron -111 + +KPX Yacute ecircumflex -111 + +KPX Yacute edieresis -71 + +KPX Yacute edotaccent -111 + +KPX Yacute egrave -71 + +KPX Yacute emacron -71 + +KPX Yacute eogonek -111 + +KPX Yacute hyphen -92 + +KPX Yacute i -37 + +KPX Yacute iacute -37 + +KPX Yacute iogonek -37 + +KPX Yacute o -111 + +KPX Yacute oacute -111 + +KPX Yacute ocircumflex -111 + +KPX Yacute odieresis -111 + +KPX Yacute ograve -111 + +KPX Yacute ohungarumlaut -111 + +KPX Yacute omacron -111 + +KPX Yacute oslash -111 + +KPX Yacute otilde -111 + +KPX Yacute period -92 + +KPX Yacute semicolon -92 + +KPX Yacute u -92 + +KPX Yacute uacute -92 + +KPX Yacute ucircumflex -92 + +KPX Yacute udieresis -92 + +KPX Yacute ugrave -92 + +KPX Yacute uhungarumlaut -92 + +KPX Yacute umacron -92 + +KPX Yacute uogonek -92 + +KPX Yacute uring -92 + +KPX Ydieresis A -110 + +KPX Ydieresis Aacute -110 + +KPX Ydieresis Abreve -110 + +KPX Ydieresis Acircumflex -110 + +KPX Ydieresis Adieresis -110 + +KPX Ydieresis Agrave -110 + +KPX Ydieresis Amacron -110 + +KPX Ydieresis Aogonek -110 + +KPX Ydieresis Aring -110 + +KPX Ydieresis Atilde -110 + +KPX Ydieresis O -35 + +KPX Ydieresis Oacute -35 + +KPX Ydieresis Ocircumflex -35 + +KPX Ydieresis Odieresis -35 + +KPX Ydieresis Ograve -35 + +KPX Ydieresis Ohungarumlaut -35 + +KPX Ydieresis Omacron -35 + +KPX Ydieresis Oslash -35 + +KPX Ydieresis Otilde -35 + +KPX Ydieresis a -85 + +KPX Ydieresis aacute -85 + +KPX Ydieresis abreve -85 + +KPX Ydieresis acircumflex -85 + +KPX Ydieresis adieresis -85 + +KPX Ydieresis agrave -85 + +KPX Ydieresis amacron -85 + +KPX Ydieresis aogonek -85 + +KPX Ydieresis aring -85 + +KPX Ydieresis atilde -85 + +KPX Ydieresis colon -92 + +KPX Ydieresis comma -92 + +KPX Ydieresis e -111 + +KPX Ydieresis eacute -111 + +KPX Ydieresis ecaron -111 + +KPX Ydieresis ecircumflex -111 + +KPX Ydieresis edieresis -71 + +KPX Ydieresis edotaccent -111 + +KPX Ydieresis egrave -71 + +KPX Ydieresis emacron -71 + +KPX Ydieresis eogonek -111 + +KPX Ydieresis hyphen -92 + +KPX Ydieresis i -37 + +KPX Ydieresis iacute -37 + +KPX Ydieresis iogonek -37 + +KPX Ydieresis o -111 + +KPX Ydieresis oacute -111 + +KPX Ydieresis ocircumflex -111 + +KPX Ydieresis odieresis -111 + +KPX Ydieresis ograve -111 + +KPX Ydieresis ohungarumlaut -111 + +KPX Ydieresis omacron -111 + +KPX Ydieresis oslash -111 + +KPX Ydieresis otilde -111 + +KPX Ydieresis period -92 + +KPX Ydieresis semicolon -92 + +KPX Ydieresis u -92 + +KPX Ydieresis uacute -92 + +KPX Ydieresis ucircumflex -92 + +KPX Ydieresis udieresis -92 + +KPX Ydieresis ugrave -92 + +KPX Ydieresis uhungarumlaut -92 + +KPX Ydieresis umacron -92 + +KPX Ydieresis uogonek -92 + +KPX Ydieresis uring -92 + +KPX a v -25 + +KPX aacute v -25 + +KPX abreve v -25 + +KPX acircumflex v -25 + +KPX adieresis v -25 + +KPX agrave v -25 + +KPX amacron v -25 + +KPX aogonek v -25 + +KPX aring v -25 + +KPX atilde v -25 + +KPX b b -10 + +KPX b period -40 + +KPX b u -20 + +KPX b uacute -20 + +KPX b ucircumflex -20 + +KPX b udieresis -20 + +KPX b ugrave -20 + +KPX b uhungarumlaut -20 + +KPX b umacron -20 + +KPX b uogonek -20 + +KPX b uring -20 + +KPX b v -15 + +KPX comma quotedblright -45 + +KPX comma quoteright -55 + +KPX d w -15 + +KPX dcroat w -15 + +KPX e v -15 + +KPX eacute v -15 + +KPX ecaron v -15 + +KPX ecircumflex v -15 + +KPX edieresis v -15 + +KPX edotaccent v -15 + +KPX egrave v -15 + +KPX emacron v -15 + +KPX eogonek v -15 + +KPX f comma -15 + +KPX f dotlessi -35 + +KPX f i -25 + +KPX f o -25 + +KPX f oacute -25 + +KPX f ocircumflex -25 + +KPX f odieresis -25 + +KPX f ograve -25 + +KPX f ohungarumlaut -25 + +KPX f omacron -25 + +KPX f oslash -25 + +KPX f otilde -25 + +KPX f period -15 + +KPX f quotedblright 50 + +KPX f quoteright 55 + +KPX g period -15 + +KPX gbreve period -15 + +KPX gcommaaccent period -15 + +KPX h y -15 + +KPX h yacute -15 + +KPX h ydieresis -15 + +KPX i v -10 + +KPX iacute v -10 + +KPX icircumflex v -10 + +KPX idieresis v -10 + +KPX igrave v -10 + +KPX imacron v -10 + +KPX iogonek v -10 + +KPX k e -10 + +KPX k eacute -10 + +KPX k ecaron -10 + +KPX k ecircumflex -10 + +KPX k edieresis -10 + +KPX k edotaccent -10 + +KPX k egrave -10 + +KPX k emacron -10 + +KPX k eogonek -10 + +KPX k o -15 + +KPX k oacute -15 + +KPX k ocircumflex -15 + +KPX k odieresis -15 + +KPX k ograve -15 + +KPX k ohungarumlaut -15 + +KPX k omacron -15 + +KPX k oslash -15 + +KPX k otilde -15 + +KPX k y -15 + +KPX k yacute -15 + +KPX k ydieresis -15 + +KPX kcommaaccent e -10 + +KPX kcommaaccent eacute -10 + +KPX kcommaaccent ecaron -10 + +KPX kcommaaccent ecircumflex -10 + +KPX kcommaaccent edieresis -10 + +KPX kcommaaccent edotaccent -10 + +KPX kcommaaccent egrave -10 + +KPX kcommaaccent emacron -10 + +KPX kcommaaccent eogonek -10 + +KPX kcommaaccent o -15 + +KPX kcommaaccent oacute -15 + +KPX kcommaaccent ocircumflex -15 + +KPX kcommaaccent odieresis -15 + +KPX kcommaaccent ograve -15 + +KPX kcommaaccent ohungarumlaut -15 + +KPX kcommaaccent omacron -15 + +KPX kcommaaccent oslash -15 + +KPX kcommaaccent otilde -15 + +KPX kcommaaccent y -15 + +KPX kcommaaccent yacute -15 + +KPX kcommaaccent ydieresis -15 + +KPX n v -40 + +KPX nacute v -40 + +KPX ncaron v -40 + +KPX ncommaaccent v -40 + +KPX ntilde v -40 + +KPX o v -10 + +KPX o w -10 + +KPX oacute v -10 + +KPX oacute w -10 + +KPX ocircumflex v -10 + +KPX ocircumflex w -10 + +KPX odieresis v -10 + +KPX odieresis w -10 + +KPX ograve v -10 + +KPX ograve w -10 + +KPX ohungarumlaut v -10 + +KPX ohungarumlaut w -10 + +KPX omacron v -10 + +KPX omacron w -10 + +KPX oslash v -10 + +KPX oslash w -10 + +KPX otilde v -10 + +KPX otilde w -10 + +KPX period quotedblright -55 + +KPX period quoteright -55 + +KPX quotedblleft A -10 + +KPX quotedblleft Aacute -10 + +KPX quotedblleft Abreve -10 + +KPX quotedblleft Acircumflex -10 + +KPX quotedblleft Adieresis -10 + +KPX quotedblleft Agrave -10 + +KPX quotedblleft Amacron -10 + +KPX quotedblleft Aogonek -10 + +KPX quotedblleft Aring -10 + +KPX quotedblleft Atilde -10 + +KPX quoteleft A -10 + +KPX quoteleft Aacute -10 + +KPX quoteleft Abreve -10 + +KPX quoteleft Acircumflex -10 + +KPX quoteleft Adieresis -10 + +KPX quoteleft Agrave -10 + +KPX quoteleft Amacron -10 + +KPX quoteleft Aogonek -10 + +KPX quoteleft Aring -10 + +KPX quoteleft Atilde -10 + +KPX quoteleft quoteleft -63 + +KPX quoteright d -20 + +KPX quoteright dcroat -20 + +KPX quoteright quoteright -63 + +KPX quoteright r -20 + +KPX quoteright racute -20 + +KPX quoteright rcaron -20 + +KPX quoteright rcommaaccent -20 + +KPX quoteright s -37 + +KPX quoteright sacute -37 + +KPX quoteright scaron -37 + +KPX quoteright scedilla -37 + +KPX quoteright scommaaccent -37 + +KPX quoteright space -74 + +KPX quoteright v -20 + +KPX r c -18 + +KPX r cacute -18 + +KPX r ccaron -18 + +KPX r ccedilla -18 + +KPX r comma -92 + +KPX r e -18 + +KPX r eacute -18 + +KPX r ecaron -18 + +KPX r ecircumflex -18 + +KPX r edieresis -18 + +KPX r edotaccent -18 + +KPX r egrave -18 + +KPX r emacron -18 + +KPX r eogonek -18 + +KPX r g -10 + +KPX r gbreve -10 + +KPX r gcommaaccent -10 + +KPX r hyphen -37 + +KPX r n -15 + +KPX r nacute -15 + +KPX r ncaron -15 + +KPX r ncommaaccent -15 + +KPX r ntilde -15 + +KPX r o -18 + +KPX r oacute -18 + +KPX r ocircumflex -18 + +KPX r odieresis -18 + +KPX r ograve -18 + +KPX r ohungarumlaut -18 + +KPX r omacron -18 + +KPX r oslash -18 + +KPX r otilde -18 + +KPX r p -10 + +KPX r period -100 + +KPX r q -18 + +KPX r v -10 + +KPX racute c -18 + +KPX racute cacute -18 + +KPX racute ccaron -18 + +KPX racute ccedilla -18 + +KPX racute comma -92 + +KPX racute e -18 + +KPX racute eacute -18 + +KPX racute ecaron -18 + +KPX racute ecircumflex -18 + +KPX racute edieresis -18 + +KPX racute edotaccent -18 + +KPX racute egrave -18 + +KPX racute emacron -18 + +KPX racute eogonek -18 + +KPX racute g -10 + +KPX racute gbreve -10 + +KPX racute gcommaaccent -10 + +KPX racute hyphen -37 + +KPX racute n -15 + +KPX racute nacute -15 + +KPX racute ncaron -15 + +KPX racute ncommaaccent -15 + +KPX racute ntilde -15 + +KPX racute o -18 + +KPX racute oacute -18 + +KPX racute ocircumflex -18 + +KPX racute odieresis -18 + +KPX racute ograve -18 + +KPX racute ohungarumlaut -18 + +KPX racute omacron -18 + +KPX racute oslash -18 + +KPX racute otilde -18 + +KPX racute p -10 + +KPX racute period -100 + +KPX racute q -18 + +KPX racute v -10 + +KPX rcaron c -18 + +KPX rcaron cacute -18 + +KPX rcaron ccaron -18 + +KPX rcaron ccedilla -18 + +KPX rcaron comma -92 + +KPX rcaron e -18 + +KPX rcaron eacute -18 + +KPX rcaron ecaron -18 + +KPX rcaron ecircumflex -18 + +KPX rcaron edieresis -18 + +KPX rcaron edotaccent -18 + +KPX rcaron egrave -18 + +KPX rcaron emacron -18 + +KPX rcaron eogonek -18 + +KPX rcaron g -10 + +KPX rcaron gbreve -10 + +KPX rcaron gcommaaccent -10 + +KPX rcaron hyphen -37 + +KPX rcaron n -15 + +KPX rcaron nacute -15 + +KPX rcaron ncaron -15 + +KPX rcaron ncommaaccent -15 + +KPX rcaron ntilde -15 + +KPX rcaron o -18 + +KPX rcaron oacute -18 + +KPX rcaron ocircumflex -18 + +KPX rcaron odieresis -18 + +KPX rcaron ograve -18 + +KPX rcaron ohungarumlaut -18 + +KPX rcaron omacron -18 + +KPX rcaron oslash -18 + +KPX rcaron otilde -18 + +KPX rcaron p -10 + +KPX rcaron period -100 + +KPX rcaron q -18 + +KPX rcaron v -10 + +KPX rcommaaccent c -18 + +KPX rcommaaccent cacute -18 + +KPX rcommaaccent ccaron -18 + +KPX rcommaaccent ccedilla -18 + +KPX rcommaaccent comma -92 + +KPX rcommaaccent e -18 + +KPX rcommaaccent eacute -18 + +KPX rcommaaccent ecaron -18 + +KPX rcommaaccent ecircumflex -18 + +KPX rcommaaccent edieresis -18 + +KPX rcommaaccent edotaccent -18 + +KPX rcommaaccent egrave -18 + +KPX rcommaaccent emacron -18 + +KPX rcommaaccent eogonek -18 + +KPX rcommaaccent g -10 + +KPX rcommaaccent gbreve -10 + +KPX rcommaaccent gcommaaccent -10 + +KPX rcommaaccent hyphen -37 + +KPX rcommaaccent n -15 + +KPX rcommaaccent nacute -15 + +KPX rcommaaccent ncaron -15 + +KPX rcommaaccent ncommaaccent -15 + +KPX rcommaaccent ntilde -15 + +KPX rcommaaccent o -18 + +KPX rcommaaccent oacute -18 + +KPX rcommaaccent ocircumflex -18 + +KPX rcommaaccent odieresis -18 + +KPX rcommaaccent ograve -18 + +KPX rcommaaccent ohungarumlaut -18 + +KPX rcommaaccent omacron -18 + +KPX rcommaaccent oslash -18 + +KPX rcommaaccent otilde -18 + +KPX rcommaaccent p -10 + +KPX rcommaaccent period -100 + +KPX rcommaaccent q -18 + +KPX rcommaaccent v -10 + +KPX space A -55 + +KPX space Aacute -55 + +KPX space Abreve -55 + +KPX space Acircumflex -55 + +KPX space Adieresis -55 + +KPX space Agrave -55 + +KPX space Amacron -55 + +KPX space Aogonek -55 + +KPX space Aring -55 + +KPX space Atilde -55 + +KPX space T -30 + +KPX space Tcaron -30 + +KPX space Tcommaaccent -30 + +KPX space V -45 + +KPX space W -30 + +KPX space Y -55 + +KPX space Yacute -55 + +KPX space Ydieresis -55 + +KPX v a -10 + +KPX v aacute -10 + +KPX v abreve -10 + +KPX v acircumflex -10 + +KPX v adieresis -10 + +KPX v agrave -10 + +KPX v amacron -10 + +KPX v aogonek -10 + +KPX v aring -10 + +KPX v atilde -10 + +KPX v comma -55 + +KPX v e -10 + +KPX v eacute -10 + +KPX v ecaron -10 + +KPX v ecircumflex -10 + +KPX v edieresis -10 + +KPX v edotaccent -10 + +KPX v egrave -10 + +KPX v emacron -10 + +KPX v eogonek -10 + +KPX v o -10 + +KPX v oacute -10 + +KPX v ocircumflex -10 + +KPX v odieresis -10 + +KPX v ograve -10 + +KPX v ohungarumlaut -10 + +KPX v omacron -10 + +KPX v oslash -10 + +KPX v otilde -10 + +KPX v period -70 + +KPX w comma -55 + +KPX w o -10 + +KPX w oacute -10 + +KPX w ocircumflex -10 + +KPX w odieresis -10 + +KPX w ograve -10 + +KPX w ohungarumlaut -10 + +KPX w omacron -10 + +KPX w oslash -10 + +KPX w otilde -10 + +KPX w period -70 + +KPX y comma -55 + +KPX y e -10 + +KPX y eacute -10 + +KPX y ecaron -10 + +KPX y ecircumflex -10 + +KPX y edieresis -10 + +KPX y edotaccent -10 + +KPX y egrave -10 + +KPX y emacron -10 + +KPX y eogonek -10 + +KPX y o -25 + +KPX y oacute -25 + +KPX y ocircumflex -25 + +KPX y odieresis -25 + +KPX y ograve -25 + +KPX y ohungarumlaut -25 + +KPX y omacron -25 + +KPX y oslash -25 + +KPX y otilde -25 + +KPX y period -70 + +KPX yacute comma -55 + +KPX yacute e -10 + +KPX yacute eacute -10 + +KPX yacute ecaron -10 + +KPX yacute ecircumflex -10 + +KPX yacute edieresis -10 + +KPX yacute edotaccent -10 + +KPX yacute egrave -10 + +KPX yacute emacron -10 + +KPX yacute eogonek -10 + +KPX yacute o -25 + +KPX yacute oacute -25 + +KPX yacute ocircumflex -25 + +KPX yacute odieresis -25 + +KPX yacute ograve -25 + +KPX yacute ohungarumlaut -25 + +KPX yacute omacron -25 + +KPX yacute oslash -25 + +KPX yacute otilde -25 + +KPX yacute period -70 + +KPX ydieresis comma -55 + +KPX ydieresis e -10 + +KPX ydieresis eacute -10 + +KPX ydieresis ecaron -10 + +KPX ydieresis ecircumflex -10 + +KPX ydieresis edieresis -10 + +KPX ydieresis edotaccent -10 + +KPX ydieresis egrave -10 + +KPX ydieresis emacron -10 + +KPX ydieresis eogonek -10 + +KPX ydieresis o -25 + +KPX ydieresis oacute -25 + +KPX ydieresis ocircumflex -25 + +KPX ydieresis odieresis -25 + +KPX ydieresis ograve -25 + +KPX ydieresis ohungarumlaut -25 + +KPX ydieresis omacron -25 + +KPX ydieresis oslash -25 + +KPX ydieresis otilde -25 + +KPX ydieresis period -70 + +EndKernPairs + +EndKernData + +EndFontMetrics + diff --git a/src/Broadside/Fonts/Data/Afm/Times-BoldItalic.afm b/src/Broadside/Fonts/Data/Afm/Times-BoldItalic.afm new file mode 100644 index 00000000..58830dac --- /dev/null +++ b/src/Broadside/Fonts/Data/Afm/Times-BoldItalic.afm @@ -0,0 +1,4768 @@ +StartFontMetrics 4.1 + +Comment Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. + +Comment Creation Date: Thu May 1 13:04:06 1997 + +Comment UniqueID 43066 + +Comment VMusage 45874 56899 + +FontName Times-BoldItalic + +FullName Times Bold Italic + +FamilyName Times + +Weight Bold + +ItalicAngle -15 + +IsFixedPitch false + +CharacterSet ExtendedRoman + +FontBBox -200 -218 996 921 + +UnderlinePosition -100 + +UnderlineThickness 50 + +Version 002.000 + +Notice Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.Times is a trademark of Linotype-Hell AG and/or its subsidiaries. + +EncodingScheme AdobeStandardEncoding + +CapHeight 669 + +XHeight 462 + +Ascender 683 + +Descender -217 + +StdHW 42 + +StdVW 121 + +StartCharMetrics 315 + +C 32 ; WX 250 ; N space ; B 0 0 0 0 ; + +C 33 ; WX 389 ; N exclam ; B 67 -13 370 684 ; + +C 34 ; WX 555 ; N quotedbl ; B 136 398 536 685 ; + +C 35 ; WX 500 ; N numbersign ; B -33 0 533 700 ; + +C 36 ; WX 500 ; N dollar ; B -20 -100 497 733 ; + +C 37 ; WX 833 ; N percent ; B 39 -10 793 692 ; + +C 38 ; WX 778 ; N ampersand ; B 5 -19 699 682 ; + +C 39 ; WX 333 ; N quoteright ; B 98 369 302 685 ; + +C 40 ; WX 333 ; N parenleft ; B 28 -179 344 685 ; + +C 41 ; WX 333 ; N parenright ; B -44 -179 271 685 ; + +C 42 ; WX 500 ; N asterisk ; B 65 249 456 685 ; + +C 43 ; WX 570 ; N plus ; B 33 0 537 506 ; + +C 44 ; WX 250 ; N comma ; B -60 -182 144 134 ; + +C 45 ; WX 333 ; N hyphen ; B 2 166 271 282 ; + +C 46 ; WX 250 ; N period ; B -9 -13 139 135 ; + +C 47 ; WX 278 ; N slash ; B -64 -18 342 685 ; + +C 48 ; WX 500 ; N zero ; B 17 -14 477 683 ; + +C 49 ; WX 500 ; N one ; B 5 0 419 683 ; + +C 50 ; WX 500 ; N two ; B -27 0 446 683 ; + +C 51 ; WX 500 ; N three ; B -15 -13 450 683 ; + +C 52 ; WX 500 ; N four ; B -15 0 503 683 ; + +C 53 ; WX 500 ; N five ; B -11 -13 487 669 ; + +C 54 ; WX 500 ; N six ; B 23 -15 509 679 ; + +C 55 ; WX 500 ; N seven ; B 52 0 525 669 ; + +C 56 ; WX 500 ; N eight ; B 3 -13 476 683 ; + +C 57 ; WX 500 ; N nine ; B -12 -10 475 683 ; + +C 58 ; WX 333 ; N colon ; B 23 -13 264 459 ; + +C 59 ; WX 333 ; N semicolon ; B -25 -183 264 459 ; + +C 60 ; WX 570 ; N less ; B 31 -8 539 514 ; + +C 61 ; WX 570 ; N equal ; B 33 107 537 399 ; + +C 62 ; WX 570 ; N greater ; B 31 -8 539 514 ; + +C 63 ; WX 500 ; N question ; B 79 -13 470 684 ; + +C 64 ; WX 832 ; N at ; B 63 -18 770 685 ; + +C 65 ; WX 667 ; N A ; B -67 0 593 683 ; + +C 66 ; WX 667 ; N B ; B -24 0 624 669 ; + +C 67 ; WX 667 ; N C ; B 32 -18 677 685 ; + +C 68 ; WX 722 ; N D ; B -46 0 685 669 ; + +C 69 ; WX 667 ; N E ; B -27 0 653 669 ; + +C 70 ; WX 667 ; N F ; B -13 0 660 669 ; + +C 71 ; WX 722 ; N G ; B 21 -18 706 685 ; + +C 72 ; WX 778 ; N H ; B -24 0 799 669 ; + +C 73 ; WX 389 ; N I ; B -32 0 406 669 ; + +C 74 ; WX 500 ; N J ; B -46 -99 524 669 ; + +C 75 ; WX 667 ; N K ; B -21 0 702 669 ; + +C 76 ; WX 611 ; N L ; B -22 0 590 669 ; + +C 77 ; WX 889 ; N M ; B -29 -12 917 669 ; + +C 78 ; WX 722 ; N N ; B -27 -15 748 669 ; + +C 79 ; WX 722 ; N O ; B 27 -18 691 685 ; + +C 80 ; WX 611 ; N P ; B -27 0 613 669 ; + +C 81 ; WX 722 ; N Q ; B 27 -208 691 685 ; + +C 82 ; WX 667 ; N R ; B -29 0 623 669 ; + +C 83 ; WX 556 ; N S ; B 2 -18 526 685 ; + +C 84 ; WX 611 ; N T ; B 50 0 650 669 ; + +C 85 ; WX 722 ; N U ; B 67 -18 744 669 ; + +C 86 ; WX 667 ; N V ; B 65 -18 715 669 ; + +C 87 ; WX 889 ; N W ; B 65 -18 940 669 ; + +C 88 ; WX 667 ; N X ; B -24 0 694 669 ; + +C 89 ; WX 611 ; N Y ; B 73 0 659 669 ; + +C 90 ; WX 611 ; N Z ; B -11 0 590 669 ; + +C 91 ; WX 333 ; N bracketleft ; B -37 -159 362 674 ; + +C 92 ; WX 278 ; N backslash ; B -1 -18 279 685 ; + +C 93 ; WX 333 ; N bracketright ; B -56 -157 343 674 ; + +C 94 ; WX 570 ; N asciicircum ; B 67 304 503 669 ; + +C 95 ; WX 500 ; N underscore ; B 0 -125 500 -75 ; + +C 96 ; WX 333 ; N quoteleft ; B 128 369 332 685 ; + +C 97 ; WX 500 ; N a ; B -21 -14 455 462 ; + +C 98 ; WX 500 ; N b ; B -14 -13 444 699 ; + +C 99 ; WX 444 ; N c ; B -5 -13 392 462 ; + +C 100 ; WX 500 ; N d ; B -21 -13 517 699 ; + +C 101 ; WX 444 ; N e ; B 5 -13 398 462 ; + +C 102 ; WX 333 ; N f ; B -169 -205 446 698 ; L i fi ; L l fl ; + +C 103 ; WX 500 ; N g ; B -52 -203 478 462 ; + +C 104 ; WX 556 ; N h ; B -13 -9 498 699 ; + +C 105 ; WX 278 ; N i ; B 2 -9 263 684 ; + +C 106 ; WX 278 ; N j ; B -189 -207 279 684 ; + +C 107 ; WX 500 ; N k ; B -23 -8 483 699 ; + +C 108 ; WX 278 ; N l ; B 2 -9 290 699 ; + +C 109 ; WX 778 ; N m ; B -14 -9 722 462 ; + +C 110 ; WX 556 ; N n ; B -6 -9 493 462 ; + +C 111 ; WX 500 ; N o ; B -3 -13 441 462 ; + +C 112 ; WX 500 ; N p ; B -120 -205 446 462 ; + +C 113 ; WX 500 ; N q ; B 1 -205 471 462 ; + +C 114 ; WX 389 ; N r ; B -21 0 389 462 ; + +C 115 ; WX 389 ; N s ; B -19 -13 333 462 ; + +C 116 ; WX 278 ; N t ; B -11 -9 281 594 ; + +C 117 ; WX 556 ; N u ; B 15 -9 492 462 ; + +C 118 ; WX 444 ; N v ; B 16 -13 401 462 ; + +C 119 ; WX 667 ; N w ; B 16 -13 614 462 ; + +C 120 ; WX 500 ; N x ; B -46 -13 469 462 ; + +C 121 ; WX 444 ; N y ; B -94 -205 392 462 ; + +C 122 ; WX 389 ; N z ; B -43 -78 368 449 ; + +C 123 ; WX 348 ; N braceleft ; B 5 -187 436 686 ; + +C 124 ; WX 220 ; N bar ; B 66 -218 154 782 ; + +C 125 ; WX 348 ; N braceright ; B -129 -187 302 686 ; + +C 126 ; WX 570 ; N asciitilde ; B 54 173 516 333 ; + +C 161 ; WX 389 ; N exclamdown ; B 19 -205 322 492 ; + +C 162 ; WX 500 ; N cent ; B 42 -143 439 576 ; + +C 163 ; WX 500 ; N sterling ; B -32 -12 510 683 ; + +C 164 ; WX 167 ; N fraction ; B -169 -14 324 683 ; + +C 165 ; WX 500 ; N yen ; B 33 0 628 669 ; + +C 166 ; WX 500 ; N florin ; B -87 -156 537 707 ; + +C 167 ; WX 500 ; N section ; B 36 -143 459 685 ; + +C 168 ; WX 500 ; N currency ; B -26 34 526 586 ; + +C 169 ; WX 278 ; N quotesingle ; B 128 398 268 685 ; + +C 170 ; WX 500 ; N quotedblleft ; B 53 369 513 685 ; + +C 171 ; WX 500 ; N guillemotleft ; B 12 32 468 415 ; + +C 172 ; WX 333 ; N guilsinglleft ; B 32 32 303 415 ; + +C 173 ; WX 333 ; N guilsinglright ; B 10 32 281 415 ; + +C 174 ; WX 556 ; N fi ; B -188 -205 514 703 ; + +C 175 ; WX 556 ; N fl ; B -186 -205 553 704 ; + +C 177 ; WX 500 ; N endash ; B -40 178 477 269 ; + +C 178 ; WX 500 ; N dagger ; B 91 -145 494 685 ; + +C 179 ; WX 500 ; N daggerdbl ; B 10 -139 493 685 ; + +C 180 ; WX 250 ; N periodcentered ; B 51 257 199 405 ; + +C 182 ; WX 500 ; N paragraph ; B -57 -193 562 669 ; + +C 183 ; WX 350 ; N bullet ; B 0 175 350 525 ; + +C 184 ; WX 333 ; N quotesinglbase ; B -5 -182 199 134 ; + +C 185 ; WX 500 ; N quotedblbase ; B -57 -182 403 134 ; + +C 186 ; WX 500 ; N quotedblright ; B 53 369 513 685 ; + +C 187 ; WX 500 ; N guillemotright ; B 12 32 468 415 ; + +C 188 ; WX 1000 ; N ellipsis ; B 40 -13 852 135 ; + +C 189 ; WX 1000 ; N perthousand ; B 7 -29 996 706 ; + +C 191 ; WX 500 ; N questiondown ; B 30 -205 421 492 ; + +C 193 ; WX 333 ; N grave ; B 85 516 297 697 ; + +C 194 ; WX 333 ; N acute ; B 139 516 379 697 ; + +C 195 ; WX 333 ; N circumflex ; B 40 516 367 690 ; + +C 196 ; WX 333 ; N tilde ; B 48 536 407 655 ; + +C 197 ; WX 333 ; N macron ; B 51 553 393 623 ; + +C 198 ; WX 333 ; N breve ; B 71 516 387 678 ; + +C 199 ; WX 333 ; N dotaccent ; B 163 550 298 684 ; + +C 200 ; WX 333 ; N dieresis ; B 55 550 402 684 ; + +C 202 ; WX 333 ; N ring ; B 127 516 340 729 ; + +C 203 ; WX 333 ; N cedilla ; B -80 -218 156 5 ; + +C 205 ; WX 333 ; N hungarumlaut ; B 69 516 498 697 ; + +C 206 ; WX 333 ; N ogonek ; B 15 -183 244 34 ; + +C 207 ; WX 333 ; N caron ; B 79 516 411 690 ; + +C 208 ; WX 1000 ; N emdash ; B -40 178 977 269 ; + +C 225 ; WX 944 ; N AE ; B -64 0 918 669 ; + +C 227 ; WX 266 ; N ordfeminine ; B 16 399 330 685 ; + +C 232 ; WX 611 ; N Lslash ; B -22 0 590 669 ; + +C 233 ; WX 722 ; N Oslash ; B 27 -125 691 764 ; + +C 234 ; WX 944 ; N OE ; B 23 -8 946 677 ; + +C 235 ; WX 300 ; N ordmasculine ; B 56 400 347 685 ; + +C 241 ; WX 722 ; N ae ; B -5 -13 673 462 ; + +C 245 ; WX 278 ; N dotlessi ; B 2 -9 238 462 ; + +C 248 ; WX 278 ; N lslash ; B -7 -9 307 699 ; + +C 249 ; WX 500 ; N oslash ; B -3 -119 441 560 ; + +C 250 ; WX 722 ; N oe ; B 6 -13 674 462 ; + +C 251 ; WX 500 ; N germandbls ; B -200 -200 473 705 ; + +C -1 ; WX 389 ; N Idieresis ; B -32 0 450 862 ; + +C -1 ; WX 444 ; N eacute ; B 5 -13 435 697 ; + +C -1 ; WX 500 ; N abreve ; B -21 -14 471 678 ; + +C -1 ; WX 556 ; N uhungarumlaut ; B 15 -9 610 697 ; + +C -1 ; WX 444 ; N ecaron ; B 5 -13 467 690 ; + +C -1 ; WX 611 ; N Ydieresis ; B 73 0 659 862 ; + +C -1 ; WX 570 ; N divide ; B 33 -29 537 535 ; + +C -1 ; WX 611 ; N Yacute ; B 73 0 659 904 ; + +C -1 ; WX 667 ; N Acircumflex ; B -67 0 593 897 ; + +C -1 ; WX 500 ; N aacute ; B -21 -14 463 697 ; + +C -1 ; WX 722 ; N Ucircumflex ; B 67 -18 744 897 ; + +C -1 ; WX 444 ; N yacute ; B -94 -205 435 697 ; + +C -1 ; WX 389 ; N scommaaccent ; B -19 -218 333 462 ; + +C -1 ; WX 444 ; N ecircumflex ; B 5 -13 423 690 ; + +C -1 ; WX 722 ; N Uring ; B 67 -18 744 921 ; + +C -1 ; WX 722 ; N Udieresis ; B 67 -18 744 862 ; + +C -1 ; WX 500 ; N aogonek ; B -21 -183 455 462 ; + +C -1 ; WX 722 ; N Uacute ; B 67 -18 744 904 ; + +C -1 ; WX 556 ; N uogonek ; B 15 -183 492 462 ; + +C -1 ; WX 667 ; N Edieresis ; B -27 0 653 862 ; + +C -1 ; WX 722 ; N Dcroat ; B -31 0 700 669 ; + +C -1 ; WX 250 ; N commaaccent ; B -36 -218 131 -50 ; + +C -1 ; WX 747 ; N copyright ; B 30 -18 718 685 ; + +C -1 ; WX 667 ; N Emacron ; B -27 0 653 830 ; + +C -1 ; WX 444 ; N ccaron ; B -5 -13 467 690 ; + +C -1 ; WX 500 ; N aring ; B -21 -14 455 729 ; + +C -1 ; WX 722 ; N Ncommaaccent ; B -27 -218 748 669 ; + +C -1 ; WX 278 ; N lacute ; B 2 -9 392 904 ; + +C -1 ; WX 500 ; N agrave ; B -21 -14 455 697 ; + +C -1 ; WX 611 ; N Tcommaaccent ; B 50 -218 650 669 ; + +C -1 ; WX 667 ; N Cacute ; B 32 -18 677 904 ; + +C -1 ; WX 500 ; N atilde ; B -21 -14 491 655 ; + +C -1 ; WX 667 ; N Edotaccent ; B -27 0 653 862 ; + +C -1 ; WX 389 ; N scaron ; B -19 -13 424 690 ; + +C -1 ; WX 389 ; N scedilla ; B -19 -218 333 462 ; + +C -1 ; WX 278 ; N iacute ; B 2 -9 352 697 ; + +C -1 ; WX 494 ; N lozenge ; B 10 0 484 745 ; + +C -1 ; WX 667 ; N Rcaron ; B -29 0 623 897 ; + +C -1 ; WX 722 ; N Gcommaaccent ; B 21 -218 706 685 ; + +C -1 ; WX 556 ; N ucircumflex ; B 15 -9 492 690 ; + +C -1 ; WX 500 ; N acircumflex ; B -21 -14 455 690 ; + +C -1 ; WX 667 ; N Amacron ; B -67 0 593 830 ; + +C -1 ; WX 389 ; N rcaron ; B -21 0 424 690 ; + +C -1 ; WX 444 ; N ccedilla ; B -5 -218 392 462 ; + +C -1 ; WX 611 ; N Zdotaccent ; B -11 0 590 862 ; + +C -1 ; WX 611 ; N Thorn ; B -27 0 573 669 ; + +C -1 ; WX 722 ; N Omacron ; B 27 -18 691 830 ; + +C -1 ; WX 667 ; N Racute ; B -29 0 623 904 ; + +C -1 ; WX 556 ; N Sacute ; B 2 -18 531 904 ; + +C -1 ; WX 608 ; N dcaron ; B -21 -13 675 708 ; + +C -1 ; WX 722 ; N Umacron ; B 67 -18 744 830 ; + +C -1 ; WX 556 ; N uring ; B 15 -9 492 729 ; + +C -1 ; WX 300 ; N threesuperior ; B 17 265 321 683 ; + +C -1 ; WX 722 ; N Ograve ; B 27 -18 691 904 ; + +C -1 ; WX 667 ; N Agrave ; B -67 0 593 904 ; + +C -1 ; WX 667 ; N Abreve ; B -67 0 593 885 ; + +C -1 ; WX 570 ; N multiply ; B 48 16 522 490 ; + +C -1 ; WX 556 ; N uacute ; B 15 -9 492 697 ; + +C -1 ; WX 611 ; N Tcaron ; B 50 0 650 897 ; + +C -1 ; WX 494 ; N partialdiff ; B 11 -21 494 750 ; + +C -1 ; WX 444 ; N ydieresis ; B -94 -205 443 655 ; + +C -1 ; WX 722 ; N Nacute ; B -27 -15 748 904 ; + +C -1 ; WX 278 ; N icircumflex ; B -3 -9 324 690 ; + +C -1 ; WX 667 ; N Ecircumflex ; B -27 0 653 897 ; + +C -1 ; WX 500 ; N adieresis ; B -21 -14 476 655 ; + +C -1 ; WX 444 ; N edieresis ; B 5 -13 448 655 ; + +C -1 ; WX 444 ; N cacute ; B -5 -13 435 697 ; + +C -1 ; WX 556 ; N nacute ; B -6 -9 493 697 ; + +C -1 ; WX 556 ; N umacron ; B 15 -9 492 623 ; + +C -1 ; WX 722 ; N Ncaron ; B -27 -15 748 897 ; + +C -1 ; WX 389 ; N Iacute ; B -32 0 432 904 ; + +C -1 ; WX 570 ; N plusminus ; B 33 0 537 506 ; + +C -1 ; WX 220 ; N brokenbar ; B 66 -143 154 707 ; + +C -1 ; WX 747 ; N registered ; B 30 -18 718 685 ; + +C -1 ; WX 722 ; N Gbreve ; B 21 -18 706 885 ; + +C -1 ; WX 389 ; N Idotaccent ; B -32 0 406 862 ; + +C -1 ; WX 600 ; N summation ; B 14 -10 585 706 ; + +C -1 ; WX 667 ; N Egrave ; B -27 0 653 904 ; + +C -1 ; WX 389 ; N racute ; B -21 0 407 697 ; + +C -1 ; WX 500 ; N omacron ; B -3 -13 462 623 ; + +C -1 ; WX 611 ; N Zacute ; B -11 0 590 904 ; + +C -1 ; WX 611 ; N Zcaron ; B -11 0 590 897 ; + +C -1 ; WX 549 ; N greaterequal ; B 26 0 523 704 ; + +C -1 ; WX 722 ; N Eth ; B -31 0 700 669 ; + +C -1 ; WX 667 ; N Ccedilla ; B 32 -218 677 685 ; + +C -1 ; WX 278 ; N lcommaaccent ; B -42 -218 290 699 ; + +C -1 ; WX 366 ; N tcaron ; B -11 -9 434 754 ; + +C -1 ; WX 444 ; N eogonek ; B 5 -183 398 462 ; + +C -1 ; WX 722 ; N Uogonek ; B 67 -183 744 669 ; + +C -1 ; WX 667 ; N Aacute ; B -67 0 593 904 ; + +C -1 ; WX 667 ; N Adieresis ; B -67 0 593 862 ; + +C -1 ; WX 444 ; N egrave ; B 5 -13 398 697 ; + +C -1 ; WX 389 ; N zacute ; B -43 -78 407 697 ; + +C -1 ; WX 278 ; N iogonek ; B -20 -183 263 684 ; + +C -1 ; WX 722 ; N Oacute ; B 27 -18 691 904 ; + +C -1 ; WX 500 ; N oacute ; B -3 -13 463 697 ; + +C -1 ; WX 500 ; N amacron ; B -21 -14 467 623 ; + +C -1 ; WX 389 ; N sacute ; B -19 -13 407 697 ; + +C -1 ; WX 278 ; N idieresis ; B 2 -9 364 655 ; + +C -1 ; WX 722 ; N Ocircumflex ; B 27 -18 691 897 ; + +C -1 ; WX 722 ; N Ugrave ; B 67 -18 744 904 ; + +C -1 ; WX 612 ; N Delta ; B 6 0 608 688 ; + +C -1 ; WX 500 ; N thorn ; B -120 -205 446 699 ; + +C -1 ; WX 300 ; N twosuperior ; B 2 274 313 683 ; + +C -1 ; WX 722 ; N Odieresis ; B 27 -18 691 862 ; + +C -1 ; WX 576 ; N mu ; B -60 -207 516 449 ; + +C -1 ; WX 278 ; N igrave ; B 2 -9 259 697 ; + +C -1 ; WX 500 ; N ohungarumlaut ; B -3 -13 582 697 ; + +C -1 ; WX 667 ; N Eogonek ; B -27 -183 653 669 ; + +C -1 ; WX 500 ; N dcroat ; B -21 -13 552 699 ; + +C -1 ; WX 750 ; N threequarters ; B 7 -14 726 683 ; + +C -1 ; WX 556 ; N Scedilla ; B 2 -218 526 685 ; + +C -1 ; WX 382 ; N lcaron ; B 2 -9 448 708 ; + +C -1 ; WX 667 ; N Kcommaaccent ; B -21 -218 702 669 ; + +C -1 ; WX 611 ; N Lacute ; B -22 0 590 904 ; + +C -1 ; WX 1000 ; N trademark ; B 32 263 968 669 ; + +C -1 ; WX 444 ; N edotaccent ; B 5 -13 398 655 ; + +C -1 ; WX 389 ; N Igrave ; B -32 0 406 904 ; + +C -1 ; WX 389 ; N Imacron ; B -32 0 461 830 ; + +C -1 ; WX 611 ; N Lcaron ; B -22 0 671 718 ; + +C -1 ; WX 750 ; N onehalf ; B -9 -14 723 683 ; + +C -1 ; WX 549 ; N lessequal ; B 29 0 526 704 ; + +C -1 ; WX 500 ; N ocircumflex ; B -3 -13 451 690 ; + +C -1 ; WX 556 ; N ntilde ; B -6 -9 504 655 ; + +C -1 ; WX 722 ; N Uhungarumlaut ; B 67 -18 744 904 ; + +C -1 ; WX 667 ; N Eacute ; B -27 0 653 904 ; + +C -1 ; WX 444 ; N emacron ; B 5 -13 439 623 ; + +C -1 ; WX 500 ; N gbreve ; B -52 -203 478 678 ; + +C -1 ; WX 750 ; N onequarter ; B 7 -14 721 683 ; + +C -1 ; WX 556 ; N Scaron ; B 2 -18 553 897 ; + +C -1 ; WX 556 ; N Scommaaccent ; B 2 -218 526 685 ; + +C -1 ; WX 722 ; N Ohungarumlaut ; B 27 -18 723 904 ; + +C -1 ; WX 400 ; N degree ; B 83 397 369 683 ; + +C -1 ; WX 500 ; N ograve ; B -3 -13 441 697 ; + +C -1 ; WX 667 ; N Ccaron ; B 32 -18 677 897 ; + +C -1 ; WX 556 ; N ugrave ; B 15 -9 492 697 ; + +C -1 ; WX 549 ; N radical ; B 10 -46 512 850 ; + +C -1 ; WX 722 ; N Dcaron ; B -46 0 685 897 ; + +C -1 ; WX 389 ; N rcommaaccent ; B -67 -218 389 462 ; + +C -1 ; WX 722 ; N Ntilde ; B -27 -15 748 862 ; + +C -1 ; WX 500 ; N otilde ; B -3 -13 491 655 ; + +C -1 ; WX 667 ; N Rcommaaccent ; B -29 -218 623 669 ; + +C -1 ; WX 611 ; N Lcommaaccent ; B -22 -218 590 669 ; + +C -1 ; WX 667 ; N Atilde ; B -67 0 593 862 ; + +C -1 ; WX 667 ; N Aogonek ; B -67 -183 604 683 ; + +C -1 ; WX 667 ; N Aring ; B -67 0 593 921 ; + +C -1 ; WX 722 ; N Otilde ; B 27 -18 691 862 ; + +C -1 ; WX 389 ; N zdotaccent ; B -43 -78 368 655 ; + +C -1 ; WX 667 ; N Ecaron ; B -27 0 653 897 ; + +C -1 ; WX 389 ; N Iogonek ; B -32 -183 406 669 ; + +C -1 ; WX 500 ; N kcommaaccent ; B -23 -218 483 699 ; + +C -1 ; WX 606 ; N minus ; B 51 209 555 297 ; + +C -1 ; WX 389 ; N Icircumflex ; B -32 0 450 897 ; + +C -1 ; WX 556 ; N ncaron ; B -6 -9 523 690 ; + +C -1 ; WX 278 ; N tcommaaccent ; B -62 -218 281 594 ; + +C -1 ; WX 606 ; N logicalnot ; B 51 108 555 399 ; + +C -1 ; WX 500 ; N odieresis ; B -3 -13 471 655 ; + +C -1 ; WX 556 ; N udieresis ; B 15 -9 499 655 ; + +C -1 ; WX 549 ; N notequal ; B 15 -49 540 570 ; + +C -1 ; WX 500 ; N gcommaaccent ; B -52 -203 478 767 ; + +C -1 ; WX 500 ; N eth ; B -3 -13 454 699 ; + +C -1 ; WX 389 ; N zcaron ; B -43 -78 424 690 ; + +C -1 ; WX 556 ; N ncommaaccent ; B -6 -218 493 462 ; + +C -1 ; WX 300 ; N onesuperior ; B 30 274 301 683 ; + +C -1 ; WX 278 ; N imacron ; B 2 -9 294 623 ; + +C -1 ; WX 500 ; N Euro ; B 0 0 0 0 ; + +EndCharMetrics + +StartKernData + +StartKernPairs 2038 + +KPX A C -65 + +KPX A Cacute -65 + +KPX A Ccaron -65 + +KPX A Ccedilla -65 + +KPX A G -60 + +KPX A Gbreve -60 + +KPX A Gcommaaccent -60 + +KPX A O -50 + +KPX A Oacute -50 + +KPX A Ocircumflex -50 + +KPX A Odieresis -50 + +KPX A Ograve -50 + +KPX A Ohungarumlaut -50 + +KPX A Omacron -50 + +KPX A Oslash -50 + +KPX A Otilde -50 + +KPX A Q -55 + +KPX A T -55 + +KPX A Tcaron -55 + +KPX A Tcommaaccent -55 + +KPX A U -50 + +KPX A Uacute -50 + +KPX A Ucircumflex -50 + +KPX A Udieresis -50 + +KPX A Ugrave -50 + +KPX A Uhungarumlaut -50 + +KPX A Umacron -50 + +KPX A Uogonek -50 + +KPX A Uring -50 + +KPX A V -95 + +KPX A W -100 + +KPX A Y -70 + +KPX A Yacute -70 + +KPX A Ydieresis -70 + +KPX A quoteright -74 + +KPX A u -30 + +KPX A uacute -30 + +KPX A ucircumflex -30 + +KPX A udieresis -30 + +KPX A ugrave -30 + +KPX A uhungarumlaut -30 + +KPX A umacron -30 + +KPX A uogonek -30 + +KPX A uring -30 + +KPX A v -74 + +KPX A w -74 + +KPX A y -74 + +KPX A yacute -74 + +KPX A ydieresis -74 + +KPX Aacute C -65 + +KPX Aacute Cacute -65 + +KPX Aacute Ccaron -65 + +KPX Aacute Ccedilla -65 + +KPX Aacute G -60 + +KPX Aacute Gbreve -60 + +KPX Aacute Gcommaaccent -60 + +KPX Aacute O -50 + +KPX Aacute Oacute -50 + +KPX Aacute Ocircumflex -50 + +KPX Aacute Odieresis -50 + +KPX Aacute Ograve -50 + +KPX Aacute Ohungarumlaut -50 + +KPX Aacute Omacron -50 + +KPX Aacute Oslash -50 + +KPX Aacute Otilde -50 + +KPX Aacute Q -55 + +KPX Aacute T -55 + +KPX Aacute Tcaron -55 + +KPX Aacute Tcommaaccent -55 + +KPX Aacute U -50 + +KPX Aacute Uacute -50 + +KPX Aacute Ucircumflex -50 + +KPX Aacute Udieresis -50 + +KPX Aacute Ugrave -50 + +KPX Aacute Uhungarumlaut -50 + +KPX Aacute Umacron -50 + +KPX Aacute Uogonek -50 + +KPX Aacute Uring -50 + +KPX Aacute V -95 + +KPX Aacute W -100 + +KPX Aacute Y -70 + +KPX Aacute Yacute -70 + +KPX Aacute Ydieresis -70 + +KPX Aacute quoteright -74 + +KPX Aacute u -30 + +KPX Aacute uacute -30 + +KPX Aacute ucircumflex -30 + +KPX Aacute udieresis -30 + +KPX Aacute ugrave -30 + +KPX Aacute uhungarumlaut -30 + +KPX Aacute umacron -30 + +KPX Aacute uogonek -30 + +KPX Aacute uring -30 + +KPX Aacute v -74 + +KPX Aacute w -74 + +KPX Aacute y -74 + +KPX Aacute yacute -74 + +KPX Aacute ydieresis -74 + +KPX Abreve C -65 + +KPX Abreve Cacute -65 + +KPX Abreve Ccaron -65 + +KPX Abreve Ccedilla -65 + +KPX Abreve G -60 + +KPX Abreve Gbreve -60 + +KPX Abreve Gcommaaccent -60 + +KPX Abreve O -50 + +KPX Abreve Oacute -50 + +KPX Abreve Ocircumflex -50 + +KPX Abreve Odieresis -50 + +KPX Abreve Ograve -50 + +KPX Abreve Ohungarumlaut -50 + +KPX Abreve Omacron -50 + +KPX Abreve Oslash -50 + +KPX Abreve Otilde -50 + +KPX Abreve Q -55 + +KPX Abreve T -55 + +KPX Abreve Tcaron -55 + +KPX Abreve Tcommaaccent -55 + +KPX Abreve U -50 + +KPX Abreve Uacute -50 + +KPX Abreve Ucircumflex -50 + +KPX Abreve Udieresis -50 + +KPX Abreve Ugrave -50 + +KPX Abreve Uhungarumlaut -50 + +KPX Abreve Umacron -50 + +KPX Abreve Uogonek -50 + +KPX Abreve Uring -50 + +KPX Abreve V -95 + +KPX Abreve W -100 + +KPX Abreve Y -70 + +KPX Abreve Yacute -70 + +KPX Abreve Ydieresis -70 + +KPX Abreve quoteright -74 + +KPX Abreve u -30 + +KPX Abreve uacute -30 + +KPX Abreve ucircumflex -30 + +KPX Abreve udieresis -30 + +KPX Abreve ugrave -30 + +KPX Abreve uhungarumlaut -30 + +KPX Abreve umacron -30 + +KPX Abreve uogonek -30 + +KPX Abreve uring -30 + +KPX Abreve v -74 + +KPX Abreve w -74 + +KPX Abreve y -74 + +KPX Abreve yacute -74 + +KPX Abreve ydieresis -74 + +KPX Acircumflex C -65 + +KPX Acircumflex Cacute -65 + +KPX Acircumflex Ccaron -65 + +KPX Acircumflex Ccedilla -65 + +KPX Acircumflex G -60 + +KPX Acircumflex Gbreve -60 + +KPX Acircumflex Gcommaaccent -60 + +KPX Acircumflex O -50 + +KPX Acircumflex Oacute -50 + +KPX Acircumflex Ocircumflex -50 + +KPX Acircumflex Odieresis -50 + +KPX Acircumflex Ograve -50 + +KPX Acircumflex Ohungarumlaut -50 + +KPX Acircumflex Omacron -50 + +KPX Acircumflex Oslash -50 + +KPX Acircumflex Otilde -50 + +KPX Acircumflex Q -55 + +KPX Acircumflex T -55 + +KPX Acircumflex Tcaron -55 + +KPX Acircumflex Tcommaaccent -55 + +KPX Acircumflex U -50 + +KPX Acircumflex Uacute -50 + +KPX Acircumflex Ucircumflex -50 + +KPX Acircumflex Udieresis -50 + +KPX Acircumflex Ugrave -50 + +KPX Acircumflex Uhungarumlaut -50 + +KPX Acircumflex Umacron -50 + +KPX Acircumflex Uogonek -50 + +KPX Acircumflex Uring -50 + +KPX Acircumflex V -95 + +KPX Acircumflex W -100 + +KPX Acircumflex Y -70 + +KPX Acircumflex Yacute -70 + +KPX Acircumflex Ydieresis -70 + +KPX Acircumflex quoteright -74 + +KPX Acircumflex u -30 + +KPX Acircumflex uacute -30 + +KPX Acircumflex ucircumflex -30 + +KPX Acircumflex udieresis -30 + +KPX Acircumflex ugrave -30 + +KPX Acircumflex uhungarumlaut -30 + +KPX Acircumflex umacron -30 + +KPX Acircumflex uogonek -30 + +KPX Acircumflex uring -30 + +KPX Acircumflex v -74 + +KPX Acircumflex w -74 + +KPX Acircumflex y -74 + +KPX Acircumflex yacute -74 + +KPX Acircumflex ydieresis -74 + +KPX Adieresis C -65 + +KPX Adieresis Cacute -65 + +KPX Adieresis Ccaron -65 + +KPX Adieresis Ccedilla -65 + +KPX Adieresis G -60 + +KPX Adieresis Gbreve -60 + +KPX Adieresis Gcommaaccent -60 + +KPX Adieresis O -50 + +KPX Adieresis Oacute -50 + +KPX Adieresis Ocircumflex -50 + +KPX Adieresis Odieresis -50 + +KPX Adieresis Ograve -50 + +KPX Adieresis Ohungarumlaut -50 + +KPX Adieresis Omacron -50 + +KPX Adieresis Oslash -50 + +KPX Adieresis Otilde -50 + +KPX Adieresis Q -55 + +KPX Adieresis T -55 + +KPX Adieresis Tcaron -55 + +KPX Adieresis Tcommaaccent -55 + +KPX Adieresis U -50 + +KPX Adieresis Uacute -50 + +KPX Adieresis Ucircumflex -50 + +KPX Adieresis Udieresis -50 + +KPX Adieresis Ugrave -50 + +KPX Adieresis Uhungarumlaut -50 + +KPX Adieresis Umacron -50 + +KPX Adieresis Uogonek -50 + +KPX Adieresis Uring -50 + +KPX Adieresis V -95 + +KPX Adieresis W -100 + +KPX Adieresis Y -70 + +KPX Adieresis Yacute -70 + +KPX Adieresis Ydieresis -70 + +KPX Adieresis quoteright -74 + +KPX Adieresis u -30 + +KPX Adieresis uacute -30 + +KPX Adieresis ucircumflex -30 + +KPX Adieresis udieresis -30 + +KPX Adieresis ugrave -30 + +KPX Adieresis uhungarumlaut -30 + +KPX Adieresis umacron -30 + +KPX Adieresis uogonek -30 + +KPX Adieresis uring -30 + +KPX Adieresis v -74 + +KPX Adieresis w -74 + +KPX Adieresis y -74 + +KPX Adieresis yacute -74 + +KPX Adieresis ydieresis -74 + +KPX Agrave C -65 + +KPX Agrave Cacute -65 + +KPX Agrave Ccaron -65 + +KPX Agrave Ccedilla -65 + +KPX Agrave G -60 + +KPX Agrave Gbreve -60 + +KPX Agrave Gcommaaccent -60 + +KPX Agrave O -50 + +KPX Agrave Oacute -50 + +KPX Agrave Ocircumflex -50 + +KPX Agrave Odieresis -50 + +KPX Agrave Ograve -50 + +KPX Agrave Ohungarumlaut -50 + +KPX Agrave Omacron -50 + +KPX Agrave Oslash -50 + +KPX Agrave Otilde -50 + +KPX Agrave Q -55 + +KPX Agrave T -55 + +KPX Agrave Tcaron -55 + +KPX Agrave Tcommaaccent -55 + +KPX Agrave U -50 + +KPX Agrave Uacute -50 + +KPX Agrave Ucircumflex -50 + +KPX Agrave Udieresis -50 + +KPX Agrave Ugrave -50 + +KPX Agrave Uhungarumlaut -50 + +KPX Agrave Umacron -50 + +KPX Agrave Uogonek -50 + +KPX Agrave Uring -50 + +KPX Agrave V -95 + +KPX Agrave W -100 + +KPX Agrave Y -70 + +KPX Agrave Yacute -70 + +KPX Agrave Ydieresis -70 + +KPX Agrave quoteright -74 + +KPX Agrave u -30 + +KPX Agrave uacute -30 + +KPX Agrave ucircumflex -30 + +KPX Agrave udieresis -30 + +KPX Agrave ugrave -30 + +KPX Agrave uhungarumlaut -30 + +KPX Agrave umacron -30 + +KPX Agrave uogonek -30 + +KPX Agrave uring -30 + +KPX Agrave v -74 + +KPX Agrave w -74 + +KPX Agrave y -74 + +KPX Agrave yacute -74 + +KPX Agrave ydieresis -74 + +KPX Amacron C -65 + +KPX Amacron Cacute -65 + +KPX Amacron Ccaron -65 + +KPX Amacron Ccedilla -65 + +KPX Amacron G -60 + +KPX Amacron Gbreve -60 + +KPX Amacron Gcommaaccent -60 + +KPX Amacron O -50 + +KPX Amacron Oacute -50 + +KPX Amacron Ocircumflex -50 + +KPX Amacron Odieresis -50 + +KPX Amacron Ograve -50 + +KPX Amacron Ohungarumlaut -50 + +KPX Amacron Omacron -50 + +KPX Amacron Oslash -50 + +KPX Amacron Otilde -50 + +KPX Amacron Q -55 + +KPX Amacron T -55 + +KPX Amacron Tcaron -55 + +KPX Amacron Tcommaaccent -55 + +KPX Amacron U -50 + +KPX Amacron Uacute -50 + +KPX Amacron Ucircumflex -50 + +KPX Amacron Udieresis -50 + +KPX Amacron Ugrave -50 + +KPX Amacron Uhungarumlaut -50 + +KPX Amacron Umacron -50 + +KPX Amacron Uogonek -50 + +KPX Amacron Uring -50 + +KPX Amacron V -95 + +KPX Amacron W -100 + +KPX Amacron Y -70 + +KPX Amacron Yacute -70 + +KPX Amacron Ydieresis -70 + +KPX Amacron quoteright -74 + +KPX Amacron u -30 + +KPX Amacron uacute -30 + +KPX Amacron ucircumflex -30 + +KPX Amacron udieresis -30 + +KPX Amacron ugrave -30 + +KPX Amacron uhungarumlaut -30 + +KPX Amacron umacron -30 + +KPX Amacron uogonek -30 + +KPX Amacron uring -30 + +KPX Amacron v -74 + +KPX Amacron w -74 + +KPX Amacron y -74 + +KPX Amacron yacute -74 + +KPX Amacron ydieresis -74 + +KPX Aogonek C -65 + +KPX Aogonek Cacute -65 + +KPX Aogonek Ccaron -65 + +KPX Aogonek Ccedilla -65 + +KPX Aogonek G -60 + +KPX Aogonek Gbreve -60 + +KPX Aogonek Gcommaaccent -60 + +KPX Aogonek O -50 + +KPX Aogonek Oacute -50 + +KPX Aogonek Ocircumflex -50 + +KPX Aogonek Odieresis -50 + +KPX Aogonek Ograve -50 + +KPX Aogonek Ohungarumlaut -50 + +KPX Aogonek Omacron -50 + +KPX Aogonek Oslash -50 + +KPX Aogonek Otilde -50 + +KPX Aogonek Q -55 + +KPX Aogonek T -55 + +KPX Aogonek Tcaron -55 + +KPX Aogonek Tcommaaccent -55 + +KPX Aogonek U -50 + +KPX Aogonek Uacute -50 + +KPX Aogonek Ucircumflex -50 + +KPX Aogonek Udieresis -50 + +KPX Aogonek Ugrave -50 + +KPX Aogonek Uhungarumlaut -50 + +KPX Aogonek Umacron -50 + +KPX Aogonek Uogonek -50 + +KPX Aogonek Uring -50 + +KPX Aogonek V -95 + +KPX Aogonek W -100 + +KPX Aogonek Y -70 + +KPX Aogonek Yacute -70 + +KPX Aogonek Ydieresis -70 + +KPX Aogonek quoteright -74 + +KPX Aogonek u -30 + +KPX Aogonek uacute -30 + +KPX Aogonek ucircumflex -30 + +KPX Aogonek udieresis -30 + +KPX Aogonek ugrave -30 + +KPX Aogonek uhungarumlaut -30 + +KPX Aogonek umacron -30 + +KPX Aogonek uogonek -30 + +KPX Aogonek uring -30 + +KPX Aogonek v -74 + +KPX Aogonek w -74 + +KPX Aogonek y -34 + +KPX Aogonek yacute -34 + +KPX Aogonek ydieresis -34 + +KPX Aring C -65 + +KPX Aring Cacute -65 + +KPX Aring Ccaron -65 + +KPX Aring Ccedilla -65 + +KPX Aring G -60 + +KPX Aring Gbreve -60 + +KPX Aring Gcommaaccent -60 + +KPX Aring O -50 + +KPX Aring Oacute -50 + +KPX Aring Ocircumflex -50 + +KPX Aring Odieresis -50 + +KPX Aring Ograve -50 + +KPX Aring Ohungarumlaut -50 + +KPX Aring Omacron -50 + +KPX Aring Oslash -50 + +KPX Aring Otilde -50 + +KPX Aring Q -55 + +KPX Aring T -55 + +KPX Aring Tcaron -55 + +KPX Aring Tcommaaccent -55 + +KPX Aring U -50 + +KPX Aring Uacute -50 + +KPX Aring Ucircumflex -50 + +KPX Aring Udieresis -50 + +KPX Aring Ugrave -50 + +KPX Aring Uhungarumlaut -50 + +KPX Aring Umacron -50 + +KPX Aring Uogonek -50 + +KPX Aring Uring -50 + +KPX Aring V -95 + +KPX Aring W -100 + +KPX Aring Y -70 + +KPX Aring Yacute -70 + +KPX Aring Ydieresis -70 + +KPX Aring quoteright -74 + +KPX Aring u -30 + +KPX Aring uacute -30 + +KPX Aring ucircumflex -30 + +KPX Aring udieresis -30 + +KPX Aring ugrave -30 + +KPX Aring uhungarumlaut -30 + +KPX Aring umacron -30 + +KPX Aring uogonek -30 + +KPX Aring uring -30 + +KPX Aring v -74 + +KPX Aring w -74 + +KPX Aring y -74 + +KPX Aring yacute -74 + +KPX Aring ydieresis -74 + +KPX Atilde C -65 + +KPX Atilde Cacute -65 + +KPX Atilde Ccaron -65 + +KPX Atilde Ccedilla -65 + +KPX Atilde G -60 + +KPX Atilde Gbreve -60 + +KPX Atilde Gcommaaccent -60 + +KPX Atilde O -50 + +KPX Atilde Oacute -50 + +KPX Atilde Ocircumflex -50 + +KPX Atilde Odieresis -50 + +KPX Atilde Ograve -50 + +KPX Atilde Ohungarumlaut -50 + +KPX Atilde Omacron -50 + +KPX Atilde Oslash -50 + +KPX Atilde Otilde -50 + +KPX Atilde Q -55 + +KPX Atilde T -55 + +KPX Atilde Tcaron -55 + +KPX Atilde Tcommaaccent -55 + +KPX Atilde U -50 + +KPX Atilde Uacute -50 + +KPX Atilde Ucircumflex -50 + +KPX Atilde Udieresis -50 + +KPX Atilde Ugrave -50 + +KPX Atilde Uhungarumlaut -50 + +KPX Atilde Umacron -50 + +KPX Atilde Uogonek -50 + +KPX Atilde Uring -50 + +KPX Atilde V -95 + +KPX Atilde W -100 + +KPX Atilde Y -70 + +KPX Atilde Yacute -70 + +KPX Atilde Ydieresis -70 + +KPX Atilde quoteright -74 + +KPX Atilde u -30 + +KPX Atilde uacute -30 + +KPX Atilde ucircumflex -30 + +KPX Atilde udieresis -30 + +KPX Atilde ugrave -30 + +KPX Atilde uhungarumlaut -30 + +KPX Atilde umacron -30 + +KPX Atilde uogonek -30 + +KPX Atilde uring -30 + +KPX Atilde v -74 + +KPX Atilde w -74 + +KPX Atilde y -74 + +KPX Atilde yacute -74 + +KPX Atilde ydieresis -74 + +KPX B A -25 + +KPX B Aacute -25 + +KPX B Abreve -25 + +KPX B Acircumflex -25 + +KPX B Adieresis -25 + +KPX B Agrave -25 + +KPX B Amacron -25 + +KPX B Aogonek -25 + +KPX B Aring -25 + +KPX B Atilde -25 + +KPX B U -10 + +KPX B Uacute -10 + +KPX B Ucircumflex -10 + +KPX B Udieresis -10 + +KPX B Ugrave -10 + +KPX B Uhungarumlaut -10 + +KPX B Umacron -10 + +KPX B Uogonek -10 + +KPX B Uring -10 + +KPX D A -25 + +KPX D Aacute -25 + +KPX D Abreve -25 + +KPX D Acircumflex -25 + +KPX D Adieresis -25 + +KPX D Agrave -25 + +KPX D Amacron -25 + +KPX D Aogonek -25 + +KPX D Aring -25 + +KPX D Atilde -25 + +KPX D V -50 + +KPX D W -40 + +KPX D Y -50 + +KPX D Yacute -50 + +KPX D Ydieresis -50 + +KPX Dcaron A -25 + +KPX Dcaron Aacute -25 + +KPX Dcaron Abreve -25 + +KPX Dcaron Acircumflex -25 + +KPX Dcaron Adieresis -25 + +KPX Dcaron Agrave -25 + +KPX Dcaron Amacron -25 + +KPX Dcaron Aogonek -25 + +KPX Dcaron Aring -25 + +KPX Dcaron Atilde -25 + +KPX Dcaron V -50 + +KPX Dcaron W -40 + +KPX Dcaron Y -50 + +KPX Dcaron Yacute -50 + +KPX Dcaron Ydieresis -50 + +KPX Dcroat A -25 + +KPX Dcroat Aacute -25 + +KPX Dcroat Abreve -25 + +KPX Dcroat Acircumflex -25 + +KPX Dcroat Adieresis -25 + +KPX Dcroat Agrave -25 + +KPX Dcroat Amacron -25 + +KPX Dcroat Aogonek -25 + +KPX Dcroat Aring -25 + +KPX Dcroat Atilde -25 + +KPX Dcroat V -50 + +KPX Dcroat W -40 + +KPX Dcroat Y -50 + +KPX Dcroat Yacute -50 + +KPX Dcroat Ydieresis -50 + +KPX F A -100 + +KPX F Aacute -100 + +KPX F Abreve -100 + +KPX F Acircumflex -100 + +KPX F Adieresis -100 + +KPX F Agrave -100 + +KPX F Amacron -100 + +KPX F Aogonek -100 + +KPX F Aring -100 + +KPX F Atilde -100 + +KPX F a -95 + +KPX F aacute -95 + +KPX F abreve -95 + +KPX F acircumflex -95 + +KPX F adieresis -95 + +KPX F agrave -95 + +KPX F amacron -95 + +KPX F aogonek -95 + +KPX F aring -95 + +KPX F atilde -95 + +KPX F comma -129 + +KPX F e -100 + +KPX F eacute -100 + +KPX F ecaron -100 + +KPX F ecircumflex -100 + +KPX F edieresis -100 + +KPX F edotaccent -100 + +KPX F egrave -100 + +KPX F emacron -100 + +KPX F eogonek -100 + +KPX F i -40 + +KPX F iacute -40 + +KPX F icircumflex -40 + +KPX F idieresis -40 + +KPX F igrave -40 + +KPX F imacron -40 + +KPX F iogonek -40 + +KPX F o -70 + +KPX F oacute -70 + +KPX F ocircumflex -70 + +KPX F odieresis -70 + +KPX F ograve -70 + +KPX F ohungarumlaut -70 + +KPX F omacron -70 + +KPX F oslash -70 + +KPX F otilde -70 + +KPX F period -129 + +KPX F r -50 + +KPX F racute -50 + +KPX F rcaron -50 + +KPX F rcommaaccent -50 + +KPX J A -25 + +KPX J Aacute -25 + +KPX J Abreve -25 + +KPX J Acircumflex -25 + +KPX J Adieresis -25 + +KPX J Agrave -25 + +KPX J Amacron -25 + +KPX J Aogonek -25 + +KPX J Aring -25 + +KPX J Atilde -25 + +KPX J a -40 + +KPX J aacute -40 + +KPX J abreve -40 + +KPX J acircumflex -40 + +KPX J adieresis -40 + +KPX J agrave -40 + +KPX J amacron -40 + +KPX J aogonek -40 + +KPX J aring -40 + +KPX J atilde -40 + +KPX J comma -10 + +KPX J e -40 + +KPX J eacute -40 + +KPX J ecaron -40 + +KPX J ecircumflex -40 + +KPX J edieresis -40 + +KPX J edotaccent -40 + +KPX J egrave -40 + +KPX J emacron -40 + +KPX J eogonek -40 + +KPX J o -40 + +KPX J oacute -40 + +KPX J ocircumflex -40 + +KPX J odieresis -40 + +KPX J ograve -40 + +KPX J ohungarumlaut -40 + +KPX J omacron -40 + +KPX J oslash -40 + +KPX J otilde -40 + +KPX J period -10 + +KPX J u -40 + +KPX J uacute -40 + +KPX J ucircumflex -40 + +KPX J udieresis -40 + +KPX J ugrave -40 + +KPX J uhungarumlaut -40 + +KPX J umacron -40 + +KPX J uogonek -40 + +KPX J uring -40 + +KPX K O -30 + +KPX K Oacute -30 + +KPX K Ocircumflex -30 + +KPX K Odieresis -30 + +KPX K Ograve -30 + +KPX K Ohungarumlaut -30 + +KPX K Omacron -30 + +KPX K Oslash -30 + +KPX K Otilde -30 + +KPX K e -25 + +KPX K eacute -25 + +KPX K ecaron -25 + +KPX K ecircumflex -25 + +KPX K edieresis -25 + +KPX K edotaccent -25 + +KPX K egrave -25 + +KPX K emacron -25 + +KPX K eogonek -25 + +KPX K o -25 + +KPX K oacute -25 + +KPX K ocircumflex -25 + +KPX K odieresis -25 + +KPX K ograve -25 + +KPX K ohungarumlaut -25 + +KPX K omacron -25 + +KPX K oslash -25 + +KPX K otilde -25 + +KPX K u -20 + +KPX K uacute -20 + +KPX K ucircumflex -20 + +KPX K udieresis -20 + +KPX K ugrave -20 + +KPX K uhungarumlaut -20 + +KPX K umacron -20 + +KPX K uogonek -20 + +KPX K uring -20 + +KPX K y -20 + +KPX K yacute -20 + +KPX K ydieresis -20 + +KPX Kcommaaccent O -30 + +KPX Kcommaaccent Oacute -30 + +KPX Kcommaaccent Ocircumflex -30 + +KPX Kcommaaccent Odieresis -30 + +KPX Kcommaaccent Ograve -30 + +KPX Kcommaaccent Ohungarumlaut -30 + +KPX Kcommaaccent Omacron -30 + +KPX Kcommaaccent Oslash -30 + +KPX Kcommaaccent Otilde -30 + +KPX Kcommaaccent e -25 + +KPX Kcommaaccent eacute -25 + +KPX Kcommaaccent ecaron -25 + +KPX Kcommaaccent ecircumflex -25 + +KPX Kcommaaccent edieresis -25 + +KPX Kcommaaccent edotaccent -25 + +KPX Kcommaaccent egrave -25 + +KPX Kcommaaccent emacron -25 + +KPX Kcommaaccent eogonek -25 + +KPX Kcommaaccent o -25 + +KPX Kcommaaccent oacute -25 + +KPX Kcommaaccent ocircumflex -25 + +KPX Kcommaaccent odieresis -25 + +KPX Kcommaaccent ograve -25 + +KPX Kcommaaccent ohungarumlaut -25 + +KPX Kcommaaccent omacron -25 + +KPX Kcommaaccent oslash -25 + +KPX Kcommaaccent otilde -25 + +KPX Kcommaaccent u -20 + +KPX Kcommaaccent uacute -20 + +KPX Kcommaaccent ucircumflex -20 + +KPX Kcommaaccent udieresis -20 + +KPX Kcommaaccent ugrave -20 + +KPX Kcommaaccent uhungarumlaut -20 + +KPX Kcommaaccent umacron -20 + +KPX Kcommaaccent uogonek -20 + +KPX Kcommaaccent uring -20 + +KPX Kcommaaccent y -20 + +KPX Kcommaaccent yacute -20 + +KPX Kcommaaccent ydieresis -20 + +KPX L T -18 + +KPX L Tcaron -18 + +KPX L Tcommaaccent -18 + +KPX L V -37 + +KPX L W -37 + +KPX L Y -37 + +KPX L Yacute -37 + +KPX L Ydieresis -37 + +KPX L quoteright -55 + +KPX L y -37 + +KPX L yacute -37 + +KPX L ydieresis -37 + +KPX Lacute T -18 + +KPX Lacute Tcaron -18 + +KPX Lacute Tcommaaccent -18 + +KPX Lacute V -37 + +KPX Lacute W -37 + +KPX Lacute Y -37 + +KPX Lacute Yacute -37 + +KPX Lacute Ydieresis -37 + +KPX Lacute quoteright -55 + +KPX Lacute y -37 + +KPX Lacute yacute -37 + +KPX Lacute ydieresis -37 + +KPX Lcommaaccent T -18 + +KPX Lcommaaccent Tcaron -18 + +KPX Lcommaaccent Tcommaaccent -18 + +KPX Lcommaaccent V -37 + +KPX Lcommaaccent W -37 + +KPX Lcommaaccent Y -37 + +KPX Lcommaaccent Yacute -37 + +KPX Lcommaaccent Ydieresis -37 + +KPX Lcommaaccent quoteright -55 + +KPX Lcommaaccent y -37 + +KPX Lcommaaccent yacute -37 + +KPX Lcommaaccent ydieresis -37 + +KPX Lslash T -18 + +KPX Lslash Tcaron -18 + +KPX Lslash Tcommaaccent -18 + +KPX Lslash V -37 + +KPX Lslash W -37 + +KPX Lslash Y -37 + +KPX Lslash Yacute -37 + +KPX Lslash Ydieresis -37 + +KPX Lslash quoteright -55 + +KPX Lslash y -37 + +KPX Lslash yacute -37 + +KPX Lslash ydieresis -37 + +KPX N A -30 + +KPX N Aacute -30 + +KPX N Abreve -30 + +KPX N Acircumflex -30 + +KPX N Adieresis -30 + +KPX N Agrave -30 + +KPX N Amacron -30 + +KPX N Aogonek -30 + +KPX N Aring -30 + +KPX N Atilde -30 + +KPX Nacute A -30 + +KPX Nacute Aacute -30 + +KPX Nacute Abreve -30 + +KPX Nacute Acircumflex -30 + +KPX Nacute Adieresis -30 + +KPX Nacute Agrave -30 + +KPX Nacute Amacron -30 + +KPX Nacute Aogonek -30 + +KPX Nacute Aring -30 + +KPX Nacute Atilde -30 + +KPX Ncaron A -30 + +KPX Ncaron Aacute -30 + +KPX Ncaron Abreve -30 + +KPX Ncaron Acircumflex -30 + +KPX Ncaron Adieresis -30 + +KPX Ncaron Agrave -30 + +KPX Ncaron Amacron -30 + +KPX Ncaron Aogonek -30 + +KPX Ncaron Aring -30 + +KPX Ncaron Atilde -30 + +KPX Ncommaaccent A -30 + +KPX Ncommaaccent Aacute -30 + +KPX Ncommaaccent Abreve -30 + +KPX Ncommaaccent Acircumflex -30 + +KPX Ncommaaccent Adieresis -30 + +KPX Ncommaaccent Agrave -30 + +KPX Ncommaaccent Amacron -30 + +KPX Ncommaaccent Aogonek -30 + +KPX Ncommaaccent Aring -30 + +KPX Ncommaaccent Atilde -30 + +KPX Ntilde A -30 + +KPX Ntilde Aacute -30 + +KPX Ntilde Abreve -30 + +KPX Ntilde Acircumflex -30 + +KPX Ntilde Adieresis -30 + +KPX Ntilde Agrave -30 + +KPX Ntilde Amacron -30 + +KPX Ntilde Aogonek -30 + +KPX Ntilde Aring -30 + +KPX Ntilde Atilde -30 + +KPX O A -40 + +KPX O Aacute -40 + +KPX O Abreve -40 + +KPX O Acircumflex -40 + +KPX O Adieresis -40 + +KPX O Agrave -40 + +KPX O Amacron -40 + +KPX O Aogonek -40 + +KPX O Aring -40 + +KPX O Atilde -40 + +KPX O T -40 + +KPX O Tcaron -40 + +KPX O Tcommaaccent -40 + +KPX O V -50 + +KPX O W -50 + +KPX O X -40 + +KPX O Y -50 + +KPX O Yacute -50 + +KPX O Ydieresis -50 + +KPX Oacute A -40 + +KPX Oacute Aacute -40 + +KPX Oacute Abreve -40 + +KPX Oacute Acircumflex -40 + +KPX Oacute Adieresis -40 + +KPX Oacute Agrave -40 + +KPX Oacute Amacron -40 + +KPX Oacute Aogonek -40 + +KPX Oacute Aring -40 + +KPX Oacute Atilde -40 + +KPX Oacute T -40 + +KPX Oacute Tcaron -40 + +KPX Oacute Tcommaaccent -40 + +KPX Oacute V -50 + +KPX Oacute W -50 + +KPX Oacute X -40 + +KPX Oacute Y -50 + +KPX Oacute Yacute -50 + +KPX Oacute Ydieresis -50 + +KPX Ocircumflex A -40 + +KPX Ocircumflex Aacute -40 + +KPX Ocircumflex Abreve -40 + +KPX Ocircumflex Acircumflex -40 + +KPX Ocircumflex Adieresis -40 + +KPX Ocircumflex Agrave -40 + +KPX Ocircumflex Amacron -40 + +KPX Ocircumflex Aogonek -40 + +KPX Ocircumflex Aring -40 + +KPX Ocircumflex Atilde -40 + +KPX Ocircumflex T -40 + +KPX Ocircumflex Tcaron -40 + +KPX Ocircumflex Tcommaaccent -40 + +KPX Ocircumflex V -50 + +KPX Ocircumflex W -50 + +KPX Ocircumflex X -40 + +KPX Ocircumflex Y -50 + +KPX Ocircumflex Yacute -50 + +KPX Ocircumflex Ydieresis -50 + +KPX Odieresis A -40 + +KPX Odieresis Aacute -40 + +KPX Odieresis Abreve -40 + +KPX Odieresis Acircumflex -40 + +KPX Odieresis Adieresis -40 + +KPX Odieresis Agrave -40 + +KPX Odieresis Amacron -40 + +KPX Odieresis Aogonek -40 + +KPX Odieresis Aring -40 + +KPX Odieresis Atilde -40 + +KPX Odieresis T -40 + +KPX Odieresis Tcaron -40 + +KPX Odieresis Tcommaaccent -40 + +KPX Odieresis V -50 + +KPX Odieresis W -50 + +KPX Odieresis X -40 + +KPX Odieresis Y -50 + +KPX Odieresis Yacute -50 + +KPX Odieresis Ydieresis -50 + +KPX Ograve A -40 + +KPX Ograve Aacute -40 + +KPX Ograve Abreve -40 + +KPX Ograve Acircumflex -40 + +KPX Ograve Adieresis -40 + +KPX Ograve Agrave -40 + +KPX Ograve Amacron -40 + +KPX Ograve Aogonek -40 + +KPX Ograve Aring -40 + +KPX Ograve Atilde -40 + +KPX Ograve T -40 + +KPX Ograve Tcaron -40 + +KPX Ograve Tcommaaccent -40 + +KPX Ograve V -50 + +KPX Ograve W -50 + +KPX Ograve X -40 + +KPX Ograve Y -50 + +KPX Ograve Yacute -50 + +KPX Ograve Ydieresis -50 + +KPX Ohungarumlaut A -40 + +KPX Ohungarumlaut Aacute -40 + +KPX Ohungarumlaut Abreve -40 + +KPX Ohungarumlaut Acircumflex -40 + +KPX Ohungarumlaut Adieresis -40 + +KPX Ohungarumlaut Agrave -40 + +KPX Ohungarumlaut Amacron -40 + +KPX Ohungarumlaut Aogonek -40 + +KPX Ohungarumlaut Aring -40 + +KPX Ohungarumlaut Atilde -40 + +KPX Ohungarumlaut T -40 + +KPX Ohungarumlaut Tcaron -40 + +KPX Ohungarumlaut Tcommaaccent -40 + +KPX Ohungarumlaut V -50 + +KPX Ohungarumlaut W -50 + +KPX Ohungarumlaut X -40 + +KPX Ohungarumlaut Y -50 + +KPX Ohungarumlaut Yacute -50 + +KPX Ohungarumlaut Ydieresis -50 + +KPX Omacron A -40 + +KPX Omacron Aacute -40 + +KPX Omacron Abreve -40 + +KPX Omacron Acircumflex -40 + +KPX Omacron Adieresis -40 + +KPX Omacron Agrave -40 + +KPX Omacron Amacron -40 + +KPX Omacron Aogonek -40 + +KPX Omacron Aring -40 + +KPX Omacron Atilde -40 + +KPX Omacron T -40 + +KPX Omacron Tcaron -40 + +KPX Omacron Tcommaaccent -40 + +KPX Omacron V -50 + +KPX Omacron W -50 + +KPX Omacron X -40 + +KPX Omacron Y -50 + +KPX Omacron Yacute -50 + +KPX Omacron Ydieresis -50 + +KPX Oslash A -40 + +KPX Oslash Aacute -40 + +KPX Oslash Abreve -40 + +KPX Oslash Acircumflex -40 + +KPX Oslash Adieresis -40 + +KPX Oslash Agrave -40 + +KPX Oslash Amacron -40 + +KPX Oslash Aogonek -40 + +KPX Oslash Aring -40 + +KPX Oslash Atilde -40 + +KPX Oslash T -40 + +KPX Oslash Tcaron -40 + +KPX Oslash Tcommaaccent -40 + +KPX Oslash V -50 + +KPX Oslash W -50 + +KPX Oslash X -40 + +KPX Oslash Y -50 + +KPX Oslash Yacute -50 + +KPX Oslash Ydieresis -50 + +KPX Otilde A -40 + +KPX Otilde Aacute -40 + +KPX Otilde Abreve -40 + +KPX Otilde Acircumflex -40 + +KPX Otilde Adieresis -40 + +KPX Otilde Agrave -40 + +KPX Otilde Amacron -40 + +KPX Otilde Aogonek -40 + +KPX Otilde Aring -40 + +KPX Otilde Atilde -40 + +KPX Otilde T -40 + +KPX Otilde Tcaron -40 + +KPX Otilde Tcommaaccent -40 + +KPX Otilde V -50 + +KPX Otilde W -50 + +KPX Otilde X -40 + +KPX Otilde Y -50 + +KPX Otilde Yacute -50 + +KPX Otilde Ydieresis -50 + +KPX P A -85 + +KPX P Aacute -85 + +KPX P Abreve -85 + +KPX P Acircumflex -85 + +KPX P Adieresis -85 + +KPX P Agrave -85 + +KPX P Amacron -85 + +KPX P Aogonek -85 + +KPX P Aring -85 + +KPX P Atilde -85 + +KPX P a -40 + +KPX P aacute -40 + +KPX P abreve -40 + +KPX P acircumflex -40 + +KPX P adieresis -40 + +KPX P agrave -40 + +KPX P amacron -40 + +KPX P aogonek -40 + +KPX P aring -40 + +KPX P atilde -40 + +KPX P comma -129 + +KPX P e -50 + +KPX P eacute -50 + +KPX P ecaron -50 + +KPX P ecircumflex -50 + +KPX P edieresis -50 + +KPX P edotaccent -50 + +KPX P egrave -50 + +KPX P emacron -50 + +KPX P eogonek -50 + +KPX P o -55 + +KPX P oacute -55 + +KPX P ocircumflex -55 + +KPX P odieresis -55 + +KPX P ograve -55 + +KPX P ohungarumlaut -55 + +KPX P omacron -55 + +KPX P oslash -55 + +KPX P otilde -55 + +KPX P period -129 + +KPX Q U -10 + +KPX Q Uacute -10 + +KPX Q Ucircumflex -10 + +KPX Q Udieresis -10 + +KPX Q Ugrave -10 + +KPX Q Uhungarumlaut -10 + +KPX Q Umacron -10 + +KPX Q Uogonek -10 + +KPX Q Uring -10 + +KPX R O -40 + +KPX R Oacute -40 + +KPX R Ocircumflex -40 + +KPX R Odieresis -40 + +KPX R Ograve -40 + +KPX R Ohungarumlaut -40 + +KPX R Omacron -40 + +KPX R Oslash -40 + +KPX R Otilde -40 + +KPX R T -30 + +KPX R Tcaron -30 + +KPX R Tcommaaccent -30 + +KPX R U -40 + +KPX R Uacute -40 + +KPX R Ucircumflex -40 + +KPX R Udieresis -40 + +KPX R Ugrave -40 + +KPX R Uhungarumlaut -40 + +KPX R Umacron -40 + +KPX R Uogonek -40 + +KPX R Uring -40 + +KPX R V -18 + +KPX R W -18 + +KPX R Y -18 + +KPX R Yacute -18 + +KPX R Ydieresis -18 + +KPX Racute O -40 + +KPX Racute Oacute -40 + +KPX Racute Ocircumflex -40 + +KPX Racute Odieresis -40 + +KPX Racute Ograve -40 + +KPX Racute Ohungarumlaut -40 + +KPX Racute Omacron -40 + +KPX Racute Oslash -40 + +KPX Racute Otilde -40 + +KPX Racute T -30 + +KPX Racute Tcaron -30 + +KPX Racute Tcommaaccent -30 + +KPX Racute U -40 + +KPX Racute Uacute -40 + +KPX Racute Ucircumflex -40 + +KPX Racute Udieresis -40 + +KPX Racute Ugrave -40 + +KPX Racute Uhungarumlaut -40 + +KPX Racute Umacron -40 + +KPX Racute Uogonek -40 + +KPX Racute Uring -40 + +KPX Racute V -18 + +KPX Racute W -18 + +KPX Racute Y -18 + +KPX Racute Yacute -18 + +KPX Racute Ydieresis -18 + +KPX Rcaron O -40 + +KPX Rcaron Oacute -40 + +KPX Rcaron Ocircumflex -40 + +KPX Rcaron Odieresis -40 + +KPX Rcaron Ograve -40 + +KPX Rcaron Ohungarumlaut -40 + +KPX Rcaron Omacron -40 + +KPX Rcaron Oslash -40 + +KPX Rcaron Otilde -40 + +KPX Rcaron T -30 + +KPX Rcaron Tcaron -30 + +KPX Rcaron Tcommaaccent -30 + +KPX Rcaron U -40 + +KPX Rcaron Uacute -40 + +KPX Rcaron Ucircumflex -40 + +KPX Rcaron Udieresis -40 + +KPX Rcaron Ugrave -40 + +KPX Rcaron Uhungarumlaut -40 + +KPX Rcaron Umacron -40 + +KPX Rcaron Uogonek -40 + +KPX Rcaron Uring -40 + +KPX Rcaron V -18 + +KPX Rcaron W -18 + +KPX Rcaron Y -18 + +KPX Rcaron Yacute -18 + +KPX Rcaron Ydieresis -18 + +KPX Rcommaaccent O -40 + +KPX Rcommaaccent Oacute -40 + +KPX Rcommaaccent Ocircumflex -40 + +KPX Rcommaaccent Odieresis -40 + +KPX Rcommaaccent Ograve -40 + +KPX Rcommaaccent Ohungarumlaut -40 + +KPX Rcommaaccent Omacron -40 + +KPX Rcommaaccent Oslash -40 + +KPX Rcommaaccent Otilde -40 + +KPX Rcommaaccent T -30 + +KPX Rcommaaccent Tcaron -30 + +KPX Rcommaaccent Tcommaaccent -30 + +KPX Rcommaaccent U -40 + +KPX Rcommaaccent Uacute -40 + +KPX Rcommaaccent Ucircumflex -40 + +KPX Rcommaaccent Udieresis -40 + +KPX Rcommaaccent Ugrave -40 + +KPX Rcommaaccent Uhungarumlaut -40 + +KPX Rcommaaccent Umacron -40 + +KPX Rcommaaccent Uogonek -40 + +KPX Rcommaaccent Uring -40 + +KPX Rcommaaccent V -18 + +KPX Rcommaaccent W -18 + +KPX Rcommaaccent Y -18 + +KPX Rcommaaccent Yacute -18 + +KPX Rcommaaccent Ydieresis -18 + +KPX T A -55 + +KPX T Aacute -55 + +KPX T Abreve -55 + +KPX T Acircumflex -55 + +KPX T Adieresis -55 + +KPX T Agrave -55 + +KPX T Amacron -55 + +KPX T Aogonek -55 + +KPX T Aring -55 + +KPX T Atilde -55 + +KPX T O -18 + +KPX T Oacute -18 + +KPX T Ocircumflex -18 + +KPX T Odieresis -18 + +KPX T Ograve -18 + +KPX T Ohungarumlaut -18 + +KPX T Omacron -18 + +KPX T Oslash -18 + +KPX T Otilde -18 + +KPX T a -92 + +KPX T aacute -92 + +KPX T abreve -92 + +KPX T acircumflex -92 + +KPX T adieresis -92 + +KPX T agrave -92 + +KPX T amacron -92 + +KPX T aogonek -92 + +KPX T aring -92 + +KPX T atilde -92 + +KPX T colon -74 + +KPX T comma -92 + +KPX T e -92 + +KPX T eacute -92 + +KPX T ecaron -92 + +KPX T ecircumflex -92 + +KPX T edieresis -52 + +KPX T edotaccent -92 + +KPX T egrave -52 + +KPX T emacron -52 + +KPX T eogonek -92 + +KPX T hyphen -92 + +KPX T i -37 + +KPX T iacute -37 + +KPX T iogonek -37 + +KPX T o -95 + +KPX T oacute -95 + +KPX T ocircumflex -95 + +KPX T odieresis -95 + +KPX T ograve -95 + +KPX T ohungarumlaut -95 + +KPX T omacron -95 + +KPX T oslash -95 + +KPX T otilde -95 + +KPX T period -92 + +KPX T r -37 + +KPX T racute -37 + +KPX T rcaron -37 + +KPX T rcommaaccent -37 + +KPX T semicolon -74 + +KPX T u -37 + +KPX T uacute -37 + +KPX T ucircumflex -37 + +KPX T udieresis -37 + +KPX T ugrave -37 + +KPX T uhungarumlaut -37 + +KPX T umacron -37 + +KPX T uogonek -37 + +KPX T uring -37 + +KPX T w -37 + +KPX T y -37 + +KPX T yacute -37 + +KPX T ydieresis -37 + +KPX Tcaron A -55 + +KPX Tcaron Aacute -55 + +KPX Tcaron Abreve -55 + +KPX Tcaron Acircumflex -55 + +KPX Tcaron Adieresis -55 + +KPX Tcaron Agrave -55 + +KPX Tcaron Amacron -55 + +KPX Tcaron Aogonek -55 + +KPX Tcaron Aring -55 + +KPX Tcaron Atilde -55 + +KPX Tcaron O -18 + +KPX Tcaron Oacute -18 + +KPX Tcaron Ocircumflex -18 + +KPX Tcaron Odieresis -18 + +KPX Tcaron Ograve -18 + +KPX Tcaron Ohungarumlaut -18 + +KPX Tcaron Omacron -18 + +KPX Tcaron Oslash -18 + +KPX Tcaron Otilde -18 + +KPX Tcaron a -92 + +KPX Tcaron aacute -92 + +KPX Tcaron abreve -92 + +KPX Tcaron acircumflex -92 + +KPX Tcaron adieresis -92 + +KPX Tcaron agrave -92 + +KPX Tcaron amacron -92 + +KPX Tcaron aogonek -92 + +KPX Tcaron aring -92 + +KPX Tcaron atilde -92 + +KPX Tcaron colon -74 + +KPX Tcaron comma -92 + +KPX Tcaron e -92 + +KPX Tcaron eacute -92 + +KPX Tcaron ecaron -92 + +KPX Tcaron ecircumflex -92 + +KPX Tcaron edieresis -52 + +KPX Tcaron edotaccent -92 + +KPX Tcaron egrave -52 + +KPX Tcaron emacron -52 + +KPX Tcaron eogonek -92 + +KPX Tcaron hyphen -92 + +KPX Tcaron i -37 + +KPX Tcaron iacute -37 + +KPX Tcaron iogonek -37 + +KPX Tcaron o -95 + +KPX Tcaron oacute -95 + +KPX Tcaron ocircumflex -95 + +KPX Tcaron odieresis -95 + +KPX Tcaron ograve -95 + +KPX Tcaron ohungarumlaut -95 + +KPX Tcaron omacron -95 + +KPX Tcaron oslash -95 + +KPX Tcaron otilde -95 + +KPX Tcaron period -92 + +KPX Tcaron r -37 + +KPX Tcaron racute -37 + +KPX Tcaron rcaron -37 + +KPX Tcaron rcommaaccent -37 + +KPX Tcaron semicolon -74 + +KPX Tcaron u -37 + +KPX Tcaron uacute -37 + +KPX Tcaron ucircumflex -37 + +KPX Tcaron udieresis -37 + +KPX Tcaron ugrave -37 + +KPX Tcaron uhungarumlaut -37 + +KPX Tcaron umacron -37 + +KPX Tcaron uogonek -37 + +KPX Tcaron uring -37 + +KPX Tcaron w -37 + +KPX Tcaron y -37 + +KPX Tcaron yacute -37 + +KPX Tcaron ydieresis -37 + +KPX Tcommaaccent A -55 + +KPX Tcommaaccent Aacute -55 + +KPX Tcommaaccent Abreve -55 + +KPX Tcommaaccent Acircumflex -55 + +KPX Tcommaaccent Adieresis -55 + +KPX Tcommaaccent Agrave -55 + +KPX Tcommaaccent Amacron -55 + +KPX Tcommaaccent Aogonek -55 + +KPX Tcommaaccent Aring -55 + +KPX Tcommaaccent Atilde -55 + +KPX Tcommaaccent O -18 + +KPX Tcommaaccent Oacute -18 + +KPX Tcommaaccent Ocircumflex -18 + +KPX Tcommaaccent Odieresis -18 + +KPX Tcommaaccent Ograve -18 + +KPX Tcommaaccent Ohungarumlaut -18 + +KPX Tcommaaccent Omacron -18 + +KPX Tcommaaccent Oslash -18 + +KPX Tcommaaccent Otilde -18 + +KPX Tcommaaccent a -92 + +KPX Tcommaaccent aacute -92 + +KPX Tcommaaccent abreve -92 + +KPX Tcommaaccent acircumflex -92 + +KPX Tcommaaccent adieresis -92 + +KPX Tcommaaccent agrave -92 + +KPX Tcommaaccent amacron -92 + +KPX Tcommaaccent aogonek -92 + +KPX Tcommaaccent aring -92 + +KPX Tcommaaccent atilde -92 + +KPX Tcommaaccent colon -74 + +KPX Tcommaaccent comma -92 + +KPX Tcommaaccent e -92 + +KPX Tcommaaccent eacute -92 + +KPX Tcommaaccent ecaron -92 + +KPX Tcommaaccent ecircumflex -92 + +KPX Tcommaaccent edieresis -52 + +KPX Tcommaaccent edotaccent -92 + +KPX Tcommaaccent egrave -52 + +KPX Tcommaaccent emacron -52 + +KPX Tcommaaccent eogonek -92 + +KPX Tcommaaccent hyphen -92 + +KPX Tcommaaccent i -37 + +KPX Tcommaaccent iacute -37 + +KPX Tcommaaccent iogonek -37 + +KPX Tcommaaccent o -95 + +KPX Tcommaaccent oacute -95 + +KPX Tcommaaccent ocircumflex -95 + +KPX Tcommaaccent odieresis -95 + +KPX Tcommaaccent ograve -95 + +KPX Tcommaaccent ohungarumlaut -95 + +KPX Tcommaaccent omacron -95 + +KPX Tcommaaccent oslash -95 + +KPX Tcommaaccent otilde -95 + +KPX Tcommaaccent period -92 + +KPX Tcommaaccent r -37 + +KPX Tcommaaccent racute -37 + +KPX Tcommaaccent rcaron -37 + +KPX Tcommaaccent rcommaaccent -37 + +KPX Tcommaaccent semicolon -74 + +KPX Tcommaaccent u -37 + +KPX Tcommaaccent uacute -37 + +KPX Tcommaaccent ucircumflex -37 + +KPX Tcommaaccent udieresis -37 + +KPX Tcommaaccent ugrave -37 + +KPX Tcommaaccent uhungarumlaut -37 + +KPX Tcommaaccent umacron -37 + +KPX Tcommaaccent uogonek -37 + +KPX Tcommaaccent uring -37 + +KPX Tcommaaccent w -37 + +KPX Tcommaaccent y -37 + +KPX Tcommaaccent yacute -37 + +KPX Tcommaaccent ydieresis -37 + +KPX U A -45 + +KPX U Aacute -45 + +KPX U Abreve -45 + +KPX U Acircumflex -45 + +KPX U Adieresis -45 + +KPX U Agrave -45 + +KPX U Amacron -45 + +KPX U Aogonek -45 + +KPX U Aring -45 + +KPX U Atilde -45 + +KPX Uacute A -45 + +KPX Uacute Aacute -45 + +KPX Uacute Abreve -45 + +KPX Uacute Acircumflex -45 + +KPX Uacute Adieresis -45 + +KPX Uacute Agrave -45 + +KPX Uacute Amacron -45 + +KPX Uacute Aogonek -45 + +KPX Uacute Aring -45 + +KPX Uacute Atilde -45 + +KPX Ucircumflex A -45 + +KPX Ucircumflex Aacute -45 + +KPX Ucircumflex Abreve -45 + +KPX Ucircumflex Acircumflex -45 + +KPX Ucircumflex Adieresis -45 + +KPX Ucircumflex Agrave -45 + +KPX Ucircumflex Amacron -45 + +KPX Ucircumflex Aogonek -45 + +KPX Ucircumflex Aring -45 + +KPX Ucircumflex Atilde -45 + +KPX Udieresis A -45 + +KPX Udieresis Aacute -45 + +KPX Udieresis Abreve -45 + +KPX Udieresis Acircumflex -45 + +KPX Udieresis Adieresis -45 + +KPX Udieresis Agrave -45 + +KPX Udieresis Amacron -45 + +KPX Udieresis Aogonek -45 + +KPX Udieresis Aring -45 + +KPX Udieresis Atilde -45 + +KPX Ugrave A -45 + +KPX Ugrave Aacute -45 + +KPX Ugrave Abreve -45 + +KPX Ugrave Acircumflex -45 + +KPX Ugrave Adieresis -45 + +KPX Ugrave Agrave -45 + +KPX Ugrave Amacron -45 + +KPX Ugrave Aogonek -45 + +KPX Ugrave Aring -45 + +KPX Ugrave Atilde -45 + +KPX Uhungarumlaut A -45 + +KPX Uhungarumlaut Aacute -45 + +KPX Uhungarumlaut Abreve -45 + +KPX Uhungarumlaut Acircumflex -45 + +KPX Uhungarumlaut Adieresis -45 + +KPX Uhungarumlaut Agrave -45 + +KPX Uhungarumlaut Amacron -45 + +KPX Uhungarumlaut Aogonek -45 + +KPX Uhungarumlaut Aring -45 + +KPX Uhungarumlaut Atilde -45 + +KPX Umacron A -45 + +KPX Umacron Aacute -45 + +KPX Umacron Abreve -45 + +KPX Umacron Acircumflex -45 + +KPX Umacron Adieresis -45 + +KPX Umacron Agrave -45 + +KPX Umacron Amacron -45 + +KPX Umacron Aogonek -45 + +KPX Umacron Aring -45 + +KPX Umacron Atilde -45 + +KPX Uogonek A -45 + +KPX Uogonek Aacute -45 + +KPX Uogonek Abreve -45 + +KPX Uogonek Acircumflex -45 + +KPX Uogonek Adieresis -45 + +KPX Uogonek Agrave -45 + +KPX Uogonek Amacron -45 + +KPX Uogonek Aogonek -45 + +KPX Uogonek Aring -45 + +KPX Uogonek Atilde -45 + +KPX Uring A -45 + +KPX Uring Aacute -45 + +KPX Uring Abreve -45 + +KPX Uring Acircumflex -45 + +KPX Uring Adieresis -45 + +KPX Uring Agrave -45 + +KPX Uring Amacron -45 + +KPX Uring Aogonek -45 + +KPX Uring Aring -45 + +KPX Uring Atilde -45 + +KPX V A -85 + +KPX V Aacute -85 + +KPX V Abreve -85 + +KPX V Acircumflex -85 + +KPX V Adieresis -85 + +KPX V Agrave -85 + +KPX V Amacron -85 + +KPX V Aogonek -85 + +KPX V Aring -85 + +KPX V Atilde -85 + +KPX V G -10 + +KPX V Gbreve -10 + +KPX V Gcommaaccent -10 + +KPX V O -30 + +KPX V Oacute -30 + +KPX V Ocircumflex -30 + +KPX V Odieresis -30 + +KPX V Ograve -30 + +KPX V Ohungarumlaut -30 + +KPX V Omacron -30 + +KPX V Oslash -30 + +KPX V Otilde -30 + +KPX V a -111 + +KPX V aacute -111 + +KPX V abreve -111 + +KPX V acircumflex -111 + +KPX V adieresis -111 + +KPX V agrave -111 + +KPX V amacron -111 + +KPX V aogonek -111 + +KPX V aring -111 + +KPX V atilde -111 + +KPX V colon -74 + +KPX V comma -129 + +KPX V e -111 + +KPX V eacute -111 + +KPX V ecaron -111 + +KPX V ecircumflex -111 + +KPX V edieresis -71 + +KPX V edotaccent -111 + +KPX V egrave -71 + +KPX V emacron -71 + +KPX V eogonek -111 + +KPX V hyphen -70 + +KPX V i -55 + +KPX V iacute -55 + +KPX V iogonek -55 + +KPX V o -111 + +KPX V oacute -111 + +KPX V ocircumflex -111 + +KPX V odieresis -111 + +KPX V ograve -111 + +KPX V ohungarumlaut -111 + +KPX V omacron -111 + +KPX V oslash -111 + +KPX V otilde -111 + +KPX V period -129 + +KPX V semicolon -74 + +KPX V u -55 + +KPX V uacute -55 + +KPX V ucircumflex -55 + +KPX V udieresis -55 + +KPX V ugrave -55 + +KPX V uhungarumlaut -55 + +KPX V umacron -55 + +KPX V uogonek -55 + +KPX V uring -55 + +KPX W A -74 + +KPX W Aacute -74 + +KPX W Abreve -74 + +KPX W Acircumflex -74 + +KPX W Adieresis -74 + +KPX W Agrave -74 + +KPX W Amacron -74 + +KPX W Aogonek -74 + +KPX W Aring -74 + +KPX W Atilde -74 + +KPX W O -15 + +KPX W Oacute -15 + +KPX W Ocircumflex -15 + +KPX W Odieresis -15 + +KPX W Ograve -15 + +KPX W Ohungarumlaut -15 + +KPX W Omacron -15 + +KPX W Oslash -15 + +KPX W Otilde -15 + +KPX W a -85 + +KPX W aacute -85 + +KPX W abreve -85 + +KPX W acircumflex -85 + +KPX W adieresis -85 + +KPX W agrave -85 + +KPX W amacron -85 + +KPX W aogonek -85 + +KPX W aring -85 + +KPX W atilde -85 + +KPX W colon -55 + +KPX W comma -74 + +KPX W e -90 + +KPX W eacute -90 + +KPX W ecaron -90 + +KPX W ecircumflex -90 + +KPX W edieresis -50 + +KPX W edotaccent -90 + +KPX W egrave -50 + +KPX W emacron -50 + +KPX W eogonek -90 + +KPX W hyphen -50 + +KPX W i -37 + +KPX W iacute -37 + +KPX W iogonek -37 + +KPX W o -80 + +KPX W oacute -80 + +KPX W ocircumflex -80 + +KPX W odieresis -80 + +KPX W ograve -80 + +KPX W ohungarumlaut -80 + +KPX W omacron -80 + +KPX W oslash -80 + +KPX W otilde -80 + +KPX W period -74 + +KPX W semicolon -55 + +KPX W u -55 + +KPX W uacute -55 + +KPX W ucircumflex -55 + +KPX W udieresis -55 + +KPX W ugrave -55 + +KPX W uhungarumlaut -55 + +KPX W umacron -55 + +KPX W uogonek -55 + +KPX W uring -55 + +KPX W y -55 + +KPX W yacute -55 + +KPX W ydieresis -55 + +KPX Y A -74 + +KPX Y Aacute -74 + +KPX Y Abreve -74 + +KPX Y Acircumflex -74 + +KPX Y Adieresis -74 + +KPX Y Agrave -74 + +KPX Y Amacron -74 + +KPX Y Aogonek -74 + +KPX Y Aring -74 + +KPX Y Atilde -74 + +KPX Y O -25 + +KPX Y Oacute -25 + +KPX Y Ocircumflex -25 + +KPX Y Odieresis -25 + +KPX Y Ograve -25 + +KPX Y Ohungarumlaut -25 + +KPX Y Omacron -25 + +KPX Y Oslash -25 + +KPX Y Otilde -25 + +KPX Y a -92 + +KPX Y aacute -92 + +KPX Y abreve -92 + +KPX Y acircumflex -92 + +KPX Y adieresis -92 + +KPX Y agrave -92 + +KPX Y amacron -92 + +KPX Y aogonek -92 + +KPX Y aring -92 + +KPX Y atilde -92 + +KPX Y colon -92 + +KPX Y comma -92 + +KPX Y e -111 + +KPX Y eacute -111 + +KPX Y ecaron -111 + +KPX Y ecircumflex -71 + +KPX Y edieresis -71 + +KPX Y edotaccent -111 + +KPX Y egrave -71 + +KPX Y emacron -71 + +KPX Y eogonek -111 + +KPX Y hyphen -92 + +KPX Y i -55 + +KPX Y iacute -55 + +KPX Y iogonek -55 + +KPX Y o -111 + +KPX Y oacute -111 + +KPX Y ocircumflex -111 + +KPX Y odieresis -111 + +KPX Y ograve -111 + +KPX Y ohungarumlaut -111 + +KPX Y omacron -111 + +KPX Y oslash -111 + +KPX Y otilde -111 + +KPX Y period -74 + +KPX Y semicolon -92 + +KPX Y u -92 + +KPX Y uacute -92 + +KPX Y ucircumflex -92 + +KPX Y udieresis -92 + +KPX Y ugrave -92 + +KPX Y uhungarumlaut -92 + +KPX Y umacron -92 + +KPX Y uogonek -92 + +KPX Y uring -92 + +KPX Yacute A -74 + +KPX Yacute Aacute -74 + +KPX Yacute Abreve -74 + +KPX Yacute Acircumflex -74 + +KPX Yacute Adieresis -74 + +KPX Yacute Agrave -74 + +KPX Yacute Amacron -74 + +KPX Yacute Aogonek -74 + +KPX Yacute Aring -74 + +KPX Yacute Atilde -74 + +KPX Yacute O -25 + +KPX Yacute Oacute -25 + +KPX Yacute Ocircumflex -25 + +KPX Yacute Odieresis -25 + +KPX Yacute Ograve -25 + +KPX Yacute Ohungarumlaut -25 + +KPX Yacute Omacron -25 + +KPX Yacute Oslash -25 + +KPX Yacute Otilde -25 + +KPX Yacute a -92 + +KPX Yacute aacute -92 + +KPX Yacute abreve -92 + +KPX Yacute acircumflex -92 + +KPX Yacute adieresis -92 + +KPX Yacute agrave -92 + +KPX Yacute amacron -92 + +KPX Yacute aogonek -92 + +KPX Yacute aring -92 + +KPX Yacute atilde -92 + +KPX Yacute colon -92 + +KPX Yacute comma -92 + +KPX Yacute e -111 + +KPX Yacute eacute -111 + +KPX Yacute ecaron -111 + +KPX Yacute ecircumflex -71 + +KPX Yacute edieresis -71 + +KPX Yacute edotaccent -111 + +KPX Yacute egrave -71 + +KPX Yacute emacron -71 + +KPX Yacute eogonek -111 + +KPX Yacute hyphen -92 + +KPX Yacute i -55 + +KPX Yacute iacute -55 + +KPX Yacute iogonek -55 + +KPX Yacute o -111 + +KPX Yacute oacute -111 + +KPX Yacute ocircumflex -111 + +KPX Yacute odieresis -111 + +KPX Yacute ograve -111 + +KPX Yacute ohungarumlaut -111 + +KPX Yacute omacron -111 + +KPX Yacute oslash -111 + +KPX Yacute otilde -111 + +KPX Yacute period -74 + +KPX Yacute semicolon -92 + +KPX Yacute u -92 + +KPX Yacute uacute -92 + +KPX Yacute ucircumflex -92 + +KPX Yacute udieresis -92 + +KPX Yacute ugrave -92 + +KPX Yacute uhungarumlaut -92 + +KPX Yacute umacron -92 + +KPX Yacute uogonek -92 + +KPX Yacute uring -92 + +KPX Ydieresis A -74 + +KPX Ydieresis Aacute -74 + +KPX Ydieresis Abreve -74 + +KPX Ydieresis Acircumflex -74 + +KPX Ydieresis Adieresis -74 + +KPX Ydieresis Agrave -74 + +KPX Ydieresis Amacron -74 + +KPX Ydieresis Aogonek -74 + +KPX Ydieresis Aring -74 + +KPX Ydieresis Atilde -74 + +KPX Ydieresis O -25 + +KPX Ydieresis Oacute -25 + +KPX Ydieresis Ocircumflex -25 + +KPX Ydieresis Odieresis -25 + +KPX Ydieresis Ograve -25 + +KPX Ydieresis Ohungarumlaut -25 + +KPX Ydieresis Omacron -25 + +KPX Ydieresis Oslash -25 + +KPX Ydieresis Otilde -25 + +KPX Ydieresis a -92 + +KPX Ydieresis aacute -92 + +KPX Ydieresis abreve -92 + +KPX Ydieresis acircumflex -92 + +KPX Ydieresis adieresis -92 + +KPX Ydieresis agrave -92 + +KPX Ydieresis amacron -92 + +KPX Ydieresis aogonek -92 + +KPX Ydieresis aring -92 + +KPX Ydieresis atilde -92 + +KPX Ydieresis colon -92 + +KPX Ydieresis comma -92 + +KPX Ydieresis e -111 + +KPX Ydieresis eacute -111 + +KPX Ydieresis ecaron -111 + +KPX Ydieresis ecircumflex -71 + +KPX Ydieresis edieresis -71 + +KPX Ydieresis edotaccent -111 + +KPX Ydieresis egrave -71 + +KPX Ydieresis emacron -71 + +KPX Ydieresis eogonek -111 + +KPX Ydieresis hyphen -92 + +KPX Ydieresis i -55 + +KPX Ydieresis iacute -55 + +KPX Ydieresis iogonek -55 + +KPX Ydieresis o -111 + +KPX Ydieresis oacute -111 + +KPX Ydieresis ocircumflex -111 + +KPX Ydieresis odieresis -111 + +KPX Ydieresis ograve -111 + +KPX Ydieresis ohungarumlaut -111 + +KPX Ydieresis omacron -111 + +KPX Ydieresis oslash -111 + +KPX Ydieresis otilde -111 + +KPX Ydieresis period -74 + +KPX Ydieresis semicolon -92 + +KPX Ydieresis u -92 + +KPX Ydieresis uacute -92 + +KPX Ydieresis ucircumflex -92 + +KPX Ydieresis udieresis -92 + +KPX Ydieresis ugrave -92 + +KPX Ydieresis uhungarumlaut -92 + +KPX Ydieresis umacron -92 + +KPX Ydieresis uogonek -92 + +KPX Ydieresis uring -92 + +KPX b b -10 + +KPX b period -40 + +KPX b u -20 + +KPX b uacute -20 + +KPX b ucircumflex -20 + +KPX b udieresis -20 + +KPX b ugrave -20 + +KPX b uhungarumlaut -20 + +KPX b umacron -20 + +KPX b uogonek -20 + +KPX b uring -20 + +KPX c h -10 + +KPX c k -10 + +KPX c kcommaaccent -10 + +KPX cacute h -10 + +KPX cacute k -10 + +KPX cacute kcommaaccent -10 + +KPX ccaron h -10 + +KPX ccaron k -10 + +KPX ccaron kcommaaccent -10 + +KPX ccedilla h -10 + +KPX ccedilla k -10 + +KPX ccedilla kcommaaccent -10 + +KPX comma quotedblright -95 + +KPX comma quoteright -95 + +KPX e b -10 + +KPX eacute b -10 + +KPX ecaron b -10 + +KPX ecircumflex b -10 + +KPX edieresis b -10 + +KPX edotaccent b -10 + +KPX egrave b -10 + +KPX emacron b -10 + +KPX eogonek b -10 + +KPX f comma -10 + +KPX f dotlessi -30 + +KPX f e -10 + +KPX f eacute -10 + +KPX f edotaccent -10 + +KPX f eogonek -10 + +KPX f f -18 + +KPX f o -10 + +KPX f oacute -10 + +KPX f ocircumflex -10 + +KPX f ograve -10 + +KPX f ohungarumlaut -10 + +KPX f oslash -10 + +KPX f otilde -10 + +KPX f period -10 + +KPX f quoteright 55 + +KPX k e -30 + +KPX k eacute -30 + +KPX k ecaron -30 + +KPX k ecircumflex -30 + +KPX k edieresis -30 + +KPX k edotaccent -30 + +KPX k egrave -30 + +KPX k emacron -30 + +KPX k eogonek -30 + +KPX k o -10 + +KPX k oacute -10 + +KPX k ocircumflex -10 + +KPX k odieresis -10 + +KPX k ograve -10 + +KPX k ohungarumlaut -10 + +KPX k omacron -10 + +KPX k oslash -10 + +KPX k otilde -10 + +KPX kcommaaccent e -30 + +KPX kcommaaccent eacute -30 + +KPX kcommaaccent ecaron -30 + +KPX kcommaaccent ecircumflex -30 + +KPX kcommaaccent edieresis -30 + +KPX kcommaaccent edotaccent -30 + +KPX kcommaaccent egrave -30 + +KPX kcommaaccent emacron -30 + +KPX kcommaaccent eogonek -30 + +KPX kcommaaccent o -10 + +KPX kcommaaccent oacute -10 + +KPX kcommaaccent ocircumflex -10 + +KPX kcommaaccent odieresis -10 + +KPX kcommaaccent ograve -10 + +KPX kcommaaccent ohungarumlaut -10 + +KPX kcommaaccent omacron -10 + +KPX kcommaaccent oslash -10 + +KPX kcommaaccent otilde -10 + +KPX n v -40 + +KPX nacute v -40 + +KPX ncaron v -40 + +KPX ncommaaccent v -40 + +KPX ntilde v -40 + +KPX o v -15 + +KPX o w -25 + +KPX o x -10 + +KPX o y -10 + +KPX o yacute -10 + +KPX o ydieresis -10 + +KPX oacute v -15 + +KPX oacute w -25 + +KPX oacute x -10 + +KPX oacute y -10 + +KPX oacute yacute -10 + +KPX oacute ydieresis -10 + +KPX ocircumflex v -15 + +KPX ocircumflex w -25 + +KPX ocircumflex x -10 + +KPX ocircumflex y -10 + +KPX ocircumflex yacute -10 + +KPX ocircumflex ydieresis -10 + +KPX odieresis v -15 + +KPX odieresis w -25 + +KPX odieresis x -10 + +KPX odieresis y -10 + +KPX odieresis yacute -10 + +KPX odieresis ydieresis -10 + +KPX ograve v -15 + +KPX ograve w -25 + +KPX ograve x -10 + +KPX ograve y -10 + +KPX ograve yacute -10 + +KPX ograve ydieresis -10 + +KPX ohungarumlaut v -15 + +KPX ohungarumlaut w -25 + +KPX ohungarumlaut x -10 + +KPX ohungarumlaut y -10 + +KPX ohungarumlaut yacute -10 + +KPX ohungarumlaut ydieresis -10 + +KPX omacron v -15 + +KPX omacron w -25 + +KPX omacron x -10 + +KPX omacron y -10 + +KPX omacron yacute -10 + +KPX omacron ydieresis -10 + +KPX oslash v -15 + +KPX oslash w -25 + +KPX oslash x -10 + +KPX oslash y -10 + +KPX oslash yacute -10 + +KPX oslash ydieresis -10 + +KPX otilde v -15 + +KPX otilde w -25 + +KPX otilde x -10 + +KPX otilde y -10 + +KPX otilde yacute -10 + +KPX otilde ydieresis -10 + +KPX period quotedblright -95 + +KPX period quoteright -95 + +KPX quoteleft quoteleft -74 + +KPX quoteright d -15 + +KPX quoteright dcroat -15 + +KPX quoteright quoteright -74 + +KPX quoteright r -15 + +KPX quoteright racute -15 + +KPX quoteright rcaron -15 + +KPX quoteright rcommaaccent -15 + +KPX quoteright s -74 + +KPX quoteright sacute -74 + +KPX quoteright scaron -74 + +KPX quoteright scedilla -74 + +KPX quoteright scommaaccent -74 + +KPX quoteright space -74 + +KPX quoteright t -37 + +KPX quoteright tcommaaccent -37 + +KPX quoteright v -15 + +KPX r comma -65 + +KPX r period -65 + +KPX racute comma -65 + +KPX racute period -65 + +KPX rcaron comma -65 + +KPX rcaron period -65 + +KPX rcommaaccent comma -65 + +KPX rcommaaccent period -65 + +KPX space A -37 + +KPX space Aacute -37 + +KPX space Abreve -37 + +KPX space Acircumflex -37 + +KPX space Adieresis -37 + +KPX space Agrave -37 + +KPX space Amacron -37 + +KPX space Aogonek -37 + +KPX space Aring -37 + +KPX space Atilde -37 + +KPX space V -70 + +KPX space W -70 + +KPX space Y -70 + +KPX space Yacute -70 + +KPX space Ydieresis -70 + +KPX v comma -37 + +KPX v e -15 + +KPX v eacute -15 + +KPX v ecaron -15 + +KPX v ecircumflex -15 + +KPX v edieresis -15 + +KPX v edotaccent -15 + +KPX v egrave -15 + +KPX v emacron -15 + +KPX v eogonek -15 + +KPX v o -15 + +KPX v oacute -15 + +KPX v ocircumflex -15 + +KPX v odieresis -15 + +KPX v ograve -15 + +KPX v ohungarumlaut -15 + +KPX v omacron -15 + +KPX v oslash -15 + +KPX v otilde -15 + +KPX v period -37 + +KPX w a -10 + +KPX w aacute -10 + +KPX w abreve -10 + +KPX w acircumflex -10 + +KPX w adieresis -10 + +KPX w agrave -10 + +KPX w amacron -10 + +KPX w aogonek -10 + +KPX w aring -10 + +KPX w atilde -10 + +KPX w comma -37 + +KPX w e -10 + +KPX w eacute -10 + +KPX w ecaron -10 + +KPX w ecircumflex -10 + +KPX w edieresis -10 + +KPX w edotaccent -10 + +KPX w egrave -10 + +KPX w emacron -10 + +KPX w eogonek -10 + +KPX w o -15 + +KPX w oacute -15 + +KPX w ocircumflex -15 + +KPX w odieresis -15 + +KPX w ograve -15 + +KPX w ohungarumlaut -15 + +KPX w omacron -15 + +KPX w oslash -15 + +KPX w otilde -15 + +KPX w period -37 + +KPX x e -10 + +KPX x eacute -10 + +KPX x ecaron -10 + +KPX x ecircumflex -10 + +KPX x edieresis -10 + +KPX x edotaccent -10 + +KPX x egrave -10 + +KPX x emacron -10 + +KPX x eogonek -10 + +KPX y comma -37 + +KPX y period -37 + +KPX yacute comma -37 + +KPX yacute period -37 + +KPX ydieresis comma -37 + +KPX ydieresis period -37 + +EndKernPairs + +EndKernData + +EndFontMetrics + diff --git a/src/Broadside/Fonts/Data/Afm/Times-Italic.afm b/src/Broadside/Fonts/Data/Afm/Times-Italic.afm new file mode 100644 index 00000000..2b9341f7 --- /dev/null +++ b/src/Broadside/Fonts/Data/Afm/Times-Italic.afm @@ -0,0 +1,5334 @@ +StartFontMetrics 4.1 + +Comment Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. + +Comment Creation Date: Thu May 1 12:56:55 1997 + +Comment UniqueID 43067 + +Comment VMusage 47727 58752 + +FontName Times-Italic + +FullName Times Italic + +FamilyName Times + +Weight Medium + +ItalicAngle -15.5 + +IsFixedPitch false + +CharacterSet ExtendedRoman + +FontBBox -169 -217 1010 883 + +UnderlinePosition -100 + +UnderlineThickness 50 + +Version 002.000 + +Notice Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.Times is a trademark of Linotype-Hell AG and/or its subsidiaries. + +EncodingScheme AdobeStandardEncoding + +CapHeight 653 + +XHeight 441 + +Ascender 683 + +Descender -217 + +StdHW 32 + +StdVW 76 + +StartCharMetrics 315 + +C 32 ; WX 250 ; N space ; B 0 0 0 0 ; + +C 33 ; WX 333 ; N exclam ; B 39 -11 302 667 ; + +C 34 ; WX 420 ; N quotedbl ; B 144 421 432 666 ; + +C 35 ; WX 500 ; N numbersign ; B 2 0 540 676 ; + +C 36 ; WX 500 ; N dollar ; B 31 -89 497 731 ; + +C 37 ; WX 833 ; N percent ; B 79 -13 790 676 ; + +C 38 ; WX 778 ; N ampersand ; B 76 -18 723 666 ; + +C 39 ; WX 333 ; N quoteright ; B 151 436 290 666 ; + +C 40 ; WX 333 ; N parenleft ; B 42 -181 315 669 ; + +C 41 ; WX 333 ; N parenright ; B 16 -180 289 669 ; + +C 42 ; WX 500 ; N asterisk ; B 128 255 492 666 ; + +C 43 ; WX 675 ; N plus ; B 86 0 590 506 ; + +C 44 ; WX 250 ; N comma ; B -4 -129 135 101 ; + +C 45 ; WX 333 ; N hyphen ; B 49 192 282 255 ; + +C 46 ; WX 250 ; N period ; B 27 -11 138 100 ; + +C 47 ; WX 278 ; N slash ; B -65 -18 386 666 ; + +C 48 ; WX 500 ; N zero ; B 32 -7 497 676 ; + +C 49 ; WX 500 ; N one ; B 49 0 409 676 ; + +C 50 ; WX 500 ; N two ; B 12 0 452 676 ; + +C 51 ; WX 500 ; N three ; B 15 -7 465 676 ; + +C 52 ; WX 500 ; N four ; B 1 0 479 676 ; + +C 53 ; WX 500 ; N five ; B 15 -7 491 666 ; + +C 54 ; WX 500 ; N six ; B 30 -7 521 686 ; + +C 55 ; WX 500 ; N seven ; B 75 -8 537 666 ; + +C 56 ; WX 500 ; N eight ; B 30 -7 493 676 ; + +C 57 ; WX 500 ; N nine ; B 23 -17 492 676 ; + +C 58 ; WX 333 ; N colon ; B 50 -11 261 441 ; + +C 59 ; WX 333 ; N semicolon ; B 27 -129 261 441 ; + +C 60 ; WX 675 ; N less ; B 84 -8 592 514 ; + +C 61 ; WX 675 ; N equal ; B 86 120 590 386 ; + +C 62 ; WX 675 ; N greater ; B 84 -8 592 514 ; + +C 63 ; WX 500 ; N question ; B 132 -12 472 664 ; + +C 64 ; WX 920 ; N at ; B 118 -18 806 666 ; + +C 65 ; WX 611 ; N A ; B -51 0 564 668 ; + +C 66 ; WX 611 ; N B ; B -8 0 588 653 ; + +C 67 ; WX 667 ; N C ; B 66 -18 689 666 ; + +C 68 ; WX 722 ; N D ; B -8 0 700 653 ; + +C 69 ; WX 611 ; N E ; B -1 0 634 653 ; + +C 70 ; WX 611 ; N F ; B 8 0 645 653 ; + +C 71 ; WX 722 ; N G ; B 52 -18 722 666 ; + +C 72 ; WX 722 ; N H ; B -8 0 767 653 ; + +C 73 ; WX 333 ; N I ; B -8 0 384 653 ; + +C 74 ; WX 444 ; N J ; B -6 -18 491 653 ; + +C 75 ; WX 667 ; N K ; B 7 0 722 653 ; + +C 76 ; WX 556 ; N L ; B -8 0 559 653 ; + +C 77 ; WX 833 ; N M ; B -18 0 873 653 ; + +C 78 ; WX 667 ; N N ; B -20 -15 727 653 ; + +C 79 ; WX 722 ; N O ; B 60 -18 699 666 ; + +C 80 ; WX 611 ; N P ; B 0 0 605 653 ; + +C 81 ; WX 722 ; N Q ; B 59 -182 699 666 ; + +C 82 ; WX 611 ; N R ; B -13 0 588 653 ; + +C 83 ; WX 500 ; N S ; B 17 -18 508 667 ; + +C 84 ; WX 556 ; N T ; B 59 0 633 653 ; + +C 85 ; WX 722 ; N U ; B 102 -18 765 653 ; + +C 86 ; WX 611 ; N V ; B 76 -18 688 653 ; + +C 87 ; WX 833 ; N W ; B 71 -18 906 653 ; + +C 88 ; WX 611 ; N X ; B -29 0 655 653 ; + +C 89 ; WX 556 ; N Y ; B 78 0 633 653 ; + +C 90 ; WX 556 ; N Z ; B -6 0 606 653 ; + +C 91 ; WX 389 ; N bracketleft ; B 21 -153 391 663 ; + +C 92 ; WX 278 ; N backslash ; B -41 -18 319 666 ; + +C 93 ; WX 389 ; N bracketright ; B 12 -153 382 663 ; + +C 94 ; WX 422 ; N asciicircum ; B 0 301 422 666 ; + +C 95 ; WX 500 ; N underscore ; B 0 -125 500 -75 ; + +C 96 ; WX 333 ; N quoteleft ; B 171 436 310 666 ; + +C 97 ; WX 500 ; N a ; B 17 -11 476 441 ; + +C 98 ; WX 500 ; N b ; B 23 -11 473 683 ; + +C 99 ; WX 444 ; N c ; B 30 -11 425 441 ; + +C 100 ; WX 500 ; N d ; B 15 -13 527 683 ; + +C 101 ; WX 444 ; N e ; B 31 -11 412 441 ; + +C 102 ; WX 278 ; N f ; B -147 -207 424 678 ; L i fi ; L l fl ; + +C 103 ; WX 500 ; N g ; B 8 -206 472 441 ; + +C 104 ; WX 500 ; N h ; B 19 -9 478 683 ; + +C 105 ; WX 278 ; N i ; B 49 -11 264 654 ; + +C 106 ; WX 278 ; N j ; B -124 -207 276 654 ; + +C 107 ; WX 444 ; N k ; B 14 -11 461 683 ; + +C 108 ; WX 278 ; N l ; B 41 -11 279 683 ; + +C 109 ; WX 722 ; N m ; B 12 -9 704 441 ; + +C 110 ; WX 500 ; N n ; B 14 -9 474 441 ; + +C 111 ; WX 500 ; N o ; B 27 -11 468 441 ; + +C 112 ; WX 500 ; N p ; B -75 -205 469 441 ; + +C 113 ; WX 500 ; N q ; B 25 -209 483 441 ; + +C 114 ; WX 389 ; N r ; B 45 0 412 441 ; + +C 115 ; WX 389 ; N s ; B 16 -13 366 442 ; + +C 116 ; WX 278 ; N t ; B 37 -11 296 546 ; + +C 117 ; WX 500 ; N u ; B 42 -11 475 441 ; + +C 118 ; WX 444 ; N v ; B 21 -18 426 441 ; + +C 119 ; WX 667 ; N w ; B 16 -18 648 441 ; + +C 120 ; WX 444 ; N x ; B -27 -11 447 441 ; + +C 121 ; WX 444 ; N y ; B -24 -206 426 441 ; + +C 122 ; WX 389 ; N z ; B -2 -81 380 428 ; + +C 123 ; WX 400 ; N braceleft ; B 51 -177 407 687 ; + +C 124 ; WX 275 ; N bar ; B 105 -217 171 783 ; + +C 125 ; WX 400 ; N braceright ; B -7 -177 349 687 ; + +C 126 ; WX 541 ; N asciitilde ; B 40 183 502 323 ; + +C 161 ; WX 389 ; N exclamdown ; B 59 -205 322 473 ; + +C 162 ; WX 500 ; N cent ; B 77 -143 472 560 ; + +C 163 ; WX 500 ; N sterling ; B 10 -6 517 670 ; + +C 164 ; WX 167 ; N fraction ; B -169 -10 337 676 ; + +C 165 ; WX 500 ; N yen ; B 27 0 603 653 ; + +C 166 ; WX 500 ; N florin ; B 25 -182 507 682 ; + +C 167 ; WX 500 ; N section ; B 53 -162 461 666 ; + +C 168 ; WX 500 ; N currency ; B -22 53 522 597 ; + +C 169 ; WX 214 ; N quotesingle ; B 132 421 241 666 ; + +C 170 ; WX 556 ; N quotedblleft ; B 166 436 514 666 ; + +C 171 ; WX 500 ; N guillemotleft ; B 53 37 445 403 ; + +C 172 ; WX 333 ; N guilsinglleft ; B 51 37 281 403 ; + +C 173 ; WX 333 ; N guilsinglright ; B 52 37 282 403 ; + +C 174 ; WX 500 ; N fi ; B -141 -207 481 681 ; + +C 175 ; WX 500 ; N fl ; B -141 -204 518 682 ; + +C 177 ; WX 500 ; N endash ; B -6 197 505 243 ; + +C 178 ; WX 500 ; N dagger ; B 101 -159 488 666 ; + +C 179 ; WX 500 ; N daggerdbl ; B 22 -143 491 666 ; + +C 180 ; WX 250 ; N periodcentered ; B 70 199 181 310 ; + +C 182 ; WX 523 ; N paragraph ; B 55 -123 616 653 ; + +C 183 ; WX 350 ; N bullet ; B 40 191 310 461 ; + +C 184 ; WX 333 ; N quotesinglbase ; B 44 -129 183 101 ; + +C 185 ; WX 556 ; N quotedblbase ; B 57 -129 405 101 ; + +C 186 ; WX 556 ; N quotedblright ; B 151 436 499 666 ; + +C 187 ; WX 500 ; N guillemotright ; B 55 37 447 403 ; + +C 188 ; WX 889 ; N ellipsis ; B 57 -11 762 100 ; + +C 189 ; WX 1000 ; N perthousand ; B 25 -19 1010 706 ; + +C 191 ; WX 500 ; N questiondown ; B 28 -205 368 471 ; + +C 193 ; WX 333 ; N grave ; B 121 492 311 664 ; + +C 194 ; WX 333 ; N acute ; B 180 494 403 664 ; + +C 195 ; WX 333 ; N circumflex ; B 91 492 385 661 ; + +C 196 ; WX 333 ; N tilde ; B 100 517 427 624 ; + +C 197 ; WX 333 ; N macron ; B 99 532 411 583 ; + +C 198 ; WX 333 ; N breve ; B 117 492 418 650 ; + +C 199 ; WX 333 ; N dotaccent ; B 207 548 305 646 ; + +C 200 ; WX 333 ; N dieresis ; B 107 548 405 646 ; + +C 202 ; WX 333 ; N ring ; B 155 492 355 691 ; + +C 203 ; WX 333 ; N cedilla ; B -30 -217 182 0 ; + +C 205 ; WX 333 ; N hungarumlaut ; B 93 494 486 664 ; + +C 206 ; WX 333 ; N ogonek ; B 20 -169 203 40 ; + +C 207 ; WX 333 ; N caron ; B 121 492 426 661 ; + +C 208 ; WX 889 ; N emdash ; B -6 197 894 243 ; + +C 225 ; WX 889 ; N AE ; B -27 0 911 653 ; + +C 227 ; WX 276 ; N ordfeminine ; B 42 406 352 676 ; + +C 232 ; WX 556 ; N Lslash ; B -8 0 559 653 ; + +C 233 ; WX 722 ; N Oslash ; B 60 -105 699 722 ; + +C 234 ; WX 944 ; N OE ; B 49 -8 964 666 ; + +C 235 ; WX 310 ; N ordmasculine ; B 67 406 362 676 ; + +C 241 ; WX 667 ; N ae ; B 23 -11 640 441 ; + +C 245 ; WX 278 ; N dotlessi ; B 49 -11 235 441 ; + +C 248 ; WX 278 ; N lslash ; B 41 -11 312 683 ; + +C 249 ; WX 500 ; N oslash ; B 28 -135 469 554 ; + +C 250 ; WX 667 ; N oe ; B 20 -12 646 441 ; + +C 251 ; WX 500 ; N germandbls ; B -168 -207 493 679 ; + +C -1 ; WX 333 ; N Idieresis ; B -8 0 435 818 ; + +C -1 ; WX 444 ; N eacute ; B 31 -11 459 664 ; + +C -1 ; WX 500 ; N abreve ; B 17 -11 502 650 ; + +C -1 ; WX 500 ; N uhungarumlaut ; B 42 -11 580 664 ; + +C -1 ; WX 444 ; N ecaron ; B 31 -11 482 661 ; + +C -1 ; WX 556 ; N Ydieresis ; B 78 0 633 818 ; + +C -1 ; WX 675 ; N divide ; B 86 -11 590 517 ; + +C -1 ; WX 556 ; N Yacute ; B 78 0 633 876 ; + +C -1 ; WX 611 ; N Acircumflex ; B -51 0 564 873 ; + +C -1 ; WX 500 ; N aacute ; B 17 -11 487 664 ; + +C -1 ; WX 722 ; N Ucircumflex ; B 102 -18 765 873 ; + +C -1 ; WX 444 ; N yacute ; B -24 -206 459 664 ; + +C -1 ; WX 389 ; N scommaaccent ; B 16 -217 366 442 ; + +C -1 ; WX 444 ; N ecircumflex ; B 31 -11 441 661 ; + +C -1 ; WX 722 ; N Uring ; B 102 -18 765 883 ; + +C -1 ; WX 722 ; N Udieresis ; B 102 -18 765 818 ; + +C -1 ; WX 500 ; N aogonek ; B 17 -169 476 441 ; + +C -1 ; WX 722 ; N Uacute ; B 102 -18 765 876 ; + +C -1 ; WX 500 ; N uogonek ; B 42 -169 477 441 ; + +C -1 ; WX 611 ; N Edieresis ; B -1 0 634 818 ; + +C -1 ; WX 722 ; N Dcroat ; B -8 0 700 653 ; + +C -1 ; WX 250 ; N commaaccent ; B 8 -217 133 -50 ; + +C -1 ; WX 760 ; N copyright ; B 41 -18 719 666 ; + +C -1 ; WX 611 ; N Emacron ; B -1 0 634 795 ; + +C -1 ; WX 444 ; N ccaron ; B 30 -11 482 661 ; + +C -1 ; WX 500 ; N aring ; B 17 -11 476 691 ; + +C -1 ; WX 667 ; N Ncommaaccent ; B -20 -187 727 653 ; + +C -1 ; WX 278 ; N lacute ; B 41 -11 395 876 ; + +C -1 ; WX 500 ; N agrave ; B 17 -11 476 664 ; + +C -1 ; WX 556 ; N Tcommaaccent ; B 59 -217 633 653 ; + +C -1 ; WX 667 ; N Cacute ; B 66 -18 690 876 ; + +C -1 ; WX 500 ; N atilde ; B 17 -11 511 624 ; + +C -1 ; WX 611 ; N Edotaccent ; B -1 0 634 818 ; + +C -1 ; WX 389 ; N scaron ; B 16 -13 454 661 ; + +C -1 ; WX 389 ; N scedilla ; B 16 -217 366 442 ; + +C -1 ; WX 278 ; N iacute ; B 49 -11 355 664 ; + +C -1 ; WX 471 ; N lozenge ; B 13 0 459 724 ; + +C -1 ; WX 611 ; N Rcaron ; B -13 0 588 873 ; + +C -1 ; WX 722 ; N Gcommaaccent ; B 52 -217 722 666 ; + +C -1 ; WX 500 ; N ucircumflex ; B 42 -11 475 661 ; + +C -1 ; WX 500 ; N acircumflex ; B 17 -11 476 661 ; + +C -1 ; WX 611 ; N Amacron ; B -51 0 564 795 ; + +C -1 ; WX 389 ; N rcaron ; B 45 0 434 661 ; + +C -1 ; WX 444 ; N ccedilla ; B 30 -217 425 441 ; + +C -1 ; WX 556 ; N Zdotaccent ; B -6 0 606 818 ; + +C -1 ; WX 611 ; N Thorn ; B 0 0 569 653 ; + +C -1 ; WX 722 ; N Omacron ; B 60 -18 699 795 ; + +C -1 ; WX 611 ; N Racute ; B -13 0 588 876 ; + +C -1 ; WX 500 ; N Sacute ; B 17 -18 508 876 ; + +C -1 ; WX 544 ; N dcaron ; B 15 -13 658 683 ; + +C -1 ; WX 722 ; N Umacron ; B 102 -18 765 795 ; + +C -1 ; WX 500 ; N uring ; B 42 -11 475 691 ; + +C -1 ; WX 300 ; N threesuperior ; B 43 268 339 676 ; + +C -1 ; WX 722 ; N Ograve ; B 60 -18 699 876 ; + +C -1 ; WX 611 ; N Agrave ; B -51 0 564 876 ; + +C -1 ; WX 611 ; N Abreve ; B -51 0 564 862 ; + +C -1 ; WX 675 ; N multiply ; B 93 8 582 497 ; + +C -1 ; WX 500 ; N uacute ; B 42 -11 477 664 ; + +C -1 ; WX 556 ; N Tcaron ; B 59 0 633 873 ; + +C -1 ; WX 476 ; N partialdiff ; B 17 -38 459 710 ; + +C -1 ; WX 444 ; N ydieresis ; B -24 -206 441 606 ; + +C -1 ; WX 667 ; N Nacute ; B -20 -15 727 876 ; + +C -1 ; WX 278 ; N icircumflex ; B 33 -11 327 661 ; + +C -1 ; WX 611 ; N Ecircumflex ; B -1 0 634 873 ; + +C -1 ; WX 500 ; N adieresis ; B 17 -11 489 606 ; + +C -1 ; WX 444 ; N edieresis ; B 31 -11 451 606 ; + +C -1 ; WX 444 ; N cacute ; B 30 -11 459 664 ; + +C -1 ; WX 500 ; N nacute ; B 14 -9 477 664 ; + +C -1 ; WX 500 ; N umacron ; B 42 -11 485 583 ; + +C -1 ; WX 667 ; N Ncaron ; B -20 -15 727 873 ; + +C -1 ; WX 333 ; N Iacute ; B -8 0 433 876 ; + +C -1 ; WX 675 ; N plusminus ; B 86 0 590 506 ; + +C -1 ; WX 275 ; N brokenbar ; B 105 -142 171 708 ; + +C -1 ; WX 760 ; N registered ; B 41 -18 719 666 ; + +C -1 ; WX 722 ; N Gbreve ; B 52 -18 722 862 ; + +C -1 ; WX 333 ; N Idotaccent ; B -8 0 384 818 ; + +C -1 ; WX 600 ; N summation ; B 15 -10 585 706 ; + +C -1 ; WX 611 ; N Egrave ; B -1 0 634 876 ; + +C -1 ; WX 389 ; N racute ; B 45 0 431 664 ; + +C -1 ; WX 500 ; N omacron ; B 27 -11 495 583 ; + +C -1 ; WX 556 ; N Zacute ; B -6 0 606 876 ; + +C -1 ; WX 556 ; N Zcaron ; B -6 0 606 873 ; + +C -1 ; WX 549 ; N greaterequal ; B 26 0 523 658 ; + +C -1 ; WX 722 ; N Eth ; B -8 0 700 653 ; + +C -1 ; WX 667 ; N Ccedilla ; B 66 -217 689 666 ; + +C -1 ; WX 278 ; N lcommaaccent ; B 22 -217 279 683 ; + +C -1 ; WX 300 ; N tcaron ; B 37 -11 407 681 ; + +C -1 ; WX 444 ; N eogonek ; B 31 -169 412 441 ; + +C -1 ; WX 722 ; N Uogonek ; B 102 -184 765 653 ; + +C -1 ; WX 611 ; N Aacute ; B -51 0 564 876 ; + +C -1 ; WX 611 ; N Adieresis ; B -51 0 564 818 ; + +C -1 ; WX 444 ; N egrave ; B 31 -11 412 664 ; + +C -1 ; WX 389 ; N zacute ; B -2 -81 431 664 ; + +C -1 ; WX 278 ; N iogonek ; B 49 -169 264 654 ; + +C -1 ; WX 722 ; N Oacute ; B 60 -18 699 876 ; + +C -1 ; WX 500 ; N oacute ; B 27 -11 487 664 ; + +C -1 ; WX 500 ; N amacron ; B 17 -11 495 583 ; + +C -1 ; WX 389 ; N sacute ; B 16 -13 431 664 ; + +C -1 ; WX 278 ; N idieresis ; B 49 -11 352 606 ; + +C -1 ; WX 722 ; N Ocircumflex ; B 60 -18 699 873 ; + +C -1 ; WX 722 ; N Ugrave ; B 102 -18 765 876 ; + +C -1 ; WX 612 ; N Delta ; B 6 0 608 688 ; + +C -1 ; WX 500 ; N thorn ; B -75 -205 469 683 ; + +C -1 ; WX 300 ; N twosuperior ; B 33 271 324 676 ; + +C -1 ; WX 722 ; N Odieresis ; B 60 -18 699 818 ; + +C -1 ; WX 500 ; N mu ; B -30 -209 497 428 ; + +C -1 ; WX 278 ; N igrave ; B 49 -11 284 664 ; + +C -1 ; WX 500 ; N ohungarumlaut ; B 27 -11 590 664 ; + +C -1 ; WX 611 ; N Eogonek ; B -1 -169 634 653 ; + +C -1 ; WX 500 ; N dcroat ; B 15 -13 572 683 ; + +C -1 ; WX 750 ; N threequarters ; B 23 -10 736 676 ; + +C -1 ; WX 500 ; N Scedilla ; B 17 -217 508 667 ; + +C -1 ; WX 300 ; N lcaron ; B 41 -11 407 683 ; + +C -1 ; WX 667 ; N Kcommaaccent ; B 7 -217 722 653 ; + +C -1 ; WX 556 ; N Lacute ; B -8 0 559 876 ; + +C -1 ; WX 980 ; N trademark ; B 30 247 957 653 ; + +C -1 ; WX 444 ; N edotaccent ; B 31 -11 412 606 ; + +C -1 ; WX 333 ; N Igrave ; B -8 0 384 876 ; + +C -1 ; WX 333 ; N Imacron ; B -8 0 441 795 ; + +C -1 ; WX 611 ; N Lcaron ; B -8 0 586 653 ; + +C -1 ; WX 750 ; N onehalf ; B 34 -10 749 676 ; + +C -1 ; WX 549 ; N lessequal ; B 26 0 523 658 ; + +C -1 ; WX 500 ; N ocircumflex ; B 27 -11 468 661 ; + +C -1 ; WX 500 ; N ntilde ; B 14 -9 476 624 ; + +C -1 ; WX 722 ; N Uhungarumlaut ; B 102 -18 765 876 ; + +C -1 ; WX 611 ; N Eacute ; B -1 0 634 876 ; + +C -1 ; WX 444 ; N emacron ; B 31 -11 457 583 ; + +C -1 ; WX 500 ; N gbreve ; B 8 -206 487 650 ; + +C -1 ; WX 750 ; N onequarter ; B 33 -10 736 676 ; + +C -1 ; WX 500 ; N Scaron ; B 17 -18 520 873 ; + +C -1 ; WX 500 ; N Scommaaccent ; B 17 -217 508 667 ; + +C -1 ; WX 722 ; N Ohungarumlaut ; B 60 -18 699 876 ; + +C -1 ; WX 400 ; N degree ; B 101 390 387 676 ; + +C -1 ; WX 500 ; N ograve ; B 27 -11 468 664 ; + +C -1 ; WX 667 ; N Ccaron ; B 66 -18 689 873 ; + +C -1 ; WX 500 ; N ugrave ; B 42 -11 475 664 ; + +C -1 ; WX 453 ; N radical ; B 2 -60 452 768 ; + +C -1 ; WX 722 ; N Dcaron ; B -8 0 700 873 ; + +C -1 ; WX 389 ; N rcommaaccent ; B -3 -217 412 441 ; + +C -1 ; WX 667 ; N Ntilde ; B -20 -15 727 836 ; + +C -1 ; WX 500 ; N otilde ; B 27 -11 496 624 ; + +C -1 ; WX 611 ; N Rcommaaccent ; B -13 -187 588 653 ; + +C -1 ; WX 556 ; N Lcommaaccent ; B -8 -217 559 653 ; + +C -1 ; WX 611 ; N Atilde ; B -51 0 566 836 ; + +C -1 ; WX 611 ; N Aogonek ; B -51 -169 566 668 ; + +C -1 ; WX 611 ; N Aring ; B -51 0 564 883 ; + +C -1 ; WX 722 ; N Otilde ; B 60 -18 699 836 ; + +C -1 ; WX 389 ; N zdotaccent ; B -2 -81 380 606 ; + +C -1 ; WX 611 ; N Ecaron ; B -1 0 634 873 ; + +C -1 ; WX 333 ; N Iogonek ; B -8 -169 384 653 ; + +C -1 ; WX 444 ; N kcommaaccent ; B 14 -187 461 683 ; + +C -1 ; WX 675 ; N minus ; B 86 220 590 286 ; + +C -1 ; WX 333 ; N Icircumflex ; B -8 0 425 873 ; + +C -1 ; WX 500 ; N ncaron ; B 14 -9 510 661 ; + +C -1 ; WX 278 ; N tcommaaccent ; B 2 -217 296 546 ; + +C -1 ; WX 675 ; N logicalnot ; B 86 108 590 386 ; + +C -1 ; WX 500 ; N odieresis ; B 27 -11 489 606 ; + +C -1 ; WX 500 ; N udieresis ; B 42 -11 479 606 ; + +C -1 ; WX 549 ; N notequal ; B 12 -29 537 541 ; + +C -1 ; WX 500 ; N gcommaaccent ; B 8 -206 472 706 ; + +C -1 ; WX 500 ; N eth ; B 27 -11 482 683 ; + +C -1 ; WX 389 ; N zcaron ; B -2 -81 434 661 ; + +C -1 ; WX 500 ; N ncommaaccent ; B 14 -187 474 441 ; + +C -1 ; WX 300 ; N onesuperior ; B 43 271 284 676 ; + +C -1 ; WX 278 ; N imacron ; B 46 -11 311 583 ; + +C -1 ; WX 500 ; N Euro ; B 0 0 0 0 ; + +EndCharMetrics + +StartKernData + +StartKernPairs 2321 + +KPX A C -30 + +KPX A Cacute -30 + +KPX A Ccaron -30 + +KPX A Ccedilla -30 + +KPX A G -35 + +KPX A Gbreve -35 + +KPX A Gcommaaccent -35 + +KPX A O -40 + +KPX A Oacute -40 + +KPX A Ocircumflex -40 + +KPX A Odieresis -40 + +KPX A Ograve -40 + +KPX A Ohungarumlaut -40 + +KPX A Omacron -40 + +KPX A Oslash -40 + +KPX A Otilde -40 + +KPX A Q -40 + +KPX A T -37 + +KPX A Tcaron -37 + +KPX A Tcommaaccent -37 + +KPX A U -50 + +KPX A Uacute -50 + +KPX A Ucircumflex -50 + +KPX A Udieresis -50 + +KPX A Ugrave -50 + +KPX A Uhungarumlaut -50 + +KPX A Umacron -50 + +KPX A Uogonek -50 + +KPX A Uring -50 + +KPX A V -105 + +KPX A W -95 + +KPX A Y -55 + +KPX A Yacute -55 + +KPX A Ydieresis -55 + +KPX A quoteright -37 + +KPX A u -20 + +KPX A uacute -20 + +KPX A ucircumflex -20 + +KPX A udieresis -20 + +KPX A ugrave -20 + +KPX A uhungarumlaut -20 + +KPX A umacron -20 + +KPX A uogonek -20 + +KPX A uring -20 + +KPX A v -55 + +KPX A w -55 + +KPX A y -55 + +KPX A yacute -55 + +KPX A ydieresis -55 + +KPX Aacute C -30 + +KPX Aacute Cacute -30 + +KPX Aacute Ccaron -30 + +KPX Aacute Ccedilla -30 + +KPX Aacute G -35 + +KPX Aacute Gbreve -35 + +KPX Aacute Gcommaaccent -35 + +KPX Aacute O -40 + +KPX Aacute Oacute -40 + +KPX Aacute Ocircumflex -40 + +KPX Aacute Odieresis -40 + +KPX Aacute Ograve -40 + +KPX Aacute Ohungarumlaut -40 + +KPX Aacute Omacron -40 + +KPX Aacute Oslash -40 + +KPX Aacute Otilde -40 + +KPX Aacute Q -40 + +KPX Aacute T -37 + +KPX Aacute Tcaron -37 + +KPX Aacute Tcommaaccent -37 + +KPX Aacute U -50 + +KPX Aacute Uacute -50 + +KPX Aacute Ucircumflex -50 + +KPX Aacute Udieresis -50 + +KPX Aacute Ugrave -50 + +KPX Aacute Uhungarumlaut -50 + +KPX Aacute Umacron -50 + +KPX Aacute Uogonek -50 + +KPX Aacute Uring -50 + +KPX Aacute V -105 + +KPX Aacute W -95 + +KPX Aacute Y -55 + +KPX Aacute Yacute -55 + +KPX Aacute Ydieresis -55 + +KPX Aacute quoteright -37 + +KPX Aacute u -20 + +KPX Aacute uacute -20 + +KPX Aacute ucircumflex -20 + +KPX Aacute udieresis -20 + +KPX Aacute ugrave -20 + +KPX Aacute uhungarumlaut -20 + +KPX Aacute umacron -20 + +KPX Aacute uogonek -20 + +KPX Aacute uring -20 + +KPX Aacute v -55 + +KPX Aacute w -55 + +KPX Aacute y -55 + +KPX Aacute yacute -55 + +KPX Aacute ydieresis -55 + +KPX Abreve C -30 + +KPX Abreve Cacute -30 + +KPX Abreve Ccaron -30 + +KPX Abreve Ccedilla -30 + +KPX Abreve G -35 + +KPX Abreve Gbreve -35 + +KPX Abreve Gcommaaccent -35 + +KPX Abreve O -40 + +KPX Abreve Oacute -40 + +KPX Abreve Ocircumflex -40 + +KPX Abreve Odieresis -40 + +KPX Abreve Ograve -40 + +KPX Abreve Ohungarumlaut -40 + +KPX Abreve Omacron -40 + +KPX Abreve Oslash -40 + +KPX Abreve Otilde -40 + +KPX Abreve Q -40 + +KPX Abreve T -37 + +KPX Abreve Tcaron -37 + +KPX Abreve Tcommaaccent -37 + +KPX Abreve U -50 + +KPX Abreve Uacute -50 + +KPX Abreve Ucircumflex -50 + +KPX Abreve Udieresis -50 + +KPX Abreve Ugrave -50 + +KPX Abreve Uhungarumlaut -50 + +KPX Abreve Umacron -50 + +KPX Abreve Uogonek -50 + +KPX Abreve Uring -50 + +KPX Abreve V -105 + +KPX Abreve W -95 + +KPX Abreve Y -55 + +KPX Abreve Yacute -55 + +KPX Abreve Ydieresis -55 + +KPX Abreve quoteright -37 + +KPX Abreve u -20 + +KPX Abreve uacute -20 + +KPX Abreve ucircumflex -20 + +KPX Abreve udieresis -20 + +KPX Abreve ugrave -20 + +KPX Abreve uhungarumlaut -20 + +KPX Abreve umacron -20 + +KPX Abreve uogonek -20 + +KPX Abreve uring -20 + +KPX Abreve v -55 + +KPX Abreve w -55 + +KPX Abreve y -55 + +KPX Abreve yacute -55 + +KPX Abreve ydieresis -55 + +KPX Acircumflex C -30 + +KPX Acircumflex Cacute -30 + +KPX Acircumflex Ccaron -30 + +KPX Acircumflex Ccedilla -30 + +KPX Acircumflex G -35 + +KPX Acircumflex Gbreve -35 + +KPX Acircumflex Gcommaaccent -35 + +KPX Acircumflex O -40 + +KPX Acircumflex Oacute -40 + +KPX Acircumflex Ocircumflex -40 + +KPX Acircumflex Odieresis -40 + +KPX Acircumflex Ograve -40 + +KPX Acircumflex Ohungarumlaut -40 + +KPX Acircumflex Omacron -40 + +KPX Acircumflex Oslash -40 + +KPX Acircumflex Otilde -40 + +KPX Acircumflex Q -40 + +KPX Acircumflex T -37 + +KPX Acircumflex Tcaron -37 + +KPX Acircumflex Tcommaaccent -37 + +KPX Acircumflex U -50 + +KPX Acircumflex Uacute -50 + +KPX Acircumflex Ucircumflex -50 + +KPX Acircumflex Udieresis -50 + +KPX Acircumflex Ugrave -50 + +KPX Acircumflex Uhungarumlaut -50 + +KPX Acircumflex Umacron -50 + +KPX Acircumflex Uogonek -50 + +KPX Acircumflex Uring -50 + +KPX Acircumflex V -105 + +KPX Acircumflex W -95 + +KPX Acircumflex Y -55 + +KPX Acircumflex Yacute -55 + +KPX Acircumflex Ydieresis -55 + +KPX Acircumflex quoteright -37 + +KPX Acircumflex u -20 + +KPX Acircumflex uacute -20 + +KPX Acircumflex ucircumflex -20 + +KPX Acircumflex udieresis -20 + +KPX Acircumflex ugrave -20 + +KPX Acircumflex uhungarumlaut -20 + +KPX Acircumflex umacron -20 + +KPX Acircumflex uogonek -20 + +KPX Acircumflex uring -20 + +KPX Acircumflex v -55 + +KPX Acircumflex w -55 + +KPX Acircumflex y -55 + +KPX Acircumflex yacute -55 + +KPX Acircumflex ydieresis -55 + +KPX Adieresis C -30 + +KPX Adieresis Cacute -30 + +KPX Adieresis Ccaron -30 + +KPX Adieresis Ccedilla -30 + +KPX Adieresis G -35 + +KPX Adieresis Gbreve -35 + +KPX Adieresis Gcommaaccent -35 + +KPX Adieresis O -40 + +KPX Adieresis Oacute -40 + +KPX Adieresis Ocircumflex -40 + +KPX Adieresis Odieresis -40 + +KPX Adieresis Ograve -40 + +KPX Adieresis Ohungarumlaut -40 + +KPX Adieresis Omacron -40 + +KPX Adieresis Oslash -40 + +KPX Adieresis Otilde -40 + +KPX Adieresis Q -40 + +KPX Adieresis T -37 + +KPX Adieresis Tcaron -37 + +KPX Adieresis Tcommaaccent -37 + +KPX Adieresis U -50 + +KPX Adieresis Uacute -50 + +KPX Adieresis Ucircumflex -50 + +KPX Adieresis Udieresis -50 + +KPX Adieresis Ugrave -50 + +KPX Adieresis Uhungarumlaut -50 + +KPX Adieresis Umacron -50 + +KPX Adieresis Uogonek -50 + +KPX Adieresis Uring -50 + +KPX Adieresis V -105 + +KPX Adieresis W -95 + +KPX Adieresis Y -55 + +KPX Adieresis Yacute -55 + +KPX Adieresis Ydieresis -55 + +KPX Adieresis quoteright -37 + +KPX Adieresis u -20 + +KPX Adieresis uacute -20 + +KPX Adieresis ucircumflex -20 + +KPX Adieresis udieresis -20 + +KPX Adieresis ugrave -20 + +KPX Adieresis uhungarumlaut -20 + +KPX Adieresis umacron -20 + +KPX Adieresis uogonek -20 + +KPX Adieresis uring -20 + +KPX Adieresis v -55 + +KPX Adieresis w -55 + +KPX Adieresis y -55 + +KPX Adieresis yacute -55 + +KPX Adieresis ydieresis -55 + +KPX Agrave C -30 + +KPX Agrave Cacute -30 + +KPX Agrave Ccaron -30 + +KPX Agrave Ccedilla -30 + +KPX Agrave G -35 + +KPX Agrave Gbreve -35 + +KPX Agrave Gcommaaccent -35 + +KPX Agrave O -40 + +KPX Agrave Oacute -40 + +KPX Agrave Ocircumflex -40 + +KPX Agrave Odieresis -40 + +KPX Agrave Ograve -40 + +KPX Agrave Ohungarumlaut -40 + +KPX Agrave Omacron -40 + +KPX Agrave Oslash -40 + +KPX Agrave Otilde -40 + +KPX Agrave Q -40 + +KPX Agrave T -37 + +KPX Agrave Tcaron -37 + +KPX Agrave Tcommaaccent -37 + +KPX Agrave U -50 + +KPX Agrave Uacute -50 + +KPX Agrave Ucircumflex -50 + +KPX Agrave Udieresis -50 + +KPX Agrave Ugrave -50 + +KPX Agrave Uhungarumlaut -50 + +KPX Agrave Umacron -50 + +KPX Agrave Uogonek -50 + +KPX Agrave Uring -50 + +KPX Agrave V -105 + +KPX Agrave W -95 + +KPX Agrave Y -55 + +KPX Agrave Yacute -55 + +KPX Agrave Ydieresis -55 + +KPX Agrave quoteright -37 + +KPX Agrave u -20 + +KPX Agrave uacute -20 + +KPX Agrave ucircumflex -20 + +KPX Agrave udieresis -20 + +KPX Agrave ugrave -20 + +KPX Agrave uhungarumlaut -20 + +KPX Agrave umacron -20 + +KPX Agrave uogonek -20 + +KPX Agrave uring -20 + +KPX Agrave v -55 + +KPX Agrave w -55 + +KPX Agrave y -55 + +KPX Agrave yacute -55 + +KPX Agrave ydieresis -55 + +KPX Amacron C -30 + +KPX Amacron Cacute -30 + +KPX Amacron Ccaron -30 + +KPX Amacron Ccedilla -30 + +KPX Amacron G -35 + +KPX Amacron Gbreve -35 + +KPX Amacron Gcommaaccent -35 + +KPX Amacron O -40 + +KPX Amacron Oacute -40 + +KPX Amacron Ocircumflex -40 + +KPX Amacron Odieresis -40 + +KPX Amacron Ograve -40 + +KPX Amacron Ohungarumlaut -40 + +KPX Amacron Omacron -40 + +KPX Amacron Oslash -40 + +KPX Amacron Otilde -40 + +KPX Amacron Q -40 + +KPX Amacron T -37 + +KPX Amacron Tcaron -37 + +KPX Amacron Tcommaaccent -37 + +KPX Amacron U -50 + +KPX Amacron Uacute -50 + +KPX Amacron Ucircumflex -50 + +KPX Amacron Udieresis -50 + +KPX Amacron Ugrave -50 + +KPX Amacron Uhungarumlaut -50 + +KPX Amacron Umacron -50 + +KPX Amacron Uogonek -50 + +KPX Amacron Uring -50 + +KPX Amacron V -105 + +KPX Amacron W -95 + +KPX Amacron Y -55 + +KPX Amacron Yacute -55 + +KPX Amacron Ydieresis -55 + +KPX Amacron quoteright -37 + +KPX Amacron u -20 + +KPX Amacron uacute -20 + +KPX Amacron ucircumflex -20 + +KPX Amacron udieresis -20 + +KPX Amacron ugrave -20 + +KPX Amacron uhungarumlaut -20 + +KPX Amacron umacron -20 + +KPX Amacron uogonek -20 + +KPX Amacron uring -20 + +KPX Amacron v -55 + +KPX Amacron w -55 + +KPX Amacron y -55 + +KPX Amacron yacute -55 + +KPX Amacron ydieresis -55 + +KPX Aogonek C -30 + +KPX Aogonek Cacute -30 + +KPX Aogonek Ccaron -30 + +KPX Aogonek Ccedilla -30 + +KPX Aogonek G -35 + +KPX Aogonek Gbreve -35 + +KPX Aogonek Gcommaaccent -35 + +KPX Aogonek O -40 + +KPX Aogonek Oacute -40 + +KPX Aogonek Ocircumflex -40 + +KPX Aogonek Odieresis -40 + +KPX Aogonek Ograve -40 + +KPX Aogonek Ohungarumlaut -40 + +KPX Aogonek Omacron -40 + +KPX Aogonek Oslash -40 + +KPX Aogonek Otilde -40 + +KPX Aogonek Q -40 + +KPX Aogonek T -37 + +KPX Aogonek Tcaron -37 + +KPX Aogonek Tcommaaccent -37 + +KPX Aogonek U -50 + +KPX Aogonek Uacute -50 + +KPX Aogonek Ucircumflex -50 + +KPX Aogonek Udieresis -50 + +KPX Aogonek Ugrave -50 + +KPX Aogonek Uhungarumlaut -50 + +KPX Aogonek Umacron -50 + +KPX Aogonek Uogonek -50 + +KPX Aogonek Uring -50 + +KPX Aogonek V -105 + +KPX Aogonek W -95 + +KPX Aogonek Y -55 + +KPX Aogonek Yacute -55 + +KPX Aogonek Ydieresis -55 + +KPX Aogonek quoteright -37 + +KPX Aogonek u -20 + +KPX Aogonek uacute -20 + +KPX Aogonek ucircumflex -20 + +KPX Aogonek udieresis -20 + +KPX Aogonek ugrave -20 + +KPX Aogonek uhungarumlaut -20 + +KPX Aogonek umacron -20 + +KPX Aogonek uogonek -20 + +KPX Aogonek uring -20 + +KPX Aogonek v -55 + +KPX Aogonek w -55 + +KPX Aogonek y -55 + +KPX Aogonek yacute -55 + +KPX Aogonek ydieresis -55 + +KPX Aring C -30 + +KPX Aring Cacute -30 + +KPX Aring Ccaron -30 + +KPX Aring Ccedilla -30 + +KPX Aring G -35 + +KPX Aring Gbreve -35 + +KPX Aring Gcommaaccent -35 + +KPX Aring O -40 + +KPX Aring Oacute -40 + +KPX Aring Ocircumflex -40 + +KPX Aring Odieresis -40 + +KPX Aring Ograve -40 + +KPX Aring Ohungarumlaut -40 + +KPX Aring Omacron -40 + +KPX Aring Oslash -40 + +KPX Aring Otilde -40 + +KPX Aring Q -40 + +KPX Aring T -37 + +KPX Aring Tcaron -37 + +KPX Aring Tcommaaccent -37 + +KPX Aring U -50 + +KPX Aring Uacute -50 + +KPX Aring Ucircumflex -50 + +KPX Aring Udieresis -50 + +KPX Aring Ugrave -50 + +KPX Aring Uhungarumlaut -50 + +KPX Aring Umacron -50 + +KPX Aring Uogonek -50 + +KPX Aring Uring -50 + +KPX Aring V -105 + +KPX Aring W -95 + +KPX Aring Y -55 + +KPX Aring Yacute -55 + +KPX Aring Ydieresis -55 + +KPX Aring quoteright -37 + +KPX Aring u -20 + +KPX Aring uacute -20 + +KPX Aring ucircumflex -20 + +KPX Aring udieresis -20 + +KPX Aring ugrave -20 + +KPX Aring uhungarumlaut -20 + +KPX Aring umacron -20 + +KPX Aring uogonek -20 + +KPX Aring uring -20 + +KPX Aring v -55 + +KPX Aring w -55 + +KPX Aring y -55 + +KPX Aring yacute -55 + +KPX Aring ydieresis -55 + +KPX Atilde C -30 + +KPX Atilde Cacute -30 + +KPX Atilde Ccaron -30 + +KPX Atilde Ccedilla -30 + +KPX Atilde G -35 + +KPX Atilde Gbreve -35 + +KPX Atilde Gcommaaccent -35 + +KPX Atilde O -40 + +KPX Atilde Oacute -40 + +KPX Atilde Ocircumflex -40 + +KPX Atilde Odieresis -40 + +KPX Atilde Ograve -40 + +KPX Atilde Ohungarumlaut -40 + +KPX Atilde Omacron -40 + +KPX Atilde Oslash -40 + +KPX Atilde Otilde -40 + +KPX Atilde Q -40 + +KPX Atilde T -37 + +KPX Atilde Tcaron -37 + +KPX Atilde Tcommaaccent -37 + +KPX Atilde U -50 + +KPX Atilde Uacute -50 + +KPX Atilde Ucircumflex -50 + +KPX Atilde Udieresis -50 + +KPX Atilde Ugrave -50 + +KPX Atilde Uhungarumlaut -50 + +KPX Atilde Umacron -50 + +KPX Atilde Uogonek -50 + +KPX Atilde Uring -50 + +KPX Atilde V -105 + +KPX Atilde W -95 + +KPX Atilde Y -55 + +KPX Atilde Yacute -55 + +KPX Atilde Ydieresis -55 + +KPX Atilde quoteright -37 + +KPX Atilde u -20 + +KPX Atilde uacute -20 + +KPX Atilde ucircumflex -20 + +KPX Atilde udieresis -20 + +KPX Atilde ugrave -20 + +KPX Atilde uhungarumlaut -20 + +KPX Atilde umacron -20 + +KPX Atilde uogonek -20 + +KPX Atilde uring -20 + +KPX Atilde v -55 + +KPX Atilde w -55 + +KPX Atilde y -55 + +KPX Atilde yacute -55 + +KPX Atilde ydieresis -55 + +KPX B A -25 + +KPX B Aacute -25 + +KPX B Abreve -25 + +KPX B Acircumflex -25 + +KPX B Adieresis -25 + +KPX B Agrave -25 + +KPX B Amacron -25 + +KPX B Aogonek -25 + +KPX B Aring -25 + +KPX B Atilde -25 + +KPX B U -10 + +KPX B Uacute -10 + +KPX B Ucircumflex -10 + +KPX B Udieresis -10 + +KPX B Ugrave -10 + +KPX B Uhungarumlaut -10 + +KPX B Umacron -10 + +KPX B Uogonek -10 + +KPX B Uring -10 + +KPX D A -35 + +KPX D Aacute -35 + +KPX D Abreve -35 + +KPX D Acircumflex -35 + +KPX D Adieresis -35 + +KPX D Agrave -35 + +KPX D Amacron -35 + +KPX D Aogonek -35 + +KPX D Aring -35 + +KPX D Atilde -35 + +KPX D V -40 + +KPX D W -40 + +KPX D Y -40 + +KPX D Yacute -40 + +KPX D Ydieresis -40 + +KPX Dcaron A -35 + +KPX Dcaron Aacute -35 + +KPX Dcaron Abreve -35 + +KPX Dcaron Acircumflex -35 + +KPX Dcaron Adieresis -35 + +KPX Dcaron Agrave -35 + +KPX Dcaron Amacron -35 + +KPX Dcaron Aogonek -35 + +KPX Dcaron Aring -35 + +KPX Dcaron Atilde -35 + +KPX Dcaron V -40 + +KPX Dcaron W -40 + +KPX Dcaron Y -40 + +KPX Dcaron Yacute -40 + +KPX Dcaron Ydieresis -40 + +KPX Dcroat A -35 + +KPX Dcroat Aacute -35 + +KPX Dcroat Abreve -35 + +KPX Dcroat Acircumflex -35 + +KPX Dcroat Adieresis -35 + +KPX Dcroat Agrave -35 + +KPX Dcroat Amacron -35 + +KPX Dcroat Aogonek -35 + +KPX Dcroat Aring -35 + +KPX Dcroat Atilde -35 + +KPX Dcroat V -40 + +KPX Dcroat W -40 + +KPX Dcroat Y -40 + +KPX Dcroat Yacute -40 + +KPX Dcroat Ydieresis -40 + +KPX F A -115 + +KPX F Aacute -115 + +KPX F Abreve -115 + +KPX F Acircumflex -115 + +KPX F Adieresis -115 + +KPX F Agrave -115 + +KPX F Amacron -115 + +KPX F Aogonek -115 + +KPX F Aring -115 + +KPX F Atilde -115 + +KPX F a -75 + +KPX F aacute -75 + +KPX F abreve -75 + +KPX F acircumflex -75 + +KPX F adieresis -75 + +KPX F agrave -75 + +KPX F amacron -75 + +KPX F aogonek -75 + +KPX F aring -75 + +KPX F atilde -75 + +KPX F comma -135 + +KPX F e -75 + +KPX F eacute -75 + +KPX F ecaron -75 + +KPX F ecircumflex -75 + +KPX F edieresis -75 + +KPX F edotaccent -75 + +KPX F egrave -75 + +KPX F emacron -75 + +KPX F eogonek -75 + +KPX F i -45 + +KPX F iacute -45 + +KPX F icircumflex -45 + +KPX F idieresis -45 + +KPX F igrave -45 + +KPX F imacron -45 + +KPX F iogonek -45 + +KPX F o -105 + +KPX F oacute -105 + +KPX F ocircumflex -105 + +KPX F odieresis -105 + +KPX F ograve -105 + +KPX F ohungarumlaut -105 + +KPX F omacron -105 + +KPX F oslash -105 + +KPX F otilde -105 + +KPX F period -135 + +KPX F r -55 + +KPX F racute -55 + +KPX F rcaron -55 + +KPX F rcommaaccent -55 + +KPX J A -40 + +KPX J Aacute -40 + +KPX J Abreve -40 + +KPX J Acircumflex -40 + +KPX J Adieresis -40 + +KPX J Agrave -40 + +KPX J Amacron -40 + +KPX J Aogonek -40 + +KPX J Aring -40 + +KPX J Atilde -40 + +KPX J a -35 + +KPX J aacute -35 + +KPX J abreve -35 + +KPX J acircumflex -35 + +KPX J adieresis -35 + +KPX J agrave -35 + +KPX J amacron -35 + +KPX J aogonek -35 + +KPX J aring -35 + +KPX J atilde -35 + +KPX J comma -25 + +KPX J e -25 + +KPX J eacute -25 + +KPX J ecaron -25 + +KPX J ecircumflex -25 + +KPX J edieresis -25 + +KPX J edotaccent -25 + +KPX J egrave -25 + +KPX J emacron -25 + +KPX J eogonek -25 + +KPX J o -25 + +KPX J oacute -25 + +KPX J ocircumflex -25 + +KPX J odieresis -25 + +KPX J ograve -25 + +KPX J ohungarumlaut -25 + +KPX J omacron -25 + +KPX J oslash -25 + +KPX J otilde -25 + +KPX J period -25 + +KPX J u -35 + +KPX J uacute -35 + +KPX J ucircumflex -35 + +KPX J udieresis -35 + +KPX J ugrave -35 + +KPX J uhungarumlaut -35 + +KPX J umacron -35 + +KPX J uogonek -35 + +KPX J uring -35 + +KPX K O -50 + +KPX K Oacute -50 + +KPX K Ocircumflex -50 + +KPX K Odieresis -50 + +KPX K Ograve -50 + +KPX K Ohungarumlaut -50 + +KPX K Omacron -50 + +KPX K Oslash -50 + +KPX K Otilde -50 + +KPX K e -35 + +KPX K eacute -35 + +KPX K ecaron -35 + +KPX K ecircumflex -35 + +KPX K edieresis -35 + +KPX K edotaccent -35 + +KPX K egrave -35 + +KPX K emacron -35 + +KPX K eogonek -35 + +KPX K o -40 + +KPX K oacute -40 + +KPX K ocircumflex -40 + +KPX K odieresis -40 + +KPX K ograve -40 + +KPX K ohungarumlaut -40 + +KPX K omacron -40 + +KPX K oslash -40 + +KPX K otilde -40 + +KPX K u -40 + +KPX K uacute -40 + +KPX K ucircumflex -40 + +KPX K udieresis -40 + +KPX K ugrave -40 + +KPX K uhungarumlaut -40 + +KPX K umacron -40 + +KPX K uogonek -40 + +KPX K uring -40 + +KPX K y -40 + +KPX K yacute -40 + +KPX K ydieresis -40 + +KPX Kcommaaccent O -50 + +KPX Kcommaaccent Oacute -50 + +KPX Kcommaaccent Ocircumflex -50 + +KPX Kcommaaccent Odieresis -50 + +KPX Kcommaaccent Ograve -50 + +KPX Kcommaaccent Ohungarumlaut -50 + +KPX Kcommaaccent Omacron -50 + +KPX Kcommaaccent Oslash -50 + +KPX Kcommaaccent Otilde -50 + +KPX Kcommaaccent e -35 + +KPX Kcommaaccent eacute -35 + +KPX Kcommaaccent ecaron -35 + +KPX Kcommaaccent ecircumflex -35 + +KPX Kcommaaccent edieresis -35 + +KPX Kcommaaccent edotaccent -35 + +KPX Kcommaaccent egrave -35 + +KPX Kcommaaccent emacron -35 + +KPX Kcommaaccent eogonek -35 + +KPX Kcommaaccent o -40 + +KPX Kcommaaccent oacute -40 + +KPX Kcommaaccent ocircumflex -40 + +KPX Kcommaaccent odieresis -40 + +KPX Kcommaaccent ograve -40 + +KPX Kcommaaccent ohungarumlaut -40 + +KPX Kcommaaccent omacron -40 + +KPX Kcommaaccent oslash -40 + +KPX Kcommaaccent otilde -40 + +KPX Kcommaaccent u -40 + +KPX Kcommaaccent uacute -40 + +KPX Kcommaaccent ucircumflex -40 + +KPX Kcommaaccent udieresis -40 + +KPX Kcommaaccent ugrave -40 + +KPX Kcommaaccent uhungarumlaut -40 + +KPX Kcommaaccent umacron -40 + +KPX Kcommaaccent uogonek -40 + +KPX Kcommaaccent uring -40 + +KPX Kcommaaccent y -40 + +KPX Kcommaaccent yacute -40 + +KPX Kcommaaccent ydieresis -40 + +KPX L T -20 + +KPX L Tcaron -20 + +KPX L Tcommaaccent -20 + +KPX L V -55 + +KPX L W -55 + +KPX L Y -20 + +KPX L Yacute -20 + +KPX L Ydieresis -20 + +KPX L quoteright -37 + +KPX L y -30 + +KPX L yacute -30 + +KPX L ydieresis -30 + +KPX Lacute T -20 + +KPX Lacute Tcaron -20 + +KPX Lacute Tcommaaccent -20 + +KPX Lacute V -55 + +KPX Lacute W -55 + +KPX Lacute Y -20 + +KPX Lacute Yacute -20 + +KPX Lacute Ydieresis -20 + +KPX Lacute quoteright -37 + +KPX Lacute y -30 + +KPX Lacute yacute -30 + +KPX Lacute ydieresis -30 + +KPX Lcommaaccent T -20 + +KPX Lcommaaccent Tcaron -20 + +KPX Lcommaaccent Tcommaaccent -20 + +KPX Lcommaaccent V -55 + +KPX Lcommaaccent W -55 + +KPX Lcommaaccent Y -20 + +KPX Lcommaaccent Yacute -20 + +KPX Lcommaaccent Ydieresis -20 + +KPX Lcommaaccent quoteright -37 + +KPX Lcommaaccent y -30 + +KPX Lcommaaccent yacute -30 + +KPX Lcommaaccent ydieresis -30 + +KPX Lslash T -20 + +KPX Lslash Tcaron -20 + +KPX Lslash Tcommaaccent -20 + +KPX Lslash V -55 + +KPX Lslash W -55 + +KPX Lslash Y -20 + +KPX Lslash Yacute -20 + +KPX Lslash Ydieresis -20 + +KPX Lslash quoteright -37 + +KPX Lslash y -30 + +KPX Lslash yacute -30 + +KPX Lslash ydieresis -30 + +KPX N A -27 + +KPX N Aacute -27 + +KPX N Abreve -27 + +KPX N Acircumflex -27 + +KPX N Adieresis -27 + +KPX N Agrave -27 + +KPX N Amacron -27 + +KPX N Aogonek -27 + +KPX N Aring -27 + +KPX N Atilde -27 + +KPX Nacute A -27 + +KPX Nacute Aacute -27 + +KPX Nacute Abreve -27 + +KPX Nacute Acircumflex -27 + +KPX Nacute Adieresis -27 + +KPX Nacute Agrave -27 + +KPX Nacute Amacron -27 + +KPX Nacute Aogonek -27 + +KPX Nacute Aring -27 + +KPX Nacute Atilde -27 + +KPX Ncaron A -27 + +KPX Ncaron Aacute -27 + +KPX Ncaron Abreve -27 + +KPX Ncaron Acircumflex -27 + +KPX Ncaron Adieresis -27 + +KPX Ncaron Agrave -27 + +KPX Ncaron Amacron -27 + +KPX Ncaron Aogonek -27 + +KPX Ncaron Aring -27 + +KPX Ncaron Atilde -27 + +KPX Ncommaaccent A -27 + +KPX Ncommaaccent Aacute -27 + +KPX Ncommaaccent Abreve -27 + +KPX Ncommaaccent Acircumflex -27 + +KPX Ncommaaccent Adieresis -27 + +KPX Ncommaaccent Agrave -27 + +KPX Ncommaaccent Amacron -27 + +KPX Ncommaaccent Aogonek -27 + +KPX Ncommaaccent Aring -27 + +KPX Ncommaaccent Atilde -27 + +KPX Ntilde A -27 + +KPX Ntilde Aacute -27 + +KPX Ntilde Abreve -27 + +KPX Ntilde Acircumflex -27 + +KPX Ntilde Adieresis -27 + +KPX Ntilde Agrave -27 + +KPX Ntilde Amacron -27 + +KPX Ntilde Aogonek -27 + +KPX Ntilde Aring -27 + +KPX Ntilde Atilde -27 + +KPX O A -55 + +KPX O Aacute -55 + +KPX O Abreve -55 + +KPX O Acircumflex -55 + +KPX O Adieresis -55 + +KPX O Agrave -55 + +KPX O Amacron -55 + +KPX O Aogonek -55 + +KPX O Aring -55 + +KPX O Atilde -55 + +KPX O T -40 + +KPX O Tcaron -40 + +KPX O Tcommaaccent -40 + +KPX O V -50 + +KPX O W -50 + +KPX O X -40 + +KPX O Y -50 + +KPX O Yacute -50 + +KPX O Ydieresis -50 + +KPX Oacute A -55 + +KPX Oacute Aacute -55 + +KPX Oacute Abreve -55 + +KPX Oacute Acircumflex -55 + +KPX Oacute Adieresis -55 + +KPX Oacute Agrave -55 + +KPX Oacute Amacron -55 + +KPX Oacute Aogonek -55 + +KPX Oacute Aring -55 + +KPX Oacute Atilde -55 + +KPX Oacute T -40 + +KPX Oacute Tcaron -40 + +KPX Oacute Tcommaaccent -40 + +KPX Oacute V -50 + +KPX Oacute W -50 + +KPX Oacute X -40 + +KPX Oacute Y -50 + +KPX Oacute Yacute -50 + +KPX Oacute Ydieresis -50 + +KPX Ocircumflex A -55 + +KPX Ocircumflex Aacute -55 + +KPX Ocircumflex Abreve -55 + +KPX Ocircumflex Acircumflex -55 + +KPX Ocircumflex Adieresis -55 + +KPX Ocircumflex Agrave -55 + +KPX Ocircumflex Amacron -55 + +KPX Ocircumflex Aogonek -55 + +KPX Ocircumflex Aring -55 + +KPX Ocircumflex Atilde -55 + +KPX Ocircumflex T -40 + +KPX Ocircumflex Tcaron -40 + +KPX Ocircumflex Tcommaaccent -40 + +KPX Ocircumflex V -50 + +KPX Ocircumflex W -50 + +KPX Ocircumflex X -40 + +KPX Ocircumflex Y -50 + +KPX Ocircumflex Yacute -50 + +KPX Ocircumflex Ydieresis -50 + +KPX Odieresis A -55 + +KPX Odieresis Aacute -55 + +KPX Odieresis Abreve -55 + +KPX Odieresis Acircumflex -55 + +KPX Odieresis Adieresis -55 + +KPX Odieresis Agrave -55 + +KPX Odieresis Amacron -55 + +KPX Odieresis Aogonek -55 + +KPX Odieresis Aring -55 + +KPX Odieresis Atilde -55 + +KPX Odieresis T -40 + +KPX Odieresis Tcaron -40 + +KPX Odieresis Tcommaaccent -40 + +KPX Odieresis V -50 + +KPX Odieresis W -50 + +KPX Odieresis X -40 + +KPX Odieresis Y -50 + +KPX Odieresis Yacute -50 + +KPX Odieresis Ydieresis -50 + +KPX Ograve A -55 + +KPX Ograve Aacute -55 + +KPX Ograve Abreve -55 + +KPX Ograve Acircumflex -55 + +KPX Ograve Adieresis -55 + +KPX Ograve Agrave -55 + +KPX Ograve Amacron -55 + +KPX Ograve Aogonek -55 + +KPX Ograve Aring -55 + +KPX Ograve Atilde -55 + +KPX Ograve T -40 + +KPX Ograve Tcaron -40 + +KPX Ograve Tcommaaccent -40 + +KPX Ograve V -50 + +KPX Ograve W -50 + +KPX Ograve X -40 + +KPX Ograve Y -50 + +KPX Ograve Yacute -50 + +KPX Ograve Ydieresis -50 + +KPX Ohungarumlaut A -55 + +KPX Ohungarumlaut Aacute -55 + +KPX Ohungarumlaut Abreve -55 + +KPX Ohungarumlaut Acircumflex -55 + +KPX Ohungarumlaut Adieresis -55 + +KPX Ohungarumlaut Agrave -55 + +KPX Ohungarumlaut Amacron -55 + +KPX Ohungarumlaut Aogonek -55 + +KPX Ohungarumlaut Aring -55 + +KPX Ohungarumlaut Atilde -55 + +KPX Ohungarumlaut T -40 + +KPX Ohungarumlaut Tcaron -40 + +KPX Ohungarumlaut Tcommaaccent -40 + +KPX Ohungarumlaut V -50 + +KPX Ohungarumlaut W -50 + +KPX Ohungarumlaut X -40 + +KPX Ohungarumlaut Y -50 + +KPX Ohungarumlaut Yacute -50 + +KPX Ohungarumlaut Ydieresis -50 + +KPX Omacron A -55 + +KPX Omacron Aacute -55 + +KPX Omacron Abreve -55 + +KPX Omacron Acircumflex -55 + +KPX Omacron Adieresis -55 + +KPX Omacron Agrave -55 + +KPX Omacron Amacron -55 + +KPX Omacron Aogonek -55 + +KPX Omacron Aring -55 + +KPX Omacron Atilde -55 + +KPX Omacron T -40 + +KPX Omacron Tcaron -40 + +KPX Omacron Tcommaaccent -40 + +KPX Omacron V -50 + +KPX Omacron W -50 + +KPX Omacron X -40 + +KPX Omacron Y -50 + +KPX Omacron Yacute -50 + +KPX Omacron Ydieresis -50 + +KPX Oslash A -55 + +KPX Oslash Aacute -55 + +KPX Oslash Abreve -55 + +KPX Oslash Acircumflex -55 + +KPX Oslash Adieresis -55 + +KPX Oslash Agrave -55 + +KPX Oslash Amacron -55 + +KPX Oslash Aogonek -55 + +KPX Oslash Aring -55 + +KPX Oslash Atilde -55 + +KPX Oslash T -40 + +KPX Oslash Tcaron -40 + +KPX Oslash Tcommaaccent -40 + +KPX Oslash V -50 + +KPX Oslash W -50 + +KPX Oslash X -40 + +KPX Oslash Y -50 + +KPX Oslash Yacute -50 + +KPX Oslash Ydieresis -50 + +KPX Otilde A -55 + +KPX Otilde Aacute -55 + +KPX Otilde Abreve -55 + +KPX Otilde Acircumflex -55 + +KPX Otilde Adieresis -55 + +KPX Otilde Agrave -55 + +KPX Otilde Amacron -55 + +KPX Otilde Aogonek -55 + +KPX Otilde Aring -55 + +KPX Otilde Atilde -55 + +KPX Otilde T -40 + +KPX Otilde Tcaron -40 + +KPX Otilde Tcommaaccent -40 + +KPX Otilde V -50 + +KPX Otilde W -50 + +KPX Otilde X -40 + +KPX Otilde Y -50 + +KPX Otilde Yacute -50 + +KPX Otilde Ydieresis -50 + +KPX P A -90 + +KPX P Aacute -90 + +KPX P Abreve -90 + +KPX P Acircumflex -90 + +KPX P Adieresis -90 + +KPX P Agrave -90 + +KPX P Amacron -90 + +KPX P Aogonek -90 + +KPX P Aring -90 + +KPX P Atilde -90 + +KPX P a -80 + +KPX P aacute -80 + +KPX P abreve -80 + +KPX P acircumflex -80 + +KPX P adieresis -80 + +KPX P agrave -80 + +KPX P amacron -80 + +KPX P aogonek -80 + +KPX P aring -80 + +KPX P atilde -80 + +KPX P comma -135 + +KPX P e -80 + +KPX P eacute -80 + +KPX P ecaron -80 + +KPX P ecircumflex -80 + +KPX P edieresis -80 + +KPX P edotaccent -80 + +KPX P egrave -80 + +KPX P emacron -80 + +KPX P eogonek -80 + +KPX P o -80 + +KPX P oacute -80 + +KPX P ocircumflex -80 + +KPX P odieresis -80 + +KPX P ograve -80 + +KPX P ohungarumlaut -80 + +KPX P omacron -80 + +KPX P oslash -80 + +KPX P otilde -80 + +KPX P period -135 + +KPX Q U -10 + +KPX Q Uacute -10 + +KPX Q Ucircumflex -10 + +KPX Q Udieresis -10 + +KPX Q Ugrave -10 + +KPX Q Uhungarumlaut -10 + +KPX Q Umacron -10 + +KPX Q Uogonek -10 + +KPX Q Uring -10 + +KPX R O -40 + +KPX R Oacute -40 + +KPX R Ocircumflex -40 + +KPX R Odieresis -40 + +KPX R Ograve -40 + +KPX R Ohungarumlaut -40 + +KPX R Omacron -40 + +KPX R Oslash -40 + +KPX R Otilde -40 + +KPX R U -40 + +KPX R Uacute -40 + +KPX R Ucircumflex -40 + +KPX R Udieresis -40 + +KPX R Ugrave -40 + +KPX R Uhungarumlaut -40 + +KPX R Umacron -40 + +KPX R Uogonek -40 + +KPX R Uring -40 + +KPX R V -18 + +KPX R W -18 + +KPX R Y -18 + +KPX R Yacute -18 + +KPX R Ydieresis -18 + +KPX Racute O -40 + +KPX Racute Oacute -40 + +KPX Racute Ocircumflex -40 + +KPX Racute Odieresis -40 + +KPX Racute Ograve -40 + +KPX Racute Ohungarumlaut -40 + +KPX Racute Omacron -40 + +KPX Racute Oslash -40 + +KPX Racute Otilde -40 + +KPX Racute U -40 + +KPX Racute Uacute -40 + +KPX Racute Ucircumflex -40 + +KPX Racute Udieresis -40 + +KPX Racute Ugrave -40 + +KPX Racute Uhungarumlaut -40 + +KPX Racute Umacron -40 + +KPX Racute Uogonek -40 + +KPX Racute Uring -40 + +KPX Racute V -18 + +KPX Racute W -18 + +KPX Racute Y -18 + +KPX Racute Yacute -18 + +KPX Racute Ydieresis -18 + +KPX Rcaron O -40 + +KPX Rcaron Oacute -40 + +KPX Rcaron Ocircumflex -40 + +KPX Rcaron Odieresis -40 + +KPX Rcaron Ograve -40 + +KPX Rcaron Ohungarumlaut -40 + +KPX Rcaron Omacron -40 + +KPX Rcaron Oslash -40 + +KPX Rcaron Otilde -40 + +KPX Rcaron U -40 + +KPX Rcaron Uacute -40 + +KPX Rcaron Ucircumflex -40 + +KPX Rcaron Udieresis -40 + +KPX Rcaron Ugrave -40 + +KPX Rcaron Uhungarumlaut -40 + +KPX Rcaron Umacron -40 + +KPX Rcaron Uogonek -40 + +KPX Rcaron Uring -40 + +KPX Rcaron V -18 + +KPX Rcaron W -18 + +KPX Rcaron Y -18 + +KPX Rcaron Yacute -18 + +KPX Rcaron Ydieresis -18 + +KPX Rcommaaccent O -40 + +KPX Rcommaaccent Oacute -40 + +KPX Rcommaaccent Ocircumflex -40 + +KPX Rcommaaccent Odieresis -40 + +KPX Rcommaaccent Ograve -40 + +KPX Rcommaaccent Ohungarumlaut -40 + +KPX Rcommaaccent Omacron -40 + +KPX Rcommaaccent Oslash -40 + +KPX Rcommaaccent Otilde -40 + +KPX Rcommaaccent U -40 + +KPX Rcommaaccent Uacute -40 + +KPX Rcommaaccent Ucircumflex -40 + +KPX Rcommaaccent Udieresis -40 + +KPX Rcommaaccent Ugrave -40 + +KPX Rcommaaccent Uhungarumlaut -40 + +KPX Rcommaaccent Umacron -40 + +KPX Rcommaaccent Uogonek -40 + +KPX Rcommaaccent Uring -40 + +KPX Rcommaaccent V -18 + +KPX Rcommaaccent W -18 + +KPX Rcommaaccent Y -18 + +KPX Rcommaaccent Yacute -18 + +KPX Rcommaaccent Ydieresis -18 + +KPX T A -50 + +KPX T Aacute -50 + +KPX T Abreve -50 + +KPX T Acircumflex -50 + +KPX T Adieresis -50 + +KPX T Agrave -50 + +KPX T Amacron -50 + +KPX T Aogonek -50 + +KPX T Aring -50 + +KPX T Atilde -50 + +KPX T O -18 + +KPX T Oacute -18 + +KPX T Ocircumflex -18 + +KPX T Odieresis -18 + +KPX T Ograve -18 + +KPX T Ohungarumlaut -18 + +KPX T Omacron -18 + +KPX T Oslash -18 + +KPX T Otilde -18 + +KPX T a -92 + +KPX T aacute -92 + +KPX T abreve -92 + +KPX T acircumflex -92 + +KPX T adieresis -92 + +KPX T agrave -92 + +KPX T amacron -92 + +KPX T aogonek -92 + +KPX T aring -92 + +KPX T atilde -92 + +KPX T colon -55 + +KPX T comma -74 + +KPX T e -92 + +KPX T eacute -92 + +KPX T ecaron -92 + +KPX T ecircumflex -52 + +KPX T edieresis -52 + +KPX T edotaccent -92 + +KPX T egrave -52 + +KPX T emacron -52 + +KPX T eogonek -92 + +KPX T hyphen -74 + +KPX T i -55 + +KPX T iacute -55 + +KPX T iogonek -55 + +KPX T o -92 + +KPX T oacute -92 + +KPX T ocircumflex -92 + +KPX T odieresis -92 + +KPX T ograve -92 + +KPX T ohungarumlaut -92 + +KPX T omacron -92 + +KPX T oslash -92 + +KPX T otilde -92 + +KPX T period -74 + +KPX T r -55 + +KPX T racute -55 + +KPX T rcaron -55 + +KPX T rcommaaccent -55 + +KPX T semicolon -65 + +KPX T u -55 + +KPX T uacute -55 + +KPX T ucircumflex -55 + +KPX T udieresis -55 + +KPX T ugrave -55 + +KPX T uhungarumlaut -55 + +KPX T umacron -55 + +KPX T uogonek -55 + +KPX T uring -55 + +KPX T w -74 + +KPX T y -74 + +KPX T yacute -74 + +KPX T ydieresis -34 + +KPX Tcaron A -50 + +KPX Tcaron Aacute -50 + +KPX Tcaron Abreve -50 + +KPX Tcaron Acircumflex -50 + +KPX Tcaron Adieresis -50 + +KPX Tcaron Agrave -50 + +KPX Tcaron Amacron -50 + +KPX Tcaron Aogonek -50 + +KPX Tcaron Aring -50 + +KPX Tcaron Atilde -50 + +KPX Tcaron O -18 + +KPX Tcaron Oacute -18 + +KPX Tcaron Ocircumflex -18 + +KPX Tcaron Odieresis -18 + +KPX Tcaron Ograve -18 + +KPX Tcaron Ohungarumlaut -18 + +KPX Tcaron Omacron -18 + +KPX Tcaron Oslash -18 + +KPX Tcaron Otilde -18 + +KPX Tcaron a -92 + +KPX Tcaron aacute -92 + +KPX Tcaron abreve -92 + +KPX Tcaron acircumflex -92 + +KPX Tcaron adieresis -92 + +KPX Tcaron agrave -92 + +KPX Tcaron amacron -92 + +KPX Tcaron aogonek -92 + +KPX Tcaron aring -92 + +KPX Tcaron atilde -92 + +KPX Tcaron colon -55 + +KPX Tcaron comma -74 + +KPX Tcaron e -92 + +KPX Tcaron eacute -92 + +KPX Tcaron ecaron -92 + +KPX Tcaron ecircumflex -52 + +KPX Tcaron edieresis -52 + +KPX Tcaron edotaccent -92 + +KPX Tcaron egrave -52 + +KPX Tcaron emacron -52 + +KPX Tcaron eogonek -92 + +KPX Tcaron hyphen -74 + +KPX Tcaron i -55 + +KPX Tcaron iacute -55 + +KPX Tcaron iogonek -55 + +KPX Tcaron o -92 + +KPX Tcaron oacute -92 + +KPX Tcaron ocircumflex -92 + +KPX Tcaron odieresis -92 + +KPX Tcaron ograve -92 + +KPX Tcaron ohungarumlaut -92 + +KPX Tcaron omacron -92 + +KPX Tcaron oslash -92 + +KPX Tcaron otilde -92 + +KPX Tcaron period -74 + +KPX Tcaron r -55 + +KPX Tcaron racute -55 + +KPX Tcaron rcaron -55 + +KPX Tcaron rcommaaccent -55 + +KPX Tcaron semicolon -65 + +KPX Tcaron u -55 + +KPX Tcaron uacute -55 + +KPX Tcaron ucircumflex -55 + +KPX Tcaron udieresis -55 + +KPX Tcaron ugrave -55 + +KPX Tcaron uhungarumlaut -55 + +KPX Tcaron umacron -55 + +KPX Tcaron uogonek -55 + +KPX Tcaron uring -55 + +KPX Tcaron w -74 + +KPX Tcaron y -74 + +KPX Tcaron yacute -74 + +KPX Tcaron ydieresis -34 + +KPX Tcommaaccent A -50 + +KPX Tcommaaccent Aacute -50 + +KPX Tcommaaccent Abreve -50 + +KPX Tcommaaccent Acircumflex -50 + +KPX Tcommaaccent Adieresis -50 + +KPX Tcommaaccent Agrave -50 + +KPX Tcommaaccent Amacron -50 + +KPX Tcommaaccent Aogonek -50 + +KPX Tcommaaccent Aring -50 + +KPX Tcommaaccent Atilde -50 + +KPX Tcommaaccent O -18 + +KPX Tcommaaccent Oacute -18 + +KPX Tcommaaccent Ocircumflex -18 + +KPX Tcommaaccent Odieresis -18 + +KPX Tcommaaccent Ograve -18 + +KPX Tcommaaccent Ohungarumlaut -18 + +KPX Tcommaaccent Omacron -18 + +KPX Tcommaaccent Oslash -18 + +KPX Tcommaaccent Otilde -18 + +KPX Tcommaaccent a -92 + +KPX Tcommaaccent aacute -92 + +KPX Tcommaaccent abreve -92 + +KPX Tcommaaccent acircumflex -92 + +KPX Tcommaaccent adieresis -92 + +KPX Tcommaaccent agrave -92 + +KPX Tcommaaccent amacron -92 + +KPX Tcommaaccent aogonek -92 + +KPX Tcommaaccent aring -92 + +KPX Tcommaaccent atilde -92 + +KPX Tcommaaccent colon -55 + +KPX Tcommaaccent comma -74 + +KPX Tcommaaccent e -92 + +KPX Tcommaaccent eacute -92 + +KPX Tcommaaccent ecaron -92 + +KPX Tcommaaccent ecircumflex -52 + +KPX Tcommaaccent edieresis -52 + +KPX Tcommaaccent edotaccent -92 + +KPX Tcommaaccent egrave -52 + +KPX Tcommaaccent emacron -52 + +KPX Tcommaaccent eogonek -92 + +KPX Tcommaaccent hyphen -74 + +KPX Tcommaaccent i -55 + +KPX Tcommaaccent iacute -55 + +KPX Tcommaaccent iogonek -55 + +KPX Tcommaaccent o -92 + +KPX Tcommaaccent oacute -92 + +KPX Tcommaaccent ocircumflex -92 + +KPX Tcommaaccent odieresis -92 + +KPX Tcommaaccent ograve -92 + +KPX Tcommaaccent ohungarumlaut -92 + +KPX Tcommaaccent omacron -92 + +KPX Tcommaaccent oslash -92 + +KPX Tcommaaccent otilde -92 + +KPX Tcommaaccent period -74 + +KPX Tcommaaccent r -55 + +KPX Tcommaaccent racute -55 + +KPX Tcommaaccent rcaron -55 + +KPX Tcommaaccent rcommaaccent -55 + +KPX Tcommaaccent semicolon -65 + +KPX Tcommaaccent u -55 + +KPX Tcommaaccent uacute -55 + +KPX Tcommaaccent ucircumflex -55 + +KPX Tcommaaccent udieresis -55 + +KPX Tcommaaccent ugrave -55 + +KPX Tcommaaccent uhungarumlaut -55 + +KPX Tcommaaccent umacron -55 + +KPX Tcommaaccent uogonek -55 + +KPX Tcommaaccent uring -55 + +KPX Tcommaaccent w -74 + +KPX Tcommaaccent y -74 + +KPX Tcommaaccent yacute -74 + +KPX Tcommaaccent ydieresis -34 + +KPX U A -40 + +KPX U Aacute -40 + +KPX U Abreve -40 + +KPX U Acircumflex -40 + +KPX U Adieresis -40 + +KPX U Agrave -40 + +KPX U Amacron -40 + +KPX U Aogonek -40 + +KPX U Aring -40 + +KPX U Atilde -40 + +KPX U comma -25 + +KPX U period -25 + +KPX Uacute A -40 + +KPX Uacute Aacute -40 + +KPX Uacute Abreve -40 + +KPX Uacute Acircumflex -40 + +KPX Uacute Adieresis -40 + +KPX Uacute Agrave -40 + +KPX Uacute Amacron -40 + +KPX Uacute Aogonek -40 + +KPX Uacute Aring -40 + +KPX Uacute Atilde -40 + +KPX Uacute comma -25 + +KPX Uacute period -25 + +KPX Ucircumflex A -40 + +KPX Ucircumflex Aacute -40 + +KPX Ucircumflex Abreve -40 + +KPX Ucircumflex Acircumflex -40 + +KPX Ucircumflex Adieresis -40 + +KPX Ucircumflex Agrave -40 + +KPX Ucircumflex Amacron -40 + +KPX Ucircumflex Aogonek -40 + +KPX Ucircumflex Aring -40 + +KPX Ucircumflex Atilde -40 + +KPX Ucircumflex comma -25 + +KPX Ucircumflex period -25 + +KPX Udieresis A -40 + +KPX Udieresis Aacute -40 + +KPX Udieresis Abreve -40 + +KPX Udieresis Acircumflex -40 + +KPX Udieresis Adieresis -40 + +KPX Udieresis Agrave -40 + +KPX Udieresis Amacron -40 + +KPX Udieresis Aogonek -40 + +KPX Udieresis Aring -40 + +KPX Udieresis Atilde -40 + +KPX Udieresis comma -25 + +KPX Udieresis period -25 + +KPX Ugrave A -40 + +KPX Ugrave Aacute -40 + +KPX Ugrave Abreve -40 + +KPX Ugrave Acircumflex -40 + +KPX Ugrave Adieresis -40 + +KPX Ugrave Agrave -40 + +KPX Ugrave Amacron -40 + +KPX Ugrave Aogonek -40 + +KPX Ugrave Aring -40 + +KPX Ugrave Atilde -40 + +KPX Ugrave comma -25 + +KPX Ugrave period -25 + +KPX Uhungarumlaut A -40 + +KPX Uhungarumlaut Aacute -40 + +KPX Uhungarumlaut Abreve -40 + +KPX Uhungarumlaut Acircumflex -40 + +KPX Uhungarumlaut Adieresis -40 + +KPX Uhungarumlaut Agrave -40 + +KPX Uhungarumlaut Amacron -40 + +KPX Uhungarumlaut Aogonek -40 + +KPX Uhungarumlaut Aring -40 + +KPX Uhungarumlaut Atilde -40 + +KPX Uhungarumlaut comma -25 + +KPX Uhungarumlaut period -25 + +KPX Umacron A -40 + +KPX Umacron Aacute -40 + +KPX Umacron Abreve -40 + +KPX Umacron Acircumflex -40 + +KPX Umacron Adieresis -40 + +KPX Umacron Agrave -40 + +KPX Umacron Amacron -40 + +KPX Umacron Aogonek -40 + +KPX Umacron Aring -40 + +KPX Umacron Atilde -40 + +KPX Umacron comma -25 + +KPX Umacron period -25 + +KPX Uogonek A -40 + +KPX Uogonek Aacute -40 + +KPX Uogonek Abreve -40 + +KPX Uogonek Acircumflex -40 + +KPX Uogonek Adieresis -40 + +KPX Uogonek Agrave -40 + +KPX Uogonek Amacron -40 + +KPX Uogonek Aogonek -40 + +KPX Uogonek Aring -40 + +KPX Uogonek Atilde -40 + +KPX Uogonek comma -25 + +KPX Uogonek period -25 + +KPX Uring A -40 + +KPX Uring Aacute -40 + +KPX Uring Abreve -40 + +KPX Uring Acircumflex -40 + +KPX Uring Adieresis -40 + +KPX Uring Agrave -40 + +KPX Uring Amacron -40 + +KPX Uring Aogonek -40 + +KPX Uring Aring -40 + +KPX Uring Atilde -40 + +KPX Uring comma -25 + +KPX Uring period -25 + +KPX V A -60 + +KPX V Aacute -60 + +KPX V Abreve -60 + +KPX V Acircumflex -60 + +KPX V Adieresis -60 + +KPX V Agrave -60 + +KPX V Amacron -60 + +KPX V Aogonek -60 + +KPX V Aring -60 + +KPX V Atilde -60 + +KPX V O -30 + +KPX V Oacute -30 + +KPX V Ocircumflex -30 + +KPX V Odieresis -30 + +KPX V Ograve -30 + +KPX V Ohungarumlaut -30 + +KPX V Omacron -30 + +KPX V Oslash -30 + +KPX V Otilde -30 + +KPX V a -111 + +KPX V aacute -111 + +KPX V abreve -111 + +KPX V acircumflex -111 + +KPX V adieresis -111 + +KPX V agrave -111 + +KPX V amacron -111 + +KPX V aogonek -111 + +KPX V aring -111 + +KPX V atilde -111 + +KPX V colon -65 + +KPX V comma -129 + +KPX V e -111 + +KPX V eacute -111 + +KPX V ecaron -111 + +KPX V ecircumflex -111 + +KPX V edieresis -71 + +KPX V edotaccent -111 + +KPX V egrave -71 + +KPX V emacron -71 + +KPX V eogonek -111 + +KPX V hyphen -55 + +KPX V i -74 + +KPX V iacute -74 + +KPX V icircumflex -34 + +KPX V idieresis -34 + +KPX V igrave -34 + +KPX V imacron -34 + +KPX V iogonek -74 + +KPX V o -111 + +KPX V oacute -111 + +KPX V ocircumflex -111 + +KPX V odieresis -111 + +KPX V ograve -111 + +KPX V ohungarumlaut -111 + +KPX V omacron -111 + +KPX V oslash -111 + +KPX V otilde -111 + +KPX V period -129 + +KPX V semicolon -74 + +KPX V u -74 + +KPX V uacute -74 + +KPX V ucircumflex -74 + +KPX V udieresis -74 + +KPX V ugrave -74 + +KPX V uhungarumlaut -74 + +KPX V umacron -74 + +KPX V uogonek -74 + +KPX V uring -74 + +KPX W A -60 + +KPX W Aacute -60 + +KPX W Abreve -60 + +KPX W Acircumflex -60 + +KPX W Adieresis -60 + +KPX W Agrave -60 + +KPX W Amacron -60 + +KPX W Aogonek -60 + +KPX W Aring -60 + +KPX W Atilde -60 + +KPX W O -25 + +KPX W Oacute -25 + +KPX W Ocircumflex -25 + +KPX W Odieresis -25 + +KPX W Ograve -25 + +KPX W Ohungarumlaut -25 + +KPX W Omacron -25 + +KPX W Oslash -25 + +KPX W Otilde -25 + +KPX W a -92 + +KPX W aacute -92 + +KPX W abreve -92 + +KPX W acircumflex -92 + +KPX W adieresis -92 + +KPX W agrave -92 + +KPX W amacron -92 + +KPX W aogonek -92 + +KPX W aring -92 + +KPX W atilde -92 + +KPX W colon -65 + +KPX W comma -92 + +KPX W e -92 + +KPX W eacute -92 + +KPX W ecaron -92 + +KPX W ecircumflex -92 + +KPX W edieresis -52 + +KPX W edotaccent -92 + +KPX W egrave -52 + +KPX W emacron -52 + +KPX W eogonek -92 + +KPX W hyphen -37 + +KPX W i -55 + +KPX W iacute -55 + +KPX W iogonek -55 + +KPX W o -92 + +KPX W oacute -92 + +KPX W ocircumflex -92 + +KPX W odieresis -92 + +KPX W ograve -92 + +KPX W ohungarumlaut -92 + +KPX W omacron -92 + +KPX W oslash -92 + +KPX W otilde -92 + +KPX W period -92 + +KPX W semicolon -65 + +KPX W u -55 + +KPX W uacute -55 + +KPX W ucircumflex -55 + +KPX W udieresis -55 + +KPX W ugrave -55 + +KPX W uhungarumlaut -55 + +KPX W umacron -55 + +KPX W uogonek -55 + +KPX W uring -55 + +KPX W y -70 + +KPX W yacute -70 + +KPX W ydieresis -70 + +KPX Y A -50 + +KPX Y Aacute -50 + +KPX Y Abreve -50 + +KPX Y Acircumflex -50 + +KPX Y Adieresis -50 + +KPX Y Agrave -50 + +KPX Y Amacron -50 + +KPX Y Aogonek -50 + +KPX Y Aring -50 + +KPX Y Atilde -50 + +KPX Y O -15 + +KPX Y Oacute -15 + +KPX Y Ocircumflex -15 + +KPX Y Odieresis -15 + +KPX Y Ograve -15 + +KPX Y Ohungarumlaut -15 + +KPX Y Omacron -15 + +KPX Y Oslash -15 + +KPX Y Otilde -15 + +KPX Y a -92 + +KPX Y aacute -92 + +KPX Y abreve -92 + +KPX Y acircumflex -92 + +KPX Y adieresis -92 + +KPX Y agrave -92 + +KPX Y amacron -92 + +KPX Y aogonek -92 + +KPX Y aring -92 + +KPX Y atilde -92 + +KPX Y colon -65 + +KPX Y comma -92 + +KPX Y e -92 + +KPX Y eacute -92 + +KPX Y ecaron -92 + +KPX Y ecircumflex -92 + +KPX Y edieresis -52 + +KPX Y edotaccent -92 + +KPX Y egrave -52 + +KPX Y emacron -52 + +KPX Y eogonek -92 + +KPX Y hyphen -74 + +KPX Y i -74 + +KPX Y iacute -74 + +KPX Y icircumflex -34 + +KPX Y idieresis -34 + +KPX Y igrave -34 + +KPX Y imacron -34 + +KPX Y iogonek -74 + +KPX Y o -92 + +KPX Y oacute -92 + +KPX Y ocircumflex -92 + +KPX Y odieresis -92 + +KPX Y ograve -92 + +KPX Y ohungarumlaut -92 + +KPX Y omacron -92 + +KPX Y oslash -92 + +KPX Y otilde -92 + +KPX Y period -92 + +KPX Y semicolon -65 + +KPX Y u -92 + +KPX Y uacute -92 + +KPX Y ucircumflex -92 + +KPX Y udieresis -92 + +KPX Y ugrave -92 + +KPX Y uhungarumlaut -92 + +KPX Y umacron -92 + +KPX Y uogonek -92 + +KPX Y uring -92 + +KPX Yacute A -50 + +KPX Yacute Aacute -50 + +KPX Yacute Abreve -50 + +KPX Yacute Acircumflex -50 + +KPX Yacute Adieresis -50 + +KPX Yacute Agrave -50 + +KPX Yacute Amacron -50 + +KPX Yacute Aogonek -50 + +KPX Yacute Aring -50 + +KPX Yacute Atilde -50 + +KPX Yacute O -15 + +KPX Yacute Oacute -15 + +KPX Yacute Ocircumflex -15 + +KPX Yacute Odieresis -15 + +KPX Yacute Ograve -15 + +KPX Yacute Ohungarumlaut -15 + +KPX Yacute Omacron -15 + +KPX Yacute Oslash -15 + +KPX Yacute Otilde -15 + +KPX Yacute a -92 + +KPX Yacute aacute -92 + +KPX Yacute abreve -92 + +KPX Yacute acircumflex -92 + +KPX Yacute adieresis -92 + +KPX Yacute agrave -92 + +KPX Yacute amacron -92 + +KPX Yacute aogonek -92 + +KPX Yacute aring -92 + +KPX Yacute atilde -92 + +KPX Yacute colon -65 + +KPX Yacute comma -92 + +KPX Yacute e -92 + +KPX Yacute eacute -92 + +KPX Yacute ecaron -92 + +KPX Yacute ecircumflex -92 + +KPX Yacute edieresis -52 + +KPX Yacute edotaccent -92 + +KPX Yacute egrave -52 + +KPX Yacute emacron -52 + +KPX Yacute eogonek -92 + +KPX Yacute hyphen -74 + +KPX Yacute i -74 + +KPX Yacute iacute -74 + +KPX Yacute icircumflex -34 + +KPX Yacute idieresis -34 + +KPX Yacute igrave -34 + +KPX Yacute imacron -34 + +KPX Yacute iogonek -74 + +KPX Yacute o -92 + +KPX Yacute oacute -92 + +KPX Yacute ocircumflex -92 + +KPX Yacute odieresis -92 + +KPX Yacute ograve -92 + +KPX Yacute ohungarumlaut -92 + +KPX Yacute omacron -92 + +KPX Yacute oslash -92 + +KPX Yacute otilde -92 + +KPX Yacute period -92 + +KPX Yacute semicolon -65 + +KPX Yacute u -92 + +KPX Yacute uacute -92 + +KPX Yacute ucircumflex -92 + +KPX Yacute udieresis -92 + +KPX Yacute ugrave -92 + +KPX Yacute uhungarumlaut -92 + +KPX Yacute umacron -92 + +KPX Yacute uogonek -92 + +KPX Yacute uring -92 + +KPX Ydieresis A -50 + +KPX Ydieresis Aacute -50 + +KPX Ydieresis Abreve -50 + +KPX Ydieresis Acircumflex -50 + +KPX Ydieresis Adieresis -50 + +KPX Ydieresis Agrave -50 + +KPX Ydieresis Amacron -50 + +KPX Ydieresis Aogonek -50 + +KPX Ydieresis Aring -50 + +KPX Ydieresis Atilde -50 + +KPX Ydieresis O -15 + +KPX Ydieresis Oacute -15 + +KPX Ydieresis Ocircumflex -15 + +KPX Ydieresis Odieresis -15 + +KPX Ydieresis Ograve -15 + +KPX Ydieresis Ohungarumlaut -15 + +KPX Ydieresis Omacron -15 + +KPX Ydieresis Oslash -15 + +KPX Ydieresis Otilde -15 + +KPX Ydieresis a -92 + +KPX Ydieresis aacute -92 + +KPX Ydieresis abreve -92 + +KPX Ydieresis acircumflex -92 + +KPX Ydieresis adieresis -92 + +KPX Ydieresis agrave -92 + +KPX Ydieresis amacron -92 + +KPX Ydieresis aogonek -92 + +KPX Ydieresis aring -92 + +KPX Ydieresis atilde -92 + +KPX Ydieresis colon -65 + +KPX Ydieresis comma -92 + +KPX Ydieresis e -92 + +KPX Ydieresis eacute -92 + +KPX Ydieresis ecaron -92 + +KPX Ydieresis ecircumflex -92 + +KPX Ydieresis edieresis -52 + +KPX Ydieresis edotaccent -92 + +KPX Ydieresis egrave -52 + +KPX Ydieresis emacron -52 + +KPX Ydieresis eogonek -92 + +KPX Ydieresis hyphen -74 + +KPX Ydieresis i -74 + +KPX Ydieresis iacute -74 + +KPX Ydieresis icircumflex -34 + +KPX Ydieresis idieresis -34 + +KPX Ydieresis igrave -34 + +KPX Ydieresis imacron -34 + +KPX Ydieresis iogonek -74 + +KPX Ydieresis o -92 + +KPX Ydieresis oacute -92 + +KPX Ydieresis ocircumflex -92 + +KPX Ydieresis odieresis -92 + +KPX Ydieresis ograve -92 + +KPX Ydieresis ohungarumlaut -92 + +KPX Ydieresis omacron -92 + +KPX Ydieresis oslash -92 + +KPX Ydieresis otilde -92 + +KPX Ydieresis period -92 + +KPX Ydieresis semicolon -65 + +KPX Ydieresis u -92 + +KPX Ydieresis uacute -92 + +KPX Ydieresis ucircumflex -92 + +KPX Ydieresis udieresis -92 + +KPX Ydieresis ugrave -92 + +KPX Ydieresis uhungarumlaut -92 + +KPX Ydieresis umacron -92 + +KPX Ydieresis uogonek -92 + +KPX Ydieresis uring -92 + +KPX a g -10 + +KPX a gbreve -10 + +KPX a gcommaaccent -10 + +KPX aacute g -10 + +KPX aacute gbreve -10 + +KPX aacute gcommaaccent -10 + +KPX abreve g -10 + +KPX abreve gbreve -10 + +KPX abreve gcommaaccent -10 + +KPX acircumflex g -10 + +KPX acircumflex gbreve -10 + +KPX acircumflex gcommaaccent -10 + +KPX adieresis g -10 + +KPX adieresis gbreve -10 + +KPX adieresis gcommaaccent -10 + +KPX agrave g -10 + +KPX agrave gbreve -10 + +KPX agrave gcommaaccent -10 + +KPX amacron g -10 + +KPX amacron gbreve -10 + +KPX amacron gcommaaccent -10 + +KPX aogonek g -10 + +KPX aogonek gbreve -10 + +KPX aogonek gcommaaccent -10 + +KPX aring g -10 + +KPX aring gbreve -10 + +KPX aring gcommaaccent -10 + +KPX atilde g -10 + +KPX atilde gbreve -10 + +KPX atilde gcommaaccent -10 + +KPX b period -40 + +KPX b u -20 + +KPX b uacute -20 + +KPX b ucircumflex -20 + +KPX b udieresis -20 + +KPX b ugrave -20 + +KPX b uhungarumlaut -20 + +KPX b umacron -20 + +KPX b uogonek -20 + +KPX b uring -20 + +KPX c h -15 + +KPX c k -20 + +KPX c kcommaaccent -20 + +KPX cacute h -15 + +KPX cacute k -20 + +KPX cacute kcommaaccent -20 + +KPX ccaron h -15 + +KPX ccaron k -20 + +KPX ccaron kcommaaccent -20 + +KPX ccedilla h -15 + +KPX ccedilla k -20 + +KPX ccedilla kcommaaccent -20 + +KPX comma quotedblright -140 + +KPX comma quoteright -140 + +KPX e comma -10 + +KPX e g -40 + +KPX e gbreve -40 + +KPX e gcommaaccent -40 + +KPX e period -15 + +KPX e v -15 + +KPX e w -15 + +KPX e x -20 + +KPX e y -30 + +KPX e yacute -30 + +KPX e ydieresis -30 + +KPX eacute comma -10 + +KPX eacute g -40 + +KPX eacute gbreve -40 + +KPX eacute gcommaaccent -40 + +KPX eacute period -15 + +KPX eacute v -15 + +KPX eacute w -15 + +KPX eacute x -20 + +KPX eacute y -30 + +KPX eacute yacute -30 + +KPX eacute ydieresis -30 + +KPX ecaron comma -10 + +KPX ecaron g -40 + +KPX ecaron gbreve -40 + +KPX ecaron gcommaaccent -40 + +KPX ecaron period -15 + +KPX ecaron v -15 + +KPX ecaron w -15 + +KPX ecaron x -20 + +KPX ecaron y -30 + +KPX ecaron yacute -30 + +KPX ecaron ydieresis -30 + +KPX ecircumflex comma -10 + +KPX ecircumflex g -40 + +KPX ecircumflex gbreve -40 + +KPX ecircumflex gcommaaccent -40 + +KPX ecircumflex period -15 + +KPX ecircumflex v -15 + +KPX ecircumflex w -15 + +KPX ecircumflex x -20 + +KPX ecircumflex y -30 + +KPX ecircumflex yacute -30 + +KPX ecircumflex ydieresis -30 + +KPX edieresis comma -10 + +KPX edieresis g -40 + +KPX edieresis gbreve -40 + +KPX edieresis gcommaaccent -40 + +KPX edieresis period -15 + +KPX edieresis v -15 + +KPX edieresis w -15 + +KPX edieresis x -20 + +KPX edieresis y -30 + +KPX edieresis yacute -30 + +KPX edieresis ydieresis -30 + +KPX edotaccent comma -10 + +KPX edotaccent g -40 + +KPX edotaccent gbreve -40 + +KPX edotaccent gcommaaccent -40 + +KPX edotaccent period -15 + +KPX edotaccent v -15 + +KPX edotaccent w -15 + +KPX edotaccent x -20 + +KPX edotaccent y -30 + +KPX edotaccent yacute -30 + +KPX edotaccent ydieresis -30 + +KPX egrave comma -10 + +KPX egrave g -40 + +KPX egrave gbreve -40 + +KPX egrave gcommaaccent -40 + +KPX egrave period -15 + +KPX egrave v -15 + +KPX egrave w -15 + +KPX egrave x -20 + +KPX egrave y -30 + +KPX egrave yacute -30 + +KPX egrave ydieresis -30 + +KPX emacron comma -10 + +KPX emacron g -40 + +KPX emacron gbreve -40 + +KPX emacron gcommaaccent -40 + +KPX emacron period -15 + +KPX emacron v -15 + +KPX emacron w -15 + +KPX emacron x -20 + +KPX emacron y -30 + +KPX emacron yacute -30 + +KPX emacron ydieresis -30 + +KPX eogonek comma -10 + +KPX eogonek g -40 + +KPX eogonek gbreve -40 + +KPX eogonek gcommaaccent -40 + +KPX eogonek period -15 + +KPX eogonek v -15 + +KPX eogonek w -15 + +KPX eogonek x -20 + +KPX eogonek y -30 + +KPX eogonek yacute -30 + +KPX eogonek ydieresis -30 + +KPX f comma -10 + +KPX f dotlessi -60 + +KPX f f -18 + +KPX f i -20 + +KPX f iogonek -20 + +KPX f period -15 + +KPX f quoteright 92 + +KPX g comma -10 + +KPX g e -10 + +KPX g eacute -10 + +KPX g ecaron -10 + +KPX g ecircumflex -10 + +KPX g edieresis -10 + +KPX g edotaccent -10 + +KPX g egrave -10 + +KPX g emacron -10 + +KPX g eogonek -10 + +KPX g g -10 + +KPX g gbreve -10 + +KPX g gcommaaccent -10 + +KPX g period -15 + +KPX gbreve comma -10 + +KPX gbreve e -10 + +KPX gbreve eacute -10 + +KPX gbreve ecaron -10 + +KPX gbreve ecircumflex -10 + +KPX gbreve edieresis -10 + +KPX gbreve edotaccent -10 + +KPX gbreve egrave -10 + +KPX gbreve emacron -10 + +KPX gbreve eogonek -10 + +KPX gbreve g -10 + +KPX gbreve gbreve -10 + +KPX gbreve gcommaaccent -10 + +KPX gbreve period -15 + +KPX gcommaaccent comma -10 + +KPX gcommaaccent e -10 + +KPX gcommaaccent eacute -10 + +KPX gcommaaccent ecaron -10 + +KPX gcommaaccent ecircumflex -10 + +KPX gcommaaccent edieresis -10 + +KPX gcommaaccent edotaccent -10 + +KPX gcommaaccent egrave -10 + +KPX gcommaaccent emacron -10 + +KPX gcommaaccent eogonek -10 + +KPX gcommaaccent g -10 + +KPX gcommaaccent gbreve -10 + +KPX gcommaaccent gcommaaccent -10 + +KPX gcommaaccent period -15 + +KPX k e -10 + +KPX k eacute -10 + +KPX k ecaron -10 + +KPX k ecircumflex -10 + +KPX k edieresis -10 + +KPX k edotaccent -10 + +KPX k egrave -10 + +KPX k emacron -10 + +KPX k eogonek -10 + +KPX k o -10 + +KPX k oacute -10 + +KPX k ocircumflex -10 + +KPX k odieresis -10 + +KPX k ograve -10 + +KPX k ohungarumlaut -10 + +KPX k omacron -10 + +KPX k oslash -10 + +KPX k otilde -10 + +KPX k y -10 + +KPX k yacute -10 + +KPX k ydieresis -10 + +KPX kcommaaccent e -10 + +KPX kcommaaccent eacute -10 + +KPX kcommaaccent ecaron -10 + +KPX kcommaaccent ecircumflex -10 + +KPX kcommaaccent edieresis -10 + +KPX kcommaaccent edotaccent -10 + +KPX kcommaaccent egrave -10 + +KPX kcommaaccent emacron -10 + +KPX kcommaaccent eogonek -10 + +KPX kcommaaccent o -10 + +KPX kcommaaccent oacute -10 + +KPX kcommaaccent ocircumflex -10 + +KPX kcommaaccent odieresis -10 + +KPX kcommaaccent ograve -10 + +KPX kcommaaccent ohungarumlaut -10 + +KPX kcommaaccent omacron -10 + +KPX kcommaaccent oslash -10 + +KPX kcommaaccent otilde -10 + +KPX kcommaaccent y -10 + +KPX kcommaaccent yacute -10 + +KPX kcommaaccent ydieresis -10 + +KPX n v -40 + +KPX nacute v -40 + +KPX ncaron v -40 + +KPX ncommaaccent v -40 + +KPX ntilde v -40 + +KPX o g -10 + +KPX o gbreve -10 + +KPX o gcommaaccent -10 + +KPX o v -10 + +KPX oacute g -10 + +KPX oacute gbreve -10 + +KPX oacute gcommaaccent -10 + +KPX oacute v -10 + +KPX ocircumflex g -10 + +KPX ocircumflex gbreve -10 + +KPX ocircumflex gcommaaccent -10 + +KPX ocircumflex v -10 + +KPX odieresis g -10 + +KPX odieresis gbreve -10 + +KPX odieresis gcommaaccent -10 + +KPX odieresis v -10 + +KPX ograve g -10 + +KPX ograve gbreve -10 + +KPX ograve gcommaaccent -10 + +KPX ograve v -10 + +KPX ohungarumlaut g -10 + +KPX ohungarumlaut gbreve -10 + +KPX ohungarumlaut gcommaaccent -10 + +KPX ohungarumlaut v -10 + +KPX omacron g -10 + +KPX omacron gbreve -10 + +KPX omacron gcommaaccent -10 + +KPX omacron v -10 + +KPX oslash g -10 + +KPX oslash gbreve -10 + +KPX oslash gcommaaccent -10 + +KPX oslash v -10 + +KPX otilde g -10 + +KPX otilde gbreve -10 + +KPX otilde gcommaaccent -10 + +KPX otilde v -10 + +KPX period quotedblright -140 + +KPX period quoteright -140 + +KPX quoteleft quoteleft -111 + +KPX quoteright d -25 + +KPX quoteright dcroat -25 + +KPX quoteright quoteright -111 + +KPX quoteright r -25 + +KPX quoteright racute -25 + +KPX quoteright rcaron -25 + +KPX quoteright rcommaaccent -25 + +KPX quoteright s -40 + +KPX quoteright sacute -40 + +KPX quoteright scaron -40 + +KPX quoteright scedilla -40 + +KPX quoteright scommaaccent -40 + +KPX quoteright space -111 + +KPX quoteright t -30 + +KPX quoteright tcommaaccent -30 + +KPX quoteright v -10 + +KPX r a -15 + +KPX r aacute -15 + +KPX r abreve -15 + +KPX r acircumflex -15 + +KPX r adieresis -15 + +KPX r agrave -15 + +KPX r amacron -15 + +KPX r aogonek -15 + +KPX r aring -15 + +KPX r atilde -15 + +KPX r c -37 + +KPX r cacute -37 + +KPX r ccaron -37 + +KPX r ccedilla -37 + +KPX r comma -111 + +KPX r d -37 + +KPX r dcroat -37 + +KPX r e -37 + +KPX r eacute -37 + +KPX r ecaron -37 + +KPX r ecircumflex -37 + +KPX r edieresis -37 + +KPX r edotaccent -37 + +KPX r egrave -37 + +KPX r emacron -37 + +KPX r eogonek -37 + +KPX r g -37 + +KPX r gbreve -37 + +KPX r gcommaaccent -37 + +KPX r hyphen -20 + +KPX r o -45 + +KPX r oacute -45 + +KPX r ocircumflex -45 + +KPX r odieresis -45 + +KPX r ograve -45 + +KPX r ohungarumlaut -45 + +KPX r omacron -45 + +KPX r oslash -45 + +KPX r otilde -45 + +KPX r period -111 + +KPX r q -37 + +KPX r s -10 + +KPX r sacute -10 + +KPX r scaron -10 + +KPX r scedilla -10 + +KPX r scommaaccent -10 + +KPX racute a -15 + +KPX racute aacute -15 + +KPX racute abreve -15 + +KPX racute acircumflex -15 + +KPX racute adieresis -15 + +KPX racute agrave -15 + +KPX racute amacron -15 + +KPX racute aogonek -15 + +KPX racute aring -15 + +KPX racute atilde -15 + +KPX racute c -37 + +KPX racute cacute -37 + +KPX racute ccaron -37 + +KPX racute ccedilla -37 + +KPX racute comma -111 + +KPX racute d -37 + +KPX racute dcroat -37 + +KPX racute e -37 + +KPX racute eacute -37 + +KPX racute ecaron -37 + +KPX racute ecircumflex -37 + +KPX racute edieresis -37 + +KPX racute edotaccent -37 + +KPX racute egrave -37 + +KPX racute emacron -37 + +KPX racute eogonek -37 + +KPX racute g -37 + +KPX racute gbreve -37 + +KPX racute gcommaaccent -37 + +KPX racute hyphen -20 + +KPX racute o -45 + +KPX racute oacute -45 + +KPX racute ocircumflex -45 + +KPX racute odieresis -45 + +KPX racute ograve -45 + +KPX racute ohungarumlaut -45 + +KPX racute omacron -45 + +KPX racute oslash -45 + +KPX racute otilde -45 + +KPX racute period -111 + +KPX racute q -37 + +KPX racute s -10 + +KPX racute sacute -10 + +KPX racute scaron -10 + +KPX racute scedilla -10 + +KPX racute scommaaccent -10 + +KPX rcaron a -15 + +KPX rcaron aacute -15 + +KPX rcaron abreve -15 + +KPX rcaron acircumflex -15 + +KPX rcaron adieresis -15 + +KPX rcaron agrave -15 + +KPX rcaron amacron -15 + +KPX rcaron aogonek -15 + +KPX rcaron aring -15 + +KPX rcaron atilde -15 + +KPX rcaron c -37 + +KPX rcaron cacute -37 + +KPX rcaron ccaron -37 + +KPX rcaron ccedilla -37 + +KPX rcaron comma -111 + +KPX rcaron d -37 + +KPX rcaron dcroat -37 + +KPX rcaron e -37 + +KPX rcaron eacute -37 + +KPX rcaron ecaron -37 + +KPX rcaron ecircumflex -37 + +KPX rcaron edieresis -37 + +KPX rcaron edotaccent -37 + +KPX rcaron egrave -37 + +KPX rcaron emacron -37 + +KPX rcaron eogonek -37 + +KPX rcaron g -37 + +KPX rcaron gbreve -37 + +KPX rcaron gcommaaccent -37 + +KPX rcaron hyphen -20 + +KPX rcaron o -45 + +KPX rcaron oacute -45 + +KPX rcaron ocircumflex -45 + +KPX rcaron odieresis -45 + +KPX rcaron ograve -45 + +KPX rcaron ohungarumlaut -45 + +KPX rcaron omacron -45 + +KPX rcaron oslash -45 + +KPX rcaron otilde -45 + +KPX rcaron period -111 + +KPX rcaron q -37 + +KPX rcaron s -10 + +KPX rcaron sacute -10 + +KPX rcaron scaron -10 + +KPX rcaron scedilla -10 + +KPX rcaron scommaaccent -10 + +KPX rcommaaccent a -15 + +KPX rcommaaccent aacute -15 + +KPX rcommaaccent abreve -15 + +KPX rcommaaccent acircumflex -15 + +KPX rcommaaccent adieresis -15 + +KPX rcommaaccent agrave -15 + +KPX rcommaaccent amacron -15 + +KPX rcommaaccent aogonek -15 + +KPX rcommaaccent aring -15 + +KPX rcommaaccent atilde -15 + +KPX rcommaaccent c -37 + +KPX rcommaaccent cacute -37 + +KPX rcommaaccent ccaron -37 + +KPX rcommaaccent ccedilla -37 + +KPX rcommaaccent comma -111 + +KPX rcommaaccent d -37 + +KPX rcommaaccent dcroat -37 + +KPX rcommaaccent e -37 + +KPX rcommaaccent eacute -37 + +KPX rcommaaccent ecaron -37 + +KPX rcommaaccent ecircumflex -37 + +KPX rcommaaccent edieresis -37 + +KPX rcommaaccent edotaccent -37 + +KPX rcommaaccent egrave -37 + +KPX rcommaaccent emacron -37 + +KPX rcommaaccent eogonek -37 + +KPX rcommaaccent g -37 + +KPX rcommaaccent gbreve -37 + +KPX rcommaaccent gcommaaccent -37 + +KPX rcommaaccent hyphen -20 + +KPX rcommaaccent o -45 + +KPX rcommaaccent oacute -45 + +KPX rcommaaccent ocircumflex -45 + +KPX rcommaaccent odieresis -45 + +KPX rcommaaccent ograve -45 + +KPX rcommaaccent ohungarumlaut -45 + +KPX rcommaaccent omacron -45 + +KPX rcommaaccent oslash -45 + +KPX rcommaaccent otilde -45 + +KPX rcommaaccent period -111 + +KPX rcommaaccent q -37 + +KPX rcommaaccent s -10 + +KPX rcommaaccent sacute -10 + +KPX rcommaaccent scaron -10 + +KPX rcommaaccent scedilla -10 + +KPX rcommaaccent scommaaccent -10 + +KPX space A -18 + +KPX space Aacute -18 + +KPX space Abreve -18 + +KPX space Acircumflex -18 + +KPX space Adieresis -18 + +KPX space Agrave -18 + +KPX space Amacron -18 + +KPX space Aogonek -18 + +KPX space Aring -18 + +KPX space Atilde -18 + +KPX space T -18 + +KPX space Tcaron -18 + +KPX space Tcommaaccent -18 + +KPX space V -35 + +KPX space W -40 + +KPX space Y -75 + +KPX space Yacute -75 + +KPX space Ydieresis -75 + +KPX v comma -74 + +KPX v period -74 + +KPX w comma -74 + +KPX w period -74 + +KPX y comma -55 + +KPX y period -55 + +KPX yacute comma -55 + +KPX yacute period -55 + +KPX ydieresis comma -55 + +KPX ydieresis period -55 + +EndKernPairs + +EndKernData + +EndFontMetrics + diff --git a/src/Broadside/Fonts/Data/Afm/Times-Roman.afm b/src/Broadside/Fonts/Data/Afm/Times-Roman.afm new file mode 100644 index 00000000..d0cb874e --- /dev/null +++ b/src/Broadside/Fonts/Data/Afm/Times-Roman.afm @@ -0,0 +1,4838 @@ +StartFontMetrics 4.1 + +Comment Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. + +Comment Creation Date: Thu May 1 12:49:17 1997 + +Comment UniqueID 43068 + +Comment VMusage 43909 54934 + +FontName Times-Roman + +FullName Times Roman + +FamilyName Times + +Weight Roman + +ItalicAngle 0 + +IsFixedPitch false + +CharacterSet ExtendedRoman + +FontBBox -168 -218 1000 898 + +UnderlinePosition -100 + +UnderlineThickness 50 + +Version 002.000 + +Notice Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.Times is a trademark of Linotype-Hell AG and/or its subsidiaries. + +EncodingScheme AdobeStandardEncoding + +CapHeight 662 + +XHeight 450 + +Ascender 683 + +Descender -217 + +StdHW 28 + +StdVW 84 + +StartCharMetrics 315 + +C 32 ; WX 250 ; N space ; B 0 0 0 0 ; + +C 33 ; WX 333 ; N exclam ; B 130 -9 238 676 ; + +C 34 ; WX 408 ; N quotedbl ; B 77 431 331 676 ; + +C 35 ; WX 500 ; N numbersign ; B 5 0 496 662 ; + +C 36 ; WX 500 ; N dollar ; B 44 -87 457 727 ; + +C 37 ; WX 833 ; N percent ; B 61 -13 772 676 ; + +C 38 ; WX 778 ; N ampersand ; B 42 -13 750 676 ; + +C 39 ; WX 333 ; N quoteright ; B 79 433 218 676 ; + +C 40 ; WX 333 ; N parenleft ; B 48 -177 304 676 ; + +C 41 ; WX 333 ; N parenright ; B 29 -177 285 676 ; + +C 42 ; WX 500 ; N asterisk ; B 69 265 432 676 ; + +C 43 ; WX 564 ; N plus ; B 30 0 534 506 ; + +C 44 ; WX 250 ; N comma ; B 56 -141 195 102 ; + +C 45 ; WX 333 ; N hyphen ; B 39 194 285 257 ; + +C 46 ; WX 250 ; N period ; B 70 -11 181 100 ; + +C 47 ; WX 278 ; N slash ; B -9 -14 287 676 ; + +C 48 ; WX 500 ; N zero ; B 24 -14 476 676 ; + +C 49 ; WX 500 ; N one ; B 111 0 394 676 ; + +C 50 ; WX 500 ; N two ; B 30 0 475 676 ; + +C 51 ; WX 500 ; N three ; B 43 -14 431 676 ; + +C 52 ; WX 500 ; N four ; B 12 0 472 676 ; + +C 53 ; WX 500 ; N five ; B 32 -14 438 688 ; + +C 54 ; WX 500 ; N six ; B 34 -14 468 684 ; + +C 55 ; WX 500 ; N seven ; B 20 -8 449 662 ; + +C 56 ; WX 500 ; N eight ; B 56 -14 445 676 ; + +C 57 ; WX 500 ; N nine ; B 30 -22 459 676 ; + +C 58 ; WX 278 ; N colon ; B 81 -11 192 459 ; + +C 59 ; WX 278 ; N semicolon ; B 80 -141 219 459 ; + +C 60 ; WX 564 ; N less ; B 28 -8 536 514 ; + +C 61 ; WX 564 ; N equal ; B 30 120 534 386 ; + +C 62 ; WX 564 ; N greater ; B 28 -8 536 514 ; + +C 63 ; WX 444 ; N question ; B 68 -8 414 676 ; + +C 64 ; WX 921 ; N at ; B 116 -14 809 676 ; + +C 65 ; WX 722 ; N A ; B 15 0 706 674 ; + +C 66 ; WX 667 ; N B ; B 17 0 593 662 ; + +C 67 ; WX 667 ; N C ; B 28 -14 633 676 ; + +C 68 ; WX 722 ; N D ; B 16 0 685 662 ; + +C 69 ; WX 611 ; N E ; B 12 0 597 662 ; + +C 70 ; WX 556 ; N F ; B 12 0 546 662 ; + +C 71 ; WX 722 ; N G ; B 32 -14 709 676 ; + +C 72 ; WX 722 ; N H ; B 19 0 702 662 ; + +C 73 ; WX 333 ; N I ; B 18 0 315 662 ; + +C 74 ; WX 389 ; N J ; B 10 -14 370 662 ; + +C 75 ; WX 722 ; N K ; B 34 0 723 662 ; + +C 76 ; WX 611 ; N L ; B 12 0 598 662 ; + +C 77 ; WX 889 ; N M ; B 12 0 863 662 ; + +C 78 ; WX 722 ; N N ; B 12 -11 707 662 ; + +C 79 ; WX 722 ; N O ; B 34 -14 688 676 ; + +C 80 ; WX 556 ; N P ; B 16 0 542 662 ; + +C 81 ; WX 722 ; N Q ; B 34 -178 701 676 ; + +C 82 ; WX 667 ; N R ; B 17 0 659 662 ; + +C 83 ; WX 556 ; N S ; B 42 -14 491 676 ; + +C 84 ; WX 611 ; N T ; B 17 0 593 662 ; + +C 85 ; WX 722 ; N U ; B 14 -14 705 662 ; + +C 86 ; WX 722 ; N V ; B 16 -11 697 662 ; + +C 87 ; WX 944 ; N W ; B 5 -11 932 662 ; + +C 88 ; WX 722 ; N X ; B 10 0 704 662 ; + +C 89 ; WX 722 ; N Y ; B 22 0 703 662 ; + +C 90 ; WX 611 ; N Z ; B 9 0 597 662 ; + +C 91 ; WX 333 ; N bracketleft ; B 88 -156 299 662 ; + +C 92 ; WX 278 ; N backslash ; B -9 -14 287 676 ; + +C 93 ; WX 333 ; N bracketright ; B 34 -156 245 662 ; + +C 94 ; WX 469 ; N asciicircum ; B 24 297 446 662 ; + +C 95 ; WX 500 ; N underscore ; B 0 -125 500 -75 ; + +C 96 ; WX 333 ; N quoteleft ; B 115 433 254 676 ; + +C 97 ; WX 444 ; N a ; B 37 -10 442 460 ; + +C 98 ; WX 500 ; N b ; B 3 -10 468 683 ; + +C 99 ; WX 444 ; N c ; B 25 -10 412 460 ; + +C 100 ; WX 500 ; N d ; B 27 -10 491 683 ; + +C 101 ; WX 444 ; N e ; B 25 -10 424 460 ; + +C 102 ; WX 333 ; N f ; B 20 0 383 683 ; L i fi ; L l fl ; + +C 103 ; WX 500 ; N g ; B 28 -218 470 460 ; + +C 104 ; WX 500 ; N h ; B 9 0 487 683 ; + +C 105 ; WX 278 ; N i ; B 16 0 253 683 ; + +C 106 ; WX 278 ; N j ; B -70 -218 194 683 ; + +C 107 ; WX 500 ; N k ; B 7 0 505 683 ; + +C 108 ; WX 278 ; N l ; B 19 0 257 683 ; + +C 109 ; WX 778 ; N m ; B 16 0 775 460 ; + +C 110 ; WX 500 ; N n ; B 16 0 485 460 ; + +C 111 ; WX 500 ; N o ; B 29 -10 470 460 ; + +C 112 ; WX 500 ; N p ; B 5 -217 470 460 ; + +C 113 ; WX 500 ; N q ; B 24 -217 488 460 ; + +C 114 ; WX 333 ; N r ; B 5 0 335 460 ; + +C 115 ; WX 389 ; N s ; B 51 -10 348 460 ; + +C 116 ; WX 278 ; N t ; B 13 -10 279 579 ; + +C 117 ; WX 500 ; N u ; B 9 -10 479 450 ; + +C 118 ; WX 500 ; N v ; B 19 -14 477 450 ; + +C 119 ; WX 722 ; N w ; B 21 -14 694 450 ; + +C 120 ; WX 500 ; N x ; B 17 0 479 450 ; + +C 121 ; WX 500 ; N y ; B 14 -218 475 450 ; + +C 122 ; WX 444 ; N z ; B 27 0 418 450 ; + +C 123 ; WX 480 ; N braceleft ; B 100 -181 350 680 ; + +C 124 ; WX 200 ; N bar ; B 67 -218 133 782 ; + +C 125 ; WX 480 ; N braceright ; B 130 -181 380 680 ; + +C 126 ; WX 541 ; N asciitilde ; B 40 183 502 323 ; + +C 161 ; WX 333 ; N exclamdown ; B 97 -218 205 467 ; + +C 162 ; WX 500 ; N cent ; B 53 -138 448 579 ; + +C 163 ; WX 500 ; N sterling ; B 12 -8 490 676 ; + +C 164 ; WX 167 ; N fraction ; B -168 -14 331 676 ; + +C 165 ; WX 500 ; N yen ; B -53 0 512 662 ; + +C 166 ; WX 500 ; N florin ; B 7 -189 490 676 ; + +C 167 ; WX 500 ; N section ; B 70 -148 426 676 ; + +C 168 ; WX 500 ; N currency ; B -22 58 522 602 ; + +C 169 ; WX 180 ; N quotesingle ; B 48 431 133 676 ; + +C 170 ; WX 444 ; N quotedblleft ; B 43 433 414 676 ; + +C 171 ; WX 500 ; N guillemotleft ; B 42 33 456 416 ; + +C 172 ; WX 333 ; N guilsinglleft ; B 63 33 285 416 ; + +C 173 ; WX 333 ; N guilsinglright ; B 48 33 270 416 ; + +C 174 ; WX 556 ; N fi ; B 31 0 521 683 ; + +C 175 ; WX 556 ; N fl ; B 32 0 521 683 ; + +C 177 ; WX 500 ; N endash ; B 0 201 500 250 ; + +C 178 ; WX 500 ; N dagger ; B 59 -149 442 676 ; + +C 179 ; WX 500 ; N daggerdbl ; B 58 -153 442 676 ; + +C 180 ; WX 250 ; N periodcentered ; B 70 199 181 310 ; + +C 182 ; WX 453 ; N paragraph ; B -22 -154 450 662 ; + +C 183 ; WX 350 ; N bullet ; B 40 196 310 466 ; + +C 184 ; WX 333 ; N quotesinglbase ; B 79 -141 218 102 ; + +C 185 ; WX 444 ; N quotedblbase ; B 45 -141 416 102 ; + +C 186 ; WX 444 ; N quotedblright ; B 30 433 401 676 ; + +C 187 ; WX 500 ; N guillemotright ; B 44 33 458 416 ; + +C 188 ; WX 1000 ; N ellipsis ; B 111 -11 888 100 ; + +C 189 ; WX 1000 ; N perthousand ; B 7 -19 994 706 ; + +C 191 ; WX 444 ; N questiondown ; B 30 -218 376 466 ; + +C 193 ; WX 333 ; N grave ; B 19 507 242 678 ; + +C 194 ; WX 333 ; N acute ; B 93 507 317 678 ; + +C 195 ; WX 333 ; N circumflex ; B 11 507 322 674 ; + +C 196 ; WX 333 ; N tilde ; B 1 532 331 638 ; + +C 197 ; WX 333 ; N macron ; B 11 547 322 601 ; + +C 198 ; WX 333 ; N breve ; B 26 507 307 664 ; + +C 199 ; WX 333 ; N dotaccent ; B 118 581 216 681 ; + +C 200 ; WX 333 ; N dieresis ; B 18 581 315 681 ; + +C 202 ; WX 333 ; N ring ; B 67 512 266 711 ; + +C 203 ; WX 333 ; N cedilla ; B 52 -215 261 0 ; + +C 205 ; WX 333 ; N hungarumlaut ; B -3 507 377 678 ; + +C 206 ; WX 333 ; N ogonek ; B 62 -165 243 0 ; + +C 207 ; WX 333 ; N caron ; B 11 507 322 674 ; + +C 208 ; WX 1000 ; N emdash ; B 0 201 1000 250 ; + +C 225 ; WX 889 ; N AE ; B 0 0 863 662 ; + +C 227 ; WX 276 ; N ordfeminine ; B 4 394 270 676 ; + +C 232 ; WX 611 ; N Lslash ; B 12 0 598 662 ; + +C 233 ; WX 722 ; N Oslash ; B 34 -80 688 734 ; + +C 234 ; WX 889 ; N OE ; B 30 -6 885 668 ; + +C 235 ; WX 310 ; N ordmasculine ; B 6 394 304 676 ; + +C 241 ; WX 667 ; N ae ; B 38 -10 632 460 ; + +C 245 ; WX 278 ; N dotlessi ; B 16 0 253 460 ; + +C 248 ; WX 278 ; N lslash ; B 19 0 259 683 ; + +C 249 ; WX 500 ; N oslash ; B 29 -112 470 551 ; + +C 250 ; WX 722 ; N oe ; B 30 -10 690 460 ; + +C 251 ; WX 500 ; N germandbls ; B 12 -9 468 683 ; + +C -1 ; WX 333 ; N Idieresis ; B 18 0 315 835 ; + +C -1 ; WX 444 ; N eacute ; B 25 -10 424 678 ; + +C -1 ; WX 444 ; N abreve ; B 37 -10 442 664 ; + +C -1 ; WX 500 ; N uhungarumlaut ; B 9 -10 501 678 ; + +C -1 ; WX 444 ; N ecaron ; B 25 -10 424 674 ; + +C -1 ; WX 722 ; N Ydieresis ; B 22 0 703 835 ; + +C -1 ; WX 564 ; N divide ; B 30 -10 534 516 ; + +C -1 ; WX 722 ; N Yacute ; B 22 0 703 890 ; + +C -1 ; WX 722 ; N Acircumflex ; B 15 0 706 886 ; + +C -1 ; WX 444 ; N aacute ; B 37 -10 442 678 ; + +C -1 ; WX 722 ; N Ucircumflex ; B 14 -14 705 886 ; + +C -1 ; WX 500 ; N yacute ; B 14 -218 475 678 ; + +C -1 ; WX 389 ; N scommaaccent ; B 51 -218 348 460 ; + +C -1 ; WX 444 ; N ecircumflex ; B 25 -10 424 674 ; + +C -1 ; WX 722 ; N Uring ; B 14 -14 705 898 ; + +C -1 ; WX 722 ; N Udieresis ; B 14 -14 705 835 ; + +C -1 ; WX 444 ; N aogonek ; B 37 -165 469 460 ; + +C -1 ; WX 722 ; N Uacute ; B 14 -14 705 890 ; + +C -1 ; WX 500 ; N uogonek ; B 9 -155 487 450 ; + +C -1 ; WX 611 ; N Edieresis ; B 12 0 597 835 ; + +C -1 ; WX 722 ; N Dcroat ; B 16 0 685 662 ; + +C -1 ; WX 250 ; N commaaccent ; B 59 -218 184 -50 ; + +C -1 ; WX 760 ; N copyright ; B 38 -14 722 676 ; + +C -1 ; WX 611 ; N Emacron ; B 12 0 597 813 ; + +C -1 ; WX 444 ; N ccaron ; B 25 -10 412 674 ; + +C -1 ; WX 444 ; N aring ; B 37 -10 442 711 ; + +C -1 ; WX 722 ; N Ncommaaccent ; B 12 -198 707 662 ; + +C -1 ; WX 278 ; N lacute ; B 19 0 290 890 ; + +C -1 ; WX 444 ; N agrave ; B 37 -10 442 678 ; + +C -1 ; WX 611 ; N Tcommaaccent ; B 17 -218 593 662 ; + +C -1 ; WX 667 ; N Cacute ; B 28 -14 633 890 ; + +C -1 ; WX 444 ; N atilde ; B 37 -10 442 638 ; + +C -1 ; WX 611 ; N Edotaccent ; B 12 0 597 835 ; + +C -1 ; WX 389 ; N scaron ; B 39 -10 350 674 ; + +C -1 ; WX 389 ; N scedilla ; B 51 -215 348 460 ; + +C -1 ; WX 278 ; N iacute ; B 16 0 290 678 ; + +C -1 ; WX 471 ; N lozenge ; B 13 0 459 724 ; + +C -1 ; WX 667 ; N Rcaron ; B 17 0 659 886 ; + +C -1 ; WX 722 ; N Gcommaaccent ; B 32 -218 709 676 ; + +C -1 ; WX 500 ; N ucircumflex ; B 9 -10 479 674 ; + +C -1 ; WX 444 ; N acircumflex ; B 37 -10 442 674 ; + +C -1 ; WX 722 ; N Amacron ; B 15 0 706 813 ; + +C -1 ; WX 333 ; N rcaron ; B 5 0 335 674 ; + +C -1 ; WX 444 ; N ccedilla ; B 25 -215 412 460 ; + +C -1 ; WX 611 ; N Zdotaccent ; B 9 0 597 835 ; + +C -1 ; WX 556 ; N Thorn ; B 16 0 542 662 ; + +C -1 ; WX 722 ; N Omacron ; B 34 -14 688 813 ; + +C -1 ; WX 667 ; N Racute ; B 17 0 659 890 ; + +C -1 ; WX 556 ; N Sacute ; B 42 -14 491 890 ; + +C -1 ; WX 588 ; N dcaron ; B 27 -10 589 695 ; + +C -1 ; WX 722 ; N Umacron ; B 14 -14 705 813 ; + +C -1 ; WX 500 ; N uring ; B 9 -10 479 711 ; + +C -1 ; WX 300 ; N threesuperior ; B 15 262 291 676 ; + +C -1 ; WX 722 ; N Ograve ; B 34 -14 688 890 ; + +C -1 ; WX 722 ; N Agrave ; B 15 0 706 890 ; + +C -1 ; WX 722 ; N Abreve ; B 15 0 706 876 ; + +C -1 ; WX 564 ; N multiply ; B 38 8 527 497 ; + +C -1 ; WX 500 ; N uacute ; B 9 -10 479 678 ; + +C -1 ; WX 611 ; N Tcaron ; B 17 0 593 886 ; + +C -1 ; WX 476 ; N partialdiff ; B 17 -38 459 710 ; + +C -1 ; WX 500 ; N ydieresis ; B 14 -218 475 623 ; + +C -1 ; WX 722 ; N Nacute ; B 12 -11 707 890 ; + +C -1 ; WX 278 ; N icircumflex ; B -16 0 295 674 ; + +C -1 ; WX 611 ; N Ecircumflex ; B 12 0 597 886 ; + +C -1 ; WX 444 ; N adieresis ; B 37 -10 442 623 ; + +C -1 ; WX 444 ; N edieresis ; B 25 -10 424 623 ; + +C -1 ; WX 444 ; N cacute ; B 25 -10 413 678 ; + +C -1 ; WX 500 ; N nacute ; B 16 0 485 678 ; + +C -1 ; WX 500 ; N umacron ; B 9 -10 479 601 ; + +C -1 ; WX 722 ; N Ncaron ; B 12 -11 707 886 ; + +C -1 ; WX 333 ; N Iacute ; B 18 0 317 890 ; + +C -1 ; WX 564 ; N plusminus ; B 30 0 534 506 ; + +C -1 ; WX 200 ; N brokenbar ; B 67 -143 133 707 ; + +C -1 ; WX 760 ; N registered ; B 38 -14 722 676 ; + +C -1 ; WX 722 ; N Gbreve ; B 32 -14 709 876 ; + +C -1 ; WX 333 ; N Idotaccent ; B 18 0 315 835 ; + +C -1 ; WX 600 ; N summation ; B 15 -10 585 706 ; + +C -1 ; WX 611 ; N Egrave ; B 12 0 597 890 ; + +C -1 ; WX 333 ; N racute ; B 5 0 335 678 ; + +C -1 ; WX 500 ; N omacron ; B 29 -10 470 601 ; + +C -1 ; WX 611 ; N Zacute ; B 9 0 597 890 ; + +C -1 ; WX 611 ; N Zcaron ; B 9 0 597 886 ; + +C -1 ; WX 549 ; N greaterequal ; B 26 0 523 666 ; + +C -1 ; WX 722 ; N Eth ; B 16 0 685 662 ; + +C -1 ; WX 667 ; N Ccedilla ; B 28 -215 633 676 ; + +C -1 ; WX 278 ; N lcommaaccent ; B 19 -218 257 683 ; + +C -1 ; WX 326 ; N tcaron ; B 13 -10 318 722 ; + +C -1 ; WX 444 ; N eogonek ; B 25 -165 424 460 ; + +C -1 ; WX 722 ; N Uogonek ; B 14 -165 705 662 ; + +C -1 ; WX 722 ; N Aacute ; B 15 0 706 890 ; + +C -1 ; WX 722 ; N Adieresis ; B 15 0 706 835 ; + +C -1 ; WX 444 ; N egrave ; B 25 -10 424 678 ; + +C -1 ; WX 444 ; N zacute ; B 27 0 418 678 ; + +C -1 ; WX 278 ; N iogonek ; B 16 -165 265 683 ; + +C -1 ; WX 722 ; N Oacute ; B 34 -14 688 890 ; + +C -1 ; WX 500 ; N oacute ; B 29 -10 470 678 ; + +C -1 ; WX 444 ; N amacron ; B 37 -10 442 601 ; + +C -1 ; WX 389 ; N sacute ; B 51 -10 348 678 ; + +C -1 ; WX 278 ; N idieresis ; B -9 0 288 623 ; + +C -1 ; WX 722 ; N Ocircumflex ; B 34 -14 688 886 ; + +C -1 ; WX 722 ; N Ugrave ; B 14 -14 705 890 ; + +C -1 ; WX 612 ; N Delta ; B 6 0 608 688 ; + +C -1 ; WX 500 ; N thorn ; B 5 -217 470 683 ; + +C -1 ; WX 300 ; N twosuperior ; B 1 270 296 676 ; + +C -1 ; WX 722 ; N Odieresis ; B 34 -14 688 835 ; + +C -1 ; WX 500 ; N mu ; B 36 -218 512 450 ; + +C -1 ; WX 278 ; N igrave ; B -8 0 253 678 ; + +C -1 ; WX 500 ; N ohungarumlaut ; B 29 -10 491 678 ; + +C -1 ; WX 611 ; N Eogonek ; B 12 -165 597 662 ; + +C -1 ; WX 500 ; N dcroat ; B 27 -10 500 683 ; + +C -1 ; WX 750 ; N threequarters ; B 15 -14 718 676 ; + +C -1 ; WX 556 ; N Scedilla ; B 42 -215 491 676 ; + +C -1 ; WX 344 ; N lcaron ; B 19 0 347 695 ; + +C -1 ; WX 722 ; N Kcommaaccent ; B 34 -198 723 662 ; + +C -1 ; WX 611 ; N Lacute ; B 12 0 598 890 ; + +C -1 ; WX 980 ; N trademark ; B 30 256 957 662 ; + +C -1 ; WX 444 ; N edotaccent ; B 25 -10 424 623 ; + +C -1 ; WX 333 ; N Igrave ; B 18 0 315 890 ; + +C -1 ; WX 333 ; N Imacron ; B 11 0 322 813 ; + +C -1 ; WX 611 ; N Lcaron ; B 12 0 598 676 ; + +C -1 ; WX 750 ; N onehalf ; B 31 -14 746 676 ; + +C -1 ; WX 549 ; N lessequal ; B 26 0 523 666 ; + +C -1 ; WX 500 ; N ocircumflex ; B 29 -10 470 674 ; + +C -1 ; WX 500 ; N ntilde ; B 16 0 485 638 ; + +C -1 ; WX 722 ; N Uhungarumlaut ; B 14 -14 705 890 ; + +C -1 ; WX 611 ; N Eacute ; B 12 0 597 890 ; + +C -1 ; WX 444 ; N emacron ; B 25 -10 424 601 ; + +C -1 ; WX 500 ; N gbreve ; B 28 -218 470 664 ; + +C -1 ; WX 750 ; N onequarter ; B 37 -14 718 676 ; + +C -1 ; WX 556 ; N Scaron ; B 42 -14 491 886 ; + +C -1 ; WX 556 ; N Scommaaccent ; B 42 -218 491 676 ; + +C -1 ; WX 722 ; N Ohungarumlaut ; B 34 -14 688 890 ; + +C -1 ; WX 400 ; N degree ; B 57 390 343 676 ; + +C -1 ; WX 500 ; N ograve ; B 29 -10 470 678 ; + +C -1 ; WX 667 ; N Ccaron ; B 28 -14 633 886 ; + +C -1 ; WX 500 ; N ugrave ; B 9 -10 479 678 ; + +C -1 ; WX 453 ; N radical ; B 2 -60 452 768 ; + +C -1 ; WX 722 ; N Dcaron ; B 16 0 685 886 ; + +C -1 ; WX 333 ; N rcommaaccent ; B 5 -218 335 460 ; + +C -1 ; WX 722 ; N Ntilde ; B 12 -11 707 850 ; + +C -1 ; WX 500 ; N otilde ; B 29 -10 470 638 ; + +C -1 ; WX 667 ; N Rcommaaccent ; B 17 -198 659 662 ; + +C -1 ; WX 611 ; N Lcommaaccent ; B 12 -218 598 662 ; + +C -1 ; WX 722 ; N Atilde ; B 15 0 706 850 ; + +C -1 ; WX 722 ; N Aogonek ; B 15 -165 738 674 ; + +C -1 ; WX 722 ; N Aring ; B 15 0 706 898 ; + +C -1 ; WX 722 ; N Otilde ; B 34 -14 688 850 ; + +C -1 ; WX 444 ; N zdotaccent ; B 27 0 418 623 ; + +C -1 ; WX 611 ; N Ecaron ; B 12 0 597 886 ; + +C -1 ; WX 333 ; N Iogonek ; B 18 -165 315 662 ; + +C -1 ; WX 500 ; N kcommaaccent ; B 7 -218 505 683 ; + +C -1 ; WX 564 ; N minus ; B 30 220 534 286 ; + +C -1 ; WX 333 ; N Icircumflex ; B 11 0 322 886 ; + +C -1 ; WX 500 ; N ncaron ; B 16 0 485 674 ; + +C -1 ; WX 278 ; N tcommaaccent ; B 13 -218 279 579 ; + +C -1 ; WX 564 ; N logicalnot ; B 30 108 534 386 ; + +C -1 ; WX 500 ; N odieresis ; B 29 -10 470 623 ; + +C -1 ; WX 500 ; N udieresis ; B 9 -10 479 623 ; + +C -1 ; WX 549 ; N notequal ; B 12 -31 537 547 ; + +C -1 ; WX 500 ; N gcommaaccent ; B 28 -218 470 749 ; + +C -1 ; WX 500 ; N eth ; B 29 -10 471 686 ; + +C -1 ; WX 444 ; N zcaron ; B 27 0 418 674 ; + +C -1 ; WX 500 ; N ncommaaccent ; B 16 -218 485 460 ; + +C -1 ; WX 300 ; N onesuperior ; B 57 270 248 676 ; + +C -1 ; WX 278 ; N imacron ; B 6 0 271 601 ; + +C -1 ; WX 500 ; N Euro ; B 0 0 0 0 ; + +EndCharMetrics + +StartKernData + +StartKernPairs 2073 + +KPX A C -40 + +KPX A Cacute -40 + +KPX A Ccaron -40 + +KPX A Ccedilla -40 + +KPX A G -40 + +KPX A Gbreve -40 + +KPX A Gcommaaccent -40 + +KPX A O -55 + +KPX A Oacute -55 + +KPX A Ocircumflex -55 + +KPX A Odieresis -55 + +KPX A Ograve -55 + +KPX A Ohungarumlaut -55 + +KPX A Omacron -55 + +KPX A Oslash -55 + +KPX A Otilde -55 + +KPX A Q -55 + +KPX A T -111 + +KPX A Tcaron -111 + +KPX A Tcommaaccent -111 + +KPX A U -55 + +KPX A Uacute -55 + +KPX A Ucircumflex -55 + +KPX A Udieresis -55 + +KPX A Ugrave -55 + +KPX A Uhungarumlaut -55 + +KPX A Umacron -55 + +KPX A Uogonek -55 + +KPX A Uring -55 + +KPX A V -135 + +KPX A W -90 + +KPX A Y -105 + +KPX A Yacute -105 + +KPX A Ydieresis -105 + +KPX A quoteright -111 + +KPX A v -74 + +KPX A w -92 + +KPX A y -92 + +KPX A yacute -92 + +KPX A ydieresis -92 + +KPX Aacute C -40 + +KPX Aacute Cacute -40 + +KPX Aacute Ccaron -40 + +KPX Aacute Ccedilla -40 + +KPX Aacute G -40 + +KPX Aacute Gbreve -40 + +KPX Aacute Gcommaaccent -40 + +KPX Aacute O -55 + +KPX Aacute Oacute -55 + +KPX Aacute Ocircumflex -55 + +KPX Aacute Odieresis -55 + +KPX Aacute Ograve -55 + +KPX Aacute Ohungarumlaut -55 + +KPX Aacute Omacron -55 + +KPX Aacute Oslash -55 + +KPX Aacute Otilde -55 + +KPX Aacute Q -55 + +KPX Aacute T -111 + +KPX Aacute Tcaron -111 + +KPX Aacute Tcommaaccent -111 + +KPX Aacute U -55 + +KPX Aacute Uacute -55 + +KPX Aacute Ucircumflex -55 + +KPX Aacute Udieresis -55 + +KPX Aacute Ugrave -55 + +KPX Aacute Uhungarumlaut -55 + +KPX Aacute Umacron -55 + +KPX Aacute Uogonek -55 + +KPX Aacute Uring -55 + +KPX Aacute V -135 + +KPX Aacute W -90 + +KPX Aacute Y -105 + +KPX Aacute Yacute -105 + +KPX Aacute Ydieresis -105 + +KPX Aacute quoteright -111 + +KPX Aacute v -74 + +KPX Aacute w -92 + +KPX Aacute y -92 + +KPX Aacute yacute -92 + +KPX Aacute ydieresis -92 + +KPX Abreve C -40 + +KPX Abreve Cacute -40 + +KPX Abreve Ccaron -40 + +KPX Abreve Ccedilla -40 + +KPX Abreve G -40 + +KPX Abreve Gbreve -40 + +KPX Abreve Gcommaaccent -40 + +KPX Abreve O -55 + +KPX Abreve Oacute -55 + +KPX Abreve Ocircumflex -55 + +KPX Abreve Odieresis -55 + +KPX Abreve Ograve -55 + +KPX Abreve Ohungarumlaut -55 + +KPX Abreve Omacron -55 + +KPX Abreve Oslash -55 + +KPX Abreve Otilde -55 + +KPX Abreve Q -55 + +KPX Abreve T -111 + +KPX Abreve Tcaron -111 + +KPX Abreve Tcommaaccent -111 + +KPX Abreve U -55 + +KPX Abreve Uacute -55 + +KPX Abreve Ucircumflex -55 + +KPX Abreve Udieresis -55 + +KPX Abreve Ugrave -55 + +KPX Abreve Uhungarumlaut -55 + +KPX Abreve Umacron -55 + +KPX Abreve Uogonek -55 + +KPX Abreve Uring -55 + +KPX Abreve V -135 + +KPX Abreve W -90 + +KPX Abreve Y -105 + +KPX Abreve Yacute -105 + +KPX Abreve Ydieresis -105 + +KPX Abreve quoteright -111 + +KPX Abreve v -74 + +KPX Abreve w -92 + +KPX Abreve y -92 + +KPX Abreve yacute -92 + +KPX Abreve ydieresis -92 + +KPX Acircumflex C -40 + +KPX Acircumflex Cacute -40 + +KPX Acircumflex Ccaron -40 + +KPX Acircumflex Ccedilla -40 + +KPX Acircumflex G -40 + +KPX Acircumflex Gbreve -40 + +KPX Acircumflex Gcommaaccent -40 + +KPX Acircumflex O -55 + +KPX Acircumflex Oacute -55 + +KPX Acircumflex Ocircumflex -55 + +KPX Acircumflex Odieresis -55 + +KPX Acircumflex Ograve -55 + +KPX Acircumflex Ohungarumlaut -55 + +KPX Acircumflex Omacron -55 + +KPX Acircumflex Oslash -55 + +KPX Acircumflex Otilde -55 + +KPX Acircumflex Q -55 + +KPX Acircumflex T -111 + +KPX Acircumflex Tcaron -111 + +KPX Acircumflex Tcommaaccent -111 + +KPX Acircumflex U -55 + +KPX Acircumflex Uacute -55 + +KPX Acircumflex Ucircumflex -55 + +KPX Acircumflex Udieresis -55 + +KPX Acircumflex Ugrave -55 + +KPX Acircumflex Uhungarumlaut -55 + +KPX Acircumflex Umacron -55 + +KPX Acircumflex Uogonek -55 + +KPX Acircumflex Uring -55 + +KPX Acircumflex V -135 + +KPX Acircumflex W -90 + +KPX Acircumflex Y -105 + +KPX Acircumflex Yacute -105 + +KPX Acircumflex Ydieresis -105 + +KPX Acircumflex quoteright -111 + +KPX Acircumflex v -74 + +KPX Acircumflex w -92 + +KPX Acircumflex y -92 + +KPX Acircumflex yacute -92 + +KPX Acircumflex ydieresis -92 + +KPX Adieresis C -40 + +KPX Adieresis Cacute -40 + +KPX Adieresis Ccaron -40 + +KPX Adieresis Ccedilla -40 + +KPX Adieresis G -40 + +KPX Adieresis Gbreve -40 + +KPX Adieresis Gcommaaccent -40 + +KPX Adieresis O -55 + +KPX Adieresis Oacute -55 + +KPX Adieresis Ocircumflex -55 + +KPX Adieresis Odieresis -55 + +KPX Adieresis Ograve -55 + +KPX Adieresis Ohungarumlaut -55 + +KPX Adieresis Omacron -55 + +KPX Adieresis Oslash -55 + +KPX Adieresis Otilde -55 + +KPX Adieresis Q -55 + +KPX Adieresis T -111 + +KPX Adieresis Tcaron -111 + +KPX Adieresis Tcommaaccent -111 + +KPX Adieresis U -55 + +KPX Adieresis Uacute -55 + +KPX Adieresis Ucircumflex -55 + +KPX Adieresis Udieresis -55 + +KPX Adieresis Ugrave -55 + +KPX Adieresis Uhungarumlaut -55 + +KPX Adieresis Umacron -55 + +KPX Adieresis Uogonek -55 + +KPX Adieresis Uring -55 + +KPX Adieresis V -135 + +KPX Adieresis W -90 + +KPX Adieresis Y -105 + +KPX Adieresis Yacute -105 + +KPX Adieresis Ydieresis -105 + +KPX Adieresis quoteright -111 + +KPX Adieresis v -74 + +KPX Adieresis w -92 + +KPX Adieresis y -92 + +KPX Adieresis yacute -92 + +KPX Adieresis ydieresis -92 + +KPX Agrave C -40 + +KPX Agrave Cacute -40 + +KPX Agrave Ccaron -40 + +KPX Agrave Ccedilla -40 + +KPX Agrave G -40 + +KPX Agrave Gbreve -40 + +KPX Agrave Gcommaaccent -40 + +KPX Agrave O -55 + +KPX Agrave Oacute -55 + +KPX Agrave Ocircumflex -55 + +KPX Agrave Odieresis -55 + +KPX Agrave Ograve -55 + +KPX Agrave Ohungarumlaut -55 + +KPX Agrave Omacron -55 + +KPX Agrave Oslash -55 + +KPX Agrave Otilde -55 + +KPX Agrave Q -55 + +KPX Agrave T -111 + +KPX Agrave Tcaron -111 + +KPX Agrave Tcommaaccent -111 + +KPX Agrave U -55 + +KPX Agrave Uacute -55 + +KPX Agrave Ucircumflex -55 + +KPX Agrave Udieresis -55 + +KPX Agrave Ugrave -55 + +KPX Agrave Uhungarumlaut -55 + +KPX Agrave Umacron -55 + +KPX Agrave Uogonek -55 + +KPX Agrave Uring -55 + +KPX Agrave V -135 + +KPX Agrave W -90 + +KPX Agrave Y -105 + +KPX Agrave Yacute -105 + +KPX Agrave Ydieresis -105 + +KPX Agrave quoteright -111 + +KPX Agrave v -74 + +KPX Agrave w -92 + +KPX Agrave y -92 + +KPX Agrave yacute -92 + +KPX Agrave ydieresis -92 + +KPX Amacron C -40 + +KPX Amacron Cacute -40 + +KPX Amacron Ccaron -40 + +KPX Amacron Ccedilla -40 + +KPX Amacron G -40 + +KPX Amacron Gbreve -40 + +KPX Amacron Gcommaaccent -40 + +KPX Amacron O -55 + +KPX Amacron Oacute -55 + +KPX Amacron Ocircumflex -55 + +KPX Amacron Odieresis -55 + +KPX Amacron Ograve -55 + +KPX Amacron Ohungarumlaut -55 + +KPX Amacron Omacron -55 + +KPX Amacron Oslash -55 + +KPX Amacron Otilde -55 + +KPX Amacron Q -55 + +KPX Amacron T -111 + +KPX Amacron Tcaron -111 + +KPX Amacron Tcommaaccent -111 + +KPX Amacron U -55 + +KPX Amacron Uacute -55 + +KPX Amacron Ucircumflex -55 + +KPX Amacron Udieresis -55 + +KPX Amacron Ugrave -55 + +KPX Amacron Uhungarumlaut -55 + +KPX Amacron Umacron -55 + +KPX Amacron Uogonek -55 + +KPX Amacron Uring -55 + +KPX Amacron V -135 + +KPX Amacron W -90 + +KPX Amacron Y -105 + +KPX Amacron Yacute -105 + +KPX Amacron Ydieresis -105 + +KPX Amacron quoteright -111 + +KPX Amacron v -74 + +KPX Amacron w -92 + +KPX Amacron y -92 + +KPX Amacron yacute -92 + +KPX Amacron ydieresis -92 + +KPX Aogonek C -40 + +KPX Aogonek Cacute -40 + +KPX Aogonek Ccaron -40 + +KPX Aogonek Ccedilla -40 + +KPX Aogonek G -40 + +KPX Aogonek Gbreve -40 + +KPX Aogonek Gcommaaccent -40 + +KPX Aogonek O -55 + +KPX Aogonek Oacute -55 + +KPX Aogonek Ocircumflex -55 + +KPX Aogonek Odieresis -55 + +KPX Aogonek Ograve -55 + +KPX Aogonek Ohungarumlaut -55 + +KPX Aogonek Omacron -55 + +KPX Aogonek Oslash -55 + +KPX Aogonek Otilde -55 + +KPX Aogonek Q -55 + +KPX Aogonek T -111 + +KPX Aogonek Tcaron -111 + +KPX Aogonek Tcommaaccent -111 + +KPX Aogonek U -55 + +KPX Aogonek Uacute -55 + +KPX Aogonek Ucircumflex -55 + +KPX Aogonek Udieresis -55 + +KPX Aogonek Ugrave -55 + +KPX Aogonek Uhungarumlaut -55 + +KPX Aogonek Umacron -55 + +KPX Aogonek Uogonek -55 + +KPX Aogonek Uring -55 + +KPX Aogonek V -135 + +KPX Aogonek W -90 + +KPX Aogonek Y -105 + +KPX Aogonek Yacute -105 + +KPX Aogonek Ydieresis -105 + +KPX Aogonek quoteright -111 + +KPX Aogonek v -74 + +KPX Aogonek w -52 + +KPX Aogonek y -52 + +KPX Aogonek yacute -52 + +KPX Aogonek ydieresis -52 + +KPX Aring C -40 + +KPX Aring Cacute -40 + +KPX Aring Ccaron -40 + +KPX Aring Ccedilla -40 + +KPX Aring G -40 + +KPX Aring Gbreve -40 + +KPX Aring Gcommaaccent -40 + +KPX Aring O -55 + +KPX Aring Oacute -55 + +KPX Aring Ocircumflex -55 + +KPX Aring Odieresis -55 + +KPX Aring Ograve -55 + +KPX Aring Ohungarumlaut -55 + +KPX Aring Omacron -55 + +KPX Aring Oslash -55 + +KPX Aring Otilde -55 + +KPX Aring Q -55 + +KPX Aring T -111 + +KPX Aring Tcaron -111 + +KPX Aring Tcommaaccent -111 + +KPX Aring U -55 + +KPX Aring Uacute -55 + +KPX Aring Ucircumflex -55 + +KPX Aring Udieresis -55 + +KPX Aring Ugrave -55 + +KPX Aring Uhungarumlaut -55 + +KPX Aring Umacron -55 + +KPX Aring Uogonek -55 + +KPX Aring Uring -55 + +KPX Aring V -135 + +KPX Aring W -90 + +KPX Aring Y -105 + +KPX Aring Yacute -105 + +KPX Aring Ydieresis -105 + +KPX Aring quoteright -111 + +KPX Aring v -74 + +KPX Aring w -92 + +KPX Aring y -92 + +KPX Aring yacute -92 + +KPX Aring ydieresis -92 + +KPX Atilde C -40 + +KPX Atilde Cacute -40 + +KPX Atilde Ccaron -40 + +KPX Atilde Ccedilla -40 + +KPX Atilde G -40 + +KPX Atilde Gbreve -40 + +KPX Atilde Gcommaaccent -40 + +KPX Atilde O -55 + +KPX Atilde Oacute -55 + +KPX Atilde Ocircumflex -55 + +KPX Atilde Odieresis -55 + +KPX Atilde Ograve -55 + +KPX Atilde Ohungarumlaut -55 + +KPX Atilde Omacron -55 + +KPX Atilde Oslash -55 + +KPX Atilde Otilde -55 + +KPX Atilde Q -55 + +KPX Atilde T -111 + +KPX Atilde Tcaron -111 + +KPX Atilde Tcommaaccent -111 + +KPX Atilde U -55 + +KPX Atilde Uacute -55 + +KPX Atilde Ucircumflex -55 + +KPX Atilde Udieresis -55 + +KPX Atilde Ugrave -55 + +KPX Atilde Uhungarumlaut -55 + +KPX Atilde Umacron -55 + +KPX Atilde Uogonek -55 + +KPX Atilde Uring -55 + +KPX Atilde V -135 + +KPX Atilde W -90 + +KPX Atilde Y -105 + +KPX Atilde Yacute -105 + +KPX Atilde Ydieresis -105 + +KPX Atilde quoteright -111 + +KPX Atilde v -74 + +KPX Atilde w -92 + +KPX Atilde y -92 + +KPX Atilde yacute -92 + +KPX Atilde ydieresis -92 + +KPX B A -35 + +KPX B Aacute -35 + +KPX B Abreve -35 + +KPX B Acircumflex -35 + +KPX B Adieresis -35 + +KPX B Agrave -35 + +KPX B Amacron -35 + +KPX B Aogonek -35 + +KPX B Aring -35 + +KPX B Atilde -35 + +KPX B U -10 + +KPX B Uacute -10 + +KPX B Ucircumflex -10 + +KPX B Udieresis -10 + +KPX B Ugrave -10 + +KPX B Uhungarumlaut -10 + +KPX B Umacron -10 + +KPX B Uogonek -10 + +KPX B Uring -10 + +KPX D A -40 + +KPX D Aacute -40 + +KPX D Abreve -40 + +KPX D Acircumflex -40 + +KPX D Adieresis -40 + +KPX D Agrave -40 + +KPX D Amacron -40 + +KPX D Aogonek -40 + +KPX D Aring -40 + +KPX D Atilde -40 + +KPX D V -40 + +KPX D W -30 + +KPX D Y -55 + +KPX D Yacute -55 + +KPX D Ydieresis -55 + +KPX Dcaron A -40 + +KPX Dcaron Aacute -40 + +KPX Dcaron Abreve -40 + +KPX Dcaron Acircumflex -40 + +KPX Dcaron Adieresis -40 + +KPX Dcaron Agrave -40 + +KPX Dcaron Amacron -40 + +KPX Dcaron Aogonek -40 + +KPX Dcaron Aring -40 + +KPX Dcaron Atilde -40 + +KPX Dcaron V -40 + +KPX Dcaron W -30 + +KPX Dcaron Y -55 + +KPX Dcaron Yacute -55 + +KPX Dcaron Ydieresis -55 + +KPX Dcroat A -40 + +KPX Dcroat Aacute -40 + +KPX Dcroat Abreve -40 + +KPX Dcroat Acircumflex -40 + +KPX Dcroat Adieresis -40 + +KPX Dcroat Agrave -40 + +KPX Dcroat Amacron -40 + +KPX Dcroat Aogonek -40 + +KPX Dcroat Aring -40 + +KPX Dcroat Atilde -40 + +KPX Dcroat V -40 + +KPX Dcroat W -30 + +KPX Dcroat Y -55 + +KPX Dcroat Yacute -55 + +KPX Dcroat Ydieresis -55 + +KPX F A -74 + +KPX F Aacute -74 + +KPX F Abreve -74 + +KPX F Acircumflex -74 + +KPX F Adieresis -74 + +KPX F Agrave -74 + +KPX F Amacron -74 + +KPX F Aogonek -74 + +KPX F Aring -74 + +KPX F Atilde -74 + +KPX F a -15 + +KPX F aacute -15 + +KPX F abreve -15 + +KPX F acircumflex -15 + +KPX F adieresis -15 + +KPX F agrave -15 + +KPX F amacron -15 + +KPX F aogonek -15 + +KPX F aring -15 + +KPX F atilde -15 + +KPX F comma -80 + +KPX F o -15 + +KPX F oacute -15 + +KPX F ocircumflex -15 + +KPX F odieresis -15 + +KPX F ograve -15 + +KPX F ohungarumlaut -15 + +KPX F omacron -15 + +KPX F oslash -15 + +KPX F otilde -15 + +KPX F period -80 + +KPX J A -60 + +KPX J Aacute -60 + +KPX J Abreve -60 + +KPX J Acircumflex -60 + +KPX J Adieresis -60 + +KPX J Agrave -60 + +KPX J Amacron -60 + +KPX J Aogonek -60 + +KPX J Aring -60 + +KPX J Atilde -60 + +KPX K O -30 + +KPX K Oacute -30 + +KPX K Ocircumflex -30 + +KPX K Odieresis -30 + +KPX K Ograve -30 + +KPX K Ohungarumlaut -30 + +KPX K Omacron -30 + +KPX K Oslash -30 + +KPX K Otilde -30 + +KPX K e -25 + +KPX K eacute -25 + +KPX K ecaron -25 + +KPX K ecircumflex -25 + +KPX K edieresis -25 + +KPX K edotaccent -25 + +KPX K egrave -25 + +KPX K emacron -25 + +KPX K eogonek -25 + +KPX K o -35 + +KPX K oacute -35 + +KPX K ocircumflex -35 + +KPX K odieresis -35 + +KPX K ograve -35 + +KPX K ohungarumlaut -35 + +KPX K omacron -35 + +KPX K oslash -35 + +KPX K otilde -35 + +KPX K u -15 + +KPX K uacute -15 + +KPX K ucircumflex -15 + +KPX K udieresis -15 + +KPX K ugrave -15 + +KPX K uhungarumlaut -15 + +KPX K umacron -15 + +KPX K uogonek -15 + +KPX K uring -15 + +KPX K y -25 + +KPX K yacute -25 + +KPX K ydieresis -25 + +KPX Kcommaaccent O -30 + +KPX Kcommaaccent Oacute -30 + +KPX Kcommaaccent Ocircumflex -30 + +KPX Kcommaaccent Odieresis -30 + +KPX Kcommaaccent Ograve -30 + +KPX Kcommaaccent Ohungarumlaut -30 + +KPX Kcommaaccent Omacron -30 + +KPX Kcommaaccent Oslash -30 + +KPX Kcommaaccent Otilde -30 + +KPX Kcommaaccent e -25 + +KPX Kcommaaccent eacute -25 + +KPX Kcommaaccent ecaron -25 + +KPX Kcommaaccent ecircumflex -25 + +KPX Kcommaaccent edieresis -25 + +KPX Kcommaaccent edotaccent -25 + +KPX Kcommaaccent egrave -25 + +KPX Kcommaaccent emacron -25 + +KPX Kcommaaccent eogonek -25 + +KPX Kcommaaccent o -35 + +KPX Kcommaaccent oacute -35 + +KPX Kcommaaccent ocircumflex -35 + +KPX Kcommaaccent odieresis -35 + +KPX Kcommaaccent ograve -35 + +KPX Kcommaaccent ohungarumlaut -35 + +KPX Kcommaaccent omacron -35 + +KPX Kcommaaccent oslash -35 + +KPX Kcommaaccent otilde -35 + +KPX Kcommaaccent u -15 + +KPX Kcommaaccent uacute -15 + +KPX Kcommaaccent ucircumflex -15 + +KPX Kcommaaccent udieresis -15 + +KPX Kcommaaccent ugrave -15 + +KPX Kcommaaccent uhungarumlaut -15 + +KPX Kcommaaccent umacron -15 + +KPX Kcommaaccent uogonek -15 + +KPX Kcommaaccent uring -15 + +KPX Kcommaaccent y -25 + +KPX Kcommaaccent yacute -25 + +KPX Kcommaaccent ydieresis -25 + +KPX L T -92 + +KPX L Tcaron -92 + +KPX L Tcommaaccent -92 + +KPX L V -100 + +KPX L W -74 + +KPX L Y -100 + +KPX L Yacute -100 + +KPX L Ydieresis -100 + +KPX L quoteright -92 + +KPX L y -55 + +KPX L yacute -55 + +KPX L ydieresis -55 + +KPX Lacute T -92 + +KPX Lacute Tcaron -92 + +KPX Lacute Tcommaaccent -92 + +KPX Lacute V -100 + +KPX Lacute W -74 + +KPX Lacute Y -100 + +KPX Lacute Yacute -100 + +KPX Lacute Ydieresis -100 + +KPX Lacute quoteright -92 + +KPX Lacute y -55 + +KPX Lacute yacute -55 + +KPX Lacute ydieresis -55 + +KPX Lcaron quoteright -92 + +KPX Lcaron y -55 + +KPX Lcaron yacute -55 + +KPX Lcaron ydieresis -55 + +KPX Lcommaaccent T -92 + +KPX Lcommaaccent Tcaron -92 + +KPX Lcommaaccent Tcommaaccent -92 + +KPX Lcommaaccent V -100 + +KPX Lcommaaccent W -74 + +KPX Lcommaaccent Y -100 + +KPX Lcommaaccent Yacute -100 + +KPX Lcommaaccent Ydieresis -100 + +KPX Lcommaaccent quoteright -92 + +KPX Lcommaaccent y -55 + +KPX Lcommaaccent yacute -55 + +KPX Lcommaaccent ydieresis -55 + +KPX Lslash T -92 + +KPX Lslash Tcaron -92 + +KPX Lslash Tcommaaccent -92 + +KPX Lslash V -100 + +KPX Lslash W -74 + +KPX Lslash Y -100 + +KPX Lslash Yacute -100 + +KPX Lslash Ydieresis -100 + +KPX Lslash quoteright -92 + +KPX Lslash y -55 + +KPX Lslash yacute -55 + +KPX Lslash ydieresis -55 + +KPX N A -35 + +KPX N Aacute -35 + +KPX N Abreve -35 + +KPX N Acircumflex -35 + +KPX N Adieresis -35 + +KPX N Agrave -35 + +KPX N Amacron -35 + +KPX N Aogonek -35 + +KPX N Aring -35 + +KPX N Atilde -35 + +KPX Nacute A -35 + +KPX Nacute Aacute -35 + +KPX Nacute Abreve -35 + +KPX Nacute Acircumflex -35 + +KPX Nacute Adieresis -35 + +KPX Nacute Agrave -35 + +KPX Nacute Amacron -35 + +KPX Nacute Aogonek -35 + +KPX Nacute Aring -35 + +KPX Nacute Atilde -35 + +KPX Ncaron A -35 + +KPX Ncaron Aacute -35 + +KPX Ncaron Abreve -35 + +KPX Ncaron Acircumflex -35 + +KPX Ncaron Adieresis -35 + +KPX Ncaron Agrave -35 + +KPX Ncaron Amacron -35 + +KPX Ncaron Aogonek -35 + +KPX Ncaron Aring -35 + +KPX Ncaron Atilde -35 + +KPX Ncommaaccent A -35 + +KPX Ncommaaccent Aacute -35 + +KPX Ncommaaccent Abreve -35 + +KPX Ncommaaccent Acircumflex -35 + +KPX Ncommaaccent Adieresis -35 + +KPX Ncommaaccent Agrave -35 + +KPX Ncommaaccent Amacron -35 + +KPX Ncommaaccent Aogonek -35 + +KPX Ncommaaccent Aring -35 + +KPX Ncommaaccent Atilde -35 + +KPX Ntilde A -35 + +KPX Ntilde Aacute -35 + +KPX Ntilde Abreve -35 + +KPX Ntilde Acircumflex -35 + +KPX Ntilde Adieresis -35 + +KPX Ntilde Agrave -35 + +KPX Ntilde Amacron -35 + +KPX Ntilde Aogonek -35 + +KPX Ntilde Aring -35 + +KPX Ntilde Atilde -35 + +KPX O A -35 + +KPX O Aacute -35 + +KPX O Abreve -35 + +KPX O Acircumflex -35 + +KPX O Adieresis -35 + +KPX O Agrave -35 + +KPX O Amacron -35 + +KPX O Aogonek -35 + +KPX O Aring -35 + +KPX O Atilde -35 + +KPX O T -40 + +KPX O Tcaron -40 + +KPX O Tcommaaccent -40 + +KPX O V -50 + +KPX O W -35 + +KPX O X -40 + +KPX O Y -50 + +KPX O Yacute -50 + +KPX O Ydieresis -50 + +KPX Oacute A -35 + +KPX Oacute Aacute -35 + +KPX Oacute Abreve -35 + +KPX Oacute Acircumflex -35 + +KPX Oacute Adieresis -35 + +KPX Oacute Agrave -35 + +KPX Oacute Amacron -35 + +KPX Oacute Aogonek -35 + +KPX Oacute Aring -35 + +KPX Oacute Atilde -35 + +KPX Oacute T -40 + +KPX Oacute Tcaron -40 + +KPX Oacute Tcommaaccent -40 + +KPX Oacute V -50 + +KPX Oacute W -35 + +KPX Oacute X -40 + +KPX Oacute Y -50 + +KPX Oacute Yacute -50 + +KPX Oacute Ydieresis -50 + +KPX Ocircumflex A -35 + +KPX Ocircumflex Aacute -35 + +KPX Ocircumflex Abreve -35 + +KPX Ocircumflex Acircumflex -35 + +KPX Ocircumflex Adieresis -35 + +KPX Ocircumflex Agrave -35 + +KPX Ocircumflex Amacron -35 + +KPX Ocircumflex Aogonek -35 + +KPX Ocircumflex Aring -35 + +KPX Ocircumflex Atilde -35 + +KPX Ocircumflex T -40 + +KPX Ocircumflex Tcaron -40 + +KPX Ocircumflex Tcommaaccent -40 + +KPX Ocircumflex V -50 + +KPX Ocircumflex W -35 + +KPX Ocircumflex X -40 + +KPX Ocircumflex Y -50 + +KPX Ocircumflex Yacute -50 + +KPX Ocircumflex Ydieresis -50 + +KPX Odieresis A -35 + +KPX Odieresis Aacute -35 + +KPX Odieresis Abreve -35 + +KPX Odieresis Acircumflex -35 + +KPX Odieresis Adieresis -35 + +KPX Odieresis Agrave -35 + +KPX Odieresis Amacron -35 + +KPX Odieresis Aogonek -35 + +KPX Odieresis Aring -35 + +KPX Odieresis Atilde -35 + +KPX Odieresis T -40 + +KPX Odieresis Tcaron -40 + +KPX Odieresis Tcommaaccent -40 + +KPX Odieresis V -50 + +KPX Odieresis W -35 + +KPX Odieresis X -40 + +KPX Odieresis Y -50 + +KPX Odieresis Yacute -50 + +KPX Odieresis Ydieresis -50 + +KPX Ograve A -35 + +KPX Ograve Aacute -35 + +KPX Ograve Abreve -35 + +KPX Ograve Acircumflex -35 + +KPX Ograve Adieresis -35 + +KPX Ograve Agrave -35 + +KPX Ograve Amacron -35 + +KPX Ograve Aogonek -35 + +KPX Ograve Aring -35 + +KPX Ograve Atilde -35 + +KPX Ograve T -40 + +KPX Ograve Tcaron -40 + +KPX Ograve Tcommaaccent -40 + +KPX Ograve V -50 + +KPX Ograve W -35 + +KPX Ograve X -40 + +KPX Ograve Y -50 + +KPX Ograve Yacute -50 + +KPX Ograve Ydieresis -50 + +KPX Ohungarumlaut A -35 + +KPX Ohungarumlaut Aacute -35 + +KPX Ohungarumlaut Abreve -35 + +KPX Ohungarumlaut Acircumflex -35 + +KPX Ohungarumlaut Adieresis -35 + +KPX Ohungarumlaut Agrave -35 + +KPX Ohungarumlaut Amacron -35 + +KPX Ohungarumlaut Aogonek -35 + +KPX Ohungarumlaut Aring -35 + +KPX Ohungarumlaut Atilde -35 + +KPX Ohungarumlaut T -40 + +KPX Ohungarumlaut Tcaron -40 + +KPX Ohungarumlaut Tcommaaccent -40 + +KPX Ohungarumlaut V -50 + +KPX Ohungarumlaut W -35 + +KPX Ohungarumlaut X -40 + +KPX Ohungarumlaut Y -50 + +KPX Ohungarumlaut Yacute -50 + +KPX Ohungarumlaut Ydieresis -50 + +KPX Omacron A -35 + +KPX Omacron Aacute -35 + +KPX Omacron Abreve -35 + +KPX Omacron Acircumflex -35 + +KPX Omacron Adieresis -35 + +KPX Omacron Agrave -35 + +KPX Omacron Amacron -35 + +KPX Omacron Aogonek -35 + +KPX Omacron Aring -35 + +KPX Omacron Atilde -35 + +KPX Omacron T -40 + +KPX Omacron Tcaron -40 + +KPX Omacron Tcommaaccent -40 + +KPX Omacron V -50 + +KPX Omacron W -35 + +KPX Omacron X -40 + +KPX Omacron Y -50 + +KPX Omacron Yacute -50 + +KPX Omacron Ydieresis -50 + +KPX Oslash A -35 + +KPX Oslash Aacute -35 + +KPX Oslash Abreve -35 + +KPX Oslash Acircumflex -35 + +KPX Oslash Adieresis -35 + +KPX Oslash Agrave -35 + +KPX Oslash Amacron -35 + +KPX Oslash Aogonek -35 + +KPX Oslash Aring -35 + +KPX Oslash Atilde -35 + +KPX Oslash T -40 + +KPX Oslash Tcaron -40 + +KPX Oslash Tcommaaccent -40 + +KPX Oslash V -50 + +KPX Oslash W -35 + +KPX Oslash X -40 + +KPX Oslash Y -50 + +KPX Oslash Yacute -50 + +KPX Oslash Ydieresis -50 + +KPX Otilde A -35 + +KPX Otilde Aacute -35 + +KPX Otilde Abreve -35 + +KPX Otilde Acircumflex -35 + +KPX Otilde Adieresis -35 + +KPX Otilde Agrave -35 + +KPX Otilde Amacron -35 + +KPX Otilde Aogonek -35 + +KPX Otilde Aring -35 + +KPX Otilde Atilde -35 + +KPX Otilde T -40 + +KPX Otilde Tcaron -40 + +KPX Otilde Tcommaaccent -40 + +KPX Otilde V -50 + +KPX Otilde W -35 + +KPX Otilde X -40 + +KPX Otilde Y -50 + +KPX Otilde Yacute -50 + +KPX Otilde Ydieresis -50 + +KPX P A -92 + +KPX P Aacute -92 + +KPX P Abreve -92 + +KPX P Acircumflex -92 + +KPX P Adieresis -92 + +KPX P Agrave -92 + +KPX P Amacron -92 + +KPX P Aogonek -92 + +KPX P Aring -92 + +KPX P Atilde -92 + +KPX P a -15 + +KPX P aacute -15 + +KPX P abreve -15 + +KPX P acircumflex -15 + +KPX P adieresis -15 + +KPX P agrave -15 + +KPX P amacron -15 + +KPX P aogonek -15 + +KPX P aring -15 + +KPX P atilde -15 + +KPX P comma -111 + +KPX P period -111 + +KPX Q U -10 + +KPX Q Uacute -10 + +KPX Q Ucircumflex -10 + +KPX Q Udieresis -10 + +KPX Q Ugrave -10 + +KPX Q Uhungarumlaut -10 + +KPX Q Umacron -10 + +KPX Q Uogonek -10 + +KPX Q Uring -10 + +KPX R O -40 + +KPX R Oacute -40 + +KPX R Ocircumflex -40 + +KPX R Odieresis -40 + +KPX R Ograve -40 + +KPX R Ohungarumlaut -40 + +KPX R Omacron -40 + +KPX R Oslash -40 + +KPX R Otilde -40 + +KPX R T -60 + +KPX R Tcaron -60 + +KPX R Tcommaaccent -60 + +KPX R U -40 + +KPX R Uacute -40 + +KPX R Ucircumflex -40 + +KPX R Udieresis -40 + +KPX R Ugrave -40 + +KPX R Uhungarumlaut -40 + +KPX R Umacron -40 + +KPX R Uogonek -40 + +KPX R Uring -40 + +KPX R V -80 + +KPX R W -55 + +KPX R Y -65 + +KPX R Yacute -65 + +KPX R Ydieresis -65 + +KPX Racute O -40 + +KPX Racute Oacute -40 + +KPX Racute Ocircumflex -40 + +KPX Racute Odieresis -40 + +KPX Racute Ograve -40 + +KPX Racute Ohungarumlaut -40 + +KPX Racute Omacron -40 + +KPX Racute Oslash -40 + +KPX Racute Otilde -40 + +KPX Racute T -60 + +KPX Racute Tcaron -60 + +KPX Racute Tcommaaccent -60 + +KPX Racute U -40 + +KPX Racute Uacute -40 + +KPX Racute Ucircumflex -40 + +KPX Racute Udieresis -40 + +KPX Racute Ugrave -40 + +KPX Racute Uhungarumlaut -40 + +KPX Racute Umacron -40 + +KPX Racute Uogonek -40 + +KPX Racute Uring -40 + +KPX Racute V -80 + +KPX Racute W -55 + +KPX Racute Y -65 + +KPX Racute Yacute -65 + +KPX Racute Ydieresis -65 + +KPX Rcaron O -40 + +KPX Rcaron Oacute -40 + +KPX Rcaron Ocircumflex -40 + +KPX Rcaron Odieresis -40 + +KPX Rcaron Ograve -40 + +KPX Rcaron Ohungarumlaut -40 + +KPX Rcaron Omacron -40 + +KPX Rcaron Oslash -40 + +KPX Rcaron Otilde -40 + +KPX Rcaron T -60 + +KPX Rcaron Tcaron -60 + +KPX Rcaron Tcommaaccent -60 + +KPX Rcaron U -40 + +KPX Rcaron Uacute -40 + +KPX Rcaron Ucircumflex -40 + +KPX Rcaron Udieresis -40 + +KPX Rcaron Ugrave -40 + +KPX Rcaron Uhungarumlaut -40 + +KPX Rcaron Umacron -40 + +KPX Rcaron Uogonek -40 + +KPX Rcaron Uring -40 + +KPX Rcaron V -80 + +KPX Rcaron W -55 + +KPX Rcaron Y -65 + +KPX Rcaron Yacute -65 + +KPX Rcaron Ydieresis -65 + +KPX Rcommaaccent O -40 + +KPX Rcommaaccent Oacute -40 + +KPX Rcommaaccent Ocircumflex -40 + +KPX Rcommaaccent Odieresis -40 + +KPX Rcommaaccent Ograve -40 + +KPX Rcommaaccent Ohungarumlaut -40 + +KPX Rcommaaccent Omacron -40 + +KPX Rcommaaccent Oslash -40 + +KPX Rcommaaccent Otilde -40 + +KPX Rcommaaccent T -60 + +KPX Rcommaaccent Tcaron -60 + +KPX Rcommaaccent Tcommaaccent -60 + +KPX Rcommaaccent U -40 + +KPX Rcommaaccent Uacute -40 + +KPX Rcommaaccent Ucircumflex -40 + +KPX Rcommaaccent Udieresis -40 + +KPX Rcommaaccent Ugrave -40 + +KPX Rcommaaccent Uhungarumlaut -40 + +KPX Rcommaaccent Umacron -40 + +KPX Rcommaaccent Uogonek -40 + +KPX Rcommaaccent Uring -40 + +KPX Rcommaaccent V -80 + +KPX Rcommaaccent W -55 + +KPX Rcommaaccent Y -65 + +KPX Rcommaaccent Yacute -65 + +KPX Rcommaaccent Ydieresis -65 + +KPX T A -93 + +KPX T Aacute -93 + +KPX T Abreve -93 + +KPX T Acircumflex -93 + +KPX T Adieresis -93 + +KPX T Agrave -93 + +KPX T Amacron -93 + +KPX T Aogonek -93 + +KPX T Aring -93 + +KPX T Atilde -93 + +KPX T O -18 + +KPX T Oacute -18 + +KPX T Ocircumflex -18 + +KPX T Odieresis -18 + +KPX T Ograve -18 + +KPX T Ohungarumlaut -18 + +KPX T Omacron -18 + +KPX T Oslash -18 + +KPX T Otilde -18 + +KPX T a -80 + +KPX T aacute -80 + +KPX T abreve -80 + +KPX T acircumflex -80 + +KPX T adieresis -40 + +KPX T agrave -40 + +KPX T amacron -40 + +KPX T aogonek -80 + +KPX T aring -80 + +KPX T atilde -40 + +KPX T colon -50 + +KPX T comma -74 + +KPX T e -70 + +KPX T eacute -70 + +KPX T ecaron -70 + +KPX T ecircumflex -70 + +KPX T edieresis -30 + +KPX T edotaccent -70 + +KPX T egrave -70 + +KPX T emacron -30 + +KPX T eogonek -70 + +KPX T hyphen -92 + +KPX T i -35 + +KPX T iacute -35 + +KPX T iogonek -35 + +KPX T o -80 + +KPX T oacute -80 + +KPX T ocircumflex -80 + +KPX T odieresis -80 + +KPX T ograve -80 + +KPX T ohungarumlaut -80 + +KPX T omacron -80 + +KPX T oslash -80 + +KPX T otilde -80 + +KPX T period -74 + +KPX T r -35 + +KPX T racute -35 + +KPX T rcaron -35 + +KPX T rcommaaccent -35 + +KPX T semicolon -55 + +KPX T u -45 + +KPX T uacute -45 + +KPX T ucircumflex -45 + +KPX T udieresis -45 + +KPX T ugrave -45 + +KPX T uhungarumlaut -45 + +KPX T umacron -45 + +KPX T uogonek -45 + +KPX T uring -45 + +KPX T w -80 + +KPX T y -80 + +KPX T yacute -80 + +KPX T ydieresis -80 + +KPX Tcaron A -93 + +KPX Tcaron Aacute -93 + +KPX Tcaron Abreve -93 + +KPX Tcaron Acircumflex -93 + +KPX Tcaron Adieresis -93 + +KPX Tcaron Agrave -93 + +KPX Tcaron Amacron -93 + +KPX Tcaron Aogonek -93 + +KPX Tcaron Aring -93 + +KPX Tcaron Atilde -93 + +KPX Tcaron O -18 + +KPX Tcaron Oacute -18 + +KPX Tcaron Ocircumflex -18 + +KPX Tcaron Odieresis -18 + +KPX Tcaron Ograve -18 + +KPX Tcaron Ohungarumlaut -18 + +KPX Tcaron Omacron -18 + +KPX Tcaron Oslash -18 + +KPX Tcaron Otilde -18 + +KPX Tcaron a -80 + +KPX Tcaron aacute -80 + +KPX Tcaron abreve -80 + +KPX Tcaron acircumflex -80 + +KPX Tcaron adieresis -40 + +KPX Tcaron agrave -40 + +KPX Tcaron amacron -40 + +KPX Tcaron aogonek -80 + +KPX Tcaron aring -80 + +KPX Tcaron atilde -40 + +KPX Tcaron colon -50 + +KPX Tcaron comma -74 + +KPX Tcaron e -70 + +KPX Tcaron eacute -70 + +KPX Tcaron ecaron -70 + +KPX Tcaron ecircumflex -30 + +KPX Tcaron edieresis -30 + +KPX Tcaron edotaccent -70 + +KPX Tcaron egrave -70 + +KPX Tcaron emacron -30 + +KPX Tcaron eogonek -70 + +KPX Tcaron hyphen -92 + +KPX Tcaron i -35 + +KPX Tcaron iacute -35 + +KPX Tcaron iogonek -35 + +KPX Tcaron o -80 + +KPX Tcaron oacute -80 + +KPX Tcaron ocircumflex -80 + +KPX Tcaron odieresis -80 + +KPX Tcaron ograve -80 + +KPX Tcaron ohungarumlaut -80 + +KPX Tcaron omacron -80 + +KPX Tcaron oslash -80 + +KPX Tcaron otilde -80 + +KPX Tcaron period -74 + +KPX Tcaron r -35 + +KPX Tcaron racute -35 + +KPX Tcaron rcaron -35 + +KPX Tcaron rcommaaccent -35 + +KPX Tcaron semicolon -55 + +KPX Tcaron u -45 + +KPX Tcaron uacute -45 + +KPX Tcaron ucircumflex -45 + +KPX Tcaron udieresis -45 + +KPX Tcaron ugrave -45 + +KPX Tcaron uhungarumlaut -45 + +KPX Tcaron umacron -45 + +KPX Tcaron uogonek -45 + +KPX Tcaron uring -45 + +KPX Tcaron w -80 + +KPX Tcaron y -80 + +KPX Tcaron yacute -80 + +KPX Tcaron ydieresis -80 + +KPX Tcommaaccent A -93 + +KPX Tcommaaccent Aacute -93 + +KPX Tcommaaccent Abreve -93 + +KPX Tcommaaccent Acircumflex -93 + +KPX Tcommaaccent Adieresis -93 + +KPX Tcommaaccent Agrave -93 + +KPX Tcommaaccent Amacron -93 + +KPX Tcommaaccent Aogonek -93 + +KPX Tcommaaccent Aring -93 + +KPX Tcommaaccent Atilde -93 + +KPX Tcommaaccent O -18 + +KPX Tcommaaccent Oacute -18 + +KPX Tcommaaccent Ocircumflex -18 + +KPX Tcommaaccent Odieresis -18 + +KPX Tcommaaccent Ograve -18 + +KPX Tcommaaccent Ohungarumlaut -18 + +KPX Tcommaaccent Omacron -18 + +KPX Tcommaaccent Oslash -18 + +KPX Tcommaaccent Otilde -18 + +KPX Tcommaaccent a -80 + +KPX Tcommaaccent aacute -80 + +KPX Tcommaaccent abreve -80 + +KPX Tcommaaccent acircumflex -80 + +KPX Tcommaaccent adieresis -40 + +KPX Tcommaaccent agrave -40 + +KPX Tcommaaccent amacron -40 + +KPX Tcommaaccent aogonek -80 + +KPX Tcommaaccent aring -80 + +KPX Tcommaaccent atilde -40 + +KPX Tcommaaccent colon -50 + +KPX Tcommaaccent comma -74 + +KPX Tcommaaccent e -70 + +KPX Tcommaaccent eacute -70 + +KPX Tcommaaccent ecaron -70 + +KPX Tcommaaccent ecircumflex -30 + +KPX Tcommaaccent edieresis -30 + +KPX Tcommaaccent edotaccent -70 + +KPX Tcommaaccent egrave -30 + +KPX Tcommaaccent emacron -70 + +KPX Tcommaaccent eogonek -70 + +KPX Tcommaaccent hyphen -92 + +KPX Tcommaaccent i -35 + +KPX Tcommaaccent iacute -35 + +KPX Tcommaaccent iogonek -35 + +KPX Tcommaaccent o -80 + +KPX Tcommaaccent oacute -80 + +KPX Tcommaaccent ocircumflex -80 + +KPX Tcommaaccent odieresis -80 + +KPX Tcommaaccent ograve -80 + +KPX Tcommaaccent ohungarumlaut -80 + +KPX Tcommaaccent omacron -80 + +KPX Tcommaaccent oslash -80 + +KPX Tcommaaccent otilde -80 + +KPX Tcommaaccent period -74 + +KPX Tcommaaccent r -35 + +KPX Tcommaaccent racute -35 + +KPX Tcommaaccent rcaron -35 + +KPX Tcommaaccent rcommaaccent -35 + +KPX Tcommaaccent semicolon -55 + +KPX Tcommaaccent u -45 + +KPX Tcommaaccent uacute -45 + +KPX Tcommaaccent ucircumflex -45 + +KPX Tcommaaccent udieresis -45 + +KPX Tcommaaccent ugrave -45 + +KPX Tcommaaccent uhungarumlaut -45 + +KPX Tcommaaccent umacron -45 + +KPX Tcommaaccent uogonek -45 + +KPX Tcommaaccent uring -45 + +KPX Tcommaaccent w -80 + +KPX Tcommaaccent y -80 + +KPX Tcommaaccent yacute -80 + +KPX Tcommaaccent ydieresis -80 + +KPX U A -40 + +KPX U Aacute -40 + +KPX U Abreve -40 + +KPX U Acircumflex -40 + +KPX U Adieresis -40 + +KPX U Agrave -40 + +KPX U Amacron -40 + +KPX U Aogonek -40 + +KPX U Aring -40 + +KPX U Atilde -40 + +KPX Uacute A -40 + +KPX Uacute Aacute -40 + +KPX Uacute Abreve -40 + +KPX Uacute Acircumflex -40 + +KPX Uacute Adieresis -40 + +KPX Uacute Agrave -40 + +KPX Uacute Amacron -40 + +KPX Uacute Aogonek -40 + +KPX Uacute Aring -40 + +KPX Uacute Atilde -40 + +KPX Ucircumflex A -40 + +KPX Ucircumflex Aacute -40 + +KPX Ucircumflex Abreve -40 + +KPX Ucircumflex Acircumflex -40 + +KPX Ucircumflex Adieresis -40 + +KPX Ucircumflex Agrave -40 + +KPX Ucircumflex Amacron -40 + +KPX Ucircumflex Aogonek -40 + +KPX Ucircumflex Aring -40 + +KPX Ucircumflex Atilde -40 + +KPX Udieresis A -40 + +KPX Udieresis Aacute -40 + +KPX Udieresis Abreve -40 + +KPX Udieresis Acircumflex -40 + +KPX Udieresis Adieresis -40 + +KPX Udieresis Agrave -40 + +KPX Udieresis Amacron -40 + +KPX Udieresis Aogonek -40 + +KPX Udieresis Aring -40 + +KPX Udieresis Atilde -40 + +KPX Ugrave A -40 + +KPX Ugrave Aacute -40 + +KPX Ugrave Abreve -40 + +KPX Ugrave Acircumflex -40 + +KPX Ugrave Adieresis -40 + +KPX Ugrave Agrave -40 + +KPX Ugrave Amacron -40 + +KPX Ugrave Aogonek -40 + +KPX Ugrave Aring -40 + +KPX Ugrave Atilde -40 + +KPX Uhungarumlaut A -40 + +KPX Uhungarumlaut Aacute -40 + +KPX Uhungarumlaut Abreve -40 + +KPX Uhungarumlaut Acircumflex -40 + +KPX Uhungarumlaut Adieresis -40 + +KPX Uhungarumlaut Agrave -40 + +KPX Uhungarumlaut Amacron -40 + +KPX Uhungarumlaut Aogonek -40 + +KPX Uhungarumlaut Aring -40 + +KPX Uhungarumlaut Atilde -40 + +KPX Umacron A -40 + +KPX Umacron Aacute -40 + +KPX Umacron Abreve -40 + +KPX Umacron Acircumflex -40 + +KPX Umacron Adieresis -40 + +KPX Umacron Agrave -40 + +KPX Umacron Amacron -40 + +KPX Umacron Aogonek -40 + +KPX Umacron Aring -40 + +KPX Umacron Atilde -40 + +KPX Uogonek A -40 + +KPX Uogonek Aacute -40 + +KPX Uogonek Abreve -40 + +KPX Uogonek Acircumflex -40 + +KPX Uogonek Adieresis -40 + +KPX Uogonek Agrave -40 + +KPX Uogonek Amacron -40 + +KPX Uogonek Aogonek -40 + +KPX Uogonek Aring -40 + +KPX Uogonek Atilde -40 + +KPX Uring A -40 + +KPX Uring Aacute -40 + +KPX Uring Abreve -40 + +KPX Uring Acircumflex -40 + +KPX Uring Adieresis -40 + +KPX Uring Agrave -40 + +KPX Uring Amacron -40 + +KPX Uring Aogonek -40 + +KPX Uring Aring -40 + +KPX Uring Atilde -40 + +KPX V A -135 + +KPX V Aacute -135 + +KPX V Abreve -135 + +KPX V Acircumflex -135 + +KPX V Adieresis -135 + +KPX V Agrave -135 + +KPX V Amacron -135 + +KPX V Aogonek -135 + +KPX V Aring -135 + +KPX V Atilde -135 + +KPX V G -15 + +KPX V Gbreve -15 + +KPX V Gcommaaccent -15 + +KPX V O -40 + +KPX V Oacute -40 + +KPX V Ocircumflex -40 + +KPX V Odieresis -40 + +KPX V Ograve -40 + +KPX V Ohungarumlaut -40 + +KPX V Omacron -40 + +KPX V Oslash -40 + +KPX V Otilde -40 + +KPX V a -111 + +KPX V aacute -111 + +KPX V abreve -111 + +KPX V acircumflex -71 + +KPX V adieresis -71 + +KPX V agrave -71 + +KPX V amacron -71 + +KPX V aogonek -111 + +KPX V aring -111 + +KPX V atilde -71 + +KPX V colon -74 + +KPX V comma -129 + +KPX V e -111 + +KPX V eacute -111 + +KPX V ecaron -71 + +KPX V ecircumflex -71 + +KPX V edieresis -71 + +KPX V edotaccent -111 + +KPX V egrave -71 + +KPX V emacron -71 + +KPX V eogonek -111 + +KPX V hyphen -100 + +KPX V i -60 + +KPX V iacute -60 + +KPX V icircumflex -20 + +KPX V idieresis -20 + +KPX V igrave -20 + +KPX V imacron -20 + +KPX V iogonek -60 + +KPX V o -129 + +KPX V oacute -129 + +KPX V ocircumflex -129 + +KPX V odieresis -89 + +KPX V ograve -89 + +KPX V ohungarumlaut -129 + +KPX V omacron -89 + +KPX V oslash -129 + +KPX V otilde -89 + +KPX V period -129 + +KPX V semicolon -74 + +KPX V u -75 + +KPX V uacute -75 + +KPX V ucircumflex -75 + +KPX V udieresis -75 + +KPX V ugrave -75 + +KPX V uhungarumlaut -75 + +KPX V umacron -75 + +KPX V uogonek -75 + +KPX V uring -75 + +KPX W A -120 + +KPX W Aacute -120 + +KPX W Abreve -120 + +KPX W Acircumflex -120 + +KPX W Adieresis -120 + +KPX W Agrave -120 + +KPX W Amacron -120 + +KPX W Aogonek -120 + +KPX W Aring -120 + +KPX W Atilde -120 + +KPX W O -10 + +KPX W Oacute -10 + +KPX W Ocircumflex -10 + +KPX W Odieresis -10 + +KPX W Ograve -10 + +KPX W Ohungarumlaut -10 + +KPX W Omacron -10 + +KPX W Oslash -10 + +KPX W Otilde -10 + +KPX W a -80 + +KPX W aacute -80 + +KPX W abreve -80 + +KPX W acircumflex -80 + +KPX W adieresis -80 + +KPX W agrave -80 + +KPX W amacron -80 + +KPX W aogonek -80 + +KPX W aring -80 + +KPX W atilde -80 + +KPX W colon -37 + +KPX W comma -92 + +KPX W e -80 + +KPX W eacute -80 + +KPX W ecaron -80 + +KPX W ecircumflex -80 + +KPX W edieresis -40 + +KPX W edotaccent -80 + +KPX W egrave -40 + +KPX W emacron -40 + +KPX W eogonek -80 + +KPX W hyphen -65 + +KPX W i -40 + +KPX W iacute -40 + +KPX W iogonek -40 + +KPX W o -80 + +KPX W oacute -80 + +KPX W ocircumflex -80 + +KPX W odieresis -80 + +KPX W ograve -80 + +KPX W ohungarumlaut -80 + +KPX W omacron -80 + +KPX W oslash -80 + +KPX W otilde -80 + +KPX W period -92 + +KPX W semicolon -37 + +KPX W u -50 + +KPX W uacute -50 + +KPX W ucircumflex -50 + +KPX W udieresis -50 + +KPX W ugrave -50 + +KPX W uhungarumlaut -50 + +KPX W umacron -50 + +KPX W uogonek -50 + +KPX W uring -50 + +KPX W y -73 + +KPX W yacute -73 + +KPX W ydieresis -73 + +KPX Y A -120 + +KPX Y Aacute -120 + +KPX Y Abreve -120 + +KPX Y Acircumflex -120 + +KPX Y Adieresis -120 + +KPX Y Agrave -120 + +KPX Y Amacron -120 + +KPX Y Aogonek -120 + +KPX Y Aring -120 + +KPX Y Atilde -120 + +KPX Y O -30 + +KPX Y Oacute -30 + +KPX Y Ocircumflex -30 + +KPX Y Odieresis -30 + +KPX Y Ograve -30 + +KPX Y Ohungarumlaut -30 + +KPX Y Omacron -30 + +KPX Y Oslash -30 + +KPX Y Otilde -30 + +KPX Y a -100 + +KPX Y aacute -100 + +KPX Y abreve -100 + +KPX Y acircumflex -100 + +KPX Y adieresis -60 + +KPX Y agrave -60 + +KPX Y amacron -60 + +KPX Y aogonek -100 + +KPX Y aring -100 + +KPX Y atilde -60 + +KPX Y colon -92 + +KPX Y comma -129 + +KPX Y e -100 + +KPX Y eacute -100 + +KPX Y ecaron -100 + +KPX Y ecircumflex -100 + +KPX Y edieresis -60 + +KPX Y edotaccent -100 + +KPX Y egrave -60 + +KPX Y emacron -60 + +KPX Y eogonek -100 + +KPX Y hyphen -111 + +KPX Y i -55 + +KPX Y iacute -55 + +KPX Y iogonek -55 + +KPX Y o -110 + +KPX Y oacute -110 + +KPX Y ocircumflex -110 + +KPX Y odieresis -70 + +KPX Y ograve -70 + +KPX Y ohungarumlaut -110 + +KPX Y omacron -70 + +KPX Y oslash -110 + +KPX Y otilde -70 + +KPX Y period -129 + +KPX Y semicolon -92 + +KPX Y u -111 + +KPX Y uacute -111 + +KPX Y ucircumflex -111 + +KPX Y udieresis -71 + +KPX Y ugrave -71 + +KPX Y uhungarumlaut -111 + +KPX Y umacron -71 + +KPX Y uogonek -111 + +KPX Y uring -111 + +KPX Yacute A -120 + +KPX Yacute Aacute -120 + +KPX Yacute Abreve -120 + +KPX Yacute Acircumflex -120 + +KPX Yacute Adieresis -120 + +KPX Yacute Agrave -120 + +KPX Yacute Amacron -120 + +KPX Yacute Aogonek -120 + +KPX Yacute Aring -120 + +KPX Yacute Atilde -120 + +KPX Yacute O -30 + +KPX Yacute Oacute -30 + +KPX Yacute Ocircumflex -30 + +KPX Yacute Odieresis -30 + +KPX Yacute Ograve -30 + +KPX Yacute Ohungarumlaut -30 + +KPX Yacute Omacron -30 + +KPX Yacute Oslash -30 + +KPX Yacute Otilde -30 + +KPX Yacute a -100 + +KPX Yacute aacute -100 + +KPX Yacute abreve -100 + +KPX Yacute acircumflex -100 + +KPX Yacute adieresis -60 + +KPX Yacute agrave -60 + +KPX Yacute amacron -60 + +KPX Yacute aogonek -100 + +KPX Yacute aring -100 + +KPX Yacute atilde -60 + +KPX Yacute colon -92 + +KPX Yacute comma -129 + +KPX Yacute e -100 + +KPX Yacute eacute -100 + +KPX Yacute ecaron -100 + +KPX Yacute ecircumflex -100 + +KPX Yacute edieresis -60 + +KPX Yacute edotaccent -100 + +KPX Yacute egrave -60 + +KPX Yacute emacron -60 + +KPX Yacute eogonek -100 + +KPX Yacute hyphen -111 + +KPX Yacute i -55 + +KPX Yacute iacute -55 + +KPX Yacute iogonek -55 + +KPX Yacute o -110 + +KPX Yacute oacute -110 + +KPX Yacute ocircumflex -110 + +KPX Yacute odieresis -70 + +KPX Yacute ograve -70 + +KPX Yacute ohungarumlaut -110 + +KPX Yacute omacron -70 + +KPX Yacute oslash -110 + +KPX Yacute otilde -70 + +KPX Yacute period -129 + +KPX Yacute semicolon -92 + +KPX Yacute u -111 + +KPX Yacute uacute -111 + +KPX Yacute ucircumflex -111 + +KPX Yacute udieresis -71 + +KPX Yacute ugrave -71 + +KPX Yacute uhungarumlaut -111 + +KPX Yacute umacron -71 + +KPX Yacute uogonek -111 + +KPX Yacute uring -111 + +KPX Ydieresis A -120 + +KPX Ydieresis Aacute -120 + +KPX Ydieresis Abreve -120 + +KPX Ydieresis Acircumflex -120 + +KPX Ydieresis Adieresis -120 + +KPX Ydieresis Agrave -120 + +KPX Ydieresis Amacron -120 + +KPX Ydieresis Aogonek -120 + +KPX Ydieresis Aring -120 + +KPX Ydieresis Atilde -120 + +KPX Ydieresis O -30 + +KPX Ydieresis Oacute -30 + +KPX Ydieresis Ocircumflex -30 + +KPX Ydieresis Odieresis -30 + +KPX Ydieresis Ograve -30 + +KPX Ydieresis Ohungarumlaut -30 + +KPX Ydieresis Omacron -30 + +KPX Ydieresis Oslash -30 + +KPX Ydieresis Otilde -30 + +KPX Ydieresis a -100 + +KPX Ydieresis aacute -100 + +KPX Ydieresis abreve -100 + +KPX Ydieresis acircumflex -100 + +KPX Ydieresis adieresis -60 + +KPX Ydieresis agrave -60 + +KPX Ydieresis amacron -60 + +KPX Ydieresis aogonek -100 + +KPX Ydieresis aring -100 + +KPX Ydieresis atilde -100 + +KPX Ydieresis colon -92 + +KPX Ydieresis comma -129 + +KPX Ydieresis e -100 + +KPX Ydieresis eacute -100 + +KPX Ydieresis ecaron -100 + +KPX Ydieresis ecircumflex -100 + +KPX Ydieresis edieresis -60 + +KPX Ydieresis edotaccent -100 + +KPX Ydieresis egrave -60 + +KPX Ydieresis emacron -60 + +KPX Ydieresis eogonek -100 + +KPX Ydieresis hyphen -111 + +KPX Ydieresis i -55 + +KPX Ydieresis iacute -55 + +KPX Ydieresis iogonek -55 + +KPX Ydieresis o -110 + +KPX Ydieresis oacute -110 + +KPX Ydieresis ocircumflex -110 + +KPX Ydieresis odieresis -70 + +KPX Ydieresis ograve -70 + +KPX Ydieresis ohungarumlaut -110 + +KPX Ydieresis omacron -70 + +KPX Ydieresis oslash -110 + +KPX Ydieresis otilde -70 + +KPX Ydieresis period -129 + +KPX Ydieresis semicolon -92 + +KPX Ydieresis u -111 + +KPX Ydieresis uacute -111 + +KPX Ydieresis ucircumflex -111 + +KPX Ydieresis udieresis -71 + +KPX Ydieresis ugrave -71 + +KPX Ydieresis uhungarumlaut -111 + +KPX Ydieresis umacron -71 + +KPX Ydieresis uogonek -111 + +KPX Ydieresis uring -111 + +KPX a v -20 + +KPX a w -15 + +KPX aacute v -20 + +KPX aacute w -15 + +KPX abreve v -20 + +KPX abreve w -15 + +KPX acircumflex v -20 + +KPX acircumflex w -15 + +KPX adieresis v -20 + +KPX adieresis w -15 + +KPX agrave v -20 + +KPX agrave w -15 + +KPX amacron v -20 + +KPX amacron w -15 + +KPX aogonek v -20 + +KPX aogonek w -15 + +KPX aring v -20 + +KPX aring w -15 + +KPX atilde v -20 + +KPX atilde w -15 + +KPX b period -40 + +KPX b u -20 + +KPX b uacute -20 + +KPX b ucircumflex -20 + +KPX b udieresis -20 + +KPX b ugrave -20 + +KPX b uhungarumlaut -20 + +KPX b umacron -20 + +KPX b uogonek -20 + +KPX b uring -20 + +KPX b v -15 + +KPX c y -15 + +KPX c yacute -15 + +KPX c ydieresis -15 + +KPX cacute y -15 + +KPX cacute yacute -15 + +KPX cacute ydieresis -15 + +KPX ccaron y -15 + +KPX ccaron yacute -15 + +KPX ccaron ydieresis -15 + +KPX ccedilla y -15 + +KPX ccedilla yacute -15 + +KPX ccedilla ydieresis -15 + +KPX comma quotedblright -70 + +KPX comma quoteright -70 + +KPX e g -15 + +KPX e gbreve -15 + +KPX e gcommaaccent -15 + +KPX e v -25 + +KPX e w -25 + +KPX e x -15 + +KPX e y -15 + +KPX e yacute -15 + +KPX e ydieresis -15 + +KPX eacute g -15 + +KPX eacute gbreve -15 + +KPX eacute gcommaaccent -15 + +KPX eacute v -25 + +KPX eacute w -25 + +KPX eacute x -15 + +KPX eacute y -15 + +KPX eacute yacute -15 + +KPX eacute ydieresis -15 + +KPX ecaron g -15 + +KPX ecaron gbreve -15 + +KPX ecaron gcommaaccent -15 + +KPX ecaron v -25 + +KPX ecaron w -25 + +KPX ecaron x -15 + +KPX ecaron y -15 + +KPX ecaron yacute -15 + +KPX ecaron ydieresis -15 + +KPX ecircumflex g -15 + +KPX ecircumflex gbreve -15 + +KPX ecircumflex gcommaaccent -15 + +KPX ecircumflex v -25 + +KPX ecircumflex w -25 + +KPX ecircumflex x -15 + +KPX ecircumflex y -15 + +KPX ecircumflex yacute -15 + +KPX ecircumflex ydieresis -15 + +KPX edieresis g -15 + +KPX edieresis gbreve -15 + +KPX edieresis gcommaaccent -15 + +KPX edieresis v -25 + +KPX edieresis w -25 + +KPX edieresis x -15 + +KPX edieresis y -15 + +KPX edieresis yacute -15 + +KPX edieresis ydieresis -15 + +KPX edotaccent g -15 + +KPX edotaccent gbreve -15 + +KPX edotaccent gcommaaccent -15 + +KPX edotaccent v -25 + +KPX edotaccent w -25 + +KPX edotaccent x -15 + +KPX edotaccent y -15 + +KPX edotaccent yacute -15 + +KPX edotaccent ydieresis -15 + +KPX egrave g -15 + +KPX egrave gbreve -15 + +KPX egrave gcommaaccent -15 + +KPX egrave v -25 + +KPX egrave w -25 + +KPX egrave x -15 + +KPX egrave y -15 + +KPX egrave yacute -15 + +KPX egrave ydieresis -15 + +KPX emacron g -15 + +KPX emacron gbreve -15 + +KPX emacron gcommaaccent -15 + +KPX emacron v -25 + +KPX emacron w -25 + +KPX emacron x -15 + +KPX emacron y -15 + +KPX emacron yacute -15 + +KPX emacron ydieresis -15 + +KPX eogonek g -15 + +KPX eogonek gbreve -15 + +KPX eogonek gcommaaccent -15 + +KPX eogonek v -25 + +KPX eogonek w -25 + +KPX eogonek x -15 + +KPX eogonek y -15 + +KPX eogonek yacute -15 + +KPX eogonek ydieresis -15 + +KPX f a -10 + +KPX f aacute -10 + +KPX f abreve -10 + +KPX f acircumflex -10 + +KPX f adieresis -10 + +KPX f agrave -10 + +KPX f amacron -10 + +KPX f aogonek -10 + +KPX f aring -10 + +KPX f atilde -10 + +KPX f dotlessi -50 + +KPX f f -25 + +KPX f i -20 + +KPX f iacute -20 + +KPX f quoteright 55 + +KPX g a -5 + +KPX g aacute -5 + +KPX g abreve -5 + +KPX g acircumflex -5 + +KPX g adieresis -5 + +KPX g agrave -5 + +KPX g amacron -5 + +KPX g aogonek -5 + +KPX g aring -5 + +KPX g atilde -5 + +KPX gbreve a -5 + +KPX gbreve aacute -5 + +KPX gbreve abreve -5 + +KPX gbreve acircumflex -5 + +KPX gbreve adieresis -5 + +KPX gbreve agrave -5 + +KPX gbreve amacron -5 + +KPX gbreve aogonek -5 + +KPX gbreve aring -5 + +KPX gbreve atilde -5 + +KPX gcommaaccent a -5 + +KPX gcommaaccent aacute -5 + +KPX gcommaaccent abreve -5 + +KPX gcommaaccent acircumflex -5 + +KPX gcommaaccent adieresis -5 + +KPX gcommaaccent agrave -5 + +KPX gcommaaccent amacron -5 + +KPX gcommaaccent aogonek -5 + +KPX gcommaaccent aring -5 + +KPX gcommaaccent atilde -5 + +KPX h y -5 + +KPX h yacute -5 + +KPX h ydieresis -5 + +KPX i v -25 + +KPX iacute v -25 + +KPX icircumflex v -25 + +KPX idieresis v -25 + +KPX igrave v -25 + +KPX imacron v -25 + +KPX iogonek v -25 + +KPX k e -10 + +KPX k eacute -10 + +KPX k ecaron -10 + +KPX k ecircumflex -10 + +KPX k edieresis -10 + +KPX k edotaccent -10 + +KPX k egrave -10 + +KPX k emacron -10 + +KPX k eogonek -10 + +KPX k o -10 + +KPX k oacute -10 + +KPX k ocircumflex -10 + +KPX k odieresis -10 + +KPX k ograve -10 + +KPX k ohungarumlaut -10 + +KPX k omacron -10 + +KPX k oslash -10 + +KPX k otilde -10 + +KPX k y -15 + +KPX k yacute -15 + +KPX k ydieresis -15 + +KPX kcommaaccent e -10 + +KPX kcommaaccent eacute -10 + +KPX kcommaaccent ecaron -10 + +KPX kcommaaccent ecircumflex -10 + +KPX kcommaaccent edieresis -10 + +KPX kcommaaccent edotaccent -10 + +KPX kcommaaccent egrave -10 + +KPX kcommaaccent emacron -10 + +KPX kcommaaccent eogonek -10 + +KPX kcommaaccent o -10 + +KPX kcommaaccent oacute -10 + +KPX kcommaaccent ocircumflex -10 + +KPX kcommaaccent odieresis -10 + +KPX kcommaaccent ograve -10 + +KPX kcommaaccent ohungarumlaut -10 + +KPX kcommaaccent omacron -10 + +KPX kcommaaccent oslash -10 + +KPX kcommaaccent otilde -10 + +KPX kcommaaccent y -15 + +KPX kcommaaccent yacute -15 + +KPX kcommaaccent ydieresis -15 + +KPX l w -10 + +KPX lacute w -10 + +KPX lcommaaccent w -10 + +KPX lslash w -10 + +KPX n v -40 + +KPX n y -15 + +KPX n yacute -15 + +KPX n ydieresis -15 + +KPX nacute v -40 + +KPX nacute y -15 + +KPX nacute yacute -15 + +KPX nacute ydieresis -15 + +KPX ncaron v -40 + +KPX ncaron y -15 + +KPX ncaron yacute -15 + +KPX ncaron ydieresis -15 + +KPX ncommaaccent v -40 + +KPX ncommaaccent y -15 + +KPX ncommaaccent yacute -15 + +KPX ncommaaccent ydieresis -15 + +KPX ntilde v -40 + +KPX ntilde y -15 + +KPX ntilde yacute -15 + +KPX ntilde ydieresis -15 + +KPX o v -15 + +KPX o w -25 + +KPX o y -10 + +KPX o yacute -10 + +KPX o ydieresis -10 + +KPX oacute v -15 + +KPX oacute w -25 + +KPX oacute y -10 + +KPX oacute yacute -10 + +KPX oacute ydieresis -10 + +KPX ocircumflex v -15 + +KPX ocircumflex w -25 + +KPX ocircumflex y -10 + +KPX ocircumflex yacute -10 + +KPX ocircumflex ydieresis -10 + +KPX odieresis v -15 + +KPX odieresis w -25 + +KPX odieresis y -10 + +KPX odieresis yacute -10 + +KPX odieresis ydieresis -10 + +KPX ograve v -15 + +KPX ograve w -25 + +KPX ograve y -10 + +KPX ograve yacute -10 + +KPX ograve ydieresis -10 + +KPX ohungarumlaut v -15 + +KPX ohungarumlaut w -25 + +KPX ohungarumlaut y -10 + +KPX ohungarumlaut yacute -10 + +KPX ohungarumlaut ydieresis -10 + +KPX omacron v -15 + +KPX omacron w -25 + +KPX omacron y -10 + +KPX omacron yacute -10 + +KPX omacron ydieresis -10 + +KPX oslash v -15 + +KPX oslash w -25 + +KPX oslash y -10 + +KPX oslash yacute -10 + +KPX oslash ydieresis -10 + +KPX otilde v -15 + +KPX otilde w -25 + +KPX otilde y -10 + +KPX otilde yacute -10 + +KPX otilde ydieresis -10 + +KPX p y -10 + +KPX p yacute -10 + +KPX p ydieresis -10 + +KPX period quotedblright -70 + +KPX period quoteright -70 + +KPX quotedblleft A -80 + +KPX quotedblleft Aacute -80 + +KPX quotedblleft Abreve -80 + +KPX quotedblleft Acircumflex -80 + +KPX quotedblleft Adieresis -80 + +KPX quotedblleft Agrave -80 + +KPX quotedblleft Amacron -80 + +KPX quotedblleft Aogonek -80 + +KPX quotedblleft Aring -80 + +KPX quotedblleft Atilde -80 + +KPX quoteleft A -80 + +KPX quoteleft Aacute -80 + +KPX quoteleft Abreve -80 + +KPX quoteleft Acircumflex -80 + +KPX quoteleft Adieresis -80 + +KPX quoteleft Agrave -80 + +KPX quoteleft Amacron -80 + +KPX quoteleft Aogonek -80 + +KPX quoteleft Aring -80 + +KPX quoteleft Atilde -80 + +KPX quoteleft quoteleft -74 + +KPX quoteright d -50 + +KPX quoteright dcroat -50 + +KPX quoteright l -10 + +KPX quoteright lacute -10 + +KPX quoteright lcommaaccent -10 + +KPX quoteright lslash -10 + +KPX quoteright quoteright -74 + +KPX quoteright r -50 + +KPX quoteright racute -50 + +KPX quoteright rcaron -50 + +KPX quoteright rcommaaccent -50 + +KPX quoteright s -55 + +KPX quoteright sacute -55 + +KPX quoteright scaron -55 + +KPX quoteright scedilla -55 + +KPX quoteright scommaaccent -55 + +KPX quoteright space -74 + +KPX quoteright t -18 + +KPX quoteright tcommaaccent -18 + +KPX quoteright v -50 + +KPX r comma -40 + +KPX r g -18 + +KPX r gbreve -18 + +KPX r gcommaaccent -18 + +KPX r hyphen -20 + +KPX r period -55 + +KPX racute comma -40 + +KPX racute g -18 + +KPX racute gbreve -18 + +KPX racute gcommaaccent -18 + +KPX racute hyphen -20 + +KPX racute period -55 + +KPX rcaron comma -40 + +KPX rcaron g -18 + +KPX rcaron gbreve -18 + +KPX rcaron gcommaaccent -18 + +KPX rcaron hyphen -20 + +KPX rcaron period -55 + +KPX rcommaaccent comma -40 + +KPX rcommaaccent g -18 + +KPX rcommaaccent gbreve -18 + +KPX rcommaaccent gcommaaccent -18 + +KPX rcommaaccent hyphen -20 + +KPX rcommaaccent period -55 + +KPX space A -55 + +KPX space Aacute -55 + +KPX space Abreve -55 + +KPX space Acircumflex -55 + +KPX space Adieresis -55 + +KPX space Agrave -55 + +KPX space Amacron -55 + +KPX space Aogonek -55 + +KPX space Aring -55 + +KPX space Atilde -55 + +KPX space T -18 + +KPX space Tcaron -18 + +KPX space Tcommaaccent -18 + +KPX space V -50 + +KPX space W -30 + +KPX space Y -90 + +KPX space Yacute -90 + +KPX space Ydieresis -90 + +KPX v a -25 + +KPX v aacute -25 + +KPX v abreve -25 + +KPX v acircumflex -25 + +KPX v adieresis -25 + +KPX v agrave -25 + +KPX v amacron -25 + +KPX v aogonek -25 + +KPX v aring -25 + +KPX v atilde -25 + +KPX v comma -65 + +KPX v e -15 + +KPX v eacute -15 + +KPX v ecaron -15 + +KPX v ecircumflex -15 + +KPX v edieresis -15 + +KPX v edotaccent -15 + +KPX v egrave -15 + +KPX v emacron -15 + +KPX v eogonek -15 + +KPX v o -20 + +KPX v oacute -20 + +KPX v ocircumflex -20 + +KPX v odieresis -20 + +KPX v ograve -20 + +KPX v ohungarumlaut -20 + +KPX v omacron -20 + +KPX v oslash -20 + +KPX v otilde -20 + +KPX v period -65 + +KPX w a -10 + +KPX w aacute -10 + +KPX w abreve -10 + +KPX w acircumflex -10 + +KPX w adieresis -10 + +KPX w agrave -10 + +KPX w amacron -10 + +KPX w aogonek -10 + +KPX w aring -10 + +KPX w atilde -10 + +KPX w comma -65 + +KPX w o -10 + +KPX w oacute -10 + +KPX w ocircumflex -10 + +KPX w odieresis -10 + +KPX w ograve -10 + +KPX w ohungarumlaut -10 + +KPX w omacron -10 + +KPX w oslash -10 + +KPX w otilde -10 + +KPX w period -65 + +KPX x e -15 + +KPX x eacute -15 + +KPX x ecaron -15 + +KPX x ecircumflex -15 + +KPX x edieresis -15 + +KPX x edotaccent -15 + +KPX x egrave -15 + +KPX x emacron -15 + +KPX x eogonek -15 + +KPX y comma -65 + +KPX y period -65 + +KPX yacute comma -65 + +KPX yacute period -65 + +KPX ydieresis comma -65 + +KPX ydieresis period -65 + +EndKernPairs + +EndKernData + +EndFontMetrics + diff --git a/src/Broadside/Fonts/Data/Afm/ZapfDingbats.afm b/src/Broadside/Fonts/Data/Afm/ZapfDingbats.afm new file mode 100644 index 00000000..40828706 --- /dev/null +++ b/src/Broadside/Fonts/Data/Afm/ZapfDingbats.afm @@ -0,0 +1,450 @@ +StartFontMetrics 4.1 + +Comment Copyright (c) 1985, 1987, 1988, 1989, 1997 Adobe Systems Incorporated. All Rights Reserved. + +Comment Creation Date: Thu May 1 15:14:13 1997 + +Comment UniqueID 43082 + +Comment VMusage 45775 55535 + +FontName ZapfDingbats + +FullName ITC Zapf Dingbats + +FamilyName ZapfDingbats + +Weight Medium + +ItalicAngle 0 + +IsFixedPitch false + +CharacterSet Special + +FontBBox -1 -143 981 820 + +UnderlinePosition -100 + +UnderlineThickness 50 + +Version 002.000 + +Notice Copyright (c) 1985, 1987, 1988, 1989, 1997 Adobe Systems Incorporated. All Rights Reserved.ITC Zapf Dingbats is a registered trademark of International Typeface Corporation. + +EncodingScheme FontSpecific + +StdHW 28 + +StdVW 90 + +StartCharMetrics 202 + +C 32 ; WX 278 ; N space ; B 0 0 0 0 ; + +C 33 ; WX 974 ; N a1 ; B 35 72 939 621 ; + +C 34 ; WX 961 ; N a2 ; B 35 81 927 611 ; + +C 35 ; WX 974 ; N a202 ; B 35 72 939 621 ; + +C 36 ; WX 980 ; N a3 ; B 35 0 945 692 ; + +C 37 ; WX 719 ; N a4 ; B 34 139 685 566 ; + +C 38 ; WX 789 ; N a5 ; B 35 -14 755 705 ; + +C 39 ; WX 790 ; N a119 ; B 35 -14 755 705 ; + +C 40 ; WX 791 ; N a118 ; B 35 -13 761 705 ; + +C 41 ; WX 690 ; N a117 ; B 34 138 655 553 ; + +C 42 ; WX 960 ; N a11 ; B 35 123 925 568 ; + +C 43 ; WX 939 ; N a12 ; B 35 134 904 559 ; + +C 44 ; WX 549 ; N a13 ; B 29 -11 516 705 ; + +C 45 ; WX 855 ; N a14 ; B 34 59 820 632 ; + +C 46 ; WX 911 ; N a15 ; B 35 50 876 642 ; + +C 47 ; WX 933 ; N a16 ; B 35 139 899 550 ; + +C 48 ; WX 911 ; N a105 ; B 35 50 876 642 ; + +C 49 ; WX 945 ; N a17 ; B 35 139 909 553 ; + +C 50 ; WX 974 ; N a18 ; B 35 104 938 587 ; + +C 51 ; WX 755 ; N a19 ; B 34 -13 721 705 ; + +C 52 ; WX 846 ; N a20 ; B 36 -14 811 705 ; + +C 53 ; WX 762 ; N a21 ; B 35 0 727 692 ; + +C 54 ; WX 761 ; N a22 ; B 35 0 727 692 ; + +C 55 ; WX 571 ; N a23 ; B -1 -68 571 661 ; + +C 56 ; WX 677 ; N a24 ; B 36 -13 642 705 ; + +C 57 ; WX 763 ; N a25 ; B 35 0 728 692 ; + +C 58 ; WX 760 ; N a26 ; B 35 0 726 692 ; + +C 59 ; WX 759 ; N a27 ; B 35 0 725 692 ; + +C 60 ; WX 754 ; N a28 ; B 35 0 720 692 ; + +C 61 ; WX 494 ; N a6 ; B 35 0 460 692 ; + +C 62 ; WX 552 ; N a7 ; B 35 0 517 692 ; + +C 63 ; WX 537 ; N a8 ; B 35 0 503 692 ; + +C 64 ; WX 577 ; N a9 ; B 35 96 542 596 ; + +C 65 ; WX 692 ; N a10 ; B 35 -14 657 705 ; + +C 66 ; WX 786 ; N a29 ; B 35 -14 751 705 ; + +C 67 ; WX 788 ; N a30 ; B 35 -14 752 705 ; + +C 68 ; WX 788 ; N a31 ; B 35 -14 753 705 ; + +C 69 ; WX 790 ; N a32 ; B 35 -14 756 705 ; + +C 70 ; WX 793 ; N a33 ; B 35 -13 759 705 ; + +C 71 ; WX 794 ; N a34 ; B 35 -13 759 705 ; + +C 72 ; WX 816 ; N a35 ; B 35 -14 782 705 ; + +C 73 ; WX 823 ; N a36 ; B 35 -14 787 705 ; + +C 74 ; WX 789 ; N a37 ; B 35 -14 754 705 ; + +C 75 ; WX 841 ; N a38 ; B 35 -14 807 705 ; + +C 76 ; WX 823 ; N a39 ; B 35 -14 789 705 ; + +C 77 ; WX 833 ; N a40 ; B 35 -14 798 705 ; + +C 78 ; WX 816 ; N a41 ; B 35 -13 782 705 ; + +C 79 ; WX 831 ; N a42 ; B 35 -14 796 705 ; + +C 80 ; WX 923 ; N a43 ; B 35 -14 888 705 ; + +C 81 ; WX 744 ; N a44 ; B 35 0 710 692 ; + +C 82 ; WX 723 ; N a45 ; B 35 0 688 692 ; + +C 83 ; WX 749 ; N a46 ; B 35 0 714 692 ; + +C 84 ; WX 790 ; N a47 ; B 34 -14 756 705 ; + +C 85 ; WX 792 ; N a48 ; B 35 -14 758 705 ; + +C 86 ; WX 695 ; N a49 ; B 35 -14 661 706 ; + +C 87 ; WX 776 ; N a50 ; B 35 -6 741 699 ; + +C 88 ; WX 768 ; N a51 ; B 35 -7 734 699 ; + +C 89 ; WX 792 ; N a52 ; B 35 -14 757 705 ; + +C 90 ; WX 759 ; N a53 ; B 35 0 725 692 ; + +C 91 ; WX 707 ; N a54 ; B 35 -13 672 704 ; + +C 92 ; WX 708 ; N a55 ; B 35 -14 672 705 ; + +C 93 ; WX 682 ; N a56 ; B 35 -14 647 705 ; + +C 94 ; WX 701 ; N a57 ; B 35 -14 666 705 ; + +C 95 ; WX 826 ; N a58 ; B 35 -14 791 705 ; + +C 96 ; WX 815 ; N a59 ; B 35 -14 780 705 ; + +C 97 ; WX 789 ; N a60 ; B 35 -14 754 705 ; + +C 98 ; WX 789 ; N a61 ; B 35 -14 754 705 ; + +C 99 ; WX 707 ; N a62 ; B 34 -14 673 705 ; + +C 100 ; WX 687 ; N a63 ; B 36 0 651 692 ; + +C 101 ; WX 696 ; N a64 ; B 35 0 661 691 ; + +C 102 ; WX 689 ; N a65 ; B 35 0 655 692 ; + +C 103 ; WX 786 ; N a66 ; B 34 -14 751 705 ; + +C 104 ; WX 787 ; N a67 ; B 35 -14 752 705 ; + +C 105 ; WX 713 ; N a68 ; B 35 -14 678 705 ; + +C 106 ; WX 791 ; N a69 ; B 35 -14 756 705 ; + +C 107 ; WX 785 ; N a70 ; B 36 -14 751 705 ; + +C 108 ; WX 791 ; N a71 ; B 35 -14 757 705 ; + +C 109 ; WX 873 ; N a72 ; B 35 -14 838 705 ; + +C 110 ; WX 761 ; N a73 ; B 35 0 726 692 ; + +C 111 ; WX 762 ; N a74 ; B 35 0 727 692 ; + +C 112 ; WX 762 ; N a203 ; B 35 0 727 692 ; + +C 113 ; WX 759 ; N a75 ; B 35 0 725 692 ; + +C 114 ; WX 759 ; N a204 ; B 35 0 725 692 ; + +C 115 ; WX 892 ; N a76 ; B 35 0 858 705 ; + +C 116 ; WX 892 ; N a77 ; B 35 -14 858 692 ; + +C 117 ; WX 788 ; N a78 ; B 35 -14 754 705 ; + +C 118 ; WX 784 ; N a79 ; B 35 -14 749 705 ; + +C 119 ; WX 438 ; N a81 ; B 35 -14 403 705 ; + +C 120 ; WX 138 ; N a82 ; B 35 0 104 692 ; + +C 121 ; WX 277 ; N a83 ; B 35 0 242 692 ; + +C 122 ; WX 415 ; N a84 ; B 35 0 380 692 ; + +C 123 ; WX 392 ; N a97 ; B 35 263 357 705 ; + +C 124 ; WX 392 ; N a98 ; B 34 263 357 705 ; + +C 125 ; WX 668 ; N a99 ; B 35 263 633 705 ; + +C 126 ; WX 668 ; N a100 ; B 36 263 634 705 ; + +C 128 ; WX 390 ; N a89 ; B 35 -14 356 705 ; + +C 129 ; WX 390 ; N a90 ; B 35 -14 355 705 ; + +C 130 ; WX 317 ; N a93 ; B 35 0 283 692 ; + +C 131 ; WX 317 ; N a94 ; B 35 0 283 692 ; + +C 132 ; WX 276 ; N a91 ; B 35 0 242 692 ; + +C 133 ; WX 276 ; N a92 ; B 35 0 242 692 ; + +C 134 ; WX 509 ; N a205 ; B 35 0 475 692 ; + +C 135 ; WX 509 ; N a85 ; B 35 0 475 692 ; + +C 136 ; WX 410 ; N a206 ; B 35 0 375 692 ; + +C 137 ; WX 410 ; N a86 ; B 35 0 375 692 ; + +C 138 ; WX 234 ; N a87 ; B 35 -14 199 705 ; + +C 139 ; WX 234 ; N a88 ; B 35 -14 199 705 ; + +C 140 ; WX 334 ; N a95 ; B 35 0 299 692 ; + +C 141 ; WX 334 ; N a96 ; B 35 0 299 692 ; + +C 161 ; WX 732 ; N a101 ; B 35 -143 697 806 ; + +C 162 ; WX 544 ; N a102 ; B 56 -14 488 706 ; + +C 163 ; WX 544 ; N a103 ; B 34 -14 508 705 ; + +C 164 ; WX 910 ; N a104 ; B 35 40 875 651 ; + +C 165 ; WX 667 ; N a106 ; B 35 -14 633 705 ; + +C 166 ; WX 760 ; N a107 ; B 35 -14 726 705 ; + +C 167 ; WX 760 ; N a108 ; B 0 121 758 569 ; + +C 168 ; WX 776 ; N a112 ; B 35 0 741 705 ; + +C 169 ; WX 595 ; N a111 ; B 34 -14 560 705 ; + +C 170 ; WX 694 ; N a110 ; B 35 -14 659 705 ; + +C 171 ; WX 626 ; N a109 ; B 34 0 591 705 ; + +C 172 ; WX 788 ; N a120 ; B 35 -14 754 705 ; + +C 173 ; WX 788 ; N a121 ; B 35 -14 754 705 ; + +C 174 ; WX 788 ; N a122 ; B 35 -14 754 705 ; + +C 175 ; WX 788 ; N a123 ; B 35 -14 754 705 ; + +C 176 ; WX 788 ; N a124 ; B 35 -14 754 705 ; + +C 177 ; WX 788 ; N a125 ; B 35 -14 754 705 ; + +C 178 ; WX 788 ; N a126 ; B 35 -14 754 705 ; + +C 179 ; WX 788 ; N a127 ; B 35 -14 754 705 ; + +C 180 ; WX 788 ; N a128 ; B 35 -14 754 705 ; + +C 181 ; WX 788 ; N a129 ; B 35 -14 754 705 ; + +C 182 ; WX 788 ; N a130 ; B 35 -14 754 705 ; + +C 183 ; WX 788 ; N a131 ; B 35 -14 754 705 ; + +C 184 ; WX 788 ; N a132 ; B 35 -14 754 705 ; + +C 185 ; WX 788 ; N a133 ; B 35 -14 754 705 ; + +C 186 ; WX 788 ; N a134 ; B 35 -14 754 705 ; + +C 187 ; WX 788 ; N a135 ; B 35 -14 754 705 ; + +C 188 ; WX 788 ; N a136 ; B 35 -14 754 705 ; + +C 189 ; WX 788 ; N a137 ; B 35 -14 754 705 ; + +C 190 ; WX 788 ; N a138 ; B 35 -14 754 705 ; + +C 191 ; WX 788 ; N a139 ; B 35 -14 754 705 ; + +C 192 ; WX 788 ; N a140 ; B 35 -14 754 705 ; + +C 193 ; WX 788 ; N a141 ; B 35 -14 754 705 ; + +C 194 ; WX 788 ; N a142 ; B 35 -14 754 705 ; + +C 195 ; WX 788 ; N a143 ; B 35 -14 754 705 ; + +C 196 ; WX 788 ; N a144 ; B 35 -14 754 705 ; + +C 197 ; WX 788 ; N a145 ; B 35 -14 754 705 ; + +C 198 ; WX 788 ; N a146 ; B 35 -14 754 705 ; + +C 199 ; WX 788 ; N a147 ; B 35 -14 754 705 ; + +C 200 ; WX 788 ; N a148 ; B 35 -14 754 705 ; + +C 201 ; WX 788 ; N a149 ; B 35 -14 754 705 ; + +C 202 ; WX 788 ; N a150 ; B 35 -14 754 705 ; + +C 203 ; WX 788 ; N a151 ; B 35 -14 754 705 ; + +C 204 ; WX 788 ; N a152 ; B 35 -14 754 705 ; + +C 205 ; WX 788 ; N a153 ; B 35 -14 754 705 ; + +C 206 ; WX 788 ; N a154 ; B 35 -14 754 705 ; + +C 207 ; WX 788 ; N a155 ; B 35 -14 754 705 ; + +C 208 ; WX 788 ; N a156 ; B 35 -14 754 705 ; + +C 209 ; WX 788 ; N a157 ; B 35 -14 754 705 ; + +C 210 ; WX 788 ; N a158 ; B 35 -14 754 705 ; + +C 211 ; WX 788 ; N a159 ; B 35 -14 754 705 ; + +C 212 ; WX 894 ; N a160 ; B 35 58 860 634 ; + +C 213 ; WX 838 ; N a161 ; B 35 152 803 540 ; + +C 214 ; WX 1016 ; N a163 ; B 34 152 981 540 ; + +C 215 ; WX 458 ; N a164 ; B 35 -127 422 820 ; + +C 216 ; WX 748 ; N a196 ; B 35 94 698 597 ; + +C 217 ; WX 924 ; N a165 ; B 35 140 890 552 ; + +C 218 ; WX 748 ; N a192 ; B 35 94 698 597 ; + +C 219 ; WX 918 ; N a166 ; B 35 166 884 526 ; + +C 220 ; WX 927 ; N a167 ; B 35 32 892 660 ; + +C 221 ; WX 928 ; N a168 ; B 35 129 891 562 ; + +C 222 ; WX 928 ; N a169 ; B 35 128 893 563 ; + +C 223 ; WX 834 ; N a170 ; B 35 155 799 537 ; + +C 224 ; WX 873 ; N a171 ; B 35 93 838 599 ; + +C 225 ; WX 828 ; N a172 ; B 35 104 791 588 ; + +C 226 ; WX 924 ; N a173 ; B 35 98 889 594 ; + +C 227 ; WX 924 ; N a162 ; B 35 98 889 594 ; + +C 228 ; WX 917 ; N a174 ; B 35 0 882 692 ; + +C 229 ; WX 930 ; N a175 ; B 35 84 896 608 ; + +C 230 ; WX 931 ; N a176 ; B 35 84 896 608 ; + +C 231 ; WX 463 ; N a177 ; B 35 -99 429 791 ; + +C 232 ; WX 883 ; N a178 ; B 35 71 848 623 ; + +C 233 ; WX 836 ; N a179 ; B 35 44 802 648 ; + +C 234 ; WX 836 ; N a193 ; B 35 44 802 648 ; + +C 235 ; WX 867 ; N a180 ; B 35 101 832 591 ; + +C 236 ; WX 867 ; N a199 ; B 35 101 832 591 ; + +C 237 ; WX 696 ; N a181 ; B 35 44 661 648 ; + +C 238 ; WX 696 ; N a200 ; B 35 44 661 648 ; + +C 239 ; WX 874 ; N a182 ; B 35 77 840 619 ; + +C 241 ; WX 874 ; N a201 ; B 35 73 840 615 ; + +C 242 ; WX 760 ; N a183 ; B 35 0 725 692 ; + +C 243 ; WX 946 ; N a184 ; B 35 160 911 533 ; + +C 244 ; WX 771 ; N a197 ; B 34 37 736 655 ; + +C 245 ; WX 865 ; N a185 ; B 35 207 830 481 ; + +C 246 ; WX 771 ; N a194 ; B 34 37 736 655 ; + +C 247 ; WX 888 ; N a198 ; B 34 -19 853 712 ; + +C 248 ; WX 967 ; N a186 ; B 35 124 932 568 ; + +C 249 ; WX 888 ; N a195 ; B 34 -19 853 712 ; + +C 250 ; WX 831 ; N a187 ; B 35 113 796 579 ; + +C 251 ; WX 873 ; N a188 ; B 36 118 838 578 ; + +C 252 ; WX 927 ; N a189 ; B 35 150 891 542 ; + +C 253 ; WX 970 ; N a190 ; B 35 76 931 616 ; + +C 254 ; WX 918 ; N a191 ; B 34 99 884 593 ; + +EndCharMetrics + +EndFontMetrics + diff --git a/src/Broadside/Fonts/Data/GlyphList/LICENSE.md b/src/Broadside/Fonts/Data/GlyphList/LICENSE.md new file mode 100644 index 00000000..6fa1f178 --- /dev/null +++ b/src/Broadside/Fonts/Data/GlyphList/LICENSE.md @@ -0,0 +1,26 @@ +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +Neither the name of Adobe nor the names of its contributors may be +used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/Broadside/Fonts/Data/GlyphList/glyphlist.txt b/src/Broadside/Fonts/Data/GlyphList/glyphlist.txt new file mode 100644 index 00000000..d58003a7 --- /dev/null +++ b/src/Broadside/Fonts/Data/GlyphList/glyphlist.txt @@ -0,0 +1,4325 @@ +# ----------------------------------------------------------- +# Copyright 2002-2019 Adobe (http://www.adobe.com/). +# +# Redistribution and use in source and binary forms, with or +# without modification, are permitted provided that the +# following conditions are met: +# +# Redistributions of source code must retain the above +# copyright notice, this list of conditions and the following +# disclaimer. +# +# Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials +# provided with the distribution. +# +# Neither the name of Adobe nor the names of its contributors +# may be used to endorse or promote products derived from this +# software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ----------------------------------------------------------- +# Name: Adobe Glyph List +# Table version: 2.0 +# Date: September 20, 2002 +# URL: https://github.com/adobe-type-tools/agl-aglfn +# +# Format: two semicolon-delimited fields: +# (1) glyph name--upper/lowercase letters and digits +# (2) Unicode scalar value--four uppercase hexadecimal digits +# +A;0041 +AE;00C6 +AEacute;01FC +AEmacron;01E2 +AEsmall;F7E6 +Aacute;00C1 +Aacutesmall;F7E1 +Abreve;0102 +Abreveacute;1EAE +Abrevecyrillic;04D0 +Abrevedotbelow;1EB6 +Abrevegrave;1EB0 +Abrevehookabove;1EB2 +Abrevetilde;1EB4 +Acaron;01CD +Acircle;24B6 +Acircumflex;00C2 +Acircumflexacute;1EA4 +Acircumflexdotbelow;1EAC +Acircumflexgrave;1EA6 +Acircumflexhookabove;1EA8 +Acircumflexsmall;F7E2 +Acircumflextilde;1EAA +Acute;F6C9 +Acutesmall;F7B4 +Acyrillic;0410 +Adblgrave;0200 +Adieresis;00C4 +Adieresiscyrillic;04D2 +Adieresismacron;01DE +Adieresissmall;F7E4 +Adotbelow;1EA0 +Adotmacron;01E0 +Agrave;00C0 +Agravesmall;F7E0 +Ahookabove;1EA2 +Aiecyrillic;04D4 +Ainvertedbreve;0202 +Alpha;0391 +Alphatonos;0386 +Amacron;0100 +Amonospace;FF21 +Aogonek;0104 +Aring;00C5 +Aringacute;01FA +Aringbelow;1E00 +Aringsmall;F7E5 +Asmall;F761 +Atilde;00C3 +Atildesmall;F7E3 +Aybarmenian;0531 +B;0042 +Bcircle;24B7 +Bdotaccent;1E02 +Bdotbelow;1E04 +Becyrillic;0411 +Benarmenian;0532 +Beta;0392 +Bhook;0181 +Blinebelow;1E06 +Bmonospace;FF22 +Brevesmall;F6F4 +Bsmall;F762 +Btopbar;0182 +C;0043 +Caarmenian;053E +Cacute;0106 +Caron;F6CA +Caronsmall;F6F5 +Ccaron;010C +Ccedilla;00C7 +Ccedillaacute;1E08 +Ccedillasmall;F7E7 +Ccircle;24B8 +Ccircumflex;0108 +Cdot;010A +Cdotaccent;010A +Cedillasmall;F7B8 +Chaarmenian;0549 +Cheabkhasiancyrillic;04BC +Checyrillic;0427 +Chedescenderabkhasiancyrillic;04BE +Chedescendercyrillic;04B6 +Chedieresiscyrillic;04F4 +Cheharmenian;0543 +Chekhakassiancyrillic;04CB +Cheverticalstrokecyrillic;04B8 +Chi;03A7 +Chook;0187 +Circumflexsmall;F6F6 +Cmonospace;FF23 +Coarmenian;0551 +Csmall;F763 +D;0044 +DZ;01F1 +DZcaron;01C4 +Daarmenian;0534 +Dafrican;0189 +Dcaron;010E +Dcedilla;1E10 +Dcircle;24B9 +Dcircumflexbelow;1E12 +Dcroat;0110 +Ddotaccent;1E0A +Ddotbelow;1E0C +Decyrillic;0414 +Deicoptic;03EE +Delta;2206 +Deltagreek;0394 +Dhook;018A +Dieresis;F6CB +DieresisAcute;F6CC +DieresisGrave;F6CD +Dieresissmall;F7A8 +Digammagreek;03DC +Djecyrillic;0402 +Dlinebelow;1E0E +Dmonospace;FF24 +Dotaccentsmall;F6F7 +Dslash;0110 +Dsmall;F764 +Dtopbar;018B +Dz;01F2 +Dzcaron;01C5 +Dzeabkhasiancyrillic;04E0 +Dzecyrillic;0405 +Dzhecyrillic;040F +E;0045 +Eacute;00C9 +Eacutesmall;F7E9 +Ebreve;0114 +Ecaron;011A +Ecedillabreve;1E1C +Echarmenian;0535 +Ecircle;24BA +Ecircumflex;00CA +Ecircumflexacute;1EBE +Ecircumflexbelow;1E18 +Ecircumflexdotbelow;1EC6 +Ecircumflexgrave;1EC0 +Ecircumflexhookabove;1EC2 +Ecircumflexsmall;F7EA +Ecircumflextilde;1EC4 +Ecyrillic;0404 +Edblgrave;0204 +Edieresis;00CB +Edieresissmall;F7EB +Edot;0116 +Edotaccent;0116 +Edotbelow;1EB8 +Efcyrillic;0424 +Egrave;00C8 +Egravesmall;F7E8 +Eharmenian;0537 +Ehookabove;1EBA +Eightroman;2167 +Einvertedbreve;0206 +Eiotifiedcyrillic;0464 +Elcyrillic;041B +Elevenroman;216A +Emacron;0112 +Emacronacute;1E16 +Emacrongrave;1E14 +Emcyrillic;041C +Emonospace;FF25 +Encyrillic;041D +Endescendercyrillic;04A2 +Eng;014A +Enghecyrillic;04A4 +Enhookcyrillic;04C7 +Eogonek;0118 +Eopen;0190 +Epsilon;0395 +Epsilontonos;0388 +Ercyrillic;0420 +Ereversed;018E +Ereversedcyrillic;042D +Escyrillic;0421 +Esdescendercyrillic;04AA +Esh;01A9 +Esmall;F765 +Eta;0397 +Etarmenian;0538 +Etatonos;0389 +Eth;00D0 +Ethsmall;F7F0 +Etilde;1EBC +Etildebelow;1E1A +Euro;20AC +Ezh;01B7 +Ezhcaron;01EE +Ezhreversed;01B8 +F;0046 +Fcircle;24BB +Fdotaccent;1E1E +Feharmenian;0556 +Feicoptic;03E4 +Fhook;0191 +Fitacyrillic;0472 +Fiveroman;2164 +Fmonospace;FF26 +Fourroman;2163 +Fsmall;F766 +G;0047 +GBsquare;3387 +Gacute;01F4 +Gamma;0393 +Gammaafrican;0194 +Gangiacoptic;03EA +Gbreve;011E +Gcaron;01E6 +Gcedilla;0122 +Gcircle;24BC +Gcircumflex;011C +Gcommaaccent;0122 +Gdot;0120 +Gdotaccent;0120 +Gecyrillic;0413 +Ghadarmenian;0542 +Ghemiddlehookcyrillic;0494 +Ghestrokecyrillic;0492 +Gheupturncyrillic;0490 +Ghook;0193 +Gimarmenian;0533 +Gjecyrillic;0403 +Gmacron;1E20 +Gmonospace;FF27 +Grave;F6CE +Gravesmall;F760 +Gsmall;F767 +Gsmallhook;029B +Gstroke;01E4 +H;0048 +H18533;25CF +H18543;25AA +H18551;25AB +H22073;25A1 +HPsquare;33CB +Haabkhasiancyrillic;04A8 +Hadescendercyrillic;04B2 +Hardsigncyrillic;042A +Hbar;0126 +Hbrevebelow;1E2A +Hcedilla;1E28 +Hcircle;24BD +Hcircumflex;0124 +Hdieresis;1E26 +Hdotaccent;1E22 +Hdotbelow;1E24 +Hmonospace;FF28 +Hoarmenian;0540 +Horicoptic;03E8 +Hsmall;F768 +Hungarumlaut;F6CF +Hungarumlautsmall;F6F8 +Hzsquare;3390 +I;0049 +IAcyrillic;042F +IJ;0132 +IUcyrillic;042E +Iacute;00CD +Iacutesmall;F7ED +Ibreve;012C +Icaron;01CF +Icircle;24BE +Icircumflex;00CE +Icircumflexsmall;F7EE +Icyrillic;0406 +Idblgrave;0208 +Idieresis;00CF +Idieresisacute;1E2E +Idieresiscyrillic;04E4 +Idieresissmall;F7EF +Idot;0130 +Idotaccent;0130 +Idotbelow;1ECA +Iebrevecyrillic;04D6 +Iecyrillic;0415 +Ifraktur;2111 +Igrave;00CC +Igravesmall;F7EC +Ihookabove;1EC8 +Iicyrillic;0418 +Iinvertedbreve;020A +Iishortcyrillic;0419 +Imacron;012A +Imacroncyrillic;04E2 +Imonospace;FF29 +Iniarmenian;053B +Iocyrillic;0401 +Iogonek;012E +Iota;0399 +Iotaafrican;0196 +Iotadieresis;03AA +Iotatonos;038A +Ismall;F769 +Istroke;0197 +Itilde;0128 +Itildebelow;1E2C +Izhitsacyrillic;0474 +Izhitsadblgravecyrillic;0476 +J;004A +Jaarmenian;0541 +Jcircle;24BF +Jcircumflex;0134 +Jecyrillic;0408 +Jheharmenian;054B +Jmonospace;FF2A +Jsmall;F76A +K;004B +KBsquare;3385 +KKsquare;33CD +Kabashkircyrillic;04A0 +Kacute;1E30 +Kacyrillic;041A +Kadescendercyrillic;049A +Kahookcyrillic;04C3 +Kappa;039A +Kastrokecyrillic;049E +Kaverticalstrokecyrillic;049C +Kcaron;01E8 +Kcedilla;0136 +Kcircle;24C0 +Kcommaaccent;0136 +Kdotbelow;1E32 +Keharmenian;0554 +Kenarmenian;053F +Khacyrillic;0425 +Kheicoptic;03E6 +Khook;0198 +Kjecyrillic;040C +Klinebelow;1E34 +Kmonospace;FF2B +Koppacyrillic;0480 +Koppagreek;03DE +Ksicyrillic;046E +Ksmall;F76B +L;004C +LJ;01C7 +LL;F6BF +Lacute;0139 +Lambda;039B +Lcaron;013D +Lcedilla;013B +Lcircle;24C1 +Lcircumflexbelow;1E3C +Lcommaaccent;013B +Ldot;013F +Ldotaccent;013F +Ldotbelow;1E36 +Ldotbelowmacron;1E38 +Liwnarmenian;053C +Lj;01C8 +Ljecyrillic;0409 +Llinebelow;1E3A +Lmonospace;FF2C +Lslash;0141 +Lslashsmall;F6F9 +Lsmall;F76C +M;004D +MBsquare;3386 +Macron;F6D0 +Macronsmall;F7AF +Macute;1E3E +Mcircle;24C2 +Mdotaccent;1E40 +Mdotbelow;1E42 +Menarmenian;0544 +Mmonospace;FF2D +Msmall;F76D +Mturned;019C +Mu;039C +N;004E +NJ;01CA +Nacute;0143 +Ncaron;0147 +Ncedilla;0145 +Ncircle;24C3 +Ncircumflexbelow;1E4A +Ncommaaccent;0145 +Ndotaccent;1E44 +Ndotbelow;1E46 +Nhookleft;019D +Nineroman;2168 +Nj;01CB +Njecyrillic;040A +Nlinebelow;1E48 +Nmonospace;FF2E +Nowarmenian;0546 +Nsmall;F76E +Ntilde;00D1 +Ntildesmall;F7F1 +Nu;039D +O;004F +OE;0152 +OEsmall;F6FA +Oacute;00D3 +Oacutesmall;F7F3 +Obarredcyrillic;04E8 +Obarreddieresiscyrillic;04EA +Obreve;014E +Ocaron;01D1 +Ocenteredtilde;019F +Ocircle;24C4 +Ocircumflex;00D4 +Ocircumflexacute;1ED0 +Ocircumflexdotbelow;1ED8 +Ocircumflexgrave;1ED2 +Ocircumflexhookabove;1ED4 +Ocircumflexsmall;F7F4 +Ocircumflextilde;1ED6 +Ocyrillic;041E +Odblacute;0150 +Odblgrave;020C +Odieresis;00D6 +Odieresiscyrillic;04E6 +Odieresissmall;F7F6 +Odotbelow;1ECC +Ogoneksmall;F6FB +Ograve;00D2 +Ogravesmall;F7F2 +Oharmenian;0555 +Ohm;2126 +Ohookabove;1ECE +Ohorn;01A0 +Ohornacute;1EDA +Ohorndotbelow;1EE2 +Ohorngrave;1EDC +Ohornhookabove;1EDE +Ohorntilde;1EE0 +Ohungarumlaut;0150 +Oi;01A2 +Oinvertedbreve;020E +Omacron;014C +Omacronacute;1E52 +Omacrongrave;1E50 +Omega;2126 +Omegacyrillic;0460 +Omegagreek;03A9 +Omegaroundcyrillic;047A +Omegatitlocyrillic;047C +Omegatonos;038F +Omicron;039F +Omicrontonos;038C +Omonospace;FF2F +Oneroman;2160 +Oogonek;01EA +Oogonekmacron;01EC +Oopen;0186 +Oslash;00D8 +Oslashacute;01FE +Oslashsmall;F7F8 +Osmall;F76F +Ostrokeacute;01FE +Otcyrillic;047E +Otilde;00D5 +Otildeacute;1E4C +Otildedieresis;1E4E +Otildesmall;F7F5 +P;0050 +Pacute;1E54 +Pcircle;24C5 +Pdotaccent;1E56 +Pecyrillic;041F +Peharmenian;054A +Pemiddlehookcyrillic;04A6 +Phi;03A6 +Phook;01A4 +Pi;03A0 +Piwrarmenian;0553 +Pmonospace;FF30 +Psi;03A8 +Psicyrillic;0470 +Psmall;F770 +Q;0051 +Qcircle;24C6 +Qmonospace;FF31 +Qsmall;F771 +R;0052 +Raarmenian;054C +Racute;0154 +Rcaron;0158 +Rcedilla;0156 +Rcircle;24C7 +Rcommaaccent;0156 +Rdblgrave;0210 +Rdotaccent;1E58 +Rdotbelow;1E5A +Rdotbelowmacron;1E5C +Reharmenian;0550 +Rfraktur;211C +Rho;03A1 +Ringsmall;F6FC +Rinvertedbreve;0212 +Rlinebelow;1E5E +Rmonospace;FF32 +Rsmall;F772 +Rsmallinverted;0281 +Rsmallinvertedsuperior;02B6 +S;0053 +SF010000;250C +SF020000;2514 +SF030000;2510 +SF040000;2518 +SF050000;253C +SF060000;252C +SF070000;2534 +SF080000;251C +SF090000;2524 +SF100000;2500 +SF110000;2502 +SF190000;2561 +SF200000;2562 +SF210000;2556 +SF220000;2555 +SF230000;2563 +SF240000;2551 +SF250000;2557 +SF260000;255D +SF270000;255C +SF280000;255B +SF360000;255E +SF370000;255F +SF380000;255A +SF390000;2554 +SF400000;2569 +SF410000;2566 +SF420000;2560 +SF430000;2550 +SF440000;256C +SF450000;2567 +SF460000;2568 +SF470000;2564 +SF480000;2565 +SF490000;2559 +SF500000;2558 +SF510000;2552 +SF520000;2553 +SF530000;256B +SF540000;256A +Sacute;015A +Sacutedotaccent;1E64 +Sampigreek;03E0 +Scaron;0160 +Scarondotaccent;1E66 +Scaronsmall;F6FD +Scedilla;015E +Schwa;018F +Schwacyrillic;04D8 +Schwadieresiscyrillic;04DA +Scircle;24C8 +Scircumflex;015C +Scommaaccent;0218 +Sdotaccent;1E60 +Sdotbelow;1E62 +Sdotbelowdotaccent;1E68 +Seharmenian;054D +Sevenroman;2166 +Shaarmenian;0547 +Shacyrillic;0428 +Shchacyrillic;0429 +Sheicoptic;03E2 +Shhacyrillic;04BA +Shimacoptic;03EC +Sigma;03A3 +Sixroman;2165 +Smonospace;FF33 +Softsigncyrillic;042C +Ssmall;F773 +Stigmagreek;03DA +T;0054 +Tau;03A4 +Tbar;0166 +Tcaron;0164 +Tcedilla;0162 +Tcircle;24C9 +Tcircumflexbelow;1E70 +Tcommaaccent;0162 +Tdotaccent;1E6A +Tdotbelow;1E6C +Tecyrillic;0422 +Tedescendercyrillic;04AC +Tenroman;2169 +Tetsecyrillic;04B4 +Theta;0398 +Thook;01AC +Thorn;00DE +Thornsmall;F7FE +Threeroman;2162 +Tildesmall;F6FE +Tiwnarmenian;054F +Tlinebelow;1E6E +Tmonospace;FF34 +Toarmenian;0539 +Tonefive;01BC +Tonesix;0184 +Tonetwo;01A7 +Tretroflexhook;01AE +Tsecyrillic;0426 +Tshecyrillic;040B +Tsmall;F774 +Twelveroman;216B +Tworoman;2161 +U;0055 +Uacute;00DA +Uacutesmall;F7FA +Ubreve;016C +Ucaron;01D3 +Ucircle;24CA +Ucircumflex;00DB +Ucircumflexbelow;1E76 +Ucircumflexsmall;F7FB +Ucyrillic;0423 +Udblacute;0170 +Udblgrave;0214 +Udieresis;00DC +Udieresisacute;01D7 +Udieresisbelow;1E72 +Udieresiscaron;01D9 +Udieresiscyrillic;04F0 +Udieresisgrave;01DB +Udieresismacron;01D5 +Udieresissmall;F7FC +Udotbelow;1EE4 +Ugrave;00D9 +Ugravesmall;F7F9 +Uhookabove;1EE6 +Uhorn;01AF +Uhornacute;1EE8 +Uhorndotbelow;1EF0 +Uhorngrave;1EEA +Uhornhookabove;1EEC +Uhorntilde;1EEE +Uhungarumlaut;0170 +Uhungarumlautcyrillic;04F2 +Uinvertedbreve;0216 +Ukcyrillic;0478 +Umacron;016A +Umacroncyrillic;04EE +Umacrondieresis;1E7A +Umonospace;FF35 +Uogonek;0172 +Upsilon;03A5 +Upsilon1;03D2 +Upsilonacutehooksymbolgreek;03D3 +Upsilonafrican;01B1 +Upsilondieresis;03AB +Upsilondieresishooksymbolgreek;03D4 +Upsilonhooksymbol;03D2 +Upsilontonos;038E +Uring;016E +Ushortcyrillic;040E +Usmall;F775 +Ustraightcyrillic;04AE +Ustraightstrokecyrillic;04B0 +Utilde;0168 +Utildeacute;1E78 +Utildebelow;1E74 +V;0056 +Vcircle;24CB +Vdotbelow;1E7E +Vecyrillic;0412 +Vewarmenian;054E +Vhook;01B2 +Vmonospace;FF36 +Voarmenian;0548 +Vsmall;F776 +Vtilde;1E7C +W;0057 +Wacute;1E82 +Wcircle;24CC +Wcircumflex;0174 +Wdieresis;1E84 +Wdotaccent;1E86 +Wdotbelow;1E88 +Wgrave;1E80 +Wmonospace;FF37 +Wsmall;F777 +X;0058 +Xcircle;24CD +Xdieresis;1E8C +Xdotaccent;1E8A +Xeharmenian;053D +Xi;039E +Xmonospace;FF38 +Xsmall;F778 +Y;0059 +Yacute;00DD +Yacutesmall;F7FD +Yatcyrillic;0462 +Ycircle;24CE +Ycircumflex;0176 +Ydieresis;0178 +Ydieresissmall;F7FF +Ydotaccent;1E8E +Ydotbelow;1EF4 +Yericyrillic;042B +Yerudieresiscyrillic;04F8 +Ygrave;1EF2 +Yhook;01B3 +Yhookabove;1EF6 +Yiarmenian;0545 +Yicyrillic;0407 +Yiwnarmenian;0552 +Ymonospace;FF39 +Ysmall;F779 +Ytilde;1EF8 +Yusbigcyrillic;046A +Yusbigiotifiedcyrillic;046C +Yuslittlecyrillic;0466 +Yuslittleiotifiedcyrillic;0468 +Z;005A +Zaarmenian;0536 +Zacute;0179 +Zcaron;017D +Zcaronsmall;F6FF +Zcircle;24CF +Zcircumflex;1E90 +Zdot;017B +Zdotaccent;017B +Zdotbelow;1E92 +Zecyrillic;0417 +Zedescendercyrillic;0498 +Zedieresiscyrillic;04DE +Zeta;0396 +Zhearmenian;053A +Zhebrevecyrillic;04C1 +Zhecyrillic;0416 +Zhedescendercyrillic;0496 +Zhedieresiscyrillic;04DC +Zlinebelow;1E94 +Zmonospace;FF3A +Zsmall;F77A +Zstroke;01B5 +a;0061 +aabengali;0986 +aacute;00E1 +aadeva;0906 +aagujarati;0A86 +aagurmukhi;0A06 +aamatragurmukhi;0A3E +aarusquare;3303 +aavowelsignbengali;09BE +aavowelsigndeva;093E +aavowelsigngujarati;0ABE +abbreviationmarkarmenian;055F +abbreviationsigndeva;0970 +abengali;0985 +abopomofo;311A +abreve;0103 +abreveacute;1EAF +abrevecyrillic;04D1 +abrevedotbelow;1EB7 +abrevegrave;1EB1 +abrevehookabove;1EB3 +abrevetilde;1EB5 +acaron;01CE +acircle;24D0 +acircumflex;00E2 +acircumflexacute;1EA5 +acircumflexdotbelow;1EAD +acircumflexgrave;1EA7 +acircumflexhookabove;1EA9 +acircumflextilde;1EAB +acute;00B4 +acutebelowcmb;0317 +acutecmb;0301 +acutecomb;0301 +acutedeva;0954 +acutelowmod;02CF +acutetonecmb;0341 +acyrillic;0430 +adblgrave;0201 +addakgurmukhi;0A71 +adeva;0905 +adieresis;00E4 +adieresiscyrillic;04D3 +adieresismacron;01DF +adotbelow;1EA1 +adotmacron;01E1 +ae;00E6 +aeacute;01FD +aekorean;3150 +aemacron;01E3 +afii00208;2015 +afii08941;20A4 +afii10017;0410 +afii10018;0411 +afii10019;0412 +afii10020;0413 +afii10021;0414 +afii10022;0415 +afii10023;0401 +afii10024;0416 +afii10025;0417 +afii10026;0418 +afii10027;0419 +afii10028;041A +afii10029;041B +afii10030;041C +afii10031;041D +afii10032;041E +afii10033;041F +afii10034;0420 +afii10035;0421 +afii10036;0422 +afii10037;0423 +afii10038;0424 +afii10039;0425 +afii10040;0426 +afii10041;0427 +afii10042;0428 +afii10043;0429 +afii10044;042A +afii10045;042B +afii10046;042C +afii10047;042D +afii10048;042E +afii10049;042F +afii10050;0490 +afii10051;0402 +afii10052;0403 +afii10053;0404 +afii10054;0405 +afii10055;0406 +afii10056;0407 +afii10057;0408 +afii10058;0409 +afii10059;040A +afii10060;040B +afii10061;040C +afii10062;040E +afii10063;F6C4 +afii10064;F6C5 +afii10065;0430 +afii10066;0431 +afii10067;0432 +afii10068;0433 +afii10069;0434 +afii10070;0435 +afii10071;0451 +afii10072;0436 +afii10073;0437 +afii10074;0438 +afii10075;0439 +afii10076;043A +afii10077;043B +afii10078;043C +afii10079;043D +afii10080;043E +afii10081;043F +afii10082;0440 +afii10083;0441 +afii10084;0442 +afii10085;0443 +afii10086;0444 +afii10087;0445 +afii10088;0446 +afii10089;0447 +afii10090;0448 +afii10091;0449 +afii10092;044A +afii10093;044B +afii10094;044C +afii10095;044D +afii10096;044E +afii10097;044F +afii10098;0491 +afii10099;0452 +afii10100;0453 +afii10101;0454 +afii10102;0455 +afii10103;0456 +afii10104;0457 +afii10105;0458 +afii10106;0459 +afii10107;045A +afii10108;045B +afii10109;045C +afii10110;045E +afii10145;040F +afii10146;0462 +afii10147;0472 +afii10148;0474 +afii10192;F6C6 +afii10193;045F +afii10194;0463 +afii10195;0473 +afii10196;0475 +afii10831;F6C7 +afii10832;F6C8 +afii10846;04D9 +afii299;200E +afii300;200F +afii301;200D +afii57381;066A +afii57388;060C +afii57392;0660 +afii57393;0661 +afii57394;0662 +afii57395;0663 +afii57396;0664 +afii57397;0665 +afii57398;0666 +afii57399;0667 +afii57400;0668 +afii57401;0669 +afii57403;061B +afii57407;061F +afii57409;0621 +afii57410;0622 +afii57411;0623 +afii57412;0624 +afii57413;0625 +afii57414;0626 +afii57415;0627 +afii57416;0628 +afii57417;0629 +afii57418;062A +afii57419;062B +afii57420;062C +afii57421;062D +afii57422;062E +afii57423;062F +afii57424;0630 +afii57425;0631 +afii57426;0632 +afii57427;0633 +afii57428;0634 +afii57429;0635 +afii57430;0636 +afii57431;0637 +afii57432;0638 +afii57433;0639 +afii57434;063A +afii57440;0640 +afii57441;0641 +afii57442;0642 +afii57443;0643 +afii57444;0644 +afii57445;0645 +afii57446;0646 +afii57448;0648 +afii57449;0649 +afii57450;064A +afii57451;064B +afii57452;064C +afii57453;064D +afii57454;064E +afii57455;064F +afii57456;0650 +afii57457;0651 +afii57458;0652 +afii57470;0647 +afii57505;06A4 +afii57506;067E +afii57507;0686 +afii57508;0698 +afii57509;06AF +afii57511;0679 +afii57512;0688 +afii57513;0691 +afii57514;06BA +afii57519;06D2 +afii57534;06D5 +afii57636;20AA +afii57645;05BE +afii57658;05C3 +afii57664;05D0 +afii57665;05D1 +afii57666;05D2 +afii57667;05D3 +afii57668;05D4 +afii57669;05D5 +afii57670;05D6 +afii57671;05D7 +afii57672;05D8 +afii57673;05D9 +afii57674;05DA +afii57675;05DB +afii57676;05DC +afii57677;05DD +afii57678;05DE +afii57679;05DF +afii57680;05E0 +afii57681;05E1 +afii57682;05E2 +afii57683;05E3 +afii57684;05E4 +afii57685;05E5 +afii57686;05E6 +afii57687;05E7 +afii57688;05E8 +afii57689;05E9 +afii57690;05EA +afii57694;FB2A +afii57695;FB2B +afii57700;FB4B +afii57705;FB1F +afii57716;05F0 +afii57717;05F1 +afii57718;05F2 +afii57723;FB35 +afii57793;05B4 +afii57794;05B5 +afii57795;05B6 +afii57796;05BB +afii57797;05B8 +afii57798;05B7 +afii57799;05B0 +afii57800;05B2 +afii57801;05B1 +afii57802;05B3 +afii57803;05C2 +afii57804;05C1 +afii57806;05B9 +afii57807;05BC +afii57839;05BD +afii57841;05BF +afii57842;05C0 +afii57929;02BC +afii61248;2105 +afii61289;2113 +afii61352;2116 +afii61573;202C +afii61574;202D +afii61575;202E +afii61664;200C +afii63167;066D +afii64937;02BD +agrave;00E0 +agujarati;0A85 +agurmukhi;0A05 +ahiragana;3042 +ahookabove;1EA3 +aibengali;0990 +aibopomofo;311E +aideva;0910 +aiecyrillic;04D5 +aigujarati;0A90 +aigurmukhi;0A10 +aimatragurmukhi;0A48 +ainarabic;0639 +ainfinalarabic;FECA +aininitialarabic;FECB +ainmedialarabic;FECC +ainvertedbreve;0203 +aivowelsignbengali;09C8 +aivowelsigndeva;0948 +aivowelsigngujarati;0AC8 +akatakana;30A2 +akatakanahalfwidth;FF71 +akorean;314F +alef;05D0 +alefarabic;0627 +alefdageshhebrew;FB30 +aleffinalarabic;FE8E +alefhamzaabovearabic;0623 +alefhamzaabovefinalarabic;FE84 +alefhamzabelowarabic;0625 +alefhamzabelowfinalarabic;FE88 +alefhebrew;05D0 +aleflamedhebrew;FB4F +alefmaddaabovearabic;0622 +alefmaddaabovefinalarabic;FE82 +alefmaksuraarabic;0649 +alefmaksurafinalarabic;FEF0 +alefmaksurainitialarabic;FEF3 +alefmaksuramedialarabic;FEF4 +alefpatahhebrew;FB2E +alefqamatshebrew;FB2F +aleph;2135 +allequal;224C +alpha;03B1 +alphatonos;03AC +amacron;0101 +amonospace;FF41 +ampersand;0026 +ampersandmonospace;FF06 +ampersandsmall;F726 +amsquare;33C2 +anbopomofo;3122 +angbopomofo;3124 +angkhankhuthai;0E5A +angle;2220 +anglebracketleft;3008 +anglebracketleftvertical;FE3F +anglebracketright;3009 +anglebracketrightvertical;FE40 +angleleft;2329 +angleright;232A +angstrom;212B +anoteleia;0387 +anudattadeva;0952 +anusvarabengali;0982 +anusvaradeva;0902 +anusvaragujarati;0A82 +aogonek;0105 +apaatosquare;3300 +aparen;249C +apostrophearmenian;055A +apostrophemod;02BC +apple;F8FF +approaches;2250 +approxequal;2248 +approxequalorimage;2252 +approximatelyequal;2245 +araeaekorean;318E +araeakorean;318D +arc;2312 +arighthalfring;1E9A +aring;00E5 +aringacute;01FB +aringbelow;1E01 +arrowboth;2194 +arrowdashdown;21E3 +arrowdashleft;21E0 +arrowdashright;21E2 +arrowdashup;21E1 +arrowdblboth;21D4 +arrowdbldown;21D3 +arrowdblleft;21D0 +arrowdblright;21D2 +arrowdblup;21D1 +arrowdown;2193 +arrowdownleft;2199 +arrowdownright;2198 +arrowdownwhite;21E9 +arrowheaddownmod;02C5 +arrowheadleftmod;02C2 +arrowheadrightmod;02C3 +arrowheadupmod;02C4 +arrowhorizex;F8E7 +arrowleft;2190 +arrowleftdbl;21D0 +arrowleftdblstroke;21CD +arrowleftoverright;21C6 +arrowleftwhite;21E6 +arrowright;2192 +arrowrightdblstroke;21CF +arrowrightheavy;279E +arrowrightoverleft;21C4 +arrowrightwhite;21E8 +arrowtableft;21E4 +arrowtabright;21E5 +arrowup;2191 +arrowupdn;2195 +arrowupdnbse;21A8 +arrowupdownbase;21A8 +arrowupleft;2196 +arrowupleftofdown;21C5 +arrowupright;2197 +arrowupwhite;21E7 +arrowvertex;F8E6 +asciicircum;005E +asciicircummonospace;FF3E +asciitilde;007E +asciitildemonospace;FF5E +ascript;0251 +ascriptturned;0252 +asmallhiragana;3041 +asmallkatakana;30A1 +asmallkatakanahalfwidth;FF67 +asterisk;002A +asteriskaltonearabic;066D +asteriskarabic;066D +asteriskmath;2217 +asteriskmonospace;FF0A +asterisksmall;FE61 +asterism;2042 +asuperior;F6E9 +asymptoticallyequal;2243 +at;0040 +atilde;00E3 +atmonospace;FF20 +atsmall;FE6B +aturned;0250 +aubengali;0994 +aubopomofo;3120 +audeva;0914 +augujarati;0A94 +augurmukhi;0A14 +aulengthmarkbengali;09D7 +aumatragurmukhi;0A4C +auvowelsignbengali;09CC +auvowelsigndeva;094C +auvowelsigngujarati;0ACC +avagrahadeva;093D +aybarmenian;0561 +ayin;05E2 +ayinaltonehebrew;FB20 +ayinhebrew;05E2 +b;0062 +babengali;09AC +backslash;005C +backslashmonospace;FF3C +badeva;092C +bagujarati;0AAC +bagurmukhi;0A2C +bahiragana;3070 +bahtthai;0E3F +bakatakana;30D0 +bar;007C +barmonospace;FF5C +bbopomofo;3105 +bcircle;24D1 +bdotaccent;1E03 +bdotbelow;1E05 +beamedsixteenthnotes;266C +because;2235 +becyrillic;0431 +beharabic;0628 +behfinalarabic;FE90 +behinitialarabic;FE91 +behiragana;3079 +behmedialarabic;FE92 +behmeeminitialarabic;FC9F +behmeemisolatedarabic;FC08 +behnoonfinalarabic;FC6D +bekatakana;30D9 +benarmenian;0562 +bet;05D1 +beta;03B2 +betasymbolgreek;03D0 +betdagesh;FB31 +betdageshhebrew;FB31 +bethebrew;05D1 +betrafehebrew;FB4C +bhabengali;09AD +bhadeva;092D +bhagujarati;0AAD +bhagurmukhi;0A2D +bhook;0253 +bihiragana;3073 +bikatakana;30D3 +bilabialclick;0298 +bindigurmukhi;0A02 +birusquare;3331 +blackcircle;25CF +blackdiamond;25C6 +blackdownpointingtriangle;25BC +blackleftpointingpointer;25C4 +blackleftpointingtriangle;25C0 +blacklenticularbracketleft;3010 +blacklenticularbracketleftvertical;FE3B +blacklenticularbracketright;3011 +blacklenticularbracketrightvertical;FE3C +blacklowerlefttriangle;25E3 +blacklowerrighttriangle;25E2 +blackrectangle;25AC +blackrightpointingpointer;25BA +blackrightpointingtriangle;25B6 +blacksmallsquare;25AA +blacksmilingface;263B +blacksquare;25A0 +blackstar;2605 +blackupperlefttriangle;25E4 +blackupperrighttriangle;25E5 +blackuppointingsmalltriangle;25B4 +blackuppointingtriangle;25B2 +blank;2423 +blinebelow;1E07 +block;2588 +bmonospace;FF42 +bobaimaithai;0E1A +bohiragana;307C +bokatakana;30DC +bparen;249D +bqsquare;33C3 +braceex;F8F4 +braceleft;007B +braceleftbt;F8F3 +braceleftmid;F8F2 +braceleftmonospace;FF5B +braceleftsmall;FE5B +bracelefttp;F8F1 +braceleftvertical;FE37 +braceright;007D +bracerightbt;F8FE +bracerightmid;F8FD +bracerightmonospace;FF5D +bracerightsmall;FE5C +bracerighttp;F8FC +bracerightvertical;FE38 +bracketleft;005B +bracketleftbt;F8F0 +bracketleftex;F8EF +bracketleftmonospace;FF3B +bracketlefttp;F8EE +bracketright;005D +bracketrightbt;F8FB +bracketrightex;F8FA +bracketrightmonospace;FF3D +bracketrighttp;F8F9 +breve;02D8 +brevebelowcmb;032E +brevecmb;0306 +breveinvertedbelowcmb;032F +breveinvertedcmb;0311 +breveinverteddoublecmb;0361 +bridgebelowcmb;032A +bridgeinvertedbelowcmb;033A +brokenbar;00A6 +bstroke;0180 +bsuperior;F6EA +btopbar;0183 +buhiragana;3076 +bukatakana;30D6 +bullet;2022 +bulletinverse;25D8 +bulletoperator;2219 +bullseye;25CE +c;0063 +caarmenian;056E +cabengali;099A +cacute;0107 +cadeva;091A +cagujarati;0A9A +cagurmukhi;0A1A +calsquare;3388 +candrabindubengali;0981 +candrabinducmb;0310 +candrabindudeva;0901 +candrabindugujarati;0A81 +capslock;21EA +careof;2105 +caron;02C7 +caronbelowcmb;032C +caroncmb;030C +carriagereturn;21B5 +cbopomofo;3118 +ccaron;010D +ccedilla;00E7 +ccedillaacute;1E09 +ccircle;24D2 +ccircumflex;0109 +ccurl;0255 +cdot;010B +cdotaccent;010B +cdsquare;33C5 +cedilla;00B8 +cedillacmb;0327 +cent;00A2 +centigrade;2103 +centinferior;F6DF +centmonospace;FFE0 +centoldstyle;F7A2 +centsuperior;F6E0 +chaarmenian;0579 +chabengali;099B +chadeva;091B +chagujarati;0A9B +chagurmukhi;0A1B +chbopomofo;3114 +cheabkhasiancyrillic;04BD +checkmark;2713 +checyrillic;0447 +chedescenderabkhasiancyrillic;04BF +chedescendercyrillic;04B7 +chedieresiscyrillic;04F5 +cheharmenian;0573 +chekhakassiancyrillic;04CC +cheverticalstrokecyrillic;04B9 +chi;03C7 +chieuchacirclekorean;3277 +chieuchaparenkorean;3217 +chieuchcirclekorean;3269 +chieuchkorean;314A +chieuchparenkorean;3209 +chochangthai;0E0A +chochanthai;0E08 +chochingthai;0E09 +chochoethai;0E0C +chook;0188 +cieucacirclekorean;3276 +cieucaparenkorean;3216 +cieuccirclekorean;3268 +cieuckorean;3148 +cieucparenkorean;3208 +cieucuparenkorean;321C +circle;25CB +circlemultiply;2297 +circleot;2299 +circleplus;2295 +circlepostalmark;3036 +circlewithlefthalfblack;25D0 +circlewithrighthalfblack;25D1 +circumflex;02C6 +circumflexbelowcmb;032D +circumflexcmb;0302 +clear;2327 +clickalveolar;01C2 +clickdental;01C0 +clicklateral;01C1 +clickretroflex;01C3 +club;2663 +clubsuitblack;2663 +clubsuitwhite;2667 +cmcubedsquare;33A4 +cmonospace;FF43 +cmsquaredsquare;33A0 +coarmenian;0581 +colon;003A +colonmonetary;20A1 +colonmonospace;FF1A +colonsign;20A1 +colonsmall;FE55 +colontriangularhalfmod;02D1 +colontriangularmod;02D0 +comma;002C +commaabovecmb;0313 +commaaboverightcmb;0315 +commaaccent;F6C3 +commaarabic;060C +commaarmenian;055D +commainferior;F6E1 +commamonospace;FF0C +commareversedabovecmb;0314 +commareversedmod;02BD +commasmall;FE50 +commasuperior;F6E2 +commaturnedabovecmb;0312 +commaturnedmod;02BB +compass;263C +congruent;2245 +contourintegral;222E +control;2303 +controlACK;0006 +controlBEL;0007 +controlBS;0008 +controlCAN;0018 +controlCR;000D +controlDC1;0011 +controlDC2;0012 +controlDC3;0013 +controlDC4;0014 +controlDEL;007F +controlDLE;0010 +controlEM;0019 +controlENQ;0005 +controlEOT;0004 +controlESC;001B +controlETB;0017 +controlETX;0003 +controlFF;000C +controlFS;001C +controlGS;001D +controlHT;0009 +controlLF;000A +controlNAK;0015 +controlRS;001E +controlSI;000F +controlSO;000E +controlSOT;0002 +controlSTX;0001 +controlSUB;001A +controlSYN;0016 +controlUS;001F +controlVT;000B +copyright;00A9 +copyrightsans;F8E9 +copyrightserif;F6D9 +cornerbracketleft;300C +cornerbracketlefthalfwidth;FF62 +cornerbracketleftvertical;FE41 +cornerbracketright;300D +cornerbracketrighthalfwidth;FF63 +cornerbracketrightvertical;FE42 +corporationsquare;337F +cosquare;33C7 +coverkgsquare;33C6 +cparen;249E +cruzeiro;20A2 +cstretched;0297 +curlyand;22CF +curlyor;22CE +currency;00A4 +cyrBreve;F6D1 +cyrFlex;F6D2 +cyrbreve;F6D4 +cyrflex;F6D5 +d;0064 +daarmenian;0564 +dabengali;09A6 +dadarabic;0636 +dadeva;0926 +dadfinalarabic;FEBE +dadinitialarabic;FEBF +dadmedialarabic;FEC0 +dagesh;05BC +dageshhebrew;05BC +dagger;2020 +daggerdbl;2021 +dagujarati;0AA6 +dagurmukhi;0A26 +dahiragana;3060 +dakatakana;30C0 +dalarabic;062F +dalet;05D3 +daletdagesh;FB33 +daletdageshhebrew;FB33 +dalethatafpatah;05D3 05B2 +dalethatafpatahhebrew;05D3 05B2 +dalethatafsegol;05D3 05B1 +dalethatafsegolhebrew;05D3 05B1 +dalethebrew;05D3 +dalethiriq;05D3 05B4 +dalethiriqhebrew;05D3 05B4 +daletholam;05D3 05B9 +daletholamhebrew;05D3 05B9 +daletpatah;05D3 05B7 +daletpatahhebrew;05D3 05B7 +daletqamats;05D3 05B8 +daletqamatshebrew;05D3 05B8 +daletqubuts;05D3 05BB +daletqubutshebrew;05D3 05BB +daletsegol;05D3 05B6 +daletsegolhebrew;05D3 05B6 +daletsheva;05D3 05B0 +daletshevahebrew;05D3 05B0 +dalettsere;05D3 05B5 +dalettserehebrew;05D3 05B5 +dalfinalarabic;FEAA +dammaarabic;064F +dammalowarabic;064F +dammatanaltonearabic;064C +dammatanarabic;064C +danda;0964 +dargahebrew;05A7 +dargalefthebrew;05A7 +dasiapneumatacyrilliccmb;0485 +dblGrave;F6D3 +dblanglebracketleft;300A +dblanglebracketleftvertical;FE3D +dblanglebracketright;300B +dblanglebracketrightvertical;FE3E +dblarchinvertedbelowcmb;032B +dblarrowleft;21D4 +dblarrowright;21D2 +dbldanda;0965 +dblgrave;F6D6 +dblgravecmb;030F +dblintegral;222C +dbllowline;2017 +dbllowlinecmb;0333 +dbloverlinecmb;033F +dblprimemod;02BA +dblverticalbar;2016 +dblverticallineabovecmb;030E +dbopomofo;3109 +dbsquare;33C8 +dcaron;010F +dcedilla;1E11 +dcircle;24D3 +dcircumflexbelow;1E13 +dcroat;0111 +ddabengali;09A1 +ddadeva;0921 +ddagujarati;0AA1 +ddagurmukhi;0A21 +ddalarabic;0688 +ddalfinalarabic;FB89 +dddhadeva;095C +ddhabengali;09A2 +ddhadeva;0922 +ddhagujarati;0AA2 +ddhagurmukhi;0A22 +ddotaccent;1E0B +ddotbelow;1E0D +decimalseparatorarabic;066B +decimalseparatorpersian;066B +decyrillic;0434 +degree;00B0 +dehihebrew;05AD +dehiragana;3067 +deicoptic;03EF +dekatakana;30C7 +deleteleft;232B +deleteright;2326 +delta;03B4 +deltaturned;018D +denominatorminusonenumeratorbengali;09F8 +dezh;02A4 +dhabengali;09A7 +dhadeva;0927 +dhagujarati;0AA7 +dhagurmukhi;0A27 +dhook;0257 +dialytikatonos;0385 +dialytikatonoscmb;0344 +diamond;2666 +diamondsuitwhite;2662 +dieresis;00A8 +dieresisacute;F6D7 +dieresisbelowcmb;0324 +dieresiscmb;0308 +dieresisgrave;F6D8 +dieresistonos;0385 +dihiragana;3062 +dikatakana;30C2 +dittomark;3003 +divide;00F7 +divides;2223 +divisionslash;2215 +djecyrillic;0452 +dkshade;2593 +dlinebelow;1E0F +dlsquare;3397 +dmacron;0111 +dmonospace;FF44 +dnblock;2584 +dochadathai;0E0E +dodekthai;0E14 +dohiragana;3069 +dokatakana;30C9 +dollar;0024 +dollarinferior;F6E3 +dollarmonospace;FF04 +dollaroldstyle;F724 +dollarsmall;FE69 +dollarsuperior;F6E4 +dong;20AB +dorusquare;3326 +dotaccent;02D9 +dotaccentcmb;0307 +dotbelowcmb;0323 +dotbelowcomb;0323 +dotkatakana;30FB +dotlessi;0131 +dotlessj;F6BE +dotlessjstrokehook;0284 +dotmath;22C5 +dottedcircle;25CC +doubleyodpatah;FB1F +doubleyodpatahhebrew;FB1F +downtackbelowcmb;031E +downtackmod;02D5 +dparen;249F +dsuperior;F6EB +dtail;0256 +dtopbar;018C +duhiragana;3065 +dukatakana;30C5 +dz;01F3 +dzaltone;02A3 +dzcaron;01C6 +dzcurl;02A5 +dzeabkhasiancyrillic;04E1 +dzecyrillic;0455 +dzhecyrillic;045F +e;0065 +eacute;00E9 +earth;2641 +ebengali;098F +ebopomofo;311C +ebreve;0115 +ecandradeva;090D +ecandragujarati;0A8D +ecandravowelsigndeva;0945 +ecandravowelsigngujarati;0AC5 +ecaron;011B +ecedillabreve;1E1D +echarmenian;0565 +echyiwnarmenian;0587 +ecircle;24D4 +ecircumflex;00EA +ecircumflexacute;1EBF +ecircumflexbelow;1E19 +ecircumflexdotbelow;1EC7 +ecircumflexgrave;1EC1 +ecircumflexhookabove;1EC3 +ecircumflextilde;1EC5 +ecyrillic;0454 +edblgrave;0205 +edeva;090F +edieresis;00EB +edot;0117 +edotaccent;0117 +edotbelow;1EB9 +eegurmukhi;0A0F +eematragurmukhi;0A47 +efcyrillic;0444 +egrave;00E8 +egujarati;0A8F +eharmenian;0567 +ehbopomofo;311D +ehiragana;3048 +ehookabove;1EBB +eibopomofo;311F +eight;0038 +eightarabic;0668 +eightbengali;09EE +eightcircle;2467 +eightcircleinversesansserif;2791 +eightdeva;096E +eighteencircle;2471 +eighteenparen;2485 +eighteenperiod;2499 +eightgujarati;0AEE +eightgurmukhi;0A6E +eighthackarabic;0668 +eighthangzhou;3028 +eighthnotebeamed;266B +eightideographicparen;3227 +eightinferior;2088 +eightmonospace;FF18 +eightoldstyle;F738 +eightparen;247B +eightperiod;248F +eightpersian;06F8 +eightroman;2177 +eightsuperior;2078 +eightthai;0E58 +einvertedbreve;0207 +eiotifiedcyrillic;0465 +ekatakana;30A8 +ekatakanahalfwidth;FF74 +ekonkargurmukhi;0A74 +ekorean;3154 +elcyrillic;043B +element;2208 +elevencircle;246A +elevenparen;247E +elevenperiod;2492 +elevenroman;217A +ellipsis;2026 +ellipsisvertical;22EE +emacron;0113 +emacronacute;1E17 +emacrongrave;1E15 +emcyrillic;043C +emdash;2014 +emdashvertical;FE31 +emonospace;FF45 +emphasismarkarmenian;055B +emptyset;2205 +enbopomofo;3123 +encyrillic;043D +endash;2013 +endashvertical;FE32 +endescendercyrillic;04A3 +eng;014B +engbopomofo;3125 +enghecyrillic;04A5 +enhookcyrillic;04C8 +enspace;2002 +eogonek;0119 +eokorean;3153 +eopen;025B +eopenclosed;029A +eopenreversed;025C +eopenreversedclosed;025E +eopenreversedhook;025D +eparen;24A0 +epsilon;03B5 +epsilontonos;03AD +equal;003D +equalmonospace;FF1D +equalsmall;FE66 +equalsuperior;207C +equivalence;2261 +erbopomofo;3126 +ercyrillic;0440 +ereversed;0258 +ereversedcyrillic;044D +escyrillic;0441 +esdescendercyrillic;04AB +esh;0283 +eshcurl;0286 +eshortdeva;090E +eshortvowelsigndeva;0946 +eshreversedloop;01AA +eshsquatreversed;0285 +esmallhiragana;3047 +esmallkatakana;30A7 +esmallkatakanahalfwidth;FF6A +estimated;212E +esuperior;F6EC +eta;03B7 +etarmenian;0568 +etatonos;03AE +eth;00F0 +etilde;1EBD +etildebelow;1E1B +etnahtafoukhhebrew;0591 +etnahtafoukhlefthebrew;0591 +etnahtahebrew;0591 +etnahtalefthebrew;0591 +eturned;01DD +eukorean;3161 +euro;20AC +evowelsignbengali;09C7 +evowelsigndeva;0947 +evowelsigngujarati;0AC7 +exclam;0021 +exclamarmenian;055C +exclamdbl;203C +exclamdown;00A1 +exclamdownsmall;F7A1 +exclammonospace;FF01 +exclamsmall;F721 +existential;2203 +ezh;0292 +ezhcaron;01EF +ezhcurl;0293 +ezhreversed;01B9 +ezhtail;01BA +f;0066 +fadeva;095E +fagurmukhi;0A5E +fahrenheit;2109 +fathaarabic;064E +fathalowarabic;064E +fathatanarabic;064B +fbopomofo;3108 +fcircle;24D5 +fdotaccent;1E1F +feharabic;0641 +feharmenian;0586 +fehfinalarabic;FED2 +fehinitialarabic;FED3 +fehmedialarabic;FED4 +feicoptic;03E5 +female;2640 +ff;FB00 +ffi;FB03 +ffl;FB04 +fi;FB01 +fifteencircle;246E +fifteenparen;2482 +fifteenperiod;2496 +figuredash;2012 +filledbox;25A0 +filledrect;25AC +finalkaf;05DA +finalkafdagesh;FB3A +finalkafdageshhebrew;FB3A +finalkafhebrew;05DA +finalkafqamats;05DA 05B8 +finalkafqamatshebrew;05DA 05B8 +finalkafsheva;05DA 05B0 +finalkafshevahebrew;05DA 05B0 +finalmem;05DD +finalmemhebrew;05DD +finalnun;05DF +finalnunhebrew;05DF +finalpe;05E3 +finalpehebrew;05E3 +finaltsadi;05E5 +finaltsadihebrew;05E5 +firsttonechinese;02C9 +fisheye;25C9 +fitacyrillic;0473 +five;0035 +fivearabic;0665 +fivebengali;09EB +fivecircle;2464 +fivecircleinversesansserif;278E +fivedeva;096B +fiveeighths;215D +fivegujarati;0AEB +fivegurmukhi;0A6B +fivehackarabic;0665 +fivehangzhou;3025 +fiveideographicparen;3224 +fiveinferior;2085 +fivemonospace;FF15 +fiveoldstyle;F735 +fiveparen;2478 +fiveperiod;248C +fivepersian;06F5 +fiveroman;2174 +fivesuperior;2075 +fivethai;0E55 +fl;FB02 +florin;0192 +fmonospace;FF46 +fmsquare;3399 +fofanthai;0E1F +fofathai;0E1D +fongmanthai;0E4F +forall;2200 +four;0034 +fourarabic;0664 +fourbengali;09EA +fourcircle;2463 +fourcircleinversesansserif;278D +fourdeva;096A +fourgujarati;0AEA +fourgurmukhi;0A6A +fourhackarabic;0664 +fourhangzhou;3024 +fourideographicparen;3223 +fourinferior;2084 +fourmonospace;FF14 +fournumeratorbengali;09F7 +fouroldstyle;F734 +fourparen;2477 +fourperiod;248B +fourpersian;06F4 +fourroman;2173 +foursuperior;2074 +fourteencircle;246D +fourteenparen;2481 +fourteenperiod;2495 +fourthai;0E54 +fourthtonechinese;02CB +fparen;24A1 +fraction;2044 +franc;20A3 +g;0067 +gabengali;0997 +gacute;01F5 +gadeva;0917 +gafarabic;06AF +gaffinalarabic;FB93 +gafinitialarabic;FB94 +gafmedialarabic;FB95 +gagujarati;0A97 +gagurmukhi;0A17 +gahiragana;304C +gakatakana;30AC +gamma;03B3 +gammalatinsmall;0263 +gammasuperior;02E0 +gangiacoptic;03EB +gbopomofo;310D +gbreve;011F +gcaron;01E7 +gcedilla;0123 +gcircle;24D6 +gcircumflex;011D +gcommaaccent;0123 +gdot;0121 +gdotaccent;0121 +gecyrillic;0433 +gehiragana;3052 +gekatakana;30B2 +geometricallyequal;2251 +gereshaccenthebrew;059C +gereshhebrew;05F3 +gereshmuqdamhebrew;059D +germandbls;00DF +gershayimaccenthebrew;059E +gershayimhebrew;05F4 +getamark;3013 +ghabengali;0998 +ghadarmenian;0572 +ghadeva;0918 +ghagujarati;0A98 +ghagurmukhi;0A18 +ghainarabic;063A +ghainfinalarabic;FECE +ghaininitialarabic;FECF +ghainmedialarabic;FED0 +ghemiddlehookcyrillic;0495 +ghestrokecyrillic;0493 +gheupturncyrillic;0491 +ghhadeva;095A +ghhagurmukhi;0A5A +ghook;0260 +ghzsquare;3393 +gihiragana;304E +gikatakana;30AE +gimarmenian;0563 +gimel;05D2 +gimeldagesh;FB32 +gimeldageshhebrew;FB32 +gimelhebrew;05D2 +gjecyrillic;0453 +glottalinvertedstroke;01BE +glottalstop;0294 +glottalstopinverted;0296 +glottalstopmod;02C0 +glottalstopreversed;0295 +glottalstopreversedmod;02C1 +glottalstopreversedsuperior;02E4 +glottalstopstroke;02A1 +glottalstopstrokereversed;02A2 +gmacron;1E21 +gmonospace;FF47 +gohiragana;3054 +gokatakana;30B4 +gparen;24A2 +gpasquare;33AC +gradient;2207 +grave;0060 +gravebelowcmb;0316 +gravecmb;0300 +gravecomb;0300 +gravedeva;0953 +gravelowmod;02CE +gravemonospace;FF40 +gravetonecmb;0340 +greater;003E +greaterequal;2265 +greaterequalorless;22DB +greatermonospace;FF1E +greaterorequivalent;2273 +greaterorless;2277 +greateroverequal;2267 +greatersmall;FE65 +gscript;0261 +gstroke;01E5 +guhiragana;3050 +guillemotleft;00AB +guillemotright;00BB +guilsinglleft;2039 +guilsinglright;203A +gukatakana;30B0 +guramusquare;3318 +gysquare;33C9 +h;0068 +haabkhasiancyrillic;04A9 +haaltonearabic;06C1 +habengali;09B9 +hadescendercyrillic;04B3 +hadeva;0939 +hagujarati;0AB9 +hagurmukhi;0A39 +haharabic;062D +hahfinalarabic;FEA2 +hahinitialarabic;FEA3 +hahiragana;306F +hahmedialarabic;FEA4 +haitusquare;332A +hakatakana;30CF +hakatakanahalfwidth;FF8A +halantgurmukhi;0A4D +hamzaarabic;0621 +hamzadammaarabic;0621 064F +hamzadammatanarabic;0621 064C +hamzafathaarabic;0621 064E +hamzafathatanarabic;0621 064B +hamzalowarabic;0621 +hamzalowkasraarabic;0621 0650 +hamzalowkasratanarabic;0621 064D +hamzasukunarabic;0621 0652 +hangulfiller;3164 +hardsigncyrillic;044A +harpoonleftbarbup;21BC +harpoonrightbarbup;21C0 +hasquare;33CA +hatafpatah;05B2 +hatafpatah16;05B2 +hatafpatah23;05B2 +hatafpatah2f;05B2 +hatafpatahhebrew;05B2 +hatafpatahnarrowhebrew;05B2 +hatafpatahquarterhebrew;05B2 +hatafpatahwidehebrew;05B2 +hatafqamats;05B3 +hatafqamats1b;05B3 +hatafqamats28;05B3 +hatafqamats34;05B3 +hatafqamatshebrew;05B3 +hatafqamatsnarrowhebrew;05B3 +hatafqamatsquarterhebrew;05B3 +hatafqamatswidehebrew;05B3 +hatafsegol;05B1 +hatafsegol17;05B1 +hatafsegol24;05B1 +hatafsegol30;05B1 +hatafsegolhebrew;05B1 +hatafsegolnarrowhebrew;05B1 +hatafsegolquarterhebrew;05B1 +hatafsegolwidehebrew;05B1 +hbar;0127 +hbopomofo;310F +hbrevebelow;1E2B +hcedilla;1E29 +hcircle;24D7 +hcircumflex;0125 +hdieresis;1E27 +hdotaccent;1E23 +hdotbelow;1E25 +he;05D4 +heart;2665 +heartsuitblack;2665 +heartsuitwhite;2661 +hedagesh;FB34 +hedageshhebrew;FB34 +hehaltonearabic;06C1 +heharabic;0647 +hehebrew;05D4 +hehfinalaltonearabic;FBA7 +hehfinalalttwoarabic;FEEA +hehfinalarabic;FEEA +hehhamzaabovefinalarabic;FBA5 +hehhamzaaboveisolatedarabic;FBA4 +hehinitialaltonearabic;FBA8 +hehinitialarabic;FEEB +hehiragana;3078 +hehmedialaltonearabic;FBA9 +hehmedialarabic;FEEC +heiseierasquare;337B +hekatakana;30D8 +hekatakanahalfwidth;FF8D +hekutaarusquare;3336 +henghook;0267 +herutusquare;3339 +het;05D7 +hethebrew;05D7 +hhook;0266 +hhooksuperior;02B1 +hieuhacirclekorean;327B +hieuhaparenkorean;321B +hieuhcirclekorean;326D +hieuhkorean;314E +hieuhparenkorean;320D +hihiragana;3072 +hikatakana;30D2 +hikatakanahalfwidth;FF8B +hiriq;05B4 +hiriq14;05B4 +hiriq21;05B4 +hiriq2d;05B4 +hiriqhebrew;05B4 +hiriqnarrowhebrew;05B4 +hiriqquarterhebrew;05B4 +hiriqwidehebrew;05B4 +hlinebelow;1E96 +hmonospace;FF48 +hoarmenian;0570 +hohipthai;0E2B +hohiragana;307B +hokatakana;30DB +hokatakanahalfwidth;FF8E +holam;05B9 +holam19;05B9 +holam26;05B9 +holam32;05B9 +holamhebrew;05B9 +holamnarrowhebrew;05B9 +holamquarterhebrew;05B9 +holamwidehebrew;05B9 +honokhukthai;0E2E +hookabovecomb;0309 +hookcmb;0309 +hookpalatalizedbelowcmb;0321 +hookretroflexbelowcmb;0322 +hoonsquare;3342 +horicoptic;03E9 +horizontalbar;2015 +horncmb;031B +hotsprings;2668 +house;2302 +hparen;24A3 +hsuperior;02B0 +hturned;0265 +huhiragana;3075 +huiitosquare;3333 +hukatakana;30D5 +hukatakanahalfwidth;FF8C +hungarumlaut;02DD +hungarumlautcmb;030B +hv;0195 +hyphen;002D +hypheninferior;F6E5 +hyphenmonospace;FF0D +hyphensmall;FE63 +hyphensuperior;F6E6 +hyphentwo;2010 +i;0069 +iacute;00ED +iacyrillic;044F +ibengali;0987 +ibopomofo;3127 +ibreve;012D +icaron;01D0 +icircle;24D8 +icircumflex;00EE +icyrillic;0456 +idblgrave;0209 +ideographearthcircle;328F +ideographfirecircle;328B +ideographicallianceparen;323F +ideographiccallparen;323A +ideographiccentrecircle;32A5 +ideographicclose;3006 +ideographiccomma;3001 +ideographiccommaleft;FF64 +ideographiccongratulationparen;3237 +ideographiccorrectcircle;32A3 +ideographicearthparen;322F +ideographicenterpriseparen;323D +ideographicexcellentcircle;329D +ideographicfestivalparen;3240 +ideographicfinancialcircle;3296 +ideographicfinancialparen;3236 +ideographicfireparen;322B +ideographichaveparen;3232 +ideographichighcircle;32A4 +ideographiciterationmark;3005 +ideographiclaborcircle;3298 +ideographiclaborparen;3238 +ideographicleftcircle;32A7 +ideographiclowcircle;32A6 +ideographicmedicinecircle;32A9 +ideographicmetalparen;322E +ideographicmoonparen;322A +ideographicnameparen;3234 +ideographicperiod;3002 +ideographicprintcircle;329E +ideographicreachparen;3243 +ideographicrepresentparen;3239 +ideographicresourceparen;323E +ideographicrightcircle;32A8 +ideographicsecretcircle;3299 +ideographicselfparen;3242 +ideographicsocietyparen;3233 +ideographicspace;3000 +ideographicspecialparen;3235 +ideographicstockparen;3231 +ideographicstudyparen;323B +ideographicsunparen;3230 +ideographicsuperviseparen;323C +ideographicwaterparen;322C +ideographicwoodparen;322D +ideographiczero;3007 +ideographmetalcircle;328E +ideographmooncircle;328A +ideographnamecircle;3294 +ideographsuncircle;3290 +ideographwatercircle;328C +ideographwoodcircle;328D +ideva;0907 +idieresis;00EF +idieresisacute;1E2F +idieresiscyrillic;04E5 +idotbelow;1ECB +iebrevecyrillic;04D7 +iecyrillic;0435 +ieungacirclekorean;3275 +ieungaparenkorean;3215 +ieungcirclekorean;3267 +ieungkorean;3147 +ieungparenkorean;3207 +igrave;00EC +igujarati;0A87 +igurmukhi;0A07 +ihiragana;3044 +ihookabove;1EC9 +iibengali;0988 +iicyrillic;0438 +iideva;0908 +iigujarati;0A88 +iigurmukhi;0A08 +iimatragurmukhi;0A40 +iinvertedbreve;020B +iishortcyrillic;0439 +iivowelsignbengali;09C0 +iivowelsigndeva;0940 +iivowelsigngujarati;0AC0 +ij;0133 +ikatakana;30A4 +ikatakanahalfwidth;FF72 +ikorean;3163 +ilde;02DC +iluyhebrew;05AC +imacron;012B +imacroncyrillic;04E3 +imageorapproximatelyequal;2253 +imatragurmukhi;0A3F +imonospace;FF49 +increment;2206 +infinity;221E +iniarmenian;056B +integral;222B +integralbottom;2321 +integralbt;2321 +integralex;F8F5 +integraltop;2320 +integraltp;2320 +intersection;2229 +intisquare;3305 +invbullet;25D8 +invcircle;25D9 +invsmileface;263B +iocyrillic;0451 +iogonek;012F +iota;03B9 +iotadieresis;03CA +iotadieresistonos;0390 +iotalatin;0269 +iotatonos;03AF +iparen;24A4 +irigurmukhi;0A72 +ismallhiragana;3043 +ismallkatakana;30A3 +ismallkatakanahalfwidth;FF68 +issharbengali;09FA +istroke;0268 +isuperior;F6ED +iterationhiragana;309D +iterationkatakana;30FD +itilde;0129 +itildebelow;1E2D +iubopomofo;3129 +iucyrillic;044E +ivowelsignbengali;09BF +ivowelsigndeva;093F +ivowelsigngujarati;0ABF +izhitsacyrillic;0475 +izhitsadblgravecyrillic;0477 +j;006A +jaarmenian;0571 +jabengali;099C +jadeva;091C +jagujarati;0A9C +jagurmukhi;0A1C +jbopomofo;3110 +jcaron;01F0 +jcircle;24D9 +jcircumflex;0135 +jcrossedtail;029D +jdotlessstroke;025F +jecyrillic;0458 +jeemarabic;062C +jeemfinalarabic;FE9E +jeeminitialarabic;FE9F +jeemmedialarabic;FEA0 +jeharabic;0698 +jehfinalarabic;FB8B +jhabengali;099D +jhadeva;091D +jhagujarati;0A9D +jhagurmukhi;0A1D +jheharmenian;057B +jis;3004 +jmonospace;FF4A +jparen;24A5 +jsuperior;02B2 +k;006B +kabashkircyrillic;04A1 +kabengali;0995 +kacute;1E31 +kacyrillic;043A +kadescendercyrillic;049B +kadeva;0915 +kaf;05DB +kafarabic;0643 +kafdagesh;FB3B +kafdageshhebrew;FB3B +kaffinalarabic;FEDA +kafhebrew;05DB +kafinitialarabic;FEDB +kafmedialarabic;FEDC +kafrafehebrew;FB4D +kagujarati;0A95 +kagurmukhi;0A15 +kahiragana;304B +kahookcyrillic;04C4 +kakatakana;30AB +kakatakanahalfwidth;FF76 +kappa;03BA +kappasymbolgreek;03F0 +kapyeounmieumkorean;3171 +kapyeounphieuphkorean;3184 +kapyeounpieupkorean;3178 +kapyeounssangpieupkorean;3179 +karoriisquare;330D +kashidaautoarabic;0640 +kashidaautonosidebearingarabic;0640 +kasmallkatakana;30F5 +kasquare;3384 +kasraarabic;0650 +kasratanarabic;064D +kastrokecyrillic;049F +katahiraprolongmarkhalfwidth;FF70 +kaverticalstrokecyrillic;049D +kbopomofo;310E +kcalsquare;3389 +kcaron;01E9 +kcedilla;0137 +kcircle;24DA +kcommaaccent;0137 +kdotbelow;1E33 +keharmenian;0584 +kehiragana;3051 +kekatakana;30B1 +kekatakanahalfwidth;FF79 +kenarmenian;056F +kesmallkatakana;30F6 +kgreenlandic;0138 +khabengali;0996 +khacyrillic;0445 +khadeva;0916 +khagujarati;0A96 +khagurmukhi;0A16 +khaharabic;062E +khahfinalarabic;FEA6 +khahinitialarabic;FEA7 +khahmedialarabic;FEA8 +kheicoptic;03E7 +khhadeva;0959 +khhagurmukhi;0A59 +khieukhacirclekorean;3278 +khieukhaparenkorean;3218 +khieukhcirclekorean;326A +khieukhkorean;314B +khieukhparenkorean;320A +khokhaithai;0E02 +khokhonthai;0E05 +khokhuatthai;0E03 +khokhwaithai;0E04 +khomutthai;0E5B +khook;0199 +khorakhangthai;0E06 +khzsquare;3391 +kihiragana;304D +kikatakana;30AD +kikatakanahalfwidth;FF77 +kiroguramusquare;3315 +kiromeetorusquare;3316 +kirosquare;3314 +kiyeokacirclekorean;326E +kiyeokaparenkorean;320E +kiyeokcirclekorean;3260 +kiyeokkorean;3131 +kiyeokparenkorean;3200 +kiyeoksioskorean;3133 +kjecyrillic;045C +klinebelow;1E35 +klsquare;3398 +kmcubedsquare;33A6 +kmonospace;FF4B +kmsquaredsquare;33A2 +kohiragana;3053 +kohmsquare;33C0 +kokaithai;0E01 +kokatakana;30B3 +kokatakanahalfwidth;FF7A +kooposquare;331E +koppacyrillic;0481 +koreanstandardsymbol;327F +koroniscmb;0343 +kparen;24A6 +kpasquare;33AA +ksicyrillic;046F +ktsquare;33CF +kturned;029E +kuhiragana;304F +kukatakana;30AF +kukatakanahalfwidth;FF78 +kvsquare;33B8 +kwsquare;33BE +l;006C +labengali;09B2 +lacute;013A +ladeva;0932 +lagujarati;0AB2 +lagurmukhi;0A32 +lakkhangyaothai;0E45 +lamaleffinalarabic;FEFC +lamalefhamzaabovefinalarabic;FEF8 +lamalefhamzaaboveisolatedarabic;FEF7 +lamalefhamzabelowfinalarabic;FEFA +lamalefhamzabelowisolatedarabic;FEF9 +lamalefisolatedarabic;FEFB +lamalefmaddaabovefinalarabic;FEF6 +lamalefmaddaaboveisolatedarabic;FEF5 +lamarabic;0644 +lambda;03BB +lambdastroke;019B +lamed;05DC +lameddagesh;FB3C +lameddageshhebrew;FB3C +lamedhebrew;05DC +lamedholam;05DC 05B9 +lamedholamdagesh;05DC 05B9 05BC +lamedholamdageshhebrew;05DC 05B9 05BC +lamedholamhebrew;05DC 05B9 +lamfinalarabic;FEDE +lamhahinitialarabic;FCCA +laminitialarabic;FEDF +lamjeeminitialarabic;FCC9 +lamkhahinitialarabic;FCCB +lamlamhehisolatedarabic;FDF2 +lammedialarabic;FEE0 +lammeemhahinitialarabic;FD88 +lammeeminitialarabic;FCCC +lammeemjeeminitialarabic;FEDF FEE4 FEA0 +lammeemkhahinitialarabic;FEDF FEE4 FEA8 +largecircle;25EF +lbar;019A +lbelt;026C +lbopomofo;310C +lcaron;013E +lcedilla;013C +lcircle;24DB +lcircumflexbelow;1E3D +lcommaaccent;013C +ldot;0140 +ldotaccent;0140 +ldotbelow;1E37 +ldotbelowmacron;1E39 +leftangleabovecmb;031A +lefttackbelowcmb;0318 +less;003C +lessequal;2264 +lessequalorgreater;22DA +lessmonospace;FF1C +lessorequivalent;2272 +lessorgreater;2276 +lessoverequal;2266 +lesssmall;FE64 +lezh;026E +lfblock;258C +lhookretroflex;026D +lira;20A4 +liwnarmenian;056C +lj;01C9 +ljecyrillic;0459 +ll;F6C0 +lladeva;0933 +llagujarati;0AB3 +llinebelow;1E3B +llladeva;0934 +llvocalicbengali;09E1 +llvocalicdeva;0961 +llvocalicvowelsignbengali;09E3 +llvocalicvowelsigndeva;0963 +lmiddletilde;026B +lmonospace;FF4C +lmsquare;33D0 +lochulathai;0E2C +logicaland;2227 +logicalnot;00AC +logicalnotreversed;2310 +logicalor;2228 +lolingthai;0E25 +longs;017F +lowlinecenterline;FE4E +lowlinecmb;0332 +lowlinedashed;FE4D +lozenge;25CA +lparen;24A7 +lslash;0142 +lsquare;2113 +lsuperior;F6EE +ltshade;2591 +luthai;0E26 +lvocalicbengali;098C +lvocalicdeva;090C +lvocalicvowelsignbengali;09E2 +lvocalicvowelsigndeva;0962 +lxsquare;33D3 +m;006D +mabengali;09AE +macron;00AF +macronbelowcmb;0331 +macroncmb;0304 +macronlowmod;02CD +macronmonospace;FFE3 +macute;1E3F +madeva;092E +magujarati;0AAE +magurmukhi;0A2E +mahapakhhebrew;05A4 +mahapakhlefthebrew;05A4 +mahiragana;307E +maichattawalowleftthai;F895 +maichattawalowrightthai;F894 +maichattawathai;0E4B +maichattawaupperleftthai;F893 +maieklowleftthai;F88C +maieklowrightthai;F88B +maiekthai;0E48 +maiekupperleftthai;F88A +maihanakatleftthai;F884 +maihanakatthai;0E31 +maitaikhuleftthai;F889 +maitaikhuthai;0E47 +maitholowleftthai;F88F +maitholowrightthai;F88E +maithothai;0E49 +maithoupperleftthai;F88D +maitrilowleftthai;F892 +maitrilowrightthai;F891 +maitrithai;0E4A +maitriupperleftthai;F890 +maiyamokthai;0E46 +makatakana;30DE +makatakanahalfwidth;FF8F +male;2642 +mansyonsquare;3347 +maqafhebrew;05BE +mars;2642 +masoracirclehebrew;05AF +masquare;3383 +mbopomofo;3107 +mbsquare;33D4 +mcircle;24DC +mcubedsquare;33A5 +mdotaccent;1E41 +mdotbelow;1E43 +meemarabic;0645 +meemfinalarabic;FEE2 +meeminitialarabic;FEE3 +meemmedialarabic;FEE4 +meemmeeminitialarabic;FCD1 +meemmeemisolatedarabic;FC48 +meetorusquare;334D +mehiragana;3081 +meizierasquare;337E +mekatakana;30E1 +mekatakanahalfwidth;FF92 +mem;05DE +memdagesh;FB3E +memdageshhebrew;FB3E +memhebrew;05DE +menarmenian;0574 +merkhahebrew;05A5 +merkhakefulahebrew;05A6 +merkhakefulalefthebrew;05A6 +merkhalefthebrew;05A5 +mhook;0271 +mhzsquare;3392 +middledotkatakanahalfwidth;FF65 +middot;00B7 +mieumacirclekorean;3272 +mieumaparenkorean;3212 +mieumcirclekorean;3264 +mieumkorean;3141 +mieumpansioskorean;3170 +mieumparenkorean;3204 +mieumpieupkorean;316E +mieumsioskorean;316F +mihiragana;307F +mikatakana;30DF +mikatakanahalfwidth;FF90 +minus;2212 +minusbelowcmb;0320 +minuscircle;2296 +minusmod;02D7 +minusplus;2213 +minute;2032 +miribaarusquare;334A +mirisquare;3349 +mlonglegturned;0270 +mlsquare;3396 +mmcubedsquare;33A3 +mmonospace;FF4D +mmsquaredsquare;339F +mohiragana;3082 +mohmsquare;33C1 +mokatakana;30E2 +mokatakanahalfwidth;FF93 +molsquare;33D6 +momathai;0E21 +moverssquare;33A7 +moverssquaredsquare;33A8 +mparen;24A8 +mpasquare;33AB +mssquare;33B3 +msuperior;F6EF +mturned;026F +mu;00B5 +mu1;00B5 +muasquare;3382 +muchgreater;226B +muchless;226A +mufsquare;338C +mugreek;03BC +mugsquare;338D +muhiragana;3080 +mukatakana;30E0 +mukatakanahalfwidth;FF91 +mulsquare;3395 +multiply;00D7 +mumsquare;339B +munahhebrew;05A3 +munahlefthebrew;05A3 +musicalnote;266A +musicalnotedbl;266B +musicflatsign;266D +musicsharpsign;266F +mussquare;33B2 +muvsquare;33B6 +muwsquare;33BC +mvmegasquare;33B9 +mvsquare;33B7 +mwmegasquare;33BF +mwsquare;33BD +n;006E +nabengali;09A8 +nabla;2207 +nacute;0144 +nadeva;0928 +nagujarati;0AA8 +nagurmukhi;0A28 +nahiragana;306A +nakatakana;30CA +nakatakanahalfwidth;FF85 +napostrophe;0149 +nasquare;3381 +nbopomofo;310B +nbspace;00A0 +ncaron;0148 +ncedilla;0146 +ncircle;24DD +ncircumflexbelow;1E4B +ncommaaccent;0146 +ndotaccent;1E45 +ndotbelow;1E47 +nehiragana;306D +nekatakana;30CD +nekatakanahalfwidth;FF88 +newsheqelsign;20AA +nfsquare;338B +ngabengali;0999 +ngadeva;0919 +ngagujarati;0A99 +ngagurmukhi;0A19 +ngonguthai;0E07 +nhiragana;3093 +nhookleft;0272 +nhookretroflex;0273 +nieunacirclekorean;326F +nieunaparenkorean;320F +nieuncieuckorean;3135 +nieuncirclekorean;3261 +nieunhieuhkorean;3136 +nieunkorean;3134 +nieunpansioskorean;3168 +nieunparenkorean;3201 +nieunsioskorean;3167 +nieuntikeutkorean;3166 +nihiragana;306B +nikatakana;30CB +nikatakanahalfwidth;FF86 +nikhahitleftthai;F899 +nikhahitthai;0E4D +nine;0039 +ninearabic;0669 +ninebengali;09EF +ninecircle;2468 +ninecircleinversesansserif;2792 +ninedeva;096F +ninegujarati;0AEF +ninegurmukhi;0A6F +ninehackarabic;0669 +ninehangzhou;3029 +nineideographicparen;3228 +nineinferior;2089 +ninemonospace;FF19 +nineoldstyle;F739 +nineparen;247C +nineperiod;2490 +ninepersian;06F9 +nineroman;2178 +ninesuperior;2079 +nineteencircle;2472 +nineteenparen;2486 +nineteenperiod;249A +ninethai;0E59 +nj;01CC +njecyrillic;045A +nkatakana;30F3 +nkatakanahalfwidth;FF9D +nlegrightlong;019E +nlinebelow;1E49 +nmonospace;FF4E +nmsquare;339A +nnabengali;09A3 +nnadeva;0923 +nnagujarati;0AA3 +nnagurmukhi;0A23 +nnnadeva;0929 +nohiragana;306E +nokatakana;30CE +nokatakanahalfwidth;FF89 +nonbreakingspace;00A0 +nonenthai;0E13 +nonuthai;0E19 +noonarabic;0646 +noonfinalarabic;FEE6 +noonghunnaarabic;06BA +noonghunnafinalarabic;FB9F +noonhehinitialarabic;FEE7 FEEC +nooninitialarabic;FEE7 +noonjeeminitialarabic;FCD2 +noonjeemisolatedarabic;FC4B +noonmedialarabic;FEE8 +noonmeeminitialarabic;FCD5 +noonmeemisolatedarabic;FC4E +noonnoonfinalarabic;FC8D +notcontains;220C +notelement;2209 +notelementof;2209 +notequal;2260 +notgreater;226F +notgreaternorequal;2271 +notgreaternorless;2279 +notidentical;2262 +notless;226E +notlessnorequal;2270 +notparallel;2226 +notprecedes;2280 +notsubset;2284 +notsucceeds;2281 +notsuperset;2285 +nowarmenian;0576 +nparen;24A9 +nssquare;33B1 +nsuperior;207F +ntilde;00F1 +nu;03BD +nuhiragana;306C +nukatakana;30CC +nukatakanahalfwidth;FF87 +nuktabengali;09BC +nuktadeva;093C +nuktagujarati;0ABC +nuktagurmukhi;0A3C +numbersign;0023 +numbersignmonospace;FF03 +numbersignsmall;FE5F +numeralsigngreek;0374 +numeralsignlowergreek;0375 +numero;2116 +nun;05E0 +nundagesh;FB40 +nundageshhebrew;FB40 +nunhebrew;05E0 +nvsquare;33B5 +nwsquare;33BB +nyabengali;099E +nyadeva;091E +nyagujarati;0A9E +nyagurmukhi;0A1E +o;006F +oacute;00F3 +oangthai;0E2D +obarred;0275 +obarredcyrillic;04E9 +obarreddieresiscyrillic;04EB +obengali;0993 +obopomofo;311B +obreve;014F +ocandradeva;0911 +ocandragujarati;0A91 +ocandravowelsigndeva;0949 +ocandravowelsigngujarati;0AC9 +ocaron;01D2 +ocircle;24DE +ocircumflex;00F4 +ocircumflexacute;1ED1 +ocircumflexdotbelow;1ED9 +ocircumflexgrave;1ED3 +ocircumflexhookabove;1ED5 +ocircumflextilde;1ED7 +ocyrillic;043E +odblacute;0151 +odblgrave;020D +odeva;0913 +odieresis;00F6 +odieresiscyrillic;04E7 +odotbelow;1ECD +oe;0153 +oekorean;315A +ogonek;02DB +ogonekcmb;0328 +ograve;00F2 +ogujarati;0A93 +oharmenian;0585 +ohiragana;304A +ohookabove;1ECF +ohorn;01A1 +ohornacute;1EDB +ohorndotbelow;1EE3 +ohorngrave;1EDD +ohornhookabove;1EDF +ohorntilde;1EE1 +ohungarumlaut;0151 +oi;01A3 +oinvertedbreve;020F +okatakana;30AA +okatakanahalfwidth;FF75 +okorean;3157 +olehebrew;05AB +omacron;014D +omacronacute;1E53 +omacrongrave;1E51 +omdeva;0950 +omega;03C9 +omega1;03D6 +omegacyrillic;0461 +omegalatinclosed;0277 +omegaroundcyrillic;047B +omegatitlocyrillic;047D +omegatonos;03CE +omgujarati;0AD0 +omicron;03BF +omicrontonos;03CC +omonospace;FF4F +one;0031 +onearabic;0661 +onebengali;09E7 +onecircle;2460 +onecircleinversesansserif;278A +onedeva;0967 +onedotenleader;2024 +oneeighth;215B +onefitted;F6DC +onegujarati;0AE7 +onegurmukhi;0A67 +onehackarabic;0661 +onehalf;00BD +onehangzhou;3021 +oneideographicparen;3220 +oneinferior;2081 +onemonospace;FF11 +onenumeratorbengali;09F4 +oneoldstyle;F731 +oneparen;2474 +oneperiod;2488 +onepersian;06F1 +onequarter;00BC +oneroman;2170 +onesuperior;00B9 +onethai;0E51 +onethird;2153 +oogonek;01EB +oogonekmacron;01ED +oogurmukhi;0A13 +oomatragurmukhi;0A4B +oopen;0254 +oparen;24AA +openbullet;25E6 +option;2325 +ordfeminine;00AA +ordmasculine;00BA +orthogonal;221F +oshortdeva;0912 +oshortvowelsigndeva;094A +oslash;00F8 +oslashacute;01FF +osmallhiragana;3049 +osmallkatakana;30A9 +osmallkatakanahalfwidth;FF6B +ostrokeacute;01FF +osuperior;F6F0 +otcyrillic;047F +otilde;00F5 +otildeacute;1E4D +otildedieresis;1E4F +oubopomofo;3121 +overline;203E +overlinecenterline;FE4A +overlinecmb;0305 +overlinedashed;FE49 +overlinedblwavy;FE4C +overlinewavy;FE4B +overscore;00AF +ovowelsignbengali;09CB +ovowelsigndeva;094B +ovowelsigngujarati;0ACB +p;0070 +paampssquare;3380 +paasentosquare;332B +pabengali;09AA +pacute;1E55 +padeva;092A +pagedown;21DF +pageup;21DE +pagujarati;0AAA +pagurmukhi;0A2A +pahiragana;3071 +paiyannoithai;0E2F +pakatakana;30D1 +palatalizationcyrilliccmb;0484 +palochkacyrillic;04C0 +pansioskorean;317F +paragraph;00B6 +parallel;2225 +parenleft;0028 +parenleftaltonearabic;FD3E +parenleftbt;F8ED +parenleftex;F8EC +parenleftinferior;208D +parenleftmonospace;FF08 +parenleftsmall;FE59 +parenleftsuperior;207D +parenlefttp;F8EB +parenleftvertical;FE35 +parenright;0029 +parenrightaltonearabic;FD3F +parenrightbt;F8F8 +parenrightex;F8F7 +parenrightinferior;208E +parenrightmonospace;FF09 +parenrightsmall;FE5A +parenrightsuperior;207E +parenrighttp;F8F6 +parenrightvertical;FE36 +partialdiff;2202 +paseqhebrew;05C0 +pashtahebrew;0599 +pasquare;33A9 +patah;05B7 +patah11;05B7 +patah1d;05B7 +patah2a;05B7 +patahhebrew;05B7 +patahnarrowhebrew;05B7 +patahquarterhebrew;05B7 +patahwidehebrew;05B7 +pazerhebrew;05A1 +pbopomofo;3106 +pcircle;24DF +pdotaccent;1E57 +pe;05E4 +pecyrillic;043F +pedagesh;FB44 +pedageshhebrew;FB44 +peezisquare;333B +pefinaldageshhebrew;FB43 +peharabic;067E +peharmenian;057A +pehebrew;05E4 +pehfinalarabic;FB57 +pehinitialarabic;FB58 +pehiragana;307A +pehmedialarabic;FB59 +pekatakana;30DA +pemiddlehookcyrillic;04A7 +perafehebrew;FB4E +percent;0025 +percentarabic;066A +percentmonospace;FF05 +percentsmall;FE6A +period;002E +periodarmenian;0589 +periodcentered;00B7 +periodhalfwidth;FF61 +periodinferior;F6E7 +periodmonospace;FF0E +periodsmall;FE52 +periodsuperior;F6E8 +perispomenigreekcmb;0342 +perpendicular;22A5 +perthousand;2030 +peseta;20A7 +pfsquare;338A +phabengali;09AB +phadeva;092B +phagujarati;0AAB +phagurmukhi;0A2B +phi;03C6 +phi1;03D5 +phieuphacirclekorean;327A +phieuphaparenkorean;321A +phieuphcirclekorean;326C +phieuphkorean;314D +phieuphparenkorean;320C +philatin;0278 +phinthuthai;0E3A +phisymbolgreek;03D5 +phook;01A5 +phophanthai;0E1E +phophungthai;0E1C +phosamphaothai;0E20 +pi;03C0 +pieupacirclekorean;3273 +pieupaparenkorean;3213 +pieupcieuckorean;3176 +pieupcirclekorean;3265 +pieupkiyeokkorean;3172 +pieupkorean;3142 +pieupparenkorean;3205 +pieupsioskiyeokkorean;3174 +pieupsioskorean;3144 +pieupsiostikeutkorean;3175 +pieupthieuthkorean;3177 +pieuptikeutkorean;3173 +pihiragana;3074 +pikatakana;30D4 +pisymbolgreek;03D6 +piwrarmenian;0583 +plus;002B +plusbelowcmb;031F +pluscircle;2295 +plusminus;00B1 +plusmod;02D6 +plusmonospace;FF0B +plussmall;FE62 +plussuperior;207A +pmonospace;FF50 +pmsquare;33D8 +pohiragana;307D +pointingindexdownwhite;261F +pointingindexleftwhite;261C +pointingindexrightwhite;261E +pointingindexupwhite;261D +pokatakana;30DD +poplathai;0E1B +postalmark;3012 +postalmarkface;3020 +pparen;24AB +precedes;227A +prescription;211E +primemod;02B9 +primereversed;2035 +product;220F +projective;2305 +prolongedkana;30FC +propellor;2318 +propersubset;2282 +propersuperset;2283 +proportion;2237 +proportional;221D +psi;03C8 +psicyrillic;0471 +psilipneumatacyrilliccmb;0486 +pssquare;33B0 +puhiragana;3077 +pukatakana;30D7 +pvsquare;33B4 +pwsquare;33BA +q;0071 +qadeva;0958 +qadmahebrew;05A8 +qafarabic;0642 +qaffinalarabic;FED6 +qafinitialarabic;FED7 +qafmedialarabic;FED8 +qamats;05B8 +qamats10;05B8 +qamats1a;05B8 +qamats1c;05B8 +qamats27;05B8 +qamats29;05B8 +qamats33;05B8 +qamatsde;05B8 +qamatshebrew;05B8 +qamatsnarrowhebrew;05B8 +qamatsqatanhebrew;05B8 +qamatsqatannarrowhebrew;05B8 +qamatsqatanquarterhebrew;05B8 +qamatsqatanwidehebrew;05B8 +qamatsquarterhebrew;05B8 +qamatswidehebrew;05B8 +qarneyparahebrew;059F +qbopomofo;3111 +qcircle;24E0 +qhook;02A0 +qmonospace;FF51 +qof;05E7 +qofdagesh;FB47 +qofdageshhebrew;FB47 +qofhatafpatah;05E7 05B2 +qofhatafpatahhebrew;05E7 05B2 +qofhatafsegol;05E7 05B1 +qofhatafsegolhebrew;05E7 05B1 +qofhebrew;05E7 +qofhiriq;05E7 05B4 +qofhiriqhebrew;05E7 05B4 +qofholam;05E7 05B9 +qofholamhebrew;05E7 05B9 +qofpatah;05E7 05B7 +qofpatahhebrew;05E7 05B7 +qofqamats;05E7 05B8 +qofqamatshebrew;05E7 05B8 +qofqubuts;05E7 05BB +qofqubutshebrew;05E7 05BB +qofsegol;05E7 05B6 +qofsegolhebrew;05E7 05B6 +qofsheva;05E7 05B0 +qofshevahebrew;05E7 05B0 +qoftsere;05E7 05B5 +qoftserehebrew;05E7 05B5 +qparen;24AC +quarternote;2669 +qubuts;05BB +qubuts18;05BB +qubuts25;05BB +qubuts31;05BB +qubutshebrew;05BB +qubutsnarrowhebrew;05BB +qubutsquarterhebrew;05BB +qubutswidehebrew;05BB +question;003F +questionarabic;061F +questionarmenian;055E +questiondown;00BF +questiondownsmall;F7BF +questiongreek;037E +questionmonospace;FF1F +questionsmall;F73F +quotedbl;0022 +quotedblbase;201E +quotedblleft;201C +quotedblmonospace;FF02 +quotedblprime;301E +quotedblprimereversed;301D +quotedblright;201D +quoteleft;2018 +quoteleftreversed;201B +quotereversed;201B +quoteright;2019 +quoterightn;0149 +quotesinglbase;201A +quotesingle;0027 +quotesinglemonospace;FF07 +r;0072 +raarmenian;057C +rabengali;09B0 +racute;0155 +radeva;0930 +radical;221A +radicalex;F8E5 +radoverssquare;33AE +radoverssquaredsquare;33AF +radsquare;33AD +rafe;05BF +rafehebrew;05BF +ragujarati;0AB0 +ragurmukhi;0A30 +rahiragana;3089 +rakatakana;30E9 +rakatakanahalfwidth;FF97 +ralowerdiagonalbengali;09F1 +ramiddlediagonalbengali;09F0 +ramshorn;0264 +ratio;2236 +rbopomofo;3116 +rcaron;0159 +rcedilla;0157 +rcircle;24E1 +rcommaaccent;0157 +rdblgrave;0211 +rdotaccent;1E59 +rdotbelow;1E5B +rdotbelowmacron;1E5D +referencemark;203B +reflexsubset;2286 +reflexsuperset;2287 +registered;00AE +registersans;F8E8 +registerserif;F6DA +reharabic;0631 +reharmenian;0580 +rehfinalarabic;FEAE +rehiragana;308C +rehyehaleflamarabic;0631 FEF3 FE8E 0644 +rekatakana;30EC +rekatakanahalfwidth;FF9A +resh;05E8 +reshdageshhebrew;FB48 +reshhatafpatah;05E8 05B2 +reshhatafpatahhebrew;05E8 05B2 +reshhatafsegol;05E8 05B1 +reshhatafsegolhebrew;05E8 05B1 +reshhebrew;05E8 +reshhiriq;05E8 05B4 +reshhiriqhebrew;05E8 05B4 +reshholam;05E8 05B9 +reshholamhebrew;05E8 05B9 +reshpatah;05E8 05B7 +reshpatahhebrew;05E8 05B7 +reshqamats;05E8 05B8 +reshqamatshebrew;05E8 05B8 +reshqubuts;05E8 05BB +reshqubutshebrew;05E8 05BB +reshsegol;05E8 05B6 +reshsegolhebrew;05E8 05B6 +reshsheva;05E8 05B0 +reshshevahebrew;05E8 05B0 +reshtsere;05E8 05B5 +reshtserehebrew;05E8 05B5 +reversedtilde;223D +reviahebrew;0597 +reviamugrashhebrew;0597 +revlogicalnot;2310 +rfishhook;027E +rfishhookreversed;027F +rhabengali;09DD +rhadeva;095D +rho;03C1 +rhook;027D +rhookturned;027B +rhookturnedsuperior;02B5 +rhosymbolgreek;03F1 +rhotichookmod;02DE +rieulacirclekorean;3271 +rieulaparenkorean;3211 +rieulcirclekorean;3263 +rieulhieuhkorean;3140 +rieulkiyeokkorean;313A +rieulkiyeoksioskorean;3169 +rieulkorean;3139 +rieulmieumkorean;313B +rieulpansioskorean;316C +rieulparenkorean;3203 +rieulphieuphkorean;313F +rieulpieupkorean;313C +rieulpieupsioskorean;316B +rieulsioskorean;313D +rieulthieuthkorean;313E +rieultikeutkorean;316A +rieulyeorinhieuhkorean;316D +rightangle;221F +righttackbelowcmb;0319 +righttriangle;22BF +rihiragana;308A +rikatakana;30EA +rikatakanahalfwidth;FF98 +ring;02DA +ringbelowcmb;0325 +ringcmb;030A +ringhalfleft;02BF +ringhalfleftarmenian;0559 +ringhalfleftbelowcmb;031C +ringhalfleftcentered;02D3 +ringhalfright;02BE +ringhalfrightbelowcmb;0339 +ringhalfrightcentered;02D2 +rinvertedbreve;0213 +rittorusquare;3351 +rlinebelow;1E5F +rlongleg;027C +rlonglegturned;027A +rmonospace;FF52 +rohiragana;308D +rokatakana;30ED +rokatakanahalfwidth;FF9B +roruathai;0E23 +rparen;24AD +rrabengali;09DC +rradeva;0931 +rragurmukhi;0A5C +rreharabic;0691 +rrehfinalarabic;FB8D +rrvocalicbengali;09E0 +rrvocalicdeva;0960 +rrvocalicgujarati;0AE0 +rrvocalicvowelsignbengali;09C4 +rrvocalicvowelsigndeva;0944 +rrvocalicvowelsigngujarati;0AC4 +rsuperior;F6F1 +rtblock;2590 +rturned;0279 +rturnedsuperior;02B4 +ruhiragana;308B +rukatakana;30EB +rukatakanahalfwidth;FF99 +rupeemarkbengali;09F2 +rupeesignbengali;09F3 +rupiah;F6DD +ruthai;0E24 +rvocalicbengali;098B +rvocalicdeva;090B +rvocalicgujarati;0A8B +rvocalicvowelsignbengali;09C3 +rvocalicvowelsigndeva;0943 +rvocalicvowelsigngujarati;0AC3 +s;0073 +sabengali;09B8 +sacute;015B +sacutedotaccent;1E65 +sadarabic;0635 +sadeva;0938 +sadfinalarabic;FEBA +sadinitialarabic;FEBB +sadmedialarabic;FEBC +sagujarati;0AB8 +sagurmukhi;0A38 +sahiragana;3055 +sakatakana;30B5 +sakatakanahalfwidth;FF7B +sallallahoualayhewasallamarabic;FDFA +samekh;05E1 +samekhdagesh;FB41 +samekhdageshhebrew;FB41 +samekhhebrew;05E1 +saraaathai;0E32 +saraaethai;0E41 +saraaimaimalaithai;0E44 +saraaimaimuanthai;0E43 +saraamthai;0E33 +saraathai;0E30 +saraethai;0E40 +saraiileftthai;F886 +saraiithai;0E35 +saraileftthai;F885 +saraithai;0E34 +saraothai;0E42 +saraueeleftthai;F888 +saraueethai;0E37 +saraueleftthai;F887 +sarauethai;0E36 +sarauthai;0E38 +sarauuthai;0E39 +sbopomofo;3119 +scaron;0161 +scarondotaccent;1E67 +scedilla;015F +schwa;0259 +schwacyrillic;04D9 +schwadieresiscyrillic;04DB +schwahook;025A +scircle;24E2 +scircumflex;015D +scommaaccent;0219 +sdotaccent;1E61 +sdotbelow;1E63 +sdotbelowdotaccent;1E69 +seagullbelowcmb;033C +second;2033 +secondtonechinese;02CA +section;00A7 +seenarabic;0633 +seenfinalarabic;FEB2 +seeninitialarabic;FEB3 +seenmedialarabic;FEB4 +segol;05B6 +segol13;05B6 +segol1f;05B6 +segol2c;05B6 +segolhebrew;05B6 +segolnarrowhebrew;05B6 +segolquarterhebrew;05B6 +segoltahebrew;0592 +segolwidehebrew;05B6 +seharmenian;057D +sehiragana;305B +sekatakana;30BB +sekatakanahalfwidth;FF7E +semicolon;003B +semicolonarabic;061B +semicolonmonospace;FF1B +semicolonsmall;FE54 +semivoicedmarkkana;309C +semivoicedmarkkanahalfwidth;FF9F +sentisquare;3322 +sentosquare;3323 +seven;0037 +sevenarabic;0667 +sevenbengali;09ED +sevencircle;2466 +sevencircleinversesansserif;2790 +sevendeva;096D +seveneighths;215E +sevengujarati;0AED +sevengurmukhi;0A6D +sevenhackarabic;0667 +sevenhangzhou;3027 +sevenideographicparen;3226 +seveninferior;2087 +sevenmonospace;FF17 +sevenoldstyle;F737 +sevenparen;247A +sevenperiod;248E +sevenpersian;06F7 +sevenroman;2176 +sevensuperior;2077 +seventeencircle;2470 +seventeenparen;2484 +seventeenperiod;2498 +seventhai;0E57 +sfthyphen;00AD +shaarmenian;0577 +shabengali;09B6 +shacyrillic;0448 +shaddaarabic;0651 +shaddadammaarabic;FC61 +shaddadammatanarabic;FC5E +shaddafathaarabic;FC60 +shaddafathatanarabic;0651 064B +shaddakasraarabic;FC62 +shaddakasratanarabic;FC5F +shade;2592 +shadedark;2593 +shadelight;2591 +shademedium;2592 +shadeva;0936 +shagujarati;0AB6 +shagurmukhi;0A36 +shalshelethebrew;0593 +shbopomofo;3115 +shchacyrillic;0449 +sheenarabic;0634 +sheenfinalarabic;FEB6 +sheeninitialarabic;FEB7 +sheenmedialarabic;FEB8 +sheicoptic;03E3 +sheqel;20AA +sheqelhebrew;20AA +sheva;05B0 +sheva115;05B0 +sheva15;05B0 +sheva22;05B0 +sheva2e;05B0 +shevahebrew;05B0 +shevanarrowhebrew;05B0 +shevaquarterhebrew;05B0 +shevawidehebrew;05B0 +shhacyrillic;04BB +shimacoptic;03ED +shin;05E9 +shindagesh;FB49 +shindageshhebrew;FB49 +shindageshshindot;FB2C +shindageshshindothebrew;FB2C +shindageshsindot;FB2D +shindageshsindothebrew;FB2D +shindothebrew;05C1 +shinhebrew;05E9 +shinshindot;FB2A +shinshindothebrew;FB2A +shinsindot;FB2B +shinsindothebrew;FB2B +shook;0282 +sigma;03C3 +sigma1;03C2 +sigmafinal;03C2 +sigmalunatesymbolgreek;03F2 +sihiragana;3057 +sikatakana;30B7 +sikatakanahalfwidth;FF7C +siluqhebrew;05BD +siluqlefthebrew;05BD +similar;223C +sindothebrew;05C2 +siosacirclekorean;3274 +siosaparenkorean;3214 +sioscieuckorean;317E +sioscirclekorean;3266 +sioskiyeokkorean;317A +sioskorean;3145 +siosnieunkorean;317B +siosparenkorean;3206 +siospieupkorean;317D +siostikeutkorean;317C +six;0036 +sixarabic;0666 +sixbengali;09EC +sixcircle;2465 +sixcircleinversesansserif;278F +sixdeva;096C +sixgujarati;0AEC +sixgurmukhi;0A6C +sixhackarabic;0666 +sixhangzhou;3026 +sixideographicparen;3225 +sixinferior;2086 +sixmonospace;FF16 +sixoldstyle;F736 +sixparen;2479 +sixperiod;248D +sixpersian;06F6 +sixroman;2175 +sixsuperior;2076 +sixteencircle;246F +sixteencurrencydenominatorbengali;09F9 +sixteenparen;2483 +sixteenperiod;2497 +sixthai;0E56 +slash;002F +slashmonospace;FF0F +slong;017F +slongdotaccent;1E9B +smileface;263A +smonospace;FF53 +sofpasuqhebrew;05C3 +softhyphen;00AD +softsigncyrillic;044C +sohiragana;305D +sokatakana;30BD +sokatakanahalfwidth;FF7F +soliduslongoverlaycmb;0338 +solidusshortoverlaycmb;0337 +sorusithai;0E29 +sosalathai;0E28 +sosothai;0E0B +sosuathai;0E2A +space;0020 +spacehackarabic;0020 +spade;2660 +spadesuitblack;2660 +spadesuitwhite;2664 +sparen;24AE +squarebelowcmb;033B +squarecc;33C4 +squarecm;339D +squarediagonalcrosshatchfill;25A9 +squarehorizontalfill;25A4 +squarekg;338F +squarekm;339E +squarekmcapital;33CE +squareln;33D1 +squarelog;33D2 +squaremg;338E +squaremil;33D5 +squaremm;339C +squaremsquared;33A1 +squareorthogonalcrosshatchfill;25A6 +squareupperlefttolowerrightfill;25A7 +squareupperrighttolowerleftfill;25A8 +squareverticalfill;25A5 +squarewhitewithsmallblack;25A3 +srsquare;33DB +ssabengali;09B7 +ssadeva;0937 +ssagujarati;0AB7 +ssangcieuckorean;3149 +ssanghieuhkorean;3185 +ssangieungkorean;3180 +ssangkiyeokkorean;3132 +ssangnieunkorean;3165 +ssangpieupkorean;3143 +ssangsioskorean;3146 +ssangtikeutkorean;3138 +ssuperior;F6F2 +sterling;00A3 +sterlingmonospace;FFE1 +strokelongoverlaycmb;0336 +strokeshortoverlaycmb;0335 +subset;2282 +subsetnotequal;228A +subsetorequal;2286 +succeeds;227B +suchthat;220B +suhiragana;3059 +sukatakana;30B9 +sukatakanahalfwidth;FF7D +sukunarabic;0652 +summation;2211 +sun;263C +superset;2283 +supersetnotequal;228B +supersetorequal;2287 +svsquare;33DC +syouwaerasquare;337C +t;0074 +tabengali;09A4 +tackdown;22A4 +tackleft;22A3 +tadeva;0924 +tagujarati;0AA4 +tagurmukhi;0A24 +taharabic;0637 +tahfinalarabic;FEC2 +tahinitialarabic;FEC3 +tahiragana;305F +tahmedialarabic;FEC4 +taisyouerasquare;337D +takatakana;30BF +takatakanahalfwidth;FF80 +tatweelarabic;0640 +tau;03C4 +tav;05EA +tavdages;FB4A +tavdagesh;FB4A +tavdageshhebrew;FB4A +tavhebrew;05EA +tbar;0167 +tbopomofo;310A +tcaron;0165 +tccurl;02A8 +tcedilla;0163 +tcheharabic;0686 +tchehfinalarabic;FB7B +tchehinitialarabic;FB7C +tchehmedialarabic;FB7D +tchehmeeminitialarabic;FB7C FEE4 +tcircle;24E3 +tcircumflexbelow;1E71 +tcommaaccent;0163 +tdieresis;1E97 +tdotaccent;1E6B +tdotbelow;1E6D +tecyrillic;0442 +tedescendercyrillic;04AD +teharabic;062A +tehfinalarabic;FE96 +tehhahinitialarabic;FCA2 +tehhahisolatedarabic;FC0C +tehinitialarabic;FE97 +tehiragana;3066 +tehjeeminitialarabic;FCA1 +tehjeemisolatedarabic;FC0B +tehmarbutaarabic;0629 +tehmarbutafinalarabic;FE94 +tehmedialarabic;FE98 +tehmeeminitialarabic;FCA4 +tehmeemisolatedarabic;FC0E +tehnoonfinalarabic;FC73 +tekatakana;30C6 +tekatakanahalfwidth;FF83 +telephone;2121 +telephoneblack;260E +telishagedolahebrew;05A0 +telishaqetanahebrew;05A9 +tencircle;2469 +tenideographicparen;3229 +tenparen;247D +tenperiod;2491 +tenroman;2179 +tesh;02A7 +tet;05D8 +tetdagesh;FB38 +tetdageshhebrew;FB38 +tethebrew;05D8 +tetsecyrillic;04B5 +tevirhebrew;059B +tevirlefthebrew;059B +thabengali;09A5 +thadeva;0925 +thagujarati;0AA5 +thagurmukhi;0A25 +thalarabic;0630 +thalfinalarabic;FEAC +thanthakhatlowleftthai;F898 +thanthakhatlowrightthai;F897 +thanthakhatthai;0E4C +thanthakhatupperleftthai;F896 +theharabic;062B +thehfinalarabic;FE9A +thehinitialarabic;FE9B +thehmedialarabic;FE9C +thereexists;2203 +therefore;2234 +theta;03B8 +theta1;03D1 +thetasymbolgreek;03D1 +thieuthacirclekorean;3279 +thieuthaparenkorean;3219 +thieuthcirclekorean;326B +thieuthkorean;314C +thieuthparenkorean;320B +thirteencircle;246C +thirteenparen;2480 +thirteenperiod;2494 +thonangmonthothai;0E11 +thook;01AD +thophuthaothai;0E12 +thorn;00FE +thothahanthai;0E17 +thothanthai;0E10 +thothongthai;0E18 +thothungthai;0E16 +thousandcyrillic;0482 +thousandsseparatorarabic;066C +thousandsseparatorpersian;066C +three;0033 +threearabic;0663 +threebengali;09E9 +threecircle;2462 +threecircleinversesansserif;278C +threedeva;0969 +threeeighths;215C +threegujarati;0AE9 +threegurmukhi;0A69 +threehackarabic;0663 +threehangzhou;3023 +threeideographicparen;3222 +threeinferior;2083 +threemonospace;FF13 +threenumeratorbengali;09F6 +threeoldstyle;F733 +threeparen;2476 +threeperiod;248A +threepersian;06F3 +threequarters;00BE +threequartersemdash;F6DE +threeroman;2172 +threesuperior;00B3 +threethai;0E53 +thzsquare;3394 +tihiragana;3061 +tikatakana;30C1 +tikatakanahalfwidth;FF81 +tikeutacirclekorean;3270 +tikeutaparenkorean;3210 +tikeutcirclekorean;3262 +tikeutkorean;3137 +tikeutparenkorean;3202 +tilde;02DC +tildebelowcmb;0330 +tildecmb;0303 +tildecomb;0303 +tildedoublecmb;0360 +tildeoperator;223C +tildeoverlaycmb;0334 +tildeverticalcmb;033E +timescircle;2297 +tipehahebrew;0596 +tipehalefthebrew;0596 +tippigurmukhi;0A70 +titlocyrilliccmb;0483 +tiwnarmenian;057F +tlinebelow;1E6F +tmonospace;FF54 +toarmenian;0569 +tohiragana;3068 +tokatakana;30C8 +tokatakanahalfwidth;FF84 +tonebarextrahighmod;02E5 +tonebarextralowmod;02E9 +tonebarhighmod;02E6 +tonebarlowmod;02E8 +tonebarmidmod;02E7 +tonefive;01BD +tonesix;0185 +tonetwo;01A8 +tonos;0384 +tonsquare;3327 +topatakthai;0E0F +tortoiseshellbracketleft;3014 +tortoiseshellbracketleftsmall;FE5D +tortoiseshellbracketleftvertical;FE39 +tortoiseshellbracketright;3015 +tortoiseshellbracketrightsmall;FE5E +tortoiseshellbracketrightvertical;FE3A +totaothai;0E15 +tpalatalhook;01AB +tparen;24AF +trademark;2122 +trademarksans;F8EA +trademarkserif;F6DB +tretroflexhook;0288 +triagdn;25BC +triaglf;25C4 +triagrt;25BA +triagup;25B2 +ts;02A6 +tsadi;05E6 +tsadidagesh;FB46 +tsadidageshhebrew;FB46 +tsadihebrew;05E6 +tsecyrillic;0446 +tsere;05B5 +tsere12;05B5 +tsere1e;05B5 +tsere2b;05B5 +tserehebrew;05B5 +tserenarrowhebrew;05B5 +tserequarterhebrew;05B5 +tserewidehebrew;05B5 +tshecyrillic;045B +tsuperior;F6F3 +ttabengali;099F +ttadeva;091F +ttagujarati;0A9F +ttagurmukhi;0A1F +tteharabic;0679 +ttehfinalarabic;FB67 +ttehinitialarabic;FB68 +ttehmedialarabic;FB69 +tthabengali;09A0 +tthadeva;0920 +tthagujarati;0AA0 +tthagurmukhi;0A20 +tturned;0287 +tuhiragana;3064 +tukatakana;30C4 +tukatakanahalfwidth;FF82 +tusmallhiragana;3063 +tusmallkatakana;30C3 +tusmallkatakanahalfwidth;FF6F +twelvecircle;246B +twelveparen;247F +twelveperiod;2493 +twelveroman;217B +twentycircle;2473 +twentyhangzhou;5344 +twentyparen;2487 +twentyperiod;249B +two;0032 +twoarabic;0662 +twobengali;09E8 +twocircle;2461 +twocircleinversesansserif;278B +twodeva;0968 +twodotenleader;2025 +twodotleader;2025 +twodotleadervertical;FE30 +twogujarati;0AE8 +twogurmukhi;0A68 +twohackarabic;0662 +twohangzhou;3022 +twoideographicparen;3221 +twoinferior;2082 +twomonospace;FF12 +twonumeratorbengali;09F5 +twooldstyle;F732 +twoparen;2475 +twoperiod;2489 +twopersian;06F2 +tworoman;2171 +twostroke;01BB +twosuperior;00B2 +twothai;0E52 +twothirds;2154 +u;0075 +uacute;00FA +ubar;0289 +ubengali;0989 +ubopomofo;3128 +ubreve;016D +ucaron;01D4 +ucircle;24E4 +ucircumflex;00FB +ucircumflexbelow;1E77 +ucyrillic;0443 +udattadeva;0951 +udblacute;0171 +udblgrave;0215 +udeva;0909 +udieresis;00FC +udieresisacute;01D8 +udieresisbelow;1E73 +udieresiscaron;01DA +udieresiscyrillic;04F1 +udieresisgrave;01DC +udieresismacron;01D6 +udotbelow;1EE5 +ugrave;00F9 +ugujarati;0A89 +ugurmukhi;0A09 +uhiragana;3046 +uhookabove;1EE7 +uhorn;01B0 +uhornacute;1EE9 +uhorndotbelow;1EF1 +uhorngrave;1EEB +uhornhookabove;1EED +uhorntilde;1EEF +uhungarumlaut;0171 +uhungarumlautcyrillic;04F3 +uinvertedbreve;0217 +ukatakana;30A6 +ukatakanahalfwidth;FF73 +ukcyrillic;0479 +ukorean;315C +umacron;016B +umacroncyrillic;04EF +umacrondieresis;1E7B +umatragurmukhi;0A41 +umonospace;FF55 +underscore;005F +underscoredbl;2017 +underscoremonospace;FF3F +underscorevertical;FE33 +underscorewavy;FE4F +union;222A +universal;2200 +uogonek;0173 +uparen;24B0 +upblock;2580 +upperdothebrew;05C4 +upsilon;03C5 +upsilondieresis;03CB +upsilondieresistonos;03B0 +upsilonlatin;028A +upsilontonos;03CD +uptackbelowcmb;031D +uptackmod;02D4 +uragurmukhi;0A73 +uring;016F +ushortcyrillic;045E +usmallhiragana;3045 +usmallkatakana;30A5 +usmallkatakanahalfwidth;FF69 +ustraightcyrillic;04AF +ustraightstrokecyrillic;04B1 +utilde;0169 +utildeacute;1E79 +utildebelow;1E75 +uubengali;098A +uudeva;090A +uugujarati;0A8A +uugurmukhi;0A0A +uumatragurmukhi;0A42 +uuvowelsignbengali;09C2 +uuvowelsigndeva;0942 +uuvowelsigngujarati;0AC2 +uvowelsignbengali;09C1 +uvowelsigndeva;0941 +uvowelsigngujarati;0AC1 +v;0076 +vadeva;0935 +vagujarati;0AB5 +vagurmukhi;0A35 +vakatakana;30F7 +vav;05D5 +vavdagesh;FB35 +vavdagesh65;FB35 +vavdageshhebrew;FB35 +vavhebrew;05D5 +vavholam;FB4B +vavholamhebrew;FB4B +vavvavhebrew;05F0 +vavyodhebrew;05F1 +vcircle;24E5 +vdotbelow;1E7F +vecyrillic;0432 +veharabic;06A4 +vehfinalarabic;FB6B +vehinitialarabic;FB6C +vehmedialarabic;FB6D +vekatakana;30F9 +venus;2640 +verticalbar;007C +verticallineabovecmb;030D +verticallinebelowcmb;0329 +verticallinelowmod;02CC +verticallinemod;02C8 +vewarmenian;057E +vhook;028B +vikatakana;30F8 +viramabengali;09CD +viramadeva;094D +viramagujarati;0ACD +visargabengali;0983 +visargadeva;0903 +visargagujarati;0A83 +vmonospace;FF56 +voarmenian;0578 +voicediterationhiragana;309E +voicediterationkatakana;30FE +voicedmarkkana;309B +voicedmarkkanahalfwidth;FF9E +vokatakana;30FA +vparen;24B1 +vtilde;1E7D +vturned;028C +vuhiragana;3094 +vukatakana;30F4 +w;0077 +wacute;1E83 +waekorean;3159 +wahiragana;308F +wakatakana;30EF +wakatakanahalfwidth;FF9C +wakorean;3158 +wasmallhiragana;308E +wasmallkatakana;30EE +wattosquare;3357 +wavedash;301C +wavyunderscorevertical;FE34 +wawarabic;0648 +wawfinalarabic;FEEE +wawhamzaabovearabic;0624 +wawhamzaabovefinalarabic;FE86 +wbsquare;33DD +wcircle;24E6 +wcircumflex;0175 +wdieresis;1E85 +wdotaccent;1E87 +wdotbelow;1E89 +wehiragana;3091 +weierstrass;2118 +wekatakana;30F1 +wekorean;315E +weokorean;315D +wgrave;1E81 +whitebullet;25E6 +whitecircle;25CB +whitecircleinverse;25D9 +whitecornerbracketleft;300E +whitecornerbracketleftvertical;FE43 +whitecornerbracketright;300F +whitecornerbracketrightvertical;FE44 +whitediamond;25C7 +whitediamondcontainingblacksmalldiamond;25C8 +whitedownpointingsmalltriangle;25BF +whitedownpointingtriangle;25BD +whiteleftpointingsmalltriangle;25C3 +whiteleftpointingtriangle;25C1 +whitelenticularbracketleft;3016 +whitelenticularbracketright;3017 +whiterightpointingsmalltriangle;25B9 +whiterightpointingtriangle;25B7 +whitesmallsquare;25AB +whitesmilingface;263A +whitesquare;25A1 +whitestar;2606 +whitetelephone;260F +whitetortoiseshellbracketleft;3018 +whitetortoiseshellbracketright;3019 +whiteuppointingsmalltriangle;25B5 +whiteuppointingtriangle;25B3 +wihiragana;3090 +wikatakana;30F0 +wikorean;315F +wmonospace;FF57 +wohiragana;3092 +wokatakana;30F2 +wokatakanahalfwidth;FF66 +won;20A9 +wonmonospace;FFE6 +wowaenthai;0E27 +wparen;24B2 +wring;1E98 +wsuperior;02B7 +wturned;028D +wynn;01BF +x;0078 +xabovecmb;033D +xbopomofo;3112 +xcircle;24E7 +xdieresis;1E8D +xdotaccent;1E8B +xeharmenian;056D +xi;03BE +xmonospace;FF58 +xparen;24B3 +xsuperior;02E3 +y;0079 +yaadosquare;334E +yabengali;09AF +yacute;00FD +yadeva;092F +yaekorean;3152 +yagujarati;0AAF +yagurmukhi;0A2F +yahiragana;3084 +yakatakana;30E4 +yakatakanahalfwidth;FF94 +yakorean;3151 +yamakkanthai;0E4E +yasmallhiragana;3083 +yasmallkatakana;30E3 +yasmallkatakanahalfwidth;FF6C +yatcyrillic;0463 +ycircle;24E8 +ycircumflex;0177 +ydieresis;00FF +ydotaccent;1E8F +ydotbelow;1EF5 +yeharabic;064A +yehbarreearabic;06D2 +yehbarreefinalarabic;FBAF +yehfinalarabic;FEF2 +yehhamzaabovearabic;0626 +yehhamzaabovefinalarabic;FE8A +yehhamzaaboveinitialarabic;FE8B +yehhamzaabovemedialarabic;FE8C +yehinitialarabic;FEF3 +yehmedialarabic;FEF4 +yehmeeminitialarabic;FCDD +yehmeemisolatedarabic;FC58 +yehnoonfinalarabic;FC94 +yehthreedotsbelowarabic;06D1 +yekorean;3156 +yen;00A5 +yenmonospace;FFE5 +yeokorean;3155 +yeorinhieuhkorean;3186 +yerahbenyomohebrew;05AA +yerahbenyomolefthebrew;05AA +yericyrillic;044B +yerudieresiscyrillic;04F9 +yesieungkorean;3181 +yesieungpansioskorean;3183 +yesieungsioskorean;3182 +yetivhebrew;059A +ygrave;1EF3 +yhook;01B4 +yhookabove;1EF7 +yiarmenian;0575 +yicyrillic;0457 +yikorean;3162 +yinyang;262F +yiwnarmenian;0582 +ymonospace;FF59 +yod;05D9 +yoddagesh;FB39 +yoddageshhebrew;FB39 +yodhebrew;05D9 +yodyodhebrew;05F2 +yodyodpatahhebrew;FB1F +yohiragana;3088 +yoikorean;3189 +yokatakana;30E8 +yokatakanahalfwidth;FF96 +yokorean;315B +yosmallhiragana;3087 +yosmallkatakana;30E7 +yosmallkatakanahalfwidth;FF6E +yotgreek;03F3 +yoyaekorean;3188 +yoyakorean;3187 +yoyakthai;0E22 +yoyingthai;0E0D +yparen;24B4 +ypogegrammeni;037A +ypogegrammenigreekcmb;0345 +yr;01A6 +yring;1E99 +ysuperior;02B8 +ytilde;1EF9 +yturned;028E +yuhiragana;3086 +yuikorean;318C +yukatakana;30E6 +yukatakanahalfwidth;FF95 +yukorean;3160 +yusbigcyrillic;046B +yusbigiotifiedcyrillic;046D +yuslittlecyrillic;0467 +yuslittleiotifiedcyrillic;0469 +yusmallhiragana;3085 +yusmallkatakana;30E5 +yusmallkatakanahalfwidth;FF6D +yuyekorean;318B +yuyeokorean;318A +yyabengali;09DF +yyadeva;095F +z;007A +zaarmenian;0566 +zacute;017A +zadeva;095B +zagurmukhi;0A5B +zaharabic;0638 +zahfinalarabic;FEC6 +zahinitialarabic;FEC7 +zahiragana;3056 +zahmedialarabic;FEC8 +zainarabic;0632 +zainfinalarabic;FEB0 +zakatakana;30B6 +zaqefgadolhebrew;0595 +zaqefqatanhebrew;0594 +zarqahebrew;0598 +zayin;05D6 +zayindagesh;FB36 +zayindageshhebrew;FB36 +zayinhebrew;05D6 +zbopomofo;3117 +zcaron;017E +zcircle;24E9 +zcircumflex;1E91 +zcurl;0291 +zdot;017C +zdotaccent;017C +zdotbelow;1E93 +zecyrillic;0437 +zedescendercyrillic;0499 +zedieresiscyrillic;04DF +zehiragana;305C +zekatakana;30BC +zero;0030 +zeroarabic;0660 +zerobengali;09E6 +zerodeva;0966 +zerogujarati;0AE6 +zerogurmukhi;0A66 +zerohackarabic;0660 +zeroinferior;2080 +zeromonospace;FF10 +zerooldstyle;F730 +zeropersian;06F0 +zerosuperior;2070 +zerothai;0E50 +zerowidthjoiner;FEFF +zerowidthnonjoiner;200C +zerowidthspace;200B +zeta;03B6 +zhbopomofo;3113 +zhearmenian;056A +zhebrevecyrillic;04C2 +zhecyrillic;0436 +zhedescendercyrillic;0497 +zhedieresiscyrillic;04DD +zihiragana;3058 +zikatakana;30B8 +zinorhebrew;05AE +zlinebelow;1E95 +zmonospace;FF5A +zohiragana;305E +zokatakana;30BE +zparen;24B5 +zretroflexhook;0290 +zstroke;01B6 +zuhiragana;305A +zukatakana;30BA +# END diff --git a/src/Broadside/Fonts/Data/GlyphList/zapfdingbats.txt b/src/Broadside/Fonts/Data/GlyphList/zapfdingbats.txt new file mode 100644 index 00000000..ab52700e --- /dev/null +++ b/src/Broadside/Fonts/Data/GlyphList/zapfdingbats.txt @@ -0,0 +1,245 @@ +# ----------------------------------------------------------- +# Copyright 2002-2019 Adobe (http://www.adobe.com/). +# +# Redistribution and use in source and binary forms, with or +# without modification, are permitted provided that the +# following conditions are met: +# +# Redistributions of source code must retain the above +# copyright notice, this list of conditions and the following +# disclaimer. +# +# Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials +# provided with the distribution. +# +# Neither the name of Adobe nor the names of its contributors +# may be used to endorse or promote products derived from this +# software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ----------------------------------------------------------- +# Name: ITC Zapf Dingbats Glyph List +# Table version: 2.0 +# Date: September 20, 2002 +# URL: https://github.com/adobe-type-tools/agl-aglfn +# +# Format: two semicolon-delimited fields: +# (1) glyph name--upper/lowercase letters and digits +# (2) Unicode scalar value--four uppercase hexadecimal digits +# +a100;275E +a101;2761 +a102;2762 +a103;2763 +a104;2764 +a105;2710 +a106;2765 +a107;2766 +a108;2767 +a109;2660 +a10;2721 +a110;2665 +a111;2666 +a112;2663 +a117;2709 +a118;2708 +a119;2707 +a11;261B +a120;2460 +a121;2461 +a122;2462 +a123;2463 +a124;2464 +a125;2465 +a126;2466 +a127;2467 +a128;2468 +a129;2469 +a12;261E +a130;2776 +a131;2777 +a132;2778 +a133;2779 +a134;277A +a135;277B +a136;277C +a137;277D +a138;277E +a139;277F +a13;270C +a140;2780 +a141;2781 +a142;2782 +a143;2783 +a144;2784 +a145;2785 +a146;2786 +a147;2787 +a148;2788 +a149;2789 +a14;270D +a150;278A +a151;278B +a152;278C +a153;278D +a154;278E +a155;278F +a156;2790 +a157;2791 +a158;2792 +a159;2793 +a15;270E +a160;2794 +a161;2192 +a162;27A3 +a163;2194 +a164;2195 +a165;2799 +a166;279B +a167;279C +a168;279D +a169;279E +a16;270F +a170;279F +a171;27A0 +a172;27A1 +a173;27A2 +a174;27A4 +a175;27A5 +a176;27A6 +a177;27A7 +a178;27A8 +a179;27A9 +a17;2711 +a180;27AB +a181;27AD +a182;27AF +a183;27B2 +a184;27B3 +a185;27B5 +a186;27B8 +a187;27BA +a188;27BB +a189;27BC +a18;2712 +a190;27BD +a191;27BE +a192;279A +a193;27AA +a194;27B6 +a195;27B9 +a196;2798 +a197;27B4 +a198;27B7 +a199;27AC +a19;2713 +a1;2701 +a200;27AE +a201;27B1 +a202;2703 +a203;2750 +a204;2752 +a205;276E +a206;2770 +a20;2714 +a21;2715 +a22;2716 +a23;2717 +a24;2718 +a25;2719 +a26;271A +a27;271B +a28;271C +a29;2722 +a2;2702 +a30;2723 +a31;2724 +a32;2725 +a33;2726 +a34;2727 +a35;2605 +a36;2729 +a37;272A +a38;272B +a39;272C +a3;2704 +a40;272D +a41;272E +a42;272F +a43;2730 +a44;2731 +a45;2732 +a46;2733 +a47;2734 +a48;2735 +a49;2736 +a4;260E +a50;2737 +a51;2738 +a52;2739 +a53;273A +a54;273B +a55;273C +a56;273D +a57;273E +a58;273F +a59;2740 +a5;2706 +a60;2741 +a61;2742 +a62;2743 +a63;2744 +a64;2745 +a65;2746 +a66;2747 +a67;2748 +a68;2749 +a69;274A +a6;271D +a70;274B +a71;25CF +a72;274D +a73;25A0 +a74;274F +a75;2751 +a76;25B2 +a77;25BC +a78;25C6 +a79;2756 +a7;271E +a81;25D7 +a82;2758 +a83;2759 +a84;275A +a85;276F +a86;2771 +a87;2772 +a88;2773 +a89;2768 +a8;271F +a90;2769 +a91;276C +a92;276D +a93;276A +a94;276B +a95;2774 +a96;2775 +a97;275B +a98;275C +a99;275D +a9;2720 +# END diff --git a/src/Broadside/Fonts/Data/encodings.txt b/src/Broadside/Fonts/Data/encodings.txt new file mode 100644 index 00000000..622685b1 --- /dev/null +++ b/src/Broadside/Fonts/Data/encodings.txt @@ -0,0 +1,774 @@ +# Built-in font encodings of ISO 32000-2:2020 Annex D: code (octal) and glyph name, one per line. +# StandardEncoding, WinAnsiEncoding, MacRomanEncoding: Table D.2 columns STD, WIN, MAC, with the notes to Table D.2 +# applied (WIN 240 space and 255 hyphen; WIN 177 201 215 217 220 235 bullet; MAC 312 space). +# MacExpertEncoding: Table D.4. +# MacOSRomanAdditions: section 9.6.5.4 Table 113, the entries Mac OS Roman adds to (or replaces in) MacRomanEncoding. +# Cross-checked against the AFM C codes (StandardEncoding) and pdf.js src/core/encodings.js at +# c53f395e4057b501f478a7e98ed03d47c7c62a04 (all equal except MacRomanEncoding, where pdf.js mixes in Table 113). +[StandardEncoding] +040 space +041 exclam +042 quotedbl +043 numbersign +044 dollar +045 percent +046 ampersand +047 quoteright +050 parenleft +051 parenright +052 asterisk +053 plus +054 comma +055 hyphen +056 period +057 slash +060 zero +061 one +062 two +063 three +064 four +065 five +066 six +067 seven +070 eight +071 nine +072 colon +073 semicolon +074 less +075 equal +076 greater +077 question +100 at +101 A +102 B +103 C +104 D +105 E +106 F +107 G +110 H +111 I +112 J +113 K +114 L +115 M +116 N +117 O +120 P +121 Q +122 R +123 S +124 T +125 U +126 V +127 W +130 X +131 Y +132 Z +133 bracketleft +134 backslash +135 bracketright +136 asciicircum +137 underscore +140 quoteleft +141 a +142 b +143 c +144 d +145 e +146 f +147 g +150 h +151 i +152 j +153 k +154 l +155 m +156 n +157 o +160 p +161 q +162 r +163 s +164 t +165 u +166 v +167 w +170 x +171 y +172 z +173 braceleft +174 bar +175 braceright +176 asciitilde +241 exclamdown +242 cent +243 sterling +244 fraction +245 yen +246 florin +247 section +250 currency +251 quotesingle +252 quotedblleft +253 guillemotleft +254 guilsinglleft +255 guilsinglright +256 fi +257 fl +261 endash +262 dagger +263 daggerdbl +264 periodcentered +266 paragraph +267 bullet +270 quotesinglbase +271 quotedblbase +272 quotedblright +273 guillemotright +274 ellipsis +275 perthousand +277 questiondown +301 grave +302 acute +303 circumflex +304 tilde +305 macron +306 breve +307 dotaccent +310 dieresis +312 ring +313 cedilla +315 hungarumlaut +316 ogonek +317 caron +320 emdash +341 AE +343 ordfeminine +350 Lslash +351 Oslash +352 OE +353 ordmasculine +361 ae +365 dotlessi +370 lslash +371 oslash +372 oe +373 germandbls +[WinAnsiEncoding] +040 space +041 exclam +042 quotedbl +043 numbersign +044 dollar +045 percent +046 ampersand +047 quotesingle +050 parenleft +051 parenright +052 asterisk +053 plus +054 comma +055 hyphen +056 period +057 slash +060 zero +061 one +062 two +063 three +064 four +065 five +066 six +067 seven +070 eight +071 nine +072 colon +073 semicolon +074 less +075 equal +076 greater +077 question +100 at +101 A +102 B +103 C +104 D +105 E +106 F +107 G +110 H +111 I +112 J +113 K +114 L +115 M +116 N +117 O +120 P +121 Q +122 R +123 S +124 T +125 U +126 V +127 W +130 X +131 Y +132 Z +133 bracketleft +134 backslash +135 bracketright +136 asciicircum +137 underscore +140 grave +141 a +142 b +143 c +144 d +145 e +146 f +147 g +150 h +151 i +152 j +153 k +154 l +155 m +156 n +157 o +160 p +161 q +162 r +163 s +164 t +165 u +166 v +167 w +170 x +171 y +172 z +173 braceleft +174 bar +175 braceright +176 asciitilde +177 bullet +200 Euro +201 bullet +202 quotesinglbase +203 florin +204 quotedblbase +205 ellipsis +206 dagger +207 daggerdbl +210 circumflex +211 perthousand +212 Scaron +213 guilsinglleft +214 OE +215 bullet +216 Zcaron +217 bullet +220 bullet +221 quoteleft +222 quoteright +223 quotedblleft +224 quotedblright +225 bullet +226 endash +227 emdash +230 tilde +231 trademark +232 scaron +233 guilsinglright +234 oe +235 bullet +236 zcaron +237 Ydieresis +240 space +241 exclamdown +242 cent +243 sterling +244 currency +245 yen +246 brokenbar +247 section +250 dieresis +251 copyright +252 ordfeminine +253 guillemotleft +254 logicalnot +255 hyphen +256 registered +257 macron +260 degree +261 plusminus +262 twosuperior +263 threesuperior +264 acute +265 mu +266 paragraph +267 periodcentered +270 cedilla +271 onesuperior +272 ordmasculine +273 guillemotright +274 onequarter +275 onehalf +276 threequarters +277 questiondown +300 Agrave +301 Aacute +302 Acircumflex +303 Atilde +304 Adieresis +305 Aring +306 AE +307 Ccedilla +310 Egrave +311 Eacute +312 Ecircumflex +313 Edieresis +314 Igrave +315 Iacute +316 Icircumflex +317 Idieresis +320 Eth +321 Ntilde +322 Ograve +323 Oacute +324 Ocircumflex +325 Otilde +326 Odieresis +327 multiply +330 Oslash +331 Ugrave +332 Uacute +333 Ucircumflex +334 Udieresis +335 Yacute +336 Thorn +337 germandbls +340 agrave +341 aacute +342 acircumflex +343 atilde +344 adieresis +345 aring +346 ae +347 ccedilla +350 egrave +351 eacute +352 ecircumflex +353 edieresis +354 igrave +355 iacute +356 icircumflex +357 idieresis +360 eth +361 ntilde +362 ograve +363 oacute +364 ocircumflex +365 otilde +366 odieresis +367 divide +370 oslash +371 ugrave +372 uacute +373 ucircumflex +374 udieresis +375 yacute +376 thorn +377 ydieresis +[MacRomanEncoding] +040 space +041 exclam +042 quotedbl +043 numbersign +044 dollar +045 percent +046 ampersand +047 quotesingle +050 parenleft +051 parenright +052 asterisk +053 plus +054 comma +055 hyphen +056 period +057 slash +060 zero +061 one +062 two +063 three +064 four +065 five +066 six +067 seven +070 eight +071 nine +072 colon +073 semicolon +074 less +075 equal +076 greater +077 question +100 at +101 A +102 B +103 C +104 D +105 E +106 F +107 G +110 H +111 I +112 J +113 K +114 L +115 M +116 N +117 O +120 P +121 Q +122 R +123 S +124 T +125 U +126 V +127 W +130 X +131 Y +132 Z +133 bracketleft +134 backslash +135 bracketright +136 asciicircum +137 underscore +140 grave +141 a +142 b +143 c +144 d +145 e +146 f +147 g +150 h +151 i +152 j +153 k +154 l +155 m +156 n +157 o +160 p +161 q +162 r +163 s +164 t +165 u +166 v +167 w +170 x +171 y +172 z +173 braceleft +174 bar +175 braceright +176 asciitilde +200 Adieresis +201 Aring +202 Ccedilla +203 Eacute +204 Ntilde +205 Odieresis +206 Udieresis +207 aacute +210 agrave +211 acircumflex +212 adieresis +213 atilde +214 aring +215 ccedilla +216 eacute +217 egrave +220 ecircumflex +221 edieresis +222 iacute +223 igrave +224 icircumflex +225 idieresis +226 ntilde +227 oacute +230 ograve +231 ocircumflex +232 odieresis +233 otilde +234 uacute +235 ugrave +236 ucircumflex +237 udieresis +240 dagger +241 degree +242 cent +243 sterling +244 section +245 bullet +246 paragraph +247 germandbls +250 registered +251 copyright +252 trademark +253 acute +254 dieresis +256 AE +257 Oslash +261 plusminus +264 yen +265 mu +273 ordfeminine +274 ordmasculine +276 ae +277 oslash +300 questiondown +301 exclamdown +302 logicalnot +304 florin +307 guillemotleft +310 guillemotright +311 ellipsis +312 space +313 Agrave +314 Atilde +315 Otilde +316 OE +317 oe +320 endash +321 emdash +322 quotedblleft +323 quotedblright +324 quoteleft +325 quoteright +326 divide +330 ydieresis +331 Ydieresis +332 fraction +333 currency +334 guilsinglleft +335 guilsinglright +336 fi +337 fl +340 daggerdbl +341 periodcentered +342 quotesinglbase +343 quotedblbase +344 perthousand +345 Acircumflex +346 Ecircumflex +347 Aacute +350 Edieresis +351 Egrave +352 Iacute +353 Icircumflex +354 Idieresis +355 Igrave +356 Oacute +357 Ocircumflex +361 Ograve +362 Uacute +363 Ucircumflex +364 Ugrave +365 dotlessi +366 circumflex +367 tilde +370 macron +371 breve +372 dotaccent +373 ring +374 cedilla +375 hungarumlaut +376 ogonek +377 caron +[MacExpertEncoding] +040 space +041 exclamsmall +042 Hungarumlautsmall +043 centoldstyle +044 dollaroldstyle +045 dollarsuperior +046 ampersandsmall +047 Acutesmall +050 parenleftsuperior +051 parenrightsuperior +052 twodotenleader +053 onedotenleader +054 comma +055 hyphen +056 period +057 fraction +060 zerooldstyle +061 oneoldstyle +062 twooldstyle +063 threeoldstyle +064 fouroldstyle +065 fiveoldstyle +066 sixoldstyle +067 sevenoldstyle +070 eightoldstyle +071 nineoldstyle +072 colon +073 semicolon +075 threequartersemdash +077 questionsmall +104 Ethsmall +107 onequarter +110 onehalf +111 threequarters +112 oneeighth +113 threeeighths +114 fiveeighths +115 seveneighths +116 onethird +117 twothirds +126 ff +127 fi +130 fl +131 ffi +132 ffl +133 parenleftinferior +135 parenrightinferior +136 Circumflexsmall +137 hypheninferior +140 Gravesmall +141 Asmall +142 Bsmall +143 Csmall +144 Dsmall +145 Esmall +146 Fsmall +147 Gsmall +150 Hsmall +151 Ismall +152 Jsmall +153 Ksmall +154 Lsmall +155 Msmall +156 Nsmall +157 Osmall +160 Psmall +161 Qsmall +162 Rsmall +163 Ssmall +164 Tsmall +165 Usmall +166 Vsmall +167 Wsmall +170 Xsmall +171 Ysmall +172 Zsmall +173 colonmonetary +174 onefitted +175 rupiah +176 Tildesmall +201 asuperior +202 centsuperior +207 Aacutesmall +210 Agravesmall +211 Acircumflexsmall +212 Adieresissmall +213 Atildesmall +214 Aringsmall +215 Ccedillasmall +216 Eacutesmall +217 Egravesmall +220 Ecircumflexsmall +221 Edieresissmall +222 Iacutesmall +223 Igravesmall +224 Icircumflexsmall +225 Idieresissmall +226 Ntildesmall +227 Oacutesmall +230 Ogravesmall +231 Ocircumflexsmall +232 Odieresissmall +233 Otildesmall +234 Uacutesmall +235 Ugravesmall +236 Ucircumflexsmall +237 Udieresissmall +241 eightsuperior +242 fourinferior +243 threeinferior +244 sixinferior +245 eightinferior +246 seveninferior +247 Scaronsmall +251 centinferior +252 twoinferior +254 Dieresissmall +256 Caronsmall +257 osuperior +260 fiveinferior +262 commainferior +263 periodinferior +264 Yacutesmall +266 dollarinferior +271 Thornsmall +273 nineinferior +274 zeroinferior +275 Zcaronsmall +276 AEsmall +277 Oslashsmall +300 questiondownsmall +301 oneinferior +302 Lslashsmall +311 Cedillasmall +317 OEsmall +320 figuredash +321 hyphensuperior +326 exclamdownsmall +330 Ydieresissmall +332 onesuperior +333 twosuperior +334 threesuperior +335 foursuperior +336 fivesuperior +337 sixsuperior +340 sevensuperior +341 ninesuperior +342 zerosuperior +344 esuperior +345 rsuperior +346 tsuperior +351 isuperior +352 ssuperior +353 dsuperior +361 lsuperior +362 Ogoneksmall +363 Brevesmall +364 Macronsmall +365 bsuperior +366 nsuperior +367 msuperior +370 commasuperior +371 periodsuperior +372 Dotaccentsmall +373 Ringsmall +[MacOSRomanAdditions] +255 notequal +260 infinity +262 lessequal +263 greaterequal +266 partialdiff +267 summation +270 product +271 pi +272 integral +275 Omega +303 radical +305 approxequal +306 Delta +327 lozenge +333 Euro +360 apple diff --git a/src/Broadside/Fonts/Data/generate.py b/src/Broadside/Fonts/Data/generate.py new file mode 100644 index 00000000..71b9020f --- /dev/null +++ b/src/Broadside/Fonts/Data/generate.py @@ -0,0 +1,380 @@ +#!/usr/bin/env python3 +"""Generates the font data tables of the core from the files in this directory. + +Run with ``python3 -I src/Broadside/Fonts/Data/generate.py`` (stdlib only). The output is deterministic: +re-running it on unchanged inputs reproduces the three files byte for byte, so a reviewer can regenerate and +``git diff`` them. + +Inputs (all checked in next to this script): + +* ``Afm/*.afm`` and ``Afm/MustRead.html``: the Adobe Core 14 AFM files, unmodified, from Apache PDFBox + (https://github.com/apache/pdfbox, commit 8712d47b075511a4c5a2829c3713ba2d538999bb, + pdfbox/src/main/resources/org/apache/pdfbox/resources/afm/). Licence: MustRead.html (SPDX APAFML). +* ``GlyphList/glyphlist.txt``, ``GlyphList/zapfdingbats.txt`` and ``GlyphList/LICENSE.md``: the Adobe Glyph + List 2.0 and the ITC Zapf Dingbats Glyph List, unmodified, from https://github.com/adobe-type-tools/agl-aglfn + (commit 4036a9ca80a62f64f9de4f7321a9a045ad0ecfd6). Licence: BSD-3-Clause (LICENSE.md). +* ``encodings.txt``: StandardEncoding, WinAnsiEncoding, MacRomanEncoding and MacExpertEncoding as ISO 32000-2 + Annex D (Tables D.2 and D.4, with the notes to Table D.2 applied) and the Mac OS Roman additions of Table 113. + +Outputs (in ``src/Broadside/Fonts/``): + +* ``GlyphNameTable.g.cs``: every glyph name the built-in encodings and the AFM files use, and the encodings as + code -> name index tables. The Symbol and ZapfDingbats built-in encodings come from the AFM ``C`` codes. +* ``Standard14Data.g.cs``: per-font metrics and per-glyph widths of the 14 fonts (a modification of the AFM files: + converted to C# tables, kerning, ligature and bounding-box data removed), and, per character set, the glyphs by + Unicode value (through the glyph lists) for resolving glyph names the AFM files do not use. +* ``AdobeGlyphList.g.cs``: the two glyph lists as name -> Unicode tables. +""" + +from __future__ import annotations + +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +OUT = os.path.dirname(HERE) + +# Order is the numeric value of the public Standard14Font enum. +FONTS = [ + ("Courier", "Courier"), + ("CourierBold", "Courier-Bold"), + ("CourierOblique", "Courier-Oblique"), + ("CourierBoldOblique", "Courier-BoldOblique"), + ("Helvetica", "Helvetica"), + ("HelveticaBold", "Helvetica-Bold"), + ("HelveticaOblique", "Helvetica-Oblique"), + ("HelveticaBoldOblique", "Helvetica-BoldOblique"), + ("TimesRoman", "Times-Roman"), + ("TimesBold", "Times-Bold"), + ("TimesItalic", "Times-Italic"), + ("TimesBoldItalic", "Times-BoldItalic"), + ("Symbol", "Symbol"), + ("ZapfDingbats", "ZapfDingbats"), +] + +# ISO 32000-2 §9.8.2 Table 121 bit values. +FIXED_PITCH, SERIF, SYMBOLIC, NONSYMBOLIC, ITALIC = 1, 2, 4, 32, 64 + + +class Afm: + """The parts of an AFM file (Adobe TN 5004) the tables need: global keys and C/WX/N of each glyph.""" + + def __init__(self, path: str) -> None: + self.keys: dict[str, str] = {} + self.comments: list[str] = [] + self.glyphs: list[tuple[int, int, str]] = [] # (code or -1, width, name) + in_metrics = False + with open(path, encoding="ascii") as fh: + for raw in fh: + line = raw.strip() + if not line: + continue + key, _, value = line.partition(" ") + if key == "StartCharMetrics": + in_metrics = True + elif key == "EndCharMetrics": + in_metrics = False + elif in_metrics: + fields = {} + for part in line.split(";"): + part = part.strip() + if part: + k, _, v = part.partition(" ") + fields.setdefault(k, v.strip()) + self.glyphs.append((int(fields["C"]), int(fields["WX"]), fields["N"])) + elif key == "Comment": + self.comments.append(value.strip()) + elif key not in self.keys: + self.keys[key] = value.strip() + + def number(self, key: str) -> float | None: + return float(self.keys[key]) if key in self.keys else None + + +def read_glyph_list(path: str) -> list[tuple[str, str]]: + entries = [] + with open(path, encoding="ascii") as fh: + for line in fh: + line = line.strip() + if not line or line.startswith("#"): + continue + name, value = line.split(";") + entries.append((name, "".join(chr(int(v, 16)) for v in value.split()))) + entries.sort(key=lambda e: e[0].encode("ascii")) + names = [n for n, _ in entries] + assert len(set(names)) == len(names), "duplicate glyph list names" + return entries + + +def read_encodings(path: str) -> dict[str, list[str | None]]: + tables: dict[str, list[str | None]] = {} + current: list[str | None] | None = None + with open(path, encoding="ascii") as fh: + for line in fh: + line = line.strip() + if not line or line.startswith("#"): + continue + if line.startswith("["): + current = [None] * 256 + tables[line[1:-1]] = current + continue + code, name = line.split() + assert current is not None and current[int(code, 8)] is None + current[int(code, 8)] = name + return tables + + +def cs_string(value: str) -> str: + out = [] + for ch in value: + if ch in "\"\\" or not (0x20 <= ord(ch) < 0x7F): + out.append("\\u%04X" % ord(ch)) + else: + out.append(ch) + return '"' + "".join(out) + '"' + + +def wrap(items: list[str], indent: str, width: int = 120) -> list[str]: + lines, current = [], indent + for item in items: + piece = item + "," + if len(current) + len(piece) + 1 > width and current.strip(): + lines.append(current.rstrip()) + current = indent + current += piece + " " + if current.strip(): + lines.append(current.rstrip()) + return lines + + +def span(name: str, kind: str, values: list[int], doc: str) -> list[str]: + return ([f" /// {doc}", f" internal static ReadOnlySpan<{kind}> {name} =>", " ["] + + wrap([str(v) for v in values], " ") + [" ];", ""]) + + +def string_data(name: str, value: str, doc: str) -> list[str]: + chunks, i = [], 0 + while i < len(value): + chunks.append(value[i:i + 80]) + i += 80 + lines = [f" /// {doc}", f" private const string {name} ="] + for index, chunk in enumerate(chunks): + lines.append(" " + cs_string(chunk) + (";" if index == len(chunks) - 1 else " +")) + lines.append("") + return lines + + +def header(notices: list[str]) -> list[str]: + lines = ["// ", "// Generated by src/Broadside/Fonts/Data/generate.py. Do not edit; edit the generator or its inputs and re-run it."] + for notice in notices: + lines.append("//") + lines.extend("// " + n if n else "//" for n in notice.split("\n")) + lines += ["// ", "", "namespace Broadside.Fonts;", ""] + return lines + + +AFM_NOTICE = ( + "Derived from the Adobe Core 14 AFM files (Apache PDFBox commit 8712d47b075511a4c5a2829c3713ba2d538999bb,\n" + "pdfbox/src/main/resources/org/apache/pdfbox/resources/afm/), which carry this notice (MustRead.html):\n" + "\n" + "This file and the 14 PostScript(R) AFM files it accompanies may be used, copied, and distributed for any\n" + "purpose and without charge, with or without modification, provided that all copyright notices are retained;\n" + "that the AFM files are not distributed without this file; that all modifications to this file or any of the\n" + "AFM files are prominently noted in the modified file(s); and that this paragraph is not modified. Adobe\n" + "Systems has no responsibility or obligation to support the use of the AFM files.\n" + "\n" + "MODIFIED: the AFM files were converted to C# tables; kerning, ligature and glyph bounding-box data were\n" + "removed. The unmodified AFM files and MustRead.html are in src/Broadside/Fonts/Data/Afm/ and ship in the\n" + "package under licenses/adobe-core14-afm/.") + +AGL_NOTICE = ( + "Derived from the Adobe Glyph List and the ITC Zapf Dingbats Glyph List (https://github.com/adobe-type-tools/agl-aglfn,\n" + "commit 4036a9ca80a62f64f9de4f7321a9a045ad0ecfd6), converted to C# tables.\n" + "\n" + "Copyright 2002-2019 Adobe (http://www.adobe.com/).\n" + "\n" + "Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n" + "the following conditions are met:\n" + "\n" + "Redistributions of source code must retain the above copyright notice, this list of conditions and the\n" + "following disclaimer.\n" + "\n" + "Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n" + "following disclaimer in the documentation and/or other materials provided with the distribution.\n" + "\n" + "Neither the name of Adobe nor the names of its contributors may be used to endorse or promote products derived\n" + "from this software without specific prior written permission.\n" + "\n" + "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n" + "WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n" + "PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY\n" + "DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n" + "PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n" + "CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n" + "OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.") + + +def write(name: str, lines: list[str]) -> None: + with open(os.path.join(OUT, name), "w", encoding="utf-8", newline="\n") as fh: + fh.write("\n".join(lines).rstrip("\n") + "\n") + print("wrote", name) + + +def main() -> int: + afms = [Afm(os.path.join(HERE, "Afm", file + ".afm")) for _, file in FONTS] + for (_, file), afm in zip(FONTS, afms): + assert afm.keys["FontName"] == file, file + agl = read_glyph_list(os.path.join(HERE, "GlyphList", "glyphlist.txt")) + zapf_list = read_glyph_list(os.path.join(HERE, "GlyphList", "zapfdingbats.txt")) + encodings = read_encodings(os.path.join(HERE, "encodings.txt")) + + # The built-in encodings of the two symbolic fonts are their AFM C codes (Annex D.5, D.6). + for label, afm in (("SymbolEncoding", afms[12]), ("ZapfDingbatsEncoding", afms[13])): + table: list[str | None] = [None] * 256 + for code, _, name in afm.glyphs: + if code >= 0: + table[code] = name + encodings[label] = table + # StandardEncoding is the C codes of every Latin AFM (Annex D.2 STD column). + for afm in afms[:12]: + latin = [None] * 256 + for code, _, name in afm.glyphs: + if code >= 0: + latin[code] = name + assert latin == encodings["StandardEncoding"], afm.keys["FontName"] + # Mac OS Roman (§9.6.5.4 Table 113) = MacRomanEncoding plus the additions, Euro replacing currency. + mac_os = list(encodings["MacRomanEncoding"]) + for code, name in enumerate(encodings.pop("MacOSRomanAdditions")): + if name: + mac_os[code] = name + encodings["MacOSRomanEncoding"] = mac_os + + names = set() + for afm in afms: + names.update(name for _, _, name in afm.glyphs) + for table in encodings.values(): + names.update(n for n in table if n) + names = sorted(names, key=lambda n: n.encode("ascii")) + index = {n: i for i, n in enumerate(names)} + + # GlyphNameTable.g.cs + lines = header([AFM_NOTICE]) + lines += [ + "/// Glyph names the built-in encodings and the Standard 14 metrics use, and the built-in encodings as name indexes.", + "/// ISO 32000-2 Annex D (Tables D.2, D.4, D.5, D.6) and §9.6.5.4 Table 113.", + "internal static partial class GlyphNameTable", + "{", + " /// Every glyph name, in ordinal order.", + " internal static readonly string[] Names =", + " [", + ] + lines += wrap([cs_string(n) for n in names], " ") + lines += [" ];", ""] + order = ["StandardEncoding", "WinAnsiEncoding", "MacRomanEncoding", "MacExpertEncoding", "SymbolEncoding", + "ZapfDingbatsEncoding", "MacOSRomanEncoding"] + for label in order: + table = encodings[label] + lines += span(label, "short", [index[n] if n else -1 for n in table], + f"{label}: for each code, the index of its glyph name in , or -1.") + lines[-1:] = ["}"] + write("GlyphNameTable.g.cs", lines) + + # Standard14Data.g.cs + widths = [] + for afm in afms: + row = [-1] * len(names) + for _, wx, name in afm.glyphs: + row[index[name]] = wx + widths.extend(row) + metrics = [] + for (_, file), afm in zip(FONTS, afms): + bbox = [int(v) for v in afm.keys["FontBBox"].split()] + italic = afm.number("ItalicAngle") or 0.0 + fixed = afm.keys["IsFixedPitch"] == "true" + symbolic = afm.keys["EncodingScheme"] == "FontSpecific" + serif = file.startswith("Times") + flags = (FIXED_PITCH if fixed else 0) | (SERIF if serif else 0) | (SYMBOLIC if symbolic else NONSYMBOLIC) \ + | (ITALIC if italic != 0 else 0) + # Symbol and ZapfDingbats have no CapHeight, XHeight, Ascender or Descender: the font box stands in for + # Ascent, Descent and CapHeight, and XHeight is 0 (the §9.8.1 default). + cap = afm.number("CapHeight") if "CapHeight" in afm.keys else bbox[3] + xh = afm.number("XHeight") or 0 + asc = afm.number("Ascender") if "Ascender" in afm.keys else bbox[3] + desc = afm.number("Descender") if "Descender" in afm.keys else bbox[1] + metrics.extend(bbox + [int(round(italic * 10)), int(cap), int(xh), int(asc), int(desc), + int(afm.number("StdVW")), int(afm.number("StdHW")), flags]) + + notices = [AFM_NOTICE] + for (_, file), afm in zip(FONTS, afms): + copyright_lines = [c for c in afm.comments if c.startswith("Copyright")] + notices.append(f"{file}.afm:\n" + "\n".join(copyright_lines + ["Notice " + afm.keys["Notice"]])) + notices.append(AGL_NOTICE) + lines = header(notices) + lines += [ + "/// Metrics of the Standard 14 fonts, from the Adobe Core 14 AFM files.", + "/// ISO 32000-2 §9.6.2.2; Adobe Technical Note #5004.", + "internal static partial class Standard14Data", + "{", + f" /// The number of glyph names in ; the stride of .", + f" internal const int NameCount = {len(names)};", + "", + " /// The number of values per font in .", + " internal const int MetricsStride = 12;", + "", + ] + lines += span("Widths", "short", widths, + "For each font (in order) and each glyph name index, the AFM WX width, or -1 when the font has no such glyph.") + lines += span("FontMetrics", "short", metrics, + "For each font: FontBBox (4 values), ItalicAngle x 10, CapHeight, XHeight, Ascent, Descent, StdVW, StdHW and the ISO 32000-2 Table 121 flags.") + + def by_unicode(glyph_names: set[str], glyph_list: list[tuple[str, str]]) -> tuple[list[int], list[int]]: + lookup = dict(glyph_list) + pairs = {} + for name in sorted(glyph_names, key=lambda n: n.encode("ascii")): + value = lookup.get(name) + if value and len(value) == 1 and ord(value) not in pairs: + pairs[ord(value)] = index[name] + keys = sorted(pairs) + return keys, [pairs[k] for k in keys] + + for label, glyphs, glyph_list in ( + ("Latin", {n for _, _, n in afms[4].glyphs}, agl), + ("Symbol", {n for _, _, n in afms[12].glyphs}, agl), + ("ZapfDingbats", {n for _, _, n in afms[13].glyphs}, zapf_list)): + keys, values = by_unicode(glyphs, glyph_list) + lines += span(label + "Unicodes", "ushort", keys, + f"Unicode values of the {label} character set's glyphs, ascending; parallel to .") + lines += span(label + "UnicodeNames", "short", values, + f"For each value of , the index of the glyph's name in .") + lines[-1:] = ["}"] + write("Standard14Data.g.cs", lines) + + # AdobeGlyphList.g.cs + lines = header([AGL_NOTICE]) + lines += [ + "/// The Adobe Glyph List and the ITC Zapf Dingbats Glyph List: glyph name to Unicode.", + "/// ISO 32000-2 §9.10.2 refers to the Adobe Glyph List for mapping glyph names to Unicode.", + "internal static partial class AdobeGlyphList", + "{", + ] + for label, entries in (("Agl", agl), ("Zapf", zapf_list)): + name_data, name_offsets, value_data, value_offsets = "", [0], "", [0] + for name, value in entries: + name_data += name + name_offsets.append(len(name_data)) + value_data += value + value_offsets.append(len(value_data)) + assert len(name_data) < 65536 and len(value_data) < 65536 + lines += [f" private const int {label}Count = {len(entries)};", ""] + lines += string_data(label + "Names", name_data, "The glyph names, ordinal order, concatenated.") + lines += span(label + "NameOffsets", "ushort", name_offsets, "Where each name starts in the names; one more entry than there are names.") + lines += string_data(label + "Values", value_data, "The Unicode values of each name, concatenated.") + lines += span(label + "ValueOffsets", "ushort", value_offsets, "Where each value starts in the values; one more entry than there are names.") + lines[-1:] = ["}"] + write("AdobeGlyphList.g.cs", lines) + print(len(names), "glyph names;", len(agl), "AGL entries;", len(zapf_list), "Zapf Dingbats entries") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/Broadside/Fonts/FontNames.cs b/src/Broadside/Fonts/FontNames.cs new file mode 100644 index 00000000..fb44bfae --- /dev/null +++ b/src/Broadside/Fonts/FontNames.cs @@ -0,0 +1,127 @@ +using Broadside.Objects; + +namespace Broadside.Fonts; + +/// Names the font model looks up in font dictionaries, font descriptors and encoding dictionaries, created once. +internal static class FontNames +{ + /// /Font, the type of a font dictionary and the resource category of fonts (§9.6.2.1 Table 109, §7.8.3). + public static readonly CosName Font = new("Font"); + + /// /Subtype (§9.5 Table 108). + public static readonly CosName Subtype = new("Subtype"); + + /// /BaseFont (§9.6.2.1 Table 109). + public static readonly CosName BaseFont = new("BaseFont"); + + /// /FirstChar (§9.6.2.1 Table 109). + public static readonly CosName FirstChar = new("FirstChar"); + + /// /LastChar (§9.6.2.1 Table 109). + public static readonly CosName LastChar = new("LastChar"); + + /// /Widths (§9.6.2.1 Table 109). + public static readonly CosName Widths = new("Widths"); + + /// /FontDescriptor (§9.6.2.1 Table 109), also the type of a font descriptor (§9.8.1 Table 120). + public static readonly CosName FontDescriptor = new("FontDescriptor"); + + /// /Encoding (§9.6.2.1 Table 109), also the type of an encoding dictionary (§9.6.5.1 Table 112). + public static readonly CosName Encoding = new("Encoding"); + + /// /BaseEncoding (§9.6.5.1 Table 112). + public static readonly CosName BaseEncoding = new("BaseEncoding"); + + /// /Differences (§9.6.5.1 Table 112). + public static readonly CosName Differences = new("Differences"); + + /// /Type1 (§9.5 Table 108). + public static readonly CosName Type1 = new("Type1"); + + /// /MMType1 (§9.5 Table 108). + public static readonly CosName MMType1 = new("MMType1"); + + /// /TrueType (§9.5 Table 108). + public static readonly CosName TrueType = new("TrueType"); + + /// /Type3 (§9.5 Table 108). + public static readonly CosName Type3 = new("Type3"); + + /// /Type0 (§9.5 Table 108). + public static readonly CosName Type0 = new("Type0"); + + /// /WinAnsiEncoding (Annex D.1 Table D.1). + public static readonly CosName WinAnsiEncoding = new("WinAnsiEncoding"); + + /// /MacRomanEncoding (Annex D.1 Table D.1). + public static readonly CosName MacRomanEncoding = new("MacRomanEncoding"); + + /// /MacExpertEncoding (Annex D.1 Table D.1). + public static readonly CosName MacExpertEncoding = new("MacExpertEncoding"); + + /// /StandardEncoding: not a predefined PDF name (§9.6.5.1), but written by some producers. + public static readonly CosName StandardEncoding = new("StandardEncoding"); + + /// /FontName (§9.8.1 Table 120). + public static readonly CosName FontName = new("FontName"); + + /// /FontFamily (§9.8.1 Table 120). + public static readonly CosName FontFamily = new("FontFamily"); + + /// /FontStretch (§9.8.1 Table 120). + public static readonly CosName FontStretch = new("FontStretch"); + + /// /FontWeight (§9.8.1 Table 120). + public static readonly CosName FontWeight = new("FontWeight"); + + /// /Flags (§9.8.1 Table 120). + public static readonly CosName Flags = new("Flags"); + + /// /FontBBox (§9.8.1 Table 120). + public static readonly CosName FontBBox = new("FontBBox"); + + /// /ItalicAngle (§9.8.1 Table 120). + public static readonly CosName ItalicAngle = new("ItalicAngle"); + + /// /Ascent (§9.8.1 Table 120). + public static readonly CosName Ascent = new("Ascent"); + + /// /Descent (§9.8.1 Table 120). + public static readonly CosName Descent = new("Descent"); + + /// /Leading (§9.8.1 Table 120). + public static readonly CosName Leading = new("Leading"); + + /// /CapHeight (§9.8.1 Table 120). + public static readonly CosName CapHeight = new("CapHeight"); + + /// /XHeight (§9.8.1 Table 120). + public static readonly CosName XHeight = new("XHeight"); + + /// /StemV (§9.8.1 Table 120). + public static readonly CosName StemV = new("StemV"); + + /// /StemH (§9.8.1 Table 120). + public static readonly CosName StemH = new("StemH"); + + /// /AvgWidth (§9.8.1 Table 120). + public static readonly CosName AvgWidth = new("AvgWidth"); + + /// /MaxWidth (§9.8.1 Table 120). + public static readonly CosName MaxWidth = new("MaxWidth"); + + /// /MissingWidth (§9.8.1 Table 120). + public static readonly CosName MissingWidth = new("MissingWidth"); + + /// /FontFile (§9.8.1 Table 120). + public static readonly CosName FontFile = new("FontFile"); + + /// /FontFile2 (§9.8.1 Table 120). + public static readonly CosName FontFile2 = new("FontFile2"); + + /// /FontFile3 (§9.8.1 Table 120). + public static readonly CosName FontFile3 = new("FontFile3"); + + /// /CharSet (§9.8.1 Table 120). + public static readonly CosName CharSet = new("CharSet"); +} diff --git a/src/Broadside/Fonts/GlyphNameTable.cs b/src/Broadside/Fonts/GlyphNameTable.cs new file mode 100644 index 00000000..5504d726 --- /dev/null +++ b/src/Broadside/Fonts/GlyphNameTable.cs @@ -0,0 +1,60 @@ +namespace Broadside.Fonts; + +/// Lookups over the generated glyph name and built-in encoding tables (GlyphNameTable.g.cs). +internal static partial class GlyphNameTable +{ + /// The glyph name of a code that has none: every Type 1 font program has a glyph of this name (§9.6.5.2). + public const string NotDef = ".notdef"; + + /// Finds the index of in . + /// A glyph name. + /// The index, or -1 when no built-in encoding or Standard 14 font uses the name. + public static int IndexOf(string name) => Array.BinarySearch(Names, name, StringComparer.Ordinal) is var index and >= 0 ? index : -1; + + /// Gets the code to name-index table of a built-in encoding. + /// The encoding. + /// For each code, the index of its name in , or -1. + public static ReadOnlySpan Table(BuiltInEncoding encoding) => encoding switch + { + BuiltInEncoding.Standard => StandardEncoding, + BuiltInEncoding.WinAnsi => WinAnsiEncoding, + BuiltInEncoding.MacRoman => MacRomanEncoding, + BuiltInEncoding.MacExpert => MacExpertEncoding, + BuiltInEncoding.Symbol => SymbolEncoding, + BuiltInEncoding.ZapfDingbats => ZapfDingbatsEncoding, + BuiltInEncoding.MacOSRoman => MacOSRomanEncoding, + _ => throw new ArgumentOutOfRangeException(nameof(encoding)), + }; + + /// Gets the glyph name a built-in encoding gives a code. + /// The encoding. + /// The character code. + /// The name, or when the encoding leaves the code unused. + public static string? NameOf(BuiltInEncoding encoding, byte code) => Table(encoding)[code] is var index and >= 0 ? Names[index] : null; +} + +/// The encodings PDF predefines or uses as a default, and the built-in encodings of the two symbolic Standard 14 fonts. +/// ISO 32000-2 §9.6.5.1 and Annex D. +internal enum BuiltInEncoding : byte +{ + /// StandardEncoding, the Adobe standard Latin encoding (Annex D.2, STD column). + Standard, + + /// WinAnsiEncoding (Annex D.2, WIN column and its notes). + WinAnsi, + + /// MacRomanEncoding (Annex D.2, MAC column and its notes). + MacRoman, + + /// MacExpertEncoding (Annex D.4). + MacExpert, + + /// The built-in encoding of the Symbol font (Annex D.5). + Symbol, + + /// The built-in encoding of the ZapfDingbats font (Annex D.6, plus the codes 0x80 to 0x8D its AFM file encodes). + ZapfDingbats, + + /// Mac OS Roman: MacRomanEncoding with the §9.6.5.4 Table 113 additions, for TrueType "cmap" (1, 0) lookups. + MacOSRoman, +} diff --git a/src/Broadside/Fonts/GlyphNameTable.g.cs b/src/Broadside/Fonts/GlyphNameTable.g.cs new file mode 100644 index 00000000..01676aae --- /dev/null +++ b/src/Broadside/Fonts/GlyphNameTable.g.cs @@ -0,0 +1,224 @@ +// +// Generated by src/Broadside/Fonts/Data/generate.py. Do not edit; edit the generator or its inputs and re-run it. +// +// Derived from the Adobe Core 14 AFM files (Apache PDFBox commit 8712d47b075511a4c5a2829c3713ba2d538999bb, +// pdfbox/src/main/resources/org/apache/pdfbox/resources/afm/), which carry this notice (MustRead.html): +// +// This file and the 14 PostScript(R) AFM files it accompanies may be used, copied, and distributed for any +// purpose and without charge, with or without modification, provided that all copyright notices are retained; +// that the AFM files are not distributed without this file; that all modifications to this file or any of the +// AFM files are prominently noted in the modified file(s); and that this paragraph is not modified. Adobe +// Systems has no responsibility or obligation to support the use of the AFM files. +// +// MODIFIED: the AFM files were converted to C# tables; kerning, ligature and glyph bounding-box data were +// removed. The unmodified AFM files and MustRead.html are in src/Broadside/Fonts/Data/Afm/ and ship in the +// package under licenses/adobe-core14-afm/. +// + +namespace Broadside.Fonts; + +/// Glyph names the built-in encodings and the Standard 14 metrics use, and the built-in encodings as name indexes. +/// ISO 32000-2 Annex D (Tables D.2, D.4, D.5, D.6) and §9.6.5.4 Table 113. +internal static partial class GlyphNameTable +{ + /// Every glyph name, in ordinal order. + internal static readonly string[] Names = + [ + "A", "AE", "AEsmall", "Aacute", "Aacutesmall", "Abreve", "Acircumflex", "Acircumflexsmall", "Acutesmall", + "Adieresis", "Adieresissmall", "Agrave", "Agravesmall", "Alpha", "Amacron", "Aogonek", "Aring", "Aringsmall", + "Asmall", "Atilde", "Atildesmall", "B", "Beta", "Brevesmall", "Bsmall", "C", "Cacute", "Caronsmall", "Ccaron", + "Ccedilla", "Ccedillasmall", "Cedillasmall", "Chi", "Circumflexsmall", "Csmall", "D", "Dcaron", "Dcroat", + "Delta", "Dieresissmall", "Dotaccentsmall", "Dsmall", "E", "Eacute", "Eacutesmall", "Ecaron", "Ecircumflex", + "Ecircumflexsmall", "Edieresis", "Edieresissmall", "Edotaccent", "Egrave", "Egravesmall", "Emacron", "Eogonek", + "Epsilon", "Esmall", "Eta", "Eth", "Ethsmall", "Euro", "F", "Fsmall", "G", "Gamma", "Gbreve", "Gcommaaccent", + "Gravesmall", "Gsmall", "H", "Hsmall", "Hungarumlautsmall", "I", "Iacute", "Iacutesmall", "Icircumflex", + "Icircumflexsmall", "Idieresis", "Idieresissmall", "Idotaccent", "Ifraktur", "Igrave", "Igravesmall", + "Imacron", "Iogonek", "Iota", "Ismall", "J", "Jsmall", "K", "Kappa", "Kcommaaccent", "Ksmall", "L", "Lacute", + "Lambda", "Lcaron", "Lcommaaccent", "Lslash", "Lslashsmall", "Lsmall", "M", "Macronsmall", "Msmall", "Mu", "N", + "Nacute", "Ncaron", "Ncommaaccent", "Nsmall", "Ntilde", "Ntildesmall", "Nu", "O", "OE", "OEsmall", "Oacute", + "Oacutesmall", "Ocircumflex", "Ocircumflexsmall", "Odieresis", "Odieresissmall", "Ogoneksmall", "Ograve", + "Ogravesmall", "Ohungarumlaut", "Omacron", "Omega", "Omicron", "Oslash", "Oslashsmall", "Osmall", "Otilde", + "Otildesmall", "P", "Phi", "Pi", "Psi", "Psmall", "Q", "Qsmall", "R", "Racute", "Rcaron", "Rcommaaccent", + "Rfraktur", "Rho", "Ringsmall", "Rsmall", "S", "Sacute", "Scaron", "Scaronsmall", "Scedilla", "Scommaaccent", + "Sigma", "Ssmall", "T", "Tau", "Tcaron", "Tcommaaccent", "Theta", "Thorn", "Thornsmall", "Tildesmall", + "Tsmall", "U", "Uacute", "Uacutesmall", "Ucircumflex", "Ucircumflexsmall", "Udieresis", "Udieresissmall", + "Ugrave", "Ugravesmall", "Uhungarumlaut", "Umacron", "Uogonek", "Upsilon", "Upsilon1", "Uring", "Usmall", "V", + "Vsmall", "W", "Wsmall", "X", "Xi", "Xsmall", "Y", "Yacute", "Yacutesmall", "Ydieresis", "Ydieresissmall", + "Ysmall", "Z", "Zacute", "Zcaron", "Zcaronsmall", "Zdotaccent", "Zeta", "Zsmall", "a", "a1", "a10", "a100", + "a101", "a102", "a103", "a104", "a105", "a106", "a107", "a108", "a109", "a11", "a110", "a111", "a112", "a117", + "a118", "a119", "a12", "a120", "a121", "a122", "a123", "a124", "a125", "a126", "a127", "a128", "a129", "a13", + "a130", "a131", "a132", "a133", "a134", "a135", "a136", "a137", "a138", "a139", "a14", "a140", "a141", "a142", + "a143", "a144", "a145", "a146", "a147", "a148", "a149", "a15", "a150", "a151", "a152", "a153", "a154", "a155", + "a156", "a157", "a158", "a159", "a16", "a160", "a161", "a162", "a163", "a164", "a165", "a166", "a167", "a168", + "a169", "a17", "a170", "a171", "a172", "a173", "a174", "a175", "a176", "a177", "a178", "a179", "a18", "a180", + "a181", "a182", "a183", "a184", "a185", "a186", "a187", "a188", "a189", "a19", "a190", "a191", "a192", "a193", + "a194", "a195", "a196", "a197", "a198", "a199", "a2", "a20", "a200", "a201", "a202", "a203", "a204", "a205", + "a206", "a21", "a22", "a23", "a24", "a25", "a26", "a27", "a28", "a29", "a3", "a30", "a31", "a32", "a33", "a34", + "a35", "a36", "a37", "a38", "a39", "a4", "a40", "a41", "a42", "a43", "a44", "a45", "a46", "a47", "a48", "a49", + "a5", "a50", "a51", "a52", "a53", "a54", "a55", "a56", "a57", "a58", "a59", "a6", "a60", "a61", "a62", "a63", + "a64", "a65", "a66", "a67", "a68", "a69", "a7", "a70", "a71", "a72", "a73", "a74", "a75", "a76", "a77", "a78", + "a79", "a8", "a81", "a82", "a83", "a84", "a85", "a86", "a87", "a88", "a89", "a9", "a90", "a91", "a92", "a93", + "a94", "a95", "a96", "a97", "a98", "a99", "aacute", "abreve", "acircumflex", "acute", "adieresis", "ae", + "agrave", "aleph", "alpha", "amacron", "ampersand", "ampersandsmall", "angle", "angleleft", "angleright", + "aogonek", "apple", "approxequal", "aring", "arrowboth", "arrowdblboth", "arrowdbldown", "arrowdblleft", + "arrowdblright", "arrowdblup", "arrowdown", "arrowhorizex", "arrowleft", "arrowright", "arrowup", + "arrowvertex", "asciicircum", "asciitilde", "asterisk", "asteriskmath", "asuperior", "at", "atilde", "b", + "backslash", "bar", "beta", "braceex", "braceleft", "braceleftbt", "braceleftmid", "bracelefttp", "braceright", + "bracerightbt", "bracerightmid", "bracerighttp", "bracketleft", "bracketleftbt", "bracketleftex", + "bracketlefttp", "bracketright", "bracketrightbt", "bracketrightex", "bracketrighttp", "breve", "brokenbar", + "bsuperior", "bullet", "c", "cacute", "caron", "carriagereturn", "ccaron", "ccedilla", "cedilla", "cent", + "centinferior", "centoldstyle", "centsuperior", "chi", "circlemultiply", "circleplus", "circumflex", "club", + "colon", "colonmonetary", "comma", "commaaccent", "commainferior", "commasuperior", "congruent", "copyright", + "copyrightsans", "copyrightserif", "currency", "d", "dagger", "daggerdbl", "dcaron", "dcroat", "degree", + "delta", "diamond", "dieresis", "divide", "dollar", "dollarinferior", "dollaroldstyle", "dollarsuperior", + "dotaccent", "dotlessi", "dotmath", "dsuperior", "e", "eacute", "ecaron", "ecircumflex", "edieresis", + "edotaccent", "egrave", "eight", "eightinferior", "eightoldstyle", "eightsuperior", "element", "ellipsis", + "emacron", "emdash", "emptyset", "endash", "eogonek", "epsilon", "equal", "equivalence", "esuperior", "eta", + "eth", "exclam", "exclamdown", "exclamdownsmall", "exclamsmall", "existential", "f", "ff", "ffi", "ffl", "fi", + "figuredash", "five", "fiveeighths", "fiveinferior", "fiveoldstyle", "fivesuperior", "fl", "florin", "four", + "fourinferior", "fouroldstyle", "foursuperior", "fraction", "g", "gamma", "gbreve", "gcommaaccent", + "germandbls", "gradient", "grave", "greater", "greaterequal", "guillemotleft", "guillemotright", + "guilsinglleft", "guilsinglright", "h", "heart", "hungarumlaut", "hyphen", "hypheninferior", "hyphensuperior", + "i", "iacute", "icircumflex", "idieresis", "igrave", "imacron", "infinity", "integral", "integralbt", + "integralex", "integraltp", "intersection", "iogonek", "iota", "isuperior", "j", "k", "kappa", "kcommaaccent", + "l", "lacute", "lambda", "lcaron", "lcommaaccent", "less", "lessequal", "logicaland", "logicalnot", + "logicalor", "lozenge", "lslash", "lsuperior", "m", "macron", "minus", "minute", "msuperior", "mu", "multiply", + "n", "nacute", "ncaron", "ncommaaccent", "nine", "nineinferior", "nineoldstyle", "ninesuperior", "notelement", + "notequal", "notsubset", "nsuperior", "ntilde", "nu", "numbersign", "o", "oacute", "ocircumflex", "odieresis", + "oe", "ogonek", "ograve", "ohungarumlaut", "omacron", "omega", "omega1", "omicron", "one", "onedotenleader", + "oneeighth", "onefitted", "onehalf", "oneinferior", "oneoldstyle", "onequarter", "onesuperior", "onethird", + "ordfeminine", "ordmasculine", "oslash", "osuperior", "otilde", "p", "paragraph", "parenleft", "parenleftbt", + "parenleftex", "parenleftinferior", "parenleftsuperior", "parenlefttp", "parenright", "parenrightbt", + "parenrightex", "parenrightinferior", "parenrightsuperior", "parenrighttp", "partialdiff", "percent", "period", + "periodcentered", "periodinferior", "periodsuperior", "perpendicular", "perthousand", "phi", "phi1", "pi", + "plus", "plusminus", "product", "propersubset", "propersuperset", "proportional", "psi", "q", "question", + "questiondown", "questiondownsmall", "questionsmall", "quotedbl", "quotedblbase", "quotedblleft", + "quotedblright", "quoteleft", "quoteright", "quotesinglbase", "quotesingle", "r", "racute", "radical", + "radicalex", "rcaron", "rcommaaccent", "reflexsubset", "reflexsuperset", "registered", "registersans", + "registerserif", "rho", "ring", "rsuperior", "rupiah", "s", "sacute", "scaron", "scedilla", "scommaaccent", + "second", "section", "semicolon", "seven", "seveneighths", "seveninferior", "sevenoldstyle", "sevensuperior", + "sigma", "sigma1", "similar", "six", "sixinferior", "sixoldstyle", "sixsuperior", "slash", "space", "spade", + "ssuperior", "sterling", "suchthat", "summation", "t", "tau", "tcaron", "tcommaaccent", "therefore", "theta", + "theta1", "thorn", "three", "threeeighths", "threeinferior", "threeoldstyle", "threequarters", + "threequartersemdash", "threesuperior", "tilde", "trademark", "trademarksans", "trademarkserif", "tsuperior", + "two", "twodotenleader", "twoinferior", "twooldstyle", "twosuperior", "twothirds", "u", "uacute", + "ucircumflex", "udieresis", "ugrave", "uhungarumlaut", "umacron", "underscore", "union", "universal", + "uogonek", "upsilon", "uring", "v", "w", "weierstrass", "x", "xi", "y", "yacute", "ydieresis", "yen", "z", + "zacute", "zcaron", "zdotaccent", "zero", "zeroinferior", "zerooldstyle", "zerosuperior", "zeta", + ]; + + /// StandardEncoding: for each code, the index of its glyph name in , or -1. + internal static ReadOnlySpan StandardEncoding => + [ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 740, 536, 696, 631, 504, 674, 414, 701, 661, 667, 437, 684, 485, 575, 675, 739, 798, 644, 766, + 754, 554, 547, 735, 727, 519, 621, 483, 726, 602, 531, 566, 692, 440, 0, 21, 25, 35, 42, 61, 63, 69, 72, 87, + 89, 93, 101, 105, 113, 134, 139, 141, 149, 157, 166, 182, 184, 186, 189, 195, 455, 443, 459, 435, 779, 700, + 202, 442, 467, 494, 512, 541, 559, 572, 578, 593, 594, 597, 610, 617, 632, 659, 691, 704, 719, 746, 772, 785, + 786, 788, 790, 794, 447, 444, 451, 436, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 537, 474, 743, 558, 793, 553, 725, 493, 703, + 698, 568, 570, 571, 545, 552, -1, 528, 495, 496, 676, -1, 660, 466, 702, 697, 699, 569, 524, 680, -1, 693, -1, + 565, 407, 481, 761, 611, 463, 508, 502, -1, 716, 473, -1, 574, 637, 469, 526, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, 654, -1, -1, -1, -1, 98, 129, 114, 655, -1, -1, -1, -1, -1, 409, -1, -1, + -1, 509, -1, -1, 608, 656, 636, 563, -1, -1, -1, -1, + ]; + + /// WinAnsiEncoding: for each code, the index of its glyph name in , or -1. + internal static ReadOnlySpan WinAnsiEncoding => + [ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 740, 536, 696, 631, 504, 674, 414, 703, 661, 667, 437, 684, 485, 575, 675, 739, 798, 644, 766, + 754, 554, 547, 735, 727, 519, 621, 483, 726, 602, 531, 566, 692, 440, 0, 21, 25, 35, 42, 61, 63, 69, 72, 87, + 89, 93, 101, 105, 113, 134, 139, 141, 149, 157, 166, 182, 184, 186, 189, 195, 455, 443, 459, 435, 779, 565, + 202, 442, 467, 494, 512, 541, 559, 572, 578, 593, 594, 597, 610, 617, 632, 659, 691, 704, 719, 746, 772, 785, + 786, 788, 790, 794, 447, 444, 451, 436, 466, 60, 466, 702, 553, 697, 524, 495, 496, 481, 680, 151, 570, 114, + 466, 197, 466, 466, 700, 701, 698, 699, 466, 528, 526, 761, 762, 721, 571, 636, 466, 796, 192, 740, 537, 474, + 743, 493, 793, 464, 725, 502, 490, 654, 568, 605, 575, 712, 611, 499, 685, 770, 760, 407, 615, 660, 676, 473, + 652, 655, 569, 651, 648, 758, 693, 11, 3, 6, 19, 9, 16, 1, 29, 51, 43, 46, 48, 81, 73, 75, 77, 58, 110, 123, + 116, 118, 132, 120, 616, 129, 173, 167, 169, 171, 190, 162, 563, 410, 404, 406, 441, 408, 422, 409, 472, 518, + 513, 515, 516, 582, 579, 580, 581, 535, 629, 638, 633, 634, 658, 635, 503, 656, 776, 773, 774, 775, 791, 753, + 792, + ]; + + /// MacRomanEncoding: for each code, the index of its glyph name in , or -1. + internal static ReadOnlySpan MacRomanEncoding => + [ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 740, 536, 696, 631, 504, 674, 414, 703, 661, 667, 437, 684, 485, 575, 675, 739, 798, 644, 766, + 754, 554, 547, 735, 727, 519, 621, 483, 726, 602, 531, 566, 692, 440, 0, 21, 25, 35, 42, 61, 63, 69, 72, 87, + 89, 93, 101, 105, 113, 134, 139, 141, 149, 157, 166, 182, 184, 186, 189, 195, 455, 443, 459, 435, 779, 565, + 202, 442, 467, 494, 512, 541, 559, 572, 578, 593, 594, 597, 610, 617, 632, 659, 691, 704, 719, 746, 772, 785, + 786, 788, 790, 794, 447, 444, 451, 436, -1, 9, 16, 29, 43, 110, 120, 171, 404, 410, 406, 408, 441, 422, 472, + 513, 518, 515, 516, 579, 582, 580, 581, 629, 633, 638, 634, 635, 658, 773, 776, 774, 775, 495, 499, 474, 743, + 725, 466, 660, 563, 712, 490, 762, 407, 502, -1, 1, 129, -1, 685, -1, -1, 793, 615, -1, -1, -1, -1, -1, 654, + 655, -1, 409, 656, 693, 537, 605, -1, 553, -1, -1, 568, 569, 524, 740, 11, 19, 132, 114, 636, 528, 526, 698, + 699, 700, 701, 503, -1, 792, 192, 558, 493, 570, 571, 545, 552, 496, 676, 702, 697, 680, 6, 46, 3, 48, 51, 73, + 75, 77, 81, 116, 118, -1, 123, 167, 169, 173, 509, 481, 761, 611, 463, 508, 716, 473, 574, 637, 469, + ]; + + /// MacExpertEncoding: for each code, the index of its glyph name in , or -1. + internal static ReadOnlySpan MacExpertEncoding => + [ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 740, 539, 71, 476, 506, 507, 415, 8, 665, 671, 767, 645, 485, 575, 675, 558, 800, 650, 769, + 757, 556, 550, 737, 730, 521, 623, 483, 726, -1, 759, -1, 695, -1, -1, -1, -1, 59, -1, -1, 651, 648, 758, 646, + 755, 548, 728, 653, 771, -1, -1, -1, -1, -1, -1, 542, 545, 552, 543, 544, 664, -1, 670, 33, 576, 67, 18, 24, + 34, 41, 56, 62, 68, 70, 86, 88, 92, 100, 103, 109, 131, 138, 140, 148, 156, 165, 181, 183, 185, 188, 194, 201, + 484, 647, 718, 164, -1, -1, 439, 477, -1, -1, -1, -1, 4, 12, 7, 10, 20, 17, 30, 44, 52, 47, 49, 74, 82, 76, 78, + 111, 117, 124, 119, 121, 133, 168, 174, 170, 172, -1, 522, 555, 756, 736, 520, 729, 152, -1, 475, 768, -1, 39, + -1, 27, 657, 549, -1, 487, 677, 191, -1, 505, -1, -1, 163, -1, 622, 799, 198, 2, 130, 694, 649, 99, -1, -1, -1, + -1, -1, -1, 31, -1, -1, -1, -1, -1, 115, 546, 577, -1, -1, -1, -1, 538, -1, 193, -1, 652, 770, 760, 557, 551, + 738, 731, 624, 801, -1, 533, 717, 765, -1, -1, 592, 742, 511, -1, -1, -1, -1, -1, 609, 122, 23, 102, 465, 628, + 614, 488, 678, 40, 147, -1, -1, -1, -1, + ]; + + /// SymbolEncoding: for each code, the index of its glyph name in , or -1. + internal static ReadOnlySpan SymbolEncoding => + [ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 740, 536, 781, 631, 540, 674, 414, 744, 661, 667, 438, 684, 485, 612, 675, 739, 798, 644, 766, + 754, 554, 547, 735, 727, 519, 621, 483, 726, 602, 531, 566, 692, 489, 13, 22, 32, 38, 55, 135, 64, 57, 85, 752, + 90, 95, 104, 112, 128, 136, 161, 146, 155, 158, 178, 733, 127, 187, 137, 200, 455, 750, 459, 679, 779, 707, + 412, 445, 478, 500, 530, 681, 560, 534, 591, 682, 595, 599, 615, 630, 643, 683, 751, 715, 732, 747, 783, 642, + 641, 789, 690, 802, 447, 444, 451, 734, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 60, 179, 613, 603, 558, 584, 553, 482, 501, 573, + 741, 423, 431, 433, 432, 429, 499, 685, 724, 567, 616, 689, 673, 466, 503, 626, 532, 421, 524, 434, 430, 470, + 411, 80, 145, 787, 479, 480, 527, 589, 780, 688, 711, 627, 687, 710, 523, 625, 416, 564, 714, 492, 764, 686, + 706, 510, 605, 604, 606, 424, 426, 428, 427, 425, 607, 417, 713, 491, 763, 745, 666, 663, 662, 458, 457, 456, + 450, 449, 448, 446, -1, 418, 585, 588, 587, 586, 672, 669, 668, 462, 461, 460, 454, 453, 452, -1, + ]; + + /// ZapfDingbatsEncoding: for each code, the index of its glyph name in , or -1. + internal static ReadOnlySpan ZapfDingbatsEncoding => + [ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 740, 203, 310, 314, 328, 339, 350, 221, 220, 219, 215, 222, 233, 244, 255, 266, 210, 277, 288, + 299, 311, 319, 320, 321, 322, 323, 324, 325, 326, 361, 372, 383, 393, 204, 327, 329, 330, 331, 332, 333, 334, + 335, 336, 337, 338, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 351, 352, 353, 354, 355, 356, 357, 358, + 359, 360, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 373, 374, 375, 376, 377, 315, 378, 316, 379, 380, + 381, 382, 384, 385, 386, 387, 401, 402, 403, 205, -1, 392, 394, 397, 398, 395, 396, 317, 388, 318, 389, 390, + 391, 399, 400, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 206, 207, 208, 209, + 211, 212, 213, 218, 217, 216, 214, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 234, 235, 236, 237, 238, + 239, 240, 241, 242, 243, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 256, 257, 258, 259, 260, 261, 262, + 263, 264, 265, 267, 268, 270, 271, 306, 272, 302, 273, 274, 275, 276, 278, 279, 280, 281, 269, 282, 283, 284, + 285, 286, 287, 303, 289, 309, 290, 312, 291, -1, 313, 292, 293, 307, 294, 304, 308, 295, 305, 296, 297, 298, + 300, 301, -1, + ]; + + /// MacOSRomanEncoding: for each code, the index of its glyph name in , or -1. + internal static ReadOnlySpan MacOSRomanEncoding => + [ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 740, 536, 696, 631, 504, 674, 414, 703, 661, 667, 437, 684, 485, 575, 675, 739, 798, 644, 766, + 754, 554, 547, 735, 727, 519, 621, 483, 726, 602, 531, 566, 692, 440, 0, 21, 25, 35, 42, 61, 63, 69, 72, 87, + 89, 93, 101, 105, 113, 134, 139, 141, 149, 157, 166, 182, 184, 186, 189, 195, 455, 443, 459, 435, 779, 565, + 202, 442, 467, 494, 512, 541, 559, 572, 578, 593, 594, 597, 610, 617, 632, 659, 691, 704, 719, 746, 772, 785, + 786, 788, 790, 794, 447, 444, 451, 436, -1, 9, 16, 29, 43, 110, 120, 171, 404, 410, 406, 408, 441, 422, 472, + 513, 518, 515, 516, 579, 582, 580, 581, 629, 633, 638, 634, 635, 658, 773, 776, 774, 775, 495, 499, 474, 743, + 725, 466, 660, 563, 712, 490, 762, 407, 502, 626, 1, 129, 584, 685, 603, 567, 793, 615, 673, 745, 686, 683, + 585, 654, 655, 127, 409, 656, 693, 537, 605, 706, 553, 421, 38, 568, 569, 524, 740, 11, 19, 132, 114, 636, 528, + 526, 698, 699, 700, 701, 503, 607, 792, 192, 558, 60, 570, 571, 545, 552, 496, 676, 702, 697, 680, 6, 46, 3, + 48, 51, 73, 75, 77, 81, 116, 118, 420, 123, 167, 169, 173, 509, 481, 761, 611, 463, 508, 716, 473, 574, 637, + 469, + ]; +} diff --git a/src/Broadside/Fonts/PdfFont.cs b/src/Broadside/Fonts/PdfFont.cs new file mode 100644 index 00000000..4e2a1cc2 --- /dev/null +++ b/src/Broadside/Fonts/PdfFont.cs @@ -0,0 +1,154 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Fonts; + +/// A font: a live view over a font dictionary. +/// +/// +/// ISO 32000-2 §9.5. The type of the view follows the dictionary's Subtype (Table 108): for +/// Type1 and MMType1, , and . A +/// dictionary whose Subtype is missing or not a font type is read as a Type 1 font, with a diagnostic. +/// +/// +/// Views are obtained from or , which return the +/// same instance for the same dictionary. Properties read the COS objects when called; values derived from several entries (the +/// encoding and widths of a simple font) are cached and rebuilt when one of the dictionaries or arrays they come from changes. A +/// font is safe for concurrent reads while nobody mutates the document. +/// +/// +public abstract class PdfFont +{ + private PdfFontDescriptor? _descriptor; + + private protected PdfFont(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfFontType fontType) + { + Document = document; + Dictionary = dictionary; + Reference = reference; + FontType = fontType; + } + + /// Gets the font dictionary. + /// ISO 32000-2 §9.5; Table 109 for Type 1 fonts. + public CosDictionary Dictionary { get; } + + /// Gets the indirect reference to the font dictionary, or when the resource dictionary holds it directly. + public CosReference? Reference { get; } + + /// Gets the type of the font, from Subtype; when that is missing or not a font type. + /// ISO 32000-2 §9.5, Table 108. + public PdfFontType FontType { get; } + + /// Gets the PostScript name of the font, or when absent. + /// ISO 32000-2 §9.6.2.1, Table 109, BaseFont (required except for Type 3 fonts); §9.6.3 for TrueType fonts. + public string? BaseFont => (Get(FontNames.BaseFont) as CosName)?.Value; + + /// + /// Gets the font descriptor: a view over the dictionary's FontDescriptor, or, for a non-embedded Standard 14 font without + /// one, a descriptor synthesized from the font's metrics; otherwise. + /// + /// ISO 32000-2 §9.8 and §9.6.2.1 (the paragraph after Table 109). + public PdfFontDescriptor? Descriptor + { + get + { + if (DescriptorDictionary is not { } dictionary) + { + return SynthesizedDescriptor; + } + + PdfFontDescriptor? cached = _descriptor; + if (cached?.Dictionary != dictionary) + { + cached = new PdfFontDescriptor(Document, dictionary, Dictionary.TryGetValue(FontNames.FontDescriptor, out CosObject? value) ? value as CosReference : null); + _descriptor = cached; + } + + return cached; + } + } + + /// Gets a value indicating whether the font program is embedded: the font descriptor has a FontFile, FontFile2 or FontFile3 stream. + /// ISO 32000-2 §9.8.1, Table 120, and §9.9. + public bool IsEmbedded => DescriptorDictionary is { } descriptor && IsEmbeddedIn(descriptor); + + /// Gets the document the font belongs to. + internal PdfDocument Document { get; } + + /// Gets the font descriptor dictionary, resolved, or when absent or not a dictionary. + internal CosDictionary? DescriptorDictionary => Get(FontNames.FontDescriptor) as CosDictionary; + + /// Gets the descriptor a font without a FontDescriptor entry is given; unless a Standard 14 font. + private protected virtual PdfFontDescriptor? SynthesizedDescriptor => null; + + /// Creates the view for a font dictionary, recording a diagnostic when its Type or Subtype is not a font's. + /// The document. + /// The font dictionary. + /// The reference it was reached through, if any. + /// The view. + internal static PdfFont Create(PdfDocument document, CosDictionary dictionary, CosReference? reference) + { + DiagnosticSink diagnostics = document.DiagnosticSink; + CosObject? type = dictionary.TryGetValue(KnownNames.Type, out CosObject? typeValue) ? document.Resolve(typeValue) : null; + if (!FontNames.Font.Equals(type)) + { + diagnostics.Report( + DiagnosticCodes.FontTypeInvalid, + DiagnosticSeverity.Warning, + "A font dictionary's Type shall be Font (ISO 32000-2 §9.6.2.1, Table 109); read as a font.", + objectReference: reference); + } + + CosName? subtype = (dictionary.TryGetValue(FontNames.Subtype, out CosObject? subtypeValue) ? document.Resolve(subtypeValue) : null) as CosName; + if (FontNames.Type1.Equals(subtype)) + { + return new PdfType1Font(document, dictionary, reference, PdfFontType.Type1); + } + + if (FontNames.MMType1.Equals(subtype)) + { + return new PdfType1Font(document, dictionary, reference, PdfFontType.MMType1); + } + + if (FontNames.TrueType.Equals(subtype)) + { + return new PdfTrueTypeFont(document, dictionary, reference); + } + + if (FontNames.Type3.Equals(subtype)) + { + return new PdfType3Font(document, dictionary, reference); + } + + if (FontNames.Type0.Equals(subtype)) + { + return new PdfType0Font(document, dictionary, reference); + } + + diagnostics.Report( + DiagnosticCodes.FontSubtypeInvalid, + DiagnosticSeverity.Warning, + $"A font dictionary's Subtype shall be one of the font types of ISO 32000-2 §9.5 Table 108, not {(subtype is null ? "absent" : "/" + subtype.Value)}; read as a Type 1 font.", + objectReference: reference); + return new PdfType1Font(document, dictionary, reference, PdfFontType.Type1); + } + + /// Gets a value indicating whether a font descriptor holds a font program. + internal bool IsEmbeddedIn(CosDictionary descriptor) => + GetFrom(descriptor, FontNames.FontFile) is CosStream + || GetFrom(descriptor, FontNames.FontFile2) is CosStream + || GetFrom(descriptor, FontNames.FontFile3) is CosStream; + + /// The font dictionary's entry, resolved; when absent or a reference to nothing. + internal CosObject? Get(CosName key) => GetFrom(Dictionary, key); + + /// A dictionary's entry, resolved; when absent or a reference to nothing. + internal CosObject? GetFrom(CosDictionary dictionary, CosName key) => + dictionary.TryGetValue(key, out CosObject? value) && Document.Resolve(value) is not CosNull and var resolved ? resolved : null; + + /// Records a deviation found in this font. + internal void Report(string code, DiagnosticSeverity severity, string message) => + Document.DiagnosticSink.Report(code, severity, message, objectReference: Reference); +} diff --git a/src/Broadside/Fonts/PdfFontDescriptor.cs b/src/Broadside/Fonts/PdfFontDescriptor.cs new file mode 100644 index 00000000..af08dcb9 --- /dev/null +++ b/src/Broadside/Fonts/PdfFontDescriptor.cs @@ -0,0 +1,186 @@ +using Broadside.Objects; + +namespace Broadside.Fonts; + +/// The font-wide metrics and attributes of a simple font or CIDFont: a live view over a font descriptor dictionary. +/// +/// +/// ISO 32000-2 §9.8.1, Table 120, and §9.8.2. Every property reads the dictionary when called, so a change made through +/// is visible at once. An absent or malformed entry reads as the default Table 120 gives (0 for the optional +/// numbers), or as for entries without one; the font that uses the descriptor records a diagnostic for a +/// malformed or missing required entry when it is first used. Dimensions are in glyph space units: thousandths of text space for +/// every font type except Type 3 (§9.2.4). +/// +/// +/// A non-embedded Standard 14 font may have no font descriptor (§9.6.2.1, the paragraph after Table 109); a processor shall then +/// provide the descriptor data itself. returns a synthesized descriptor for such a font, with +/// and values from the font's AFM file: FontBBox, ItalicAngle, CapHeight, XHeight, +/// Ascender (Ascent), Descender (Descent), StdVW (StemV) and StdHW (StemH). Symbol and ZapfDingbats have no CapHeight, XHeight, +/// Ascender or Descender in their AFM files; their font box supplies Ascent, Descent and CapHeight, and XHeight is 0. +/// +/// +public sealed class PdfFontDescriptor +{ + private readonly PdfDocument? _document; + private readonly Standard14Font _standard14; + + internal PdfFontDescriptor(PdfDocument document, CosDictionary dictionary, CosReference? reference) + { + _document = document; + Dictionary = dictionary; + Reference = reference; + } + + internal PdfFontDescriptor(Standard14Font standard14) => _standard14 = standard14; + + /// Gets the font descriptor dictionary, or for the descriptor of a Standard 14 font that has none. + /// ISO 32000-2 §9.8.1, Table 120. + public CosDictionary? Dictionary { get; } + + /// Gets the indirect reference to the font descriptor, or when it is a direct object or synthesized. + public CosReference? Reference { get; } + + /// Gets a value indicating whether the descriptor is synthesized from Standard 14 metrics instead of read from the file. + /// ISO 32000-2 §9.6.2.1 (the paragraph after Table 109) and §9.6.2.2. + public bool IsSynthesized => Dictionary is null; + + /// Gets the PostScript name of the font, which shall equal the font's BaseFont; when absent. + /// ISO 32000-2 §9.8.1, Table 120, FontName (required). + public string? FontName => Dictionary is null ? Standard14Data.PostScriptName(_standard14) : (Get(FontNames.FontName) as CosName)?.Value; + + /// Gets the preferred font family name, such as Times for Times Bold Italic; when absent. + /// ISO 32000-2 §9.8.1, Table 120, FontFamily (PDF 1.5), a byte string. + public string? FontFamily => (Get(FontNames.FontFamily) as CosString)?.DecodeText(); + + /// Gets the font stretch; when absent or not one of the nine names. + /// ISO 32000-2 §9.8.1, Table 120, FontStretch (PDF 1.5). + public PdfFontStretch? FontStretch => (Get(FontNames.FontStretch) as CosName)?.Value switch + { + "UltraCondensed" => PdfFontStretch.UltraCondensed, + "ExtraCondensed" => PdfFontStretch.ExtraCondensed, + "Condensed" => PdfFontStretch.Condensed, + "SemiCondensed" => PdfFontStretch.SemiCondensed, + "Normal" => PdfFontStretch.Normal, + "SemiExpanded" => PdfFontStretch.SemiExpanded, + "Expanded" => PdfFontStretch.Expanded, + "ExtraExpanded" => PdfFontStretch.ExtraExpanded, + "UltraExpanded" => PdfFontStretch.UltraExpanded, + _ => null, + }; + + /// Gets the weight: 100 to 900 in steps of 100, 400 normal and 700 bold; when absent or another value. + /// ISO 32000-2 §9.8.1, Table 120, FontWeight (PDF 1.5). + public int? FontWeight => Get(FontNames.FontWeight) is CosNumber number && number.ToDouble() is var weight + && weight is >= 100 and <= 900 && weight % 100 == 0 ? (int)weight : null; + + /// Gets the font flags; none when absent. + /// ISO 32000-2 §9.8.1, Table 120, Flags (required), and §9.8.2, Table 121. + public PdfFontFlags Flags => Dictionary is null ? Standard14Data.Flags(_standard14) : ReadFlags(Dictionary, _document!); + + /// Gets the font bounding box in glyph space; empty at the origin when absent or malformed. + /// ISO 32000-2 §9.8.1, Table 120, FontBBox (required except for Type 3 fonts), and §7.9.5. + public PdfRectangle FontBBox => Dictionary is null ? Standard14Data.FontBBox(_standard14) : ReadRectangle(Get(FontNames.FontBBox)); + + /// Gets the angle of the dominant vertical strokes, in degrees counterclockwise from the vertical (negative for right-slanting italics). + /// ISO 32000-2 §9.8.1, Table 120, ItalicAngle (required). 0 when absent. + public double ItalicAngle => Read(FontNames.ItalicAngle, Standard14Metric.ItalicAngle); + + /// Gets the maximum height above the baseline reached by glyphs, excluding accents. + /// ISO 32000-2 §9.8.1, Table 120, Ascent (required except for Type 3 fonts). 0 when absent. + public double Ascent => Read(FontNames.Ascent, Standard14Metric.Ascent); + + /// Gets the maximum depth below the baseline reached by glyphs; a negative number. + /// ISO 32000-2 §9.8.1, Table 120, Descent (required except for Type 3 fonts). 0 when absent. + public double Descent => Read(FontNames.Descent, Standard14Metric.Descent); + + /// Gets the spacing between baselines of consecutive lines. + /// ISO 32000-2 §9.8.1, Table 120, Leading. Default 0. + public double Leading => Read(FontNames.Leading, metric: null); + + /// Gets the height of flat capital letters above the baseline. + /// ISO 32000-2 §9.8.1, Table 120, CapHeight (required for fonts with Latin characters, except Type 3). 0 when absent. + public double CapHeight => Read(FontNames.CapHeight, Standard14Metric.CapHeight); + + /// Gets the height of flat non-ascending lowercase letters above the baseline. + /// ISO 32000-2 §9.8.1, Table 120, XHeight. Default 0. + public double XHeight => Read(FontNames.XHeight, Standard14Metric.XHeight); + + /// Gets the horizontal thickness of the dominant vertical stems; 0 when unknown. + /// ISO 32000-2 §9.8.1, Table 120, StemV (required except for Type 3 fonts). 0 when absent. + public double StemV => Read(FontNames.StemV, Standard14Metric.StemV); + + /// Gets the vertical thickness of the dominant horizontal stems; 0 when unknown. + /// ISO 32000-2 §9.8.1, Table 120, StemH. Default 0. + public double StemH => Read(FontNames.StemH, Standard14Metric.StemH); + + /// Gets the average glyph width. + /// ISO 32000-2 §9.8.1, Table 120, AvgWidth. Default 0. + public double AvgWidth => Read(FontNames.AvgWidth, metric: null); + + /// Gets the maximum glyph width. + /// ISO 32000-2 §9.8.1, Table 120, MaxWidth. Default 0. + public double MaxWidth => Read(FontNames.MaxWidth, metric: null); + + /// Gets the width of character codes outside the font's FirstChar to LastChar range. + /// ISO 32000-2 §9.8.1, Table 120, MissingWidth, and §9.6.2.1, Table 109, Widths. Default 0. + public double MissingWidth => Read(FontNames.MissingWidth, metric: null); + + /// Gets the embedded Type 1 font program, or . + /// ISO 32000-2 §9.8.1, Table 120, FontFile, and §9.9. + public CosStream? FontFile => Get(FontNames.FontFile) as CosStream; + + /// Gets the embedded TrueType font program, or . + /// ISO 32000-2 §9.8.1, Table 120, FontFile2 (PDF 1.1), and §9.9. + public CosStream? FontFile2 => Get(FontNames.FontFile2) as CosStream; + + /// Gets the embedded font program whose format the stream's Subtype names, or . + /// ISO 32000-2 §9.8.1, Table 120, FontFile3 (PDF 1.2), and §9.9, Table 124. + public CosStream? FontFile3 => Get(FontNames.FontFile3) as CosStream; + + /// Gets the names of the glyphs of a Type 1 font subset, each preceded by a slash; when absent. + /// ISO 32000-2 §9.8.1, Table 120, CharSet (PDF 1.1; deprecated in PDF 2.0). + public string? CharSet => (Get(FontNames.CharSet) as CosString)?.DecodeText(); + + /// Reads Flags from a descriptor dictionary: the low 32 bits of an integer, none otherwise. + internal static PdfFontFlags ReadFlags(CosDictionary dictionary, PdfDocument document) => + dictionary.TryGetValue(FontNames.Flags, out CosObject? value) && document.Resolve(value) is CosInteger flags + ? (PdfFontFlags)unchecked((int)flags.Value) + : PdfFontFlags.None; + + /// Reads a rectangle: an array of four numbers, normalized; empty at the origin otherwise. + private PdfRectangle ReadRectangle(CosObject? value) + { + if (value is not CosArray { Count: 4 } array) + { + return default; + } + + Span corners = stackalloc double[4]; + for (int index = 0; index < 4; index++) + { + if (_document!.Resolve(array[index]) is not CosNumber number) + { + return default; + } + + corners[index] = number.ToDouble(); + } + + return new PdfRectangle(corners[0], corners[1], corners[2], corners[3]); + } + + private double Read(CosName key, Standard14Metric? metric) + { + if (Dictionary is null) + { + return metric is { } value ? Standard14Data.Metric(_standard14, value) : 0; + } + + return Get(key) is CosNumber number ? number.ToDouble() : 0; + } + + private CosObject? Get(CosName key) => + Dictionary is not null && Dictionary.TryGetValue(key, out CosObject? value) && _document!.Resolve(value) is not CosNull and var resolved + ? resolved + : null; +} diff --git a/src/Broadside/Fonts/PdfFontFlags.cs b/src/Broadside/Fonts/PdfFontFlags.cs new file mode 100644 index 00000000..28978202 --- /dev/null +++ b/src/Broadside/Fonts/PdfFontFlags.cs @@ -0,0 +1,41 @@ +namespace Broadside.Fonts; + +/// The characteristics a font descriptor's Flags entry records. +/// +/// ISO 32000-2 §9.8.2, Table 121. Bit positions are numbered from 1 (low-order); each value here is the bit's value. Bits not listed +/// are reserved. and are meant to be exclusive; when both or neither are set, a +/// processor checks (§9.8.2). +/// +[Flags] +public enum PdfFontFlags +{ + /// No flag is set. + None = 0, + + /// Bit 1: all glyphs have the same width. + FixedPitch = 1 << 0, + + /// Bit 2: glyphs have serifs. + Serif = 1 << 1, + + /// Bit 3: the font contains glyphs outside the Standard Latin character set (Annex D.2). + Symbolic = 1 << 2, + + /// Bit 4: glyphs resemble cursive handwriting. + Script = 1 << 3, + + /// Bit 6: the font uses the Standard Latin character set or a subset of it. + Nonsymbolic = 1 << 5, + + /// Bit 7: glyphs have dominant vertical strokes that are slanted. + Italic = 1 << 6, + + /// Bit 17: the font contains no lowercase letters. + AllCap = 1 << 16, + + /// Bit 18: lowercase letters are small capitals. + SmallCap = 1 << 17, + + /// Bit 19: bold glyphs are thickened at small text sizes. + ForceBold = 1 << 18, +} diff --git a/src/Broadside/Fonts/PdfFontStretch.cs b/src/Broadside/Fonts/PdfFontStretch.cs new file mode 100644 index 00000000..85b06dd6 --- /dev/null +++ b/src/Broadside/Fonts/PdfFontStretch.cs @@ -0,0 +1,33 @@ +namespace Broadside.Fonts; + +/// The stretch of a font, from narrowest to widest. +/// ISO 32000-2 §9.8.1, Table 120, FontStretch (PDF 1.5). +public enum PdfFontStretch +{ + /// UltraCondensed. + UltraCondensed = 0, + + /// ExtraCondensed. + ExtraCondensed = 1, + + /// Condensed. + Condensed = 2, + + /// SemiCondensed. + SemiCondensed = 3, + + /// Normal. + Normal = 4, + + /// SemiExpanded. + SemiExpanded = 5, + + /// Expanded. + Expanded = 6, + + /// ExtraExpanded. + ExtraExpanded = 7, + + /// UltraExpanded. + UltraExpanded = 8, +} diff --git a/src/Broadside/Fonts/PdfFontType.cs b/src/Broadside/Fonts/PdfFontType.cs new file mode 100644 index 00000000..7803de63 --- /dev/null +++ b/src/Broadside/Fonts/PdfFontType.cs @@ -0,0 +1,24 @@ +namespace Broadside.Fonts; + +/// The type of a font, from the Subtype entry of its font dictionary. +/// +/// ISO 32000-2 §9.5, Table 108. Type 0 fonts are composite; the others are simple fonts (§9.6). CIDFonts (CIDFontType0, +/// CIDFontType2) are not listed: they are used only as the descendant of a Type 0 font, never as a font on their own. +/// +public enum PdfFontType +{ + /// Type1: a Type 1 font (§9.6.2), including a Standard 14 font. + Type1 = 0, + + /// MMType1: an instance of a multiple master font (§9.6.2.3). + MMType1 = 1, + + /// TrueType: a TrueType or OpenType font (§9.6.3). + TrueType = 2, + + /// Type3: a font whose glyphs are content streams (§9.6.4). + Type3 = 3, + + /// Type0: a composite font (§9.7). + Type0 = 4, +} diff --git a/src/Broadside/Fonts/PdfSimpleFont.cs b/src/Broadside/Fonts/PdfSimpleFont.cs new file mode 100644 index 00000000..cbabdfb6 --- /dev/null +++ b/src/Broadside/Fonts/PdfSimpleFont.cs @@ -0,0 +1,85 @@ +using Broadside.Objects; + +namespace Broadside.Fonts; + +/// A simple font: one byte per character code, a 256-entry encoding from codes to glyph names, and one width per code. +/// +/// +/// ISO 32000-2 §9.6.1. applies the font's encoding (§9.6.5): the Encoding entry, a predefined +/// encoding or an encoding dictionary with BaseEncoding and Differences, over the font's built-in encoding. +/// applies FirstChar, LastChar, Widths and the descriptor's MissingWidth +/// (§9.6.2.1, Table 109), and the Standard 14 metrics for a non-embedded Standard 14 font that does not give them (§9.6.2.2). +/// +/// +/// The 256 names and widths are computed on first use and kept until the font dictionary, its Widths array, its encoding +/// dictionary, the Differences array or its font descriptor changes; looking one up then allocates nothing. Deviations +/// found while computing them are recorded once, on the font's object, when first used: in strict mode that call throws. +/// +/// +public abstract class PdfSimpleFont : PdfFont +{ + private volatile SimpleFontMetrics? _metrics; + + private protected PdfSimpleFont(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfFontType fontType) + : base(document, dictionary, reference, fontType) + { + } + + /// + /// Gets the Standard 14 font whose metrics this font uses, or . A Type 1 or TrueType font that is not + /// embedded uses them when its BaseFont is one of the fourteen names, or another name producers use for one of them + /// (such as Arial,Bold for Helvetica-Bold, recorded as an information diagnostic). + /// + /// ISO 32000-2 §9.6.2.2. + public Standard14Font? Standard14 => Metrics.Standard14; + + /// Gets the glyph name the font's encoding gives a character code; .notdef when it gives none. + /// The character code. + /// The glyph name. + /// + /// ISO 32000-2 §9.6.5. The built-in encoding is the Symbol or ZapfDingbats encoding for those two Standard 14 fonts (Annex D.5, + /// D.6) and StandardEncoding for the other twelve and for any other font that is not embedded (Annex D.2); a predefined encoding + /// named on a non-embedded Symbol or ZapfDingbats font is ignored, as pdf.js does. For a Type 3 font the encoding is entirely + /// defined by the Encoding entry (§9.6.5.3). + /// + public string GetGlyphName(byte code) => Metrics.Names[code]; + + /// Gets the width of a character code's glyph, in glyph space units: thousandths of text space, except for Type 3 fonts. + /// The character code. + /// The width. + /// + /// ISO 32000-2 §9.6.2.1, Table 109 (Widths), §9.8.1 (MissingWidth) and §9.2.4. A code from FirstChar to + /// LastChar has its Widths element; other codes have the descriptor's MissingWidth. A non-embedded Standard + /// 14 font without Widths takes the width of the code's glyph from its metrics; .notdef is 250 (600 in Courier), + /// as in Acrobat. A Type 3 font's widths are in its glyph space, which its FontMatrix maps to text space. + /// + public double GetWidth(byte code) => Metrics.Widths[code]; + + /// Gets the names and widths of all 256 codes, rebuilt when an object they come from has changed. + internal SimpleFontMetrics Metrics + { + get + { + SimpleFontMetrics? metrics = _metrics; + if (metrics is null || !metrics.IsCurrent) + { + metrics = SimpleFontMetrics.Build(this); + _metrics = metrics; + } + + return metrics; + } + } + + /// Gets a value indicating whether the font can take Standard 14 metrics when not embedded: Type 1 and TrueType fonts. + internal virtual bool CanUseStandard14 => true; + + /// + private protected override PdfFontDescriptor? SynthesizedDescriptor => Metrics.SynthesizedDescriptor; + + /// + /// Gets the built-in encoding of the embedded font program as glyph names per code, or when the program + /// is not read (the font program parsers supply it). Without it, an embedded font's default base encoding is StandardEncoding. + /// + internal virtual string?[]? GetProgramEncoding() => null; +} diff --git a/src/Broadside/Fonts/PdfTrueTypeFont.cs b/src/Broadside/Fonts/PdfTrueTypeFont.cs new file mode 100644 index 00000000..964613e6 --- /dev/null +++ b/src/Broadside/Fonts/PdfTrueTypeFont.cs @@ -0,0 +1,17 @@ +using Broadside.Objects; + +namespace Broadside.Fonts; + +/// A TrueType or OpenType font: a live view over its font dictionary. +/// +/// ISO 32000-2 §9.6.3. The dictionary has the entries of a Type 1 font dictionary (Table 109). Glyph names from the encoding are +/// what §9.6.5.4 maps through the font program's "cmap" table for a nonsymbolic font; a non-embedded TrueType font named after a +/// Standard 14 font (such as Arial) takes that font's metrics. +/// +public sealed class PdfTrueTypeFont : PdfSimpleFont +{ + internal PdfTrueTypeFont(PdfDocument document, CosDictionary dictionary, CosReference? reference) + : base(document, dictionary, reference, PdfFontType.TrueType) + { + } +} diff --git a/src/Broadside/Fonts/PdfType0Font.cs b/src/Broadside/Fonts/PdfType0Font.cs new file mode 100644 index 00000000..341b76c3 --- /dev/null +++ b/src/Broadside/Fonts/PdfType0Font.cs @@ -0,0 +1,13 @@ +using Broadside.Objects; + +namespace Broadside.Fonts; + +/// A composite (Type 0) font, whose glyphs come from a descendant CIDFont: a live view over its font dictionary. +/// ISO 32000-2 §9.7. A Type 0 font has no font descriptor of its own (§9.8.1); its CIDFont has one. +public sealed class PdfType0Font : PdfFont +{ + internal PdfType0Font(PdfDocument document, CosDictionary dictionary, CosReference? reference) + : base(document, dictionary, reference, PdfFontType.Type0) + { + } +} diff --git a/src/Broadside/Fonts/PdfType1Font.cs b/src/Broadside/Fonts/PdfType1Font.cs new file mode 100644 index 00000000..c2eb4277 --- /dev/null +++ b/src/Broadside/Fonts/PdfType1Font.cs @@ -0,0 +1,21 @@ +using Broadside.Objects; + +namespace Broadside.Fonts; + +/// A Type 1 font, or an instance of a multiple master font: a live view over its font dictionary. +/// +/// ISO 32000-2 §9.6.2 (Table 109) and §9.6.2.3. A non-embedded Type 1 font named after one of the Standard 14 fonts (§9.6.2.2) may +/// omit FirstChar, LastChar, Widths and FontDescriptor; its widths and descriptor data then come from +/// the Standard 14 metrics. The encoding of a Type 1 font overrides the font program's built-in encoding (§9.6.5.2). +/// +public sealed class PdfType1Font : PdfSimpleFont +{ + internal PdfType1Font(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfFontType fontType) + : base(document, dictionary, reference, fontType) + { + } + + /// Gets a value indicating whether the font is an instance of a multiple master font (Subtype MMType1). + /// ISO 32000-2 §9.6.2.3. An embedded program of such an instance is an ordinary Type 1 program, a snapshot of the instance. + public bool IsMultipleMaster => FontType == PdfFontType.MMType1; +} diff --git a/src/Broadside/Fonts/PdfType3Font.cs b/src/Broadside/Fonts/PdfType3Font.cs new file mode 100644 index 00000000..0455247f --- /dev/null +++ b/src/Broadside/Fonts/PdfType3Font.cs @@ -0,0 +1,20 @@ +using Broadside.Objects; + +namespace Broadside.Fonts; + +/// A Type 3 font, whose glyphs are content streams: a live view over its font dictionary. +/// +/// ISO 32000-2 §9.6.4. Its encoding is entirely defined by its Encoding entry (§9.6.5.3): the Differences of the +/// encoding dictionary, over the predefined encoding its BaseEncoding names, if any. Its widths are in its glyph space, +/// which the font matrix maps to text space; it never takes Standard 14 metrics. +/// +public sealed class PdfType3Font : PdfSimpleFont +{ + internal PdfType3Font(PdfDocument document, CosDictionary dictionary, CosReference? reference) + : base(document, dictionary, reference, PdfFontType.Type3) + { + } + + /// + internal override bool CanUseStandard14 => false; +} diff --git a/src/Broadside/Fonts/SimpleFontMetrics.cs b/src/Broadside/Fonts/SimpleFontMetrics.cs new file mode 100644 index 00000000..532c1e79 --- /dev/null +++ b/src/Broadside/Fonts/SimpleFontMetrics.cs @@ -0,0 +1,582 @@ +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Fonts; + +/// +/// The glyph name and width of each of the 256 codes of a simple font, computed once from its font dictionary, and the COS +/// containers they were computed from with their versions, so a change to any of them is noticed (pitfall: views are live). +/// +/// Immutable once built; a font replaces it, never changes it, so concurrent readers always see a whole table. +internal sealed class SimpleFontMetrics +{ + private readonly CosObject[] _sources; + private readonly int[] _versions; + + private SimpleFontMetrics(string[] names, double[] widths, Standard14Font? standard14, List sources) + { + Names = names; + Widths = widths; + Standard14 = standard14; + SynthesizedDescriptor = standard14 is { } font ? new PdfFontDescriptor(font) : null; + _sources = [.. sources]; + _versions = [.. sources.Select(VersionOf)]; + } + + /// Gets the glyph name of each code; .notdef where the encoding gives none. + public string[] Names { get; } + + /// Gets the width of each code, in glyph space units. + public double[] Widths { get; } + + /// Gets the Standard 14 font whose metrics apply, if any. + public Standard14Font? Standard14 { get; } + + /// Gets the descriptor synthesized from Standard 14 metrics, used when the font has no FontDescriptor. + public PdfFontDescriptor? SynthesizedDescriptor { get; } + + /// Gets a value indicating whether no source dictionary or array has changed since the tables were built. + public bool IsCurrent + { + get + { + for (int index = 0; index < _sources.Length; index++) + { + if (VersionOf(_sources[index]) != _versions[index]) + { + return false; + } + } + + return true; + } + } + + /// Computes the tables of a simple font, recording each deviation found on the font's object. + /// The font. + /// The tables. + public static SimpleFontMetrics Build(PdfSimpleFont font) + { + var builder = new Builder(font); + return builder.Build(); + } + + private static int VersionOf(CosObject source) => source switch + { + CosDictionary dictionary => dictionary.Version, + CosArray array => array.Version, + _ => 0, + }; + + /// One computation: ISO 32000-2 §9.6.2.1 (Table 109), §9.6.2.2, §9.6.5.1 to §9.6.5.3 and §9.8. + private sealed class Builder(PdfSimpleFont font) + { + private readonly List _sources = [font.Dictionary]; + private readonly string?[] _names = new string?[256]; + private readonly double[] _widths = new double[256]; + private CosDictionary? _descriptor; + private bool _embedded; + private Standard14Font? _standard14; + private bool _symbolic; + + private bool IsType3 => font.FontType == PdfFontType.Type3; + + public SimpleFontMetrics Build() + { + ReadDescriptor(); + MatchStandard14(); + ReadEncoding(); + string[] names = new string[256]; + for (int code = 0; code < 256; code++) + { + names[code] = _names[code] ?? GlyphNameTable.NotDef; + } + + ReadWidths(names); + CheckStandard14Entries(); + return new SimpleFontMetrics(names, _widths, _standard14, _sources); + } + + /// The font descriptor (§9.8): present, a dictionary, well-formed; whether it embeds a program; its flags. + private void ReadDescriptor() + { + CosObject? value = font.Get(FontNames.FontDescriptor); + if (value is CosDictionary descriptor) + { + _descriptor = descriptor; + _sources.Add(descriptor); + _embedded = font.IsEmbeddedIn(descriptor); + CheckDescriptor(descriptor); + } + else if (value is not null) + { + font.Report( + DiagnosticCodes.FontDescriptorInvalid, + DiagnosticSeverity.Warning, + "A font's FontDescriptor shall be a dictionary (ISO 32000-2 §9.6.2.1, Table 109); ignored."); + } + } + + private void CheckDescriptor(CosDictionary descriptor) + { + var problems = new List(); + CosObject? type = font.GetFrom(descriptor, KnownNames.Type); + if (!FontNames.FontDescriptor.Equals(type)) + { + problems.Add("its Type is not FontDescriptor"); + } + + if (font.GetFrom(descriptor, FontNames.Flags) is not CosInteger) + { + problems.Add("Flags is missing or not an integer"); + } + + CosName[] required = IsType3 + ? [FontNames.ItalicAngle] + : [FontNames.FontBBox, FontNames.ItalicAngle, FontNames.Ascent, FontNames.Descent, FontNames.StemV]; + foreach (CosName key in required) + { + CosObject? entry = font.GetFrom(descriptor, key); + bool valid = FontNames.FontBBox.Equals(key) ? entry is CosArray { Count: 4 } : entry is CosNumber; + if (!valid) + { + problems.Add($"{key.Value} is missing or malformed"); + } + } + + int programs = (font.GetFrom(descriptor, FontNames.FontFile) is null ? 0 : 1) + + (font.GetFrom(descriptor, FontNames.FontFile2) is null ? 0 : 1) + + (font.GetFrom(descriptor, FontNames.FontFile3) is null ? 0 : 1); + if (programs > 1) + { + problems.Add("it has more than one of FontFile, FontFile2 and FontFile3"); + } + + if (problems.Count > 0) + { + font.Report( + DiagnosticCodes.FontDescriptorInvalid, + DiagnosticSeverity.Warning, + $"The font descriptor deviates from ISO 32000-2 §9.8.1 Table 120: {string.Join("; ", problems)}; defaults are used."); + } + } + + /// A Type 1 or TrueType font that is not embedded and is named after a Standard 14 font takes its metrics (§9.6.2.2). + private void MatchStandard14() + { + CosObject? baseFont = font.Get(FontNames.BaseFont); + if (baseFont is not CosName name) + { + if (!IsType3) + { + font.Report( + DiagnosticCodes.FontBaseFontMissing, + DiagnosticSeverity.Warning, + "A font dictionary shall have a BaseFont name (ISO 32000-2 §9.6.2.1, Table 109)."); + } + } + else if (font.CanUseStandard14 && !_embedded && Standard14Data.TryMatch(name.Value, out Standard14Font standard14, out bool isAlias)) + { + _standard14 = standard14; + if (isAlias) + { + font.Report( + DiagnosticCodes.FontStandard14Alias, + DiagnosticSeverity.Information, + $"The font /{name.Value} is not embedded; the metrics of the Standard 14 font {Standard14Data.PostScriptName(standard14)} are used for it."); + } + } + + // §9.8.2: a processor checks the Symbolic flag. Without a descriptor, a Standard 14 font's flags come from its AFM file. + PdfFontFlags flags = _descriptor is { } descriptor + ? PdfFontDescriptor.ReadFlags(descriptor, font.Document) + : _standard14 is { } metrics ? Standard14Data.Flags(metrics) : PdfFontFlags.None; + _symbolic = flags.HasFlag(PdfFontFlags.Symbolic); + } + + /// The encoding: §9.6.5.1 Table 112, §9.6.5.2 for Type 1 and others, §9.6.5.3 for Type 3. + private void ReadEncoding() + { + CosObject? encoding = font.Get(FontNames.Encoding); + if (IsType3) + { + ReadType3Encoding(encoding); + return; + } + + bool namedEncodingIgnored = !_embedded && _standard14 is { } symbolFont && Standard14Data.IsSymbolic(symbolFont); + switch (encoding) + { + case null: + ApplyBuiltIn(); + break; + case CosName name: + if (namedEncodingIgnored) + { + ReportNamedEncodingIgnored(name); + ApplyBuiltIn(); + } + else if (ReadPredefined(name) is { } predefined) + { + Apply(predefined); + } + else + { + ApplyBuiltIn(); + } + + break; + case CosDictionary dictionary: + _sources.Add(dictionary); + BuiltInEncoding? baseEncoding = null; + if (font.GetFrom(dictionary, FontNames.BaseEncoding) is { } baseValue) + { + if (baseValue is not CosName baseName) + { + ReportEncodingInvalid("an encoding dictionary's BaseEncoding is not a name"); + } + else if (namedEncodingIgnored) + { + ReportNamedEncodingIgnored(baseName); + } + else + { + baseEncoding = ReadPredefined(baseName); + } + } + + // Table 112: without BaseEncoding, an embedded program's built-in encoding; otherwise StandardEncoding for a + // nonsymbolic font and the font's built-in encoding for a symbolic one. + if (baseEncoding is { } explicitBase) + { + Apply(explicitBase); + } + else if (_embedded || _symbolic) + { + ApplyBuiltIn(); + } + else + { + Apply(BuiltInEncoding.Standard); + } + + ApplyDifferences(dictionary); + break; + default: + ReportEncodingInvalid("Encoding is neither a name nor a dictionary"); + ApplyBuiltIn(); + break; + } + } + + /// §9.6.5.3: a Type 3 font's encoding is entirely its Encoding entry, which is required. + private void ReadType3Encoding(CosObject? encoding) + { + switch (encoding) + { + case CosDictionary dictionary: + _sources.Add(dictionary); + if (font.GetFrom(dictionary, FontNames.BaseEncoding) is CosName baseName && ReadPredefined(baseName) is { } baseEncoding) + { + Apply(baseEncoding); + } + + ApplyDifferences(dictionary); + break; + case CosName name: + ReportEncodingInvalid("a Type 3 font's Encoding shall be an encoding dictionary (§9.6.4, Table 110), not a name"); + if (ReadPredefined(name) is { } predefined) + { + Apply(predefined); + } + + break; + default: + ReportEncodingInvalid("a Type 3 font shall have an encoding dictionary (§9.6.4, Table 110); no code has a glyph"); + break; + } + } + + /// The three predefined encodings (Table 112); StandardEncoding is accepted with a diagnostic, other names are not. + private BuiltInEncoding? ReadPredefined(CosName name) + { + if (FontNames.WinAnsiEncoding.Equals(name)) + { + return BuiltInEncoding.WinAnsi; + } + + if (FontNames.MacRomanEncoding.Equals(name)) + { + return BuiltInEncoding.MacRoman; + } + + if (FontNames.MacExpertEncoding.Equals(name)) + { + return BuiltInEncoding.MacExpert; + } + + if (FontNames.StandardEncoding.Equals(name)) + { + ReportEncodingInvalid("/StandardEncoding is not a predefined encoding name (Annex D.1); StandardEncoding is used"); + return BuiltInEncoding.Standard; + } + + ReportEncodingInvalid($"/{name.Value} is not one of MacRomanEncoding, MacExpertEncoding and WinAnsiEncoding; the font's built-in encoding is used"); + return null; + } + + /// + /// The font's built-in encoding: the program's when embedded and read; the Symbol or ZapfDingbats encoding for those fonts; + /// StandardEncoding otherwise (a non-embedded font without a substitute: no other built-in encoding is known). + /// + private void ApplyBuiltIn() + { + if (_embedded) + { + if (font.GetProgramEncoding() is { } program) + { + for (int code = 0; code < 256; code++) + { + _names[code] = program[code]; + } + + return; + } + + font.Report( + DiagnosticCodes.FontBuiltInEncodingUnavailable, + DiagnosticSeverity.Information, + "The embedded font program's built-in encoding is not read; StandardEncoding stands in for it."); + Apply(BuiltInEncoding.Standard); + return; + } + + if (_standard14 is { } standard14) + { + Apply(Standard14Data.EncodingOf(standard14)); + return; + } + + if (_symbolic) + { + font.Report( + DiagnosticCodes.FontBuiltInEncodingUnavailable, + DiagnosticSeverity.Information, + "A symbolic font that is not embedded has no known built-in encoding (ISO 32000-2 §9.6.5.1); StandardEncoding stands in for it."); + } + + Apply(BuiltInEncoding.Standard); + } + + private void Apply(BuiltInEncoding encoding) + { + ReadOnlySpan table = GlyphNameTable.Table(encoding); + for (int code = 0; code < 256; code++) + { + _names[code] = table[code] >= 0 ? GlyphNameTable.Names[table[code]] : null; + } + } + + /// §9.6.5.1: code name name … code name …; each name takes the current code, which then moves on. + private void ApplyDifferences(CosDictionary encoding) + { + CosObject? value = font.GetFrom(encoding, FontNames.Differences); + if (value is null) + { + return; + } + + if (value is not CosArray differences) + { + ReportDifferencesInvalid("Differences is not an array; ignored"); + return; + } + + _sources.Add(differences); + int code = -1; + foreach (CosObject item in differences) + { + switch (font.Document.Resolve(item)) + { + case CosInteger integer: + code = integer.Value is >= int.MinValue and <= int.MaxValue ? (int)integer.Value : -1; + break; + case CosReal real when real.Value == Math.Floor(real.Value) && Math.Abs(real.Value) < int.MaxValue: + code = (int)real.Value; + break; + case CosName name: + if (code is >= 0 and <= 255) + { + // The empty name (a lone slash) can name no glyph: the code shows .notdef. + _names[code] = name.Bytes.IsEmpty ? null : name.Value; + } + else + { + ReportDifferencesInvalid(string.Create(CultureInfo.InvariantCulture, $"a name is given for code {code}, outside 0 to 255; ignored")); + } + + if (code >= 0) + { + code++; + } + + break; + default: + ReportDifferencesInvalid("an element is neither a code nor a name; skipped"); + break; + } + } + } + + /// §9.6.2.1 Table 109: Widths from FirstChar to LastChar, MissingWidth outside; Standard 14 metrics when absent. + private void ReadWidths(string[] names) + { + CosObject? value = font.Get(FontNames.Widths); + if (value is CosArray widths) + { + _sources.Add(widths); + ReadWidthsArray(widths, names); + return; + } + + if (value is not null) + { + font.Report( + DiagnosticCodes.FontWidthsInvalid, + DiagnosticSeverity.Warning, + "A font's Widths shall be an array (ISO 32000-2 §9.6.2.1, Table 109); ignored."); + } + + if (_standard14 is { } standard14) + { + for (int code = 0; code < 256; code++) + { + _widths[code] = Standard14Width(standard14, names[code]); + } + + return; + } + + font.Report( + DiagnosticCodes.FontWidthsMissing, + DiagnosticSeverity.Warning, + "The font has no Widths and is not a Standard 14 font (ISO 32000-2 §9.6.2.1, Table 109); every width is 0."); + } + + private void ReadWidthsArray(CosArray widths, string[] names) + { + int count = widths.Count; + int first; + if (font.Get(FontNames.FirstChar) is CosInteger { Value: >= 0 and <= 255 } firstChar) + { + first = (int)firstChar.Value; + } + else + { + first = 0; + ReportWidthsInvalid("FirstChar is missing or not a code from 0 to 255; 0 is used"); + } + + int last; + if (font.Get(FontNames.LastChar) is CosInteger { Value: >= 0 and <= 255 } lastChar && lastChar.Value >= first) + { + last = (int)lastChar.Value; + if (last - first + 1 != count) + { + ReportWidthsInvalid(string.Create( + CultureInfo.InvariantCulture, + $"Widths has {count} elements, but LastChar - FirstChar + 1 is {last - first + 1}; codes without an element have MissingWidth")); + } + } + else + { + last = Math.Min(255, first + count - 1); + ReportWidthsInvalid("LastChar is missing or malformed; FirstChar plus the number of widths is used"); + } + + // A code outside the range has the descriptor's MissingWidth (default 0); with no descriptor, a Standard 14 font's metrics. + double? missingWidth = _descriptor is { } descriptor + ? font.GetFrom(descriptor, FontNames.MissingWidth) is CosNumber missing ? missing.ToDouble() : 0 + : _standard14 is null ? 0 : null; + for (int code = 0; code < 256; code++) + { + int index = code - first; + if (code >= first && code <= last && index < count) + { + if (font.Document.Resolve(widths[index]) is CosNumber width) + { + _widths[code] = width.ToDouble(); + continue; + } + + ReportWidthsInvalid("an element of Widths is not a number; MissingWidth is used for its code"); + } + + _widths[code] = missingWidth ?? Standard14Width(_standard14!.Value, names[code]); + } + } + + private double Standard14Width(Standard14Font standard14, string glyphName) + { + if (Standard14Data.TryGetWidth(standard14, glyphName, out double width)) + { + return width; + } + + font.Report( + DiagnosticCodes.FontGlyphMissing, + DiagnosticSeverity.Information, + $"The Standard 14 font {Standard14Data.PostScriptName(standard14)} has no glyph /{glyphName}; its width is 0."); + return 0; + } + + /// + /// §9.6.2.1: a Standard 14 font has all four of FirstChar, LastChar, Widths and FontDescriptor or none; any other font that + /// is not Type 3 shall have a descriptor (§9.6.1). + /// + private void CheckStandard14Entries() + { + if (_standard14 is not null) + { + int present = (font.Get(FontNames.FirstChar) is null ? 0 : 1) + (font.Get(FontNames.LastChar) is null ? 0 : 1) + + (font.Get(FontNames.Widths) is null ? 0 : 1) + (font.Get(FontNames.FontDescriptor) is null ? 0 : 1); + if (present is > 0 and < 4) + { + font.Report( + DiagnosticCodes.FontStandard14EntriesIncomplete, + DiagnosticSeverity.Warning, + "A Standard 14 font shall have all or none of FirstChar, LastChar, Widths and FontDescriptor (ISO 32000-2 §9.6.2.1, Table 109); the entries present are used."); + } + } + else if (!IsType3 && _descriptor is null) + { + font.Report( + DiagnosticCodes.FontDescriptorMissing, + DiagnosticSeverity.Warning, + "A simple font that is not a Standard 14 font shall have a font descriptor (ISO 32000-2 §9.6.1, §9.6.2.1)."); + } + } + + private void ReportNamedEncodingIgnored(CosName name) => font.Report( + DiagnosticCodes.FontEncodingIgnored, + DiagnosticSeverity.Information, + $"The encoding /{name.Value} is ignored for the non-embedded symbolic font; its built-in encoding is used (as pdf.js does)."); + + private void ReportEncodingInvalid(string problem) => font.Report( + DiagnosticCodes.FontEncodingInvalid, + DiagnosticSeverity.Warning, + $"The font's encoding deviates from ISO 32000-2 §9.6.5.1 Table 112: {problem}."); + + private void ReportDifferencesInvalid(string problem) => font.Report( + DiagnosticCodes.FontDifferencesInvalid, + DiagnosticSeverity.Warning, + $"The encoding's Differences array deviates from ISO 32000-2 §9.6.5.1: {problem}."); + + private void ReportWidthsInvalid(string problem) => font.Report( + DiagnosticCodes.FontWidthsInvalid, + DiagnosticSeverity.Warning, + $"The font's widths deviate from ISO 32000-2 §9.6.2.1 Table 109: {problem}."); + } +} diff --git a/src/Broadside/Fonts/Standard14Data.cs b/src/Broadside/Fonts/Standard14Data.cs new file mode 100644 index 00000000..a67a867a --- /dev/null +++ b/src/Broadside/Fonts/Standard14Data.cs @@ -0,0 +1,304 @@ +using System.Collections.Frozen; + +namespace Broadside.Fonts; + +/// Lookups over the generated Standard 14 metrics (Standard14Data.g.cs) and the font names that select them. +/// ISO 32000-2 §9.6.2.1 (the paragraph after Table 109) and §9.6.2.2. Every lookup allocates nothing. +internal static partial class Standard14Data +{ + /// The width Acrobat gives .notdef in a Standard 14 font other than Courier (PDFBox follows it; PDFBOX-2334). + private const short NotDefWidth = 250; + + /// The PostScript names of the fourteen fonts, in order. + private static readonly string[] PostScriptNames = + [ + "Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique", + "Helvetica", "Helvetica-Bold", "Helvetica-Oblique", "Helvetica-BoldOblique", + "Times-Roman", "Times-Bold", "Times-Italic", "Times-BoldItalic", + "Symbol", "ZapfDingbats", + ]; + + /// The fourteen names exactly as §9.6.2.2 lists them. + private static readonly FrozenDictionary CanonicalNames = + PostScriptNames.Select((name, index) => KeyValuePair.Create(name, (Standard14Font)index)).ToFrozenDictionary(StringComparer.Ordinal); + + /// + /// Other names producers write for the fourteen fonts, after , compared ignoring case: the union of pdf.js + /// (getStdFontMap) and PDFBox (Standard14Fonts), without the Arial Narrow, Arial Black and Arial Unicode MS entries, + /// whose metrics differ from Helvetica's. + /// + private static readonly FrozenDictionary AliasNames = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["Courier"] = Standard14Font.Courier, + ["CourierNew"] = Standard14Font.Courier, + ["CourierNewPSMT"] = Standard14Font.Courier, + ["CourierCourierNew"] = Standard14Font.Courier, + ["Courier-Bold"] = Standard14Font.CourierBold, + ["CourierNew-Bold"] = Standard14Font.CourierBold, + ["CourierNewPS-BoldMT"] = Standard14Font.CourierBold, + ["Courier-Oblique"] = Standard14Font.CourierOblique, + ["Courier-Italic"] = Standard14Font.CourierOblique, + ["CourierNew-Italic"] = Standard14Font.CourierOblique, + ["CourierNewPS-ItalicMT"] = Standard14Font.CourierOblique, + ["Courier-BoldOblique"] = Standard14Font.CourierBoldOblique, + ["Courier-BoldItalic"] = Standard14Font.CourierBoldOblique, + ["CourierNew-BoldItalic"] = Standard14Font.CourierBoldOblique, + ["CourierNewPS-BoldItalicMT"] = Standard14Font.CourierBoldOblique, + ["Helvetica"] = Standard14Font.Helvetica, + ["Arial"] = Standard14Font.Helvetica, + ["ArialMT"] = Standard14Font.Helvetica, + ["Helvetica-Bold"] = Standard14Font.HelveticaBold, + ["Arial-Bold"] = Standard14Font.HelveticaBold, + ["Arial-BoldMT"] = Standard14Font.HelveticaBold, + ["Arial-BoldMT-Bold"] = Standard14Font.HelveticaBold, + ["HelveticaLTStd-Bold"] = Standard14Font.HelveticaBold, + ["Helvetica-Oblique"] = Standard14Font.HelveticaOblique, + ["Helvetica-Italic"] = Standard14Font.HelveticaOblique, + ["Arial-Italic"] = Standard14Font.HelveticaOblique, + ["Arial-ItalicMT"] = Standard14Font.HelveticaOblique, + ["Arial-ItalicMT-Italic"] = Standard14Font.HelveticaOblique, + ["Helvetica-BoldOblique"] = Standard14Font.HelveticaBoldOblique, + ["Helvetica-BoldItalic"] = Standard14Font.HelveticaBoldOblique, + ["Arial-BoldItalic"] = Standard14Font.HelveticaBoldOblique, + ["Arial-BoldItalicMT"] = Standard14Font.HelveticaBoldOblique, + ["Arial-BoldItalicMT-BoldItalic"] = Standard14Font.HelveticaBoldOblique, + ["Times-Roman"] = Standard14Font.TimesRoman, + ["Times"] = Standard14Font.TimesRoman, + ["TimesNewRoman"] = Standard14Font.TimesRoman, + ["TimesNewRomanPS"] = Standard14Font.TimesRoman, + ["TimesNewRomanPSMT"] = Standard14Font.TimesRoman, + ["Times-Bold"] = Standard14Font.TimesBold, + ["TimesNewRoman-Bold"] = Standard14Font.TimesBold, + ["TimesNewRomanPS-Bold"] = Standard14Font.TimesBold, + ["TimesNewRomanPS-BoldMT"] = Standard14Font.TimesBold, + ["TimesNewRomanPSMT-Bold"] = Standard14Font.TimesBold, + ["Times-Italic"] = Standard14Font.TimesItalic, + ["TimesNewRoman-Italic"] = Standard14Font.TimesItalic, + ["TimesNewRomanPS-Italic"] = Standard14Font.TimesItalic, + ["TimesNewRomanPS-ItalicMT"] = Standard14Font.TimesItalic, + ["TimesNewRomanPSMT-Italic"] = Standard14Font.TimesItalic, + ["Times-BoldItalic"] = Standard14Font.TimesBoldItalic, + ["TimesNewRoman-BoldItalic"] = Standard14Font.TimesBoldItalic, + ["TimesNewRomanPS-BoldItalic"] = Standard14Font.TimesBoldItalic, + ["TimesNewRomanPS-BoldItalicMT"] = Standard14Font.TimesBoldItalic, + ["TimesNewRomanPSMT-BoldItalic"] = Standard14Font.TimesBoldItalic, + ["Symbol"] = Standard14Font.Symbol, + ["Symbol-Bold"] = Standard14Font.Symbol, + ["Symbol-Italic"] = Standard14Font.Symbol, + ["Symbol-BoldItalic"] = Standard14Font.Symbol, + ["ZapfDingbats"] = Standard14Font.ZapfDingbats, + }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); + + /// Gets the PostScript name of a Standard 14 font, as §9.6.2.2 spells it. + /// The font. + /// The name, such as Helvetica-Bold. + public static string PostScriptName(Standard14Font font) => PostScriptNames[(int)font]; + + /// Gets a value indicating whether the font is one of the two symbolic Standard 14 fonts. + /// The font. + /// for Symbol and ZapfDingbats. + public static bool IsSymbolic(Standard14Font font) => font is Standard14Font.Symbol or Standard14Font.ZapfDingbats; + + /// Gets the built-in encoding of a Standard 14 font program (§9.6.5.1): its own for Symbol and ZapfDingbats, StandardEncoding otherwise. + /// The font. + /// The encoding. + public static BuiltInEncoding EncodingOf(Standard14Font font) => font switch + { + Standard14Font.Symbol => BuiltInEncoding.Symbol, + Standard14Font.ZapfDingbats => BuiltInEncoding.ZapfDingbats, + _ => BuiltInEncoding.Standard, + }; + + /// Gets one font-wide metric of a Standard 14 font, from the AFM file. + /// The font. + /// Which metric. + /// The value, in glyph space units (thousandths of text space); the italic angle in degrees. + public static double Metric(Standard14Font font, Standard14Metric metric) + { + short value = FontMetrics[((int)font * MetricsStride) + (int)metric]; + return metric == Standard14Metric.ItalicAngle ? value / 10.0 : value; + } + + /// Gets the font descriptor flags of a Standard 14 font, synthesized from its AFM file. + /// The font. + /// FixedPitch for Courier, Serif for Times, Italic for a non-zero italic angle, and Symbolic or Nonsymbolic from the encoding scheme. + public static PdfFontFlags Flags(Standard14Font font) => (PdfFontFlags)FontMetrics[((int)font * MetricsStride) + (int)Standard14Metric.Flags]; + + /// Gets the font bounding box of a Standard 14 font. + /// The font. + /// The AFM FontBBox. + public static PdfRectangle FontBBox(Standard14Font font) => new( + Metric(font, Standard14Metric.BBoxLeft), + Metric(font, Standard14Metric.BBoxBottom), + Metric(font, Standard14Metric.BBoxRight), + Metric(font, Standard14Metric.BBoxTop)); + + /// + /// Gets the width of a glyph of a Standard 14 font. .notdef, which the AFM files do not list, is 250 (600 in Courier), + /// as in Acrobat. A name the font does not use is looked up by its Unicode value (Adobe Glyph List, uniXXXX), with the + /// no-break space read as the space and the soft hyphen as the hyphen, as Annex D notes 5 and 6 allow. + /// + /// The font. + /// The glyph name. + /// The width in glyph space units (thousandths of text space). + /// when the font has no glyph for the name. + public static bool TryGetWidth(Standard14Font font, string glyphName, out double width) + { + int stride = (int)font * NameCount; + int index = GlyphNameTable.IndexOf(glyphName); + if (index >= 0 && Widths[stride + index] is var direct and >= 0) + { + width = direct; + return true; + } + + if (glyphName == GlyphNameTable.NotDef) + { + width = font <= Standard14Font.CourierBoldOblique ? 600 : NotDefWidth; + return true; + } + + if (AdobeGlyphList.TryGetScalar(glyphName, font == Standard14Font.ZapfDingbats, out int scalar)) + { + scalar = scalar switch + { + 0x00A0 => 0x0020, + 0x00AD => 0x002D, + _ => scalar, + }; + index = FindByUnicode(font, scalar); + if (index >= 0 && Widths[stride + index] is var byUnicode and >= 0) + { + width = byUnicode; + return true; + } + } + + width = 0; + return false; + } + + /// Gets a value indicating whether a Standard 14 font has a glyph of this name (its AFM file lists it). + /// The font. + /// The glyph name. + /// when the AFM file has the glyph. + public static bool HasGlyph(Standard14Font font, string glyphName) => + GlyphNameTable.IndexOf(glyphName) is var index and >= 0 && Widths[((int)font * NameCount) + index] >= 0; + + /// Finds the Standard 14 font a BaseFont name selects. + /// The name, possibly with a subset tag. + /// The font. + /// Whether the name is not one of the fourteen names of §9.6.2.2 but another name for the same font. + /// when the name selects a Standard 14 font. + public static bool TryMatch(string baseFont, out Standard14Font font, out bool isAlias) + { + string name = WithoutSubsetTag(baseFont); + if (CanonicalNames.TryGetValue(name, out font)) + { + isAlias = name.Length != baseFont.Length; + return true; + } + + isAlias = true; + return AliasNames.TryGetValue(Normalize(name), out font); + } + + /// Removes a subset tag, six uppercase letters and a plus sign (§9.9.2). + private static string WithoutSubsetTag(string name) + { + if (name.Length > 7 && name[6] == '+') + { + for (int index = 0; index < 6; index++) + { + if (!char.IsAsciiLetterUpper(name[index])) + { + return name; + } + } + + return name[7..]; + } + + return name; + } + + /// pdf.js's normalization: commas and underscores become hyphens, white space is removed (Arial,Bold is Arial-Bold). + private static string Normalize(string name) + { + Span buffer = name.Length <= 128 ? stackalloc char[name.Length] : new char[name.Length]; + int length = 0; + foreach (char ch in name) + { + if (char.IsWhiteSpace(ch)) + { + continue; + } + + buffer[length++] = ch is ',' or '_' ? '-' : ch; + } + + return new string(buffer[..length]); + } + + private static int FindByUnicode(Standard14Font font, int scalar) + { + if (scalar > ushort.MaxValue) + { + return -1; + } + + int position; + switch (font) + { + case Standard14Font.Symbol: + position = SymbolUnicodes.BinarySearch((ushort)scalar); + return position >= 0 ? SymbolUnicodeNames[position] : -1; + case Standard14Font.ZapfDingbats: + position = ZapfDingbatsUnicodes.BinarySearch((ushort)scalar); + return position >= 0 ? ZapfDingbatsUnicodeNames[position] : -1; + default: + position = LatinUnicodes.BinarySearch((ushort)scalar); + return position >= 0 ? LatinUnicodeNames[position] : -1; + } + } +} + +/// The font-wide metrics of , in stored order. +internal enum Standard14Metric +{ + /// FontBBox lower-left x. + BBoxLeft, + + /// FontBBox lower-left y. + BBoxBottom, + + /// FontBBox upper-right x. + BBoxRight, + + /// FontBBox upper-right y. + BBoxTop, + + /// ItalicAngle, stored times ten. + ItalicAngle, + + /// CapHeight; for Symbol and ZapfDingbats, the font box top. + CapHeight, + + /// XHeight; 0 for Symbol and ZapfDingbats. + XHeight, + + /// Ascender; for Symbol and ZapfDingbats, the font box top. + Ascent, + + /// Descender; for Symbol and ZapfDingbats, the font box bottom. + Descent, + + /// StdVW, the font descriptor's StemV. + StemV, + + /// StdHW, the font descriptor's StemH. + StemH, + + /// The synthesized Table 121 flags. + Flags, +} diff --git a/src/Broadside/Fonts/Standard14Data.g.cs b/src/Broadside/Fonts/Standard14Data.g.cs new file mode 100644 index 00000000..3ffe7965 --- /dev/null +++ b/src/Broadside/Fonts/Standard14Data.g.cs @@ -0,0 +1,674 @@ +// +// Generated by src/Broadside/Fonts/Data/generate.py. Do not edit; edit the generator or its inputs and re-run it. +// +// Derived from the Adobe Core 14 AFM files (Apache PDFBox commit 8712d47b075511a4c5a2829c3713ba2d538999bb, +// pdfbox/src/main/resources/org/apache/pdfbox/resources/afm/), which carry this notice (MustRead.html): +// +// This file and the 14 PostScript(R) AFM files it accompanies may be used, copied, and distributed for any +// purpose and without charge, with or without modification, provided that all copyright notices are retained; +// that the AFM files are not distributed without this file; that all modifications to this file or any of the +// AFM files are prominently noted in the modified file(s); and that this paragraph is not modified. Adobe +// Systems has no responsibility or obligation to support the use of the AFM files. +// +// MODIFIED: the AFM files were converted to C# tables; kerning, ligature and glyph bounding-box data were +// removed. The unmodified AFM files and MustRead.html are in src/Broadside/Fonts/Data/Afm/ and ship in the +// package under licenses/adobe-core14-afm/. +// +// Courier.afm: +// Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. +// Notice Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. +// +// Courier-Bold.afm: +// Copyright (c) 1989, 1990, 1991, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. +// Notice Copyright (c) 1989, 1990, 1991, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. +// +// Courier-Oblique.afm: +// Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. +// Notice Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. +// +// Courier-BoldOblique.afm: +// Copyright (c) 1989, 1990, 1991, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. +// Notice Copyright (c) 1989, 1990, 1991, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. +// +// Helvetica.afm: +// Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved. +// Notice Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.Helvetica is a trademark of Linotype-Hell AG and/or its subsidiaries. +// +// Helvetica-Bold.afm: +// Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved. +// Notice Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.Helvetica is a trademark of Linotype-Hell AG and/or its subsidiaries. +// +// Helvetica-Oblique.afm: +// Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved. +// Notice Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.Helvetica is a trademark of Linotype-Hell AG and/or its subsidiaries. +// +// Helvetica-BoldOblique.afm: +// Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved. +// Notice Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.Helvetica is a trademark of Linotype-Hell AG and/or its subsidiaries. +// +// Times-Roman.afm: +// Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. +// Notice Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.Times is a trademark of Linotype-Hell AG and/or its subsidiaries. +// +// Times-Bold.afm: +// Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. +// Notice Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.Times is a trademark of Linotype-Hell AG and/or its subsidiaries. +// +// Times-Italic.afm: +// Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. +// Notice Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.Times is a trademark of Linotype-Hell AG and/or its subsidiaries. +// +// Times-BoldItalic.afm: +// Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. +// Notice Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.Times is a trademark of Linotype-Hell AG and/or its subsidiaries. +// +// Symbol.afm: +// Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All rights reserved. +// Notice Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All rights reserved. +// +// ZapfDingbats.afm: +// Copyright (c) 1985, 1987, 1988, 1989, 1997 Adobe Systems Incorporated. All Rights Reserved. +// Notice Copyright (c) 1985, 1987, 1988, 1989, 1997 Adobe Systems Incorporated. All Rights Reserved.ITC Zapf Dingbats is a registered trademark of International Typeface Corporation. +// +// Derived from the Adobe Glyph List and the ITC Zapf Dingbats Glyph List (https://github.com/adobe-type-tools/agl-aglfn, +// commit 4036a9ca80a62f64f9de4f7321a9a045ad0ecfd6), converted to C# tables. +// +// Copyright 2002-2019 Adobe (http://www.adobe.com/). +// +// Redistribution and use in source and binary forms, with or without modification, are permitted provided that +// the following conditions are met: +// +// Redistributions of source code must retain the above copyright notice, this list of conditions and the +// following disclaimer. +// +// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the +// following disclaimer in the documentation and/or other materials provided with the distribution. +// +// Neither the name of Adobe nor the names of its contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED +// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY +// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// + +namespace Broadside.Fonts; + +/// Metrics of the Standard 14 fonts, from the Adobe Core 14 AFM files. +/// ISO 32000-2 §9.6.2.2; Adobe Technical Note #5004. +internal static partial class Standard14Data +{ + /// The number of glyph names in ; the stride of . + internal const int NameCount = 803; + + /// The number of values per font in . + internal const int MetricsStride = 12; + + /// For each font (in order) and each glyph name index, the AFM WX width, or -1 when the font has no such glyph. + internal static ReadOnlySpan Widths => + [ + 600, 600, -1, 600, -1, 600, 600, -1, -1, 600, -1, 600, -1, -1, 600, 600, 600, -1, -1, 600, -1, 600, -1, -1, -1, + 600, 600, -1, 600, 600, -1, -1, -1, -1, -1, 600, 600, 600, 600, -1, -1, -1, 600, 600, -1, 600, 600, -1, 600, + -1, 600, 600, -1, 600, 600, -1, -1, -1, 600, -1, 600, 600, -1, 600, -1, 600, 600, -1, -1, 600, -1, -1, 600, + 600, -1, 600, -1, 600, -1, 600, -1, 600, -1, 600, 600, -1, -1, 600, -1, 600, -1, 600, -1, 600, 600, -1, 600, + 600, 600, -1, -1, 600, -1, -1, -1, 600, 600, 600, 600, -1, 600, -1, -1, 600, 600, -1, 600, -1, 600, -1, 600, + -1, -1, 600, -1, 600, 600, -1, -1, 600, -1, -1, 600, -1, 600, -1, -1, -1, -1, 600, -1, 600, 600, 600, 600, -1, + -1, -1, -1, 600, 600, 600, -1, 600, 600, -1, -1, 600, -1, 600, 600, -1, 600, -1, -1, -1, 600, 600, -1, 600, -1, + 600, -1, 600, -1, 600, 600, 600, -1, -1, 600, -1, 600, -1, 600, -1, 600, -1, -1, 600, 600, -1, 600, -1, -1, + 600, 600, 600, -1, 600, -1, -1, 600, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 600, 600, 600, 600, 600, 600, 600, -1, -1, 600, + 600, -1, -1, -1, -1, 600, -1, -1, 600, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 600, 600, 600, -1, -1, + 600, 600, 600, 600, 600, -1, -1, 600, -1, -1, -1, 600, -1, -1, -1, 600, -1, -1, -1, 600, -1, -1, -1, 600, 600, + -1, 600, 600, 600, 600, -1, 600, 600, 600, 600, -1, -1, -1, -1, -1, -1, 600, -1, 600, -1, 600, 600, -1, -1, -1, + 600, -1, -1, 600, 600, 600, 600, 600, 600, 600, -1, -1, 600, 600, 600, -1, -1, -1, 600, 600, -1, -1, 600, 600, + 600, 600, 600, 600, 600, 600, -1, -1, -1, -1, 600, 600, 600, -1, 600, 600, -1, 600, -1, -1, -1, 600, 600, 600, + -1, -1, -1, 600, -1, -1, -1, 600, -1, 600, -1, -1, -1, -1, 600, 600, 600, -1, -1, -1, 600, 600, -1, 600, 600, + 600, -1, 600, 600, 600, 600, 600, 600, 600, 600, -1, 600, 600, -1, -1, 600, 600, 600, 600, 600, 600, -1, -1, + -1, -1, -1, -1, 600, -1, -1, 600, 600, -1, 600, 600, 600, -1, 600, 600, 600, 600, -1, 600, -1, 600, 600, -1, + 600, 600, 600, -1, -1, 600, 600, 600, 600, 600, 600, 600, -1, -1, -1, -1, 600, -1, -1, 600, -1, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, -1, -1, -1, 600, -1, -1, -1, 600, -1, -1, 600, 600, -1, 600, 600, 600, -1, + 600, 600, 600, 600, -1, -1, -1, -1, -1, 600, -1, -1, -1, -1, -1, 600, 600, 600, 600, -1, -1, -1, 600, -1, -1, + -1, 600, 600, -1, -1, -1, -1, -1, 600, 600, 600, -1, -1, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + -1, 600, 600, -1, -1, 600, -1, -1, -1, 600, -1, -1, 600, 600, 600, 600, 600, -1, 600, 600, 600, -1, -1, -1, -1, + -1, -1, -1, 600, -1, -1, -1, 600, 600, -1, -1, 600, -1, 600, 600, -1, 600, 600, -1, -1, -1, 600, 600, -1, -1, + -1, 600, -1, 600, 600, 600, -1, -1, -1, 600, -1, -1, -1, 600, -1, 600, 600, 600, 600, 600, 600, 600, 600, -1, + -1, 600, -1, 600, 600, 600, -1, 600, -1, 600, 600, 600, 600, 600, 600, 600, 600, 600, -1, -1, -1, -1, 600, 600, + -1, 600, -1, 600, 600, -1, -1, 600, -1, 600, -1, -1, 600, 600, 600, -1, -1, 600, -1, 600, -1, -1, -1, 600, 600, + -1, 600, 600, -1, -1, -1, -1, -1, 600, 600, 600, 600, -1, -1, -1, 600, 600, -1, 600, 600, -1, 600, -1, 600, + 600, -1, 600, 600, -1, -1, -1, 600, -1, 600, 600, -1, 600, -1, 600, 600, -1, -1, 600, -1, -1, 600, 600, -1, + 600, -1, 600, -1, 600, -1, 600, -1, 600, 600, -1, -1, 600, -1, 600, -1, 600, -1, 600, 600, -1, 600, 600, 600, + -1, -1, 600, -1, -1, -1, 600, 600, 600, 600, -1, 600, -1, -1, 600, 600, -1, 600, -1, 600, -1, 600, -1, -1, 600, + -1, 600, 600, -1, -1, 600, -1, -1, 600, -1, 600, -1, -1, -1, -1, 600, -1, 600, 600, 600, 600, -1, -1, -1, -1, + 600, 600, 600, -1, 600, 600, -1, -1, 600, -1, 600, 600, -1, 600, -1, -1, -1, 600, 600, -1, 600, -1, 600, -1, + 600, -1, 600, 600, 600, -1, -1, 600, -1, 600, -1, 600, -1, 600, -1, -1, 600, 600, -1, 600, -1, -1, 600, 600, + 600, -1, 600, -1, -1, 600, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 600, 600, 600, 600, 600, 600, 600, -1, -1, 600, 600, -1, -1, + -1, -1, 600, -1, -1, 600, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 600, 600, 600, -1, -1, 600, 600, 600, + 600, 600, -1, -1, 600, -1, -1, -1, 600, -1, -1, -1, 600, -1, -1, -1, 600, -1, -1, -1, 600, 600, -1, 600, 600, + 600, 600, -1, 600, 600, 600, 600, -1, -1, -1, -1, -1, -1, 600, -1, 600, -1, 600, 600, -1, -1, -1, 600, -1, -1, + 600, 600, 600, 600, 600, 600, 600, -1, -1, 600, 600, 600, -1, -1, -1, 600, 600, -1, -1, 600, 600, 600, 600, + 600, 600, 600, 600, -1, -1, -1, -1, 600, 600, 600, -1, 600, 600, -1, 600, -1, -1, -1, 600, 600, 600, -1, -1, + -1, 600, -1, -1, -1, 600, -1, 600, -1, -1, -1, -1, 600, 600, 600, -1, -1, -1, 600, 600, -1, 600, 600, 600, -1, + 600, 600, 600, 600, 600, 600, 600, 600, -1, 600, 600, -1, -1, 600, 600, 600, 600, 600, 600, -1, -1, -1, -1, -1, + -1, 600, -1, -1, 600, 600, -1, 600, 600, 600, -1, 600, 600, 600, 600, -1, 600, -1, 600, 600, -1, 600, 600, 600, + -1, -1, 600, 600, 600, 600, 600, 600, 600, -1, -1, -1, -1, 600, -1, -1, 600, -1, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, -1, -1, -1, 600, -1, -1, -1, 600, -1, -1, 600, 600, -1, 600, 600, 600, -1, 600, 600, 600, + 600, -1, -1, -1, -1, -1, 600, -1, -1, -1, -1, -1, 600, 600, 600, 600, -1, -1, -1, 600, -1, -1, -1, 600, 600, + -1, -1, -1, -1, -1, 600, 600, 600, -1, -1, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, -1, 600, 600, + -1, -1, 600, -1, -1, -1, 600, -1, -1, 600, 600, 600, 600, 600, -1, 600, 600, 600, -1, -1, -1, -1, -1, -1, -1, + 600, -1, -1, -1, 600, 600, -1, -1, 600, -1, 600, 600, -1, 600, 600, -1, -1, -1, 600, 600, -1, -1, -1, 600, -1, + 600, 600, 600, -1, -1, -1, 600, -1, -1, -1, 600, -1, 600, 600, 600, 600, 600, 600, 600, 600, -1, -1, 600, -1, + 600, 600, 600, -1, 600, -1, 600, 600, 600, 600, 600, 600, 600, 600, 600, -1, -1, -1, -1, 600, 600, -1, 600, -1, + 600, 600, -1, -1, 600, -1, 600, -1, -1, 600, 600, 600, -1, -1, 600, -1, 600, -1, -1, -1, 600, 600, -1, 600, + 600, -1, -1, -1, -1, -1, 600, 600, 600, 600, -1, -1, -1, 600, 600, -1, 600, 600, -1, 600, -1, 600, 600, -1, + 600, 600, -1, -1, -1, 600, -1, 600, 600, -1, 600, -1, 600, 600, -1, -1, 600, -1, -1, 600, 600, -1, 600, -1, + 600, -1, 600, -1, 600, -1, 600, 600, -1, -1, 600, -1, 600, -1, 600, -1, 600, 600, -1, 600, 600, 600, -1, -1, + 600, -1, -1, -1, 600, 600, 600, 600, -1, 600, -1, -1, 600, 600, -1, 600, -1, 600, -1, 600, -1, -1, 600, -1, + 600, 600, -1, -1, 600, -1, -1, 600, -1, 600, -1, -1, -1, -1, 600, -1, 600, 600, 600, 600, -1, -1, -1, -1, 600, + 600, 600, -1, 600, 600, -1, -1, 600, -1, 600, 600, -1, 600, -1, -1, -1, 600, 600, -1, 600, -1, 600, -1, 600, + -1, 600, 600, 600, -1, -1, 600, -1, 600, -1, 600, -1, 600, -1, -1, 600, 600, -1, 600, -1, -1, 600, 600, 600, + -1, 600, -1, -1, 600, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 600, 600, 600, 600, 600, 600, 600, -1, -1, 600, 600, -1, -1, -1, + -1, 600, -1, -1, 600, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 600, 600, 600, -1, -1, 600, 600, 600, + 600, 600, -1, -1, 600, -1, -1, -1, 600, -1, -1, -1, 600, -1, -1, -1, 600, -1, -1, -1, 600, 600, -1, 600, 600, + 600, 600, -1, 600, 600, 600, 600, -1, -1, -1, -1, -1, -1, 600, -1, 600, -1, 600, 600, -1, -1, -1, 600, -1, -1, + 600, 600, 600, 600, 600, 600, 600, -1, -1, 600, 600, 600, -1, -1, -1, 600, 600, -1, -1, 600, 600, 600, 600, + 600, 600, 600, 600, -1, -1, -1, -1, 600, 600, 600, -1, 600, 600, -1, 600, -1, -1, -1, 600, 600, 600, -1, -1, + -1, 600, -1, -1, -1, 600, -1, 600, -1, -1, -1, -1, 600, 600, 600, -1, -1, -1, 600, 600, -1, 600, 600, 600, -1, + 600, 600, 600, 600, 600, 600, 600, 600, -1, 600, 600, -1, -1, 600, 600, 600, 600, 600, 600, -1, -1, -1, -1, -1, + -1, 600, -1, -1, 600, 600, -1, 600, 600, 600, -1, 600, 600, 600, 600, -1, 600, -1, 600, 600, -1, 600, 600, 600, + -1, -1, 600, 600, 600, 600, 600, 600, 600, -1, -1, -1, -1, 600, -1, -1, 600, -1, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, -1, -1, -1, 600, -1, -1, -1, 600, -1, -1, 600, 600, -1, 600, 600, 600, -1, 600, 600, 600, + 600, -1, -1, -1, -1, -1, 600, -1, -1, -1, -1, -1, 600, 600, 600, 600, -1, -1, -1, 600, -1, -1, -1, 600, 600, + -1, -1, -1, -1, -1, 600, 600, 600, -1, -1, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, -1, 600, 600, + -1, -1, 600, -1, -1, -1, 600, -1, -1, 600, 600, 600, 600, 600, -1, 600, 600, 600, -1, -1, -1, -1, -1, -1, -1, + 600, -1, -1, -1, 600, 600, -1, -1, 600, -1, 600, 600, -1, 600, 600, -1, -1, -1, 600, 600, -1, -1, -1, 600, -1, + 600, 600, 600, -1, -1, -1, 600, -1, -1, -1, 600, -1, 600, 600, 600, 600, 600, 600, 600, 600, -1, -1, 600, -1, + 600, 600, 600, -1, 600, -1, 600, 600, 600, 600, 600, 600, 600, 600, 600, -1, -1, -1, -1, 600, 600, -1, 600, -1, + 600, 600, -1, -1, 600, -1, 600, -1, -1, 600, 600, 600, -1, -1, 600, -1, 600, -1, -1, -1, 600, 600, -1, 600, + 600, -1, -1, -1, -1, -1, 600, 600, 600, 600, -1, -1, -1, 600, 600, -1, 600, 600, -1, 600, -1, 600, 600, -1, + 600, 600, -1, -1, -1, 600, -1, 600, 600, -1, 600, -1, 600, 600, -1, -1, 600, -1, -1, 600, 600, -1, 600, -1, + 600, -1, 600, -1, 600, -1, 600, 600, -1, -1, 600, -1, 600, -1, 600, -1, 600, 600, -1, 600, 600, 600, -1, -1, + 600, -1, -1, -1, 600, 600, 600, 600, -1, 600, -1, -1, 600, 600, -1, 600, -1, 600, -1, 600, -1, -1, 600, -1, + 600, 600, -1, -1, 600, -1, -1, 600, -1, 600, -1, -1, -1, -1, 600, -1, 600, 600, 600, 600, -1, -1, -1, -1, 600, + 600, 600, -1, 600, 600, -1, -1, 600, -1, 600, 600, -1, 600, -1, -1, -1, 600, 600, -1, 600, -1, 600, -1, 600, + -1, 600, 600, 600, -1, -1, 600, -1, 600, -1, 600, -1, 600, -1, -1, 600, 600, -1, 600, -1, -1, 600, 600, 600, + -1, 600, -1, -1, 600, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 600, 600, 600, 600, 600, 600, 600, -1, -1, 600, 600, -1, -1, -1, + -1, 600, -1, -1, 600, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 600, 600, 600, -1, -1, 600, 600, 600, + 600, 600, -1, -1, 600, -1, -1, -1, 600, -1, -1, -1, 600, -1, -1, -1, 600, -1, -1, -1, 600, 600, -1, 600, 600, + 600, 600, -1, 600, 600, 600, 600, -1, -1, -1, -1, -1, -1, 600, -1, 600, -1, 600, 600, -1, -1, -1, 600, -1, -1, + 600, 600, 600, 600, 600, 600, 600, -1, -1, 600, 600, 600, -1, -1, -1, 600, 600, -1, -1, 600, 600, 600, 600, + 600, 600, 600, 600, -1, -1, -1, -1, 600, 600, 600, -1, 600, 600, -1, 600, -1, -1, -1, 600, 600, 600, -1, -1, + -1, 600, -1, -1, -1, 600, -1, 600, -1, -1, -1, -1, 600, 600, 600, -1, -1, -1, 600, 600, -1, 600, 600, 600, -1, + 600, 600, 600, 600, 600, 600, 600, 600, -1, 600, 600, -1, -1, 600, 600, 600, 600, 600, 600, -1, -1, -1, -1, -1, + -1, 600, -1, -1, 600, 600, -1, 600, 600, 600, -1, 600, 600, 600, 600, -1, 600, -1, 600, 600, -1, 600, 600, 600, + -1, -1, 600, 600, 600, 600, 600, 600, 600, -1, -1, -1, -1, 600, -1, -1, 600, -1, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, -1, -1, -1, 600, -1, -1, -1, 600, -1, -1, 600, 600, -1, 600, 600, 600, -1, 600, 600, 600, + 600, -1, -1, -1, -1, -1, 600, -1, -1, -1, -1, -1, 600, 600, 600, 600, -1, -1, -1, 600, -1, -1, -1, 600, 600, + -1, -1, -1, -1, -1, 600, 600, 600, -1, -1, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, -1, 600, 600, + -1, -1, 600, -1, -1, -1, 600, -1, -1, 600, 600, 600, 600, 600, -1, 600, 600, 600, -1, -1, -1, -1, -1, -1, -1, + 600, -1, -1, -1, 600, 600, -1, -1, 600, -1, 600, 600, -1, 600, 600, -1, -1, -1, 600, 600, -1, -1, -1, 600, -1, + 600, 600, 600, -1, -1, -1, 600, -1, -1, -1, 600, -1, 600, 600, 600, 600, 600, 600, 600, 600, -1, -1, 600, -1, + 600, 600, 600, -1, 600, -1, 600, 600, 600, 600, 600, 600, 600, 600, 600, -1, -1, -1, -1, 667, 1000, -1, 667, + -1, 667, 667, -1, -1, 667, -1, 667, -1, -1, 667, 667, 667, -1, -1, 667, -1, 667, -1, -1, -1, 722, 722, -1, 722, + 722, -1, -1, -1, -1, -1, 722, 722, 722, 612, -1, -1, -1, 667, 667, -1, 667, 667, -1, 667, -1, 667, 667, -1, + 667, 667, -1, -1, -1, 722, -1, 556, 611, -1, 778, -1, 778, 778, -1, -1, 722, -1, -1, 278, 278, -1, 278, -1, + 278, -1, 278, -1, 278, -1, 278, 278, -1, -1, 500, -1, 667, -1, 667, -1, 556, 556, -1, 556, 556, 556, -1, -1, + 833, -1, -1, -1, 722, 722, 722, 722, -1, 722, -1, -1, 778, 1000, -1, 778, -1, 778, -1, 778, -1, -1, 778, -1, + 778, 778, -1, -1, 778, -1, -1, 778, -1, 667, -1, -1, -1, -1, 778, -1, 722, 722, 722, 722, -1, -1, -1, -1, 667, + 667, 667, -1, 667, 667, -1, -1, 611, -1, 611, 611, -1, 667, -1, -1, -1, 722, 722, -1, 722, -1, 722, -1, 722, + -1, 722, 722, 722, -1, -1, 722, -1, 667, -1, 944, -1, 667, -1, -1, 667, 667, -1, 667, -1, -1, 611, 611, 611, + -1, 611, -1, -1, 556, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 556, 556, 556, 333, 556, 889, 556, -1, -1, 556, 667, -1, -1, -1, + -1, 556, -1, -1, 556, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 469, 584, 389, -1, -1, 1015, 556, 556, + 278, 260, -1, -1, 334, -1, -1, -1, 334, -1, -1, -1, 278, -1, -1, -1, 278, -1, -1, -1, 333, 260, -1, 350, 500, + 500, 333, -1, 500, 500, 333, 556, -1, -1, -1, -1, -1, -1, 333, -1, 278, -1, 278, 250, -1, -1, -1, 737, -1, -1, + 556, 556, 556, 556, 643, 556, 400, -1, -1, 333, 584, 556, -1, -1, -1, 333, 278, -1, -1, 556, 556, 556, 556, + 556, 556, 556, 556, -1, -1, -1, -1, 1000, 556, 1000, -1, 556, 556, -1, 584, -1, -1, -1, 556, 278, 333, -1, -1, + -1, 278, -1, -1, -1, 500, -1, 556, -1, -1, -1, -1, 500, 556, 556, -1, -1, -1, 167, 556, -1, 556, 556, 611, -1, + 333, 584, 549, 556, 556, 333, 333, 556, -1, 333, 333, -1, -1, 222, 278, 278, 278, 278, 278, -1, -1, -1, -1, -1, + -1, 222, -1, -1, 222, 500, -1, 500, 222, 222, -1, 299, 222, 584, 549, -1, 584, -1, 471, 222, -1, 833, 333, 584, + -1, -1, 556, 584, 556, 556, 556, 556, 556, -1, -1, -1, -1, 549, -1, -1, 556, -1, 556, 556, 556, 556, 556, 944, + 333, 556, 556, 556, -1, -1, -1, 556, -1, -1, -1, 834, -1, -1, 834, 333, -1, 370, 365, 611, -1, 556, 556, 537, + 333, -1, -1, -1, -1, -1, 333, -1, -1, -1, -1, -1, 476, 889, 278, 278, -1, -1, -1, 1000, -1, -1, -1, 584, 584, + -1, -1, -1, -1, -1, 556, 556, 611, -1, -1, 355, 333, 333, 333, 222, 222, 222, 191, 333, 333, 453, -1, 333, 333, + -1, -1, 737, -1, -1, -1, 333, -1, -1, 500, 500, 500, 500, 500, -1, 556, 278, 556, -1, -1, -1, -1, -1, -1, -1, + 556, -1, -1, -1, 278, 278, -1, -1, 556, -1, 600, 278, -1, 317, 278, -1, -1, -1, 556, 556, -1, -1, -1, 834, -1, + 333, 333, 1000, -1, -1, -1, 556, -1, -1, -1, 333, -1, 556, 556, 556, 556, 556, 556, 556, 556, -1, -1, 556, -1, + 556, 500, 722, -1, 500, -1, 500, 500, 500, 556, 500, 500, 500, 500, 556, -1, -1, -1, -1, 722, 1000, -1, 722, + -1, 722, 722, -1, -1, 722, -1, 722, -1, -1, 722, 722, 722, -1, -1, 722, -1, 722, -1, -1, -1, 722, 722, -1, 722, + 722, -1, -1, -1, -1, -1, 722, 722, 722, 612, -1, -1, -1, 667, 667, -1, 667, 667, -1, 667, -1, 667, 667, -1, + 667, 667, -1, -1, -1, 722, -1, 556, 611, -1, 778, -1, 778, 778, -1, -1, 722, -1, -1, 278, 278, -1, 278, -1, + 278, -1, 278, -1, 278, -1, 278, 278, -1, -1, 556, -1, 722, -1, 722, -1, 611, 611, -1, 611, 611, 611, -1, -1, + 833, -1, -1, -1, 722, 722, 722, 722, -1, 722, -1, -1, 778, 1000, -1, 778, -1, 778, -1, 778, -1, -1, 778, -1, + 778, 778, -1, -1, 778, -1, -1, 778, -1, 667, -1, -1, -1, -1, 778, -1, 722, 722, 722, 722, -1, -1, -1, -1, 667, + 667, 667, -1, 667, 667, -1, -1, 611, -1, 611, 611, -1, 667, -1, -1, -1, 722, 722, -1, 722, -1, 722, -1, 722, + -1, 722, 722, 722, -1, -1, 722, -1, 667, -1, 944, -1, 667, -1, -1, 667, 667, -1, 667, -1, -1, 611, 611, 611, + -1, 611, -1, -1, 556, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 556, 556, 556, 333, 556, 889, 556, -1, -1, 556, 722, -1, -1, -1, + -1, 556, -1, -1, 556, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 584, 584, 389, -1, -1, 975, 556, 611, + 278, 280, -1, -1, 389, -1, -1, -1, 389, -1, -1, -1, 333, -1, -1, -1, 333, -1, -1, -1, 333, 280, -1, 350, 556, + 556, 333, -1, 556, 556, 333, 556, -1, -1, -1, -1, -1, -1, 333, -1, 333, -1, 278, 250, -1, -1, -1, 737, -1, -1, + 556, 611, 556, 556, 743, 611, 400, -1, -1, 333, 584, 556, -1, -1, -1, 333, 278, -1, -1, 556, 556, 556, 556, + 556, 556, 556, 556, -1, -1, -1, -1, 1000, 556, 1000, -1, 556, 556, -1, 584, -1, -1, -1, 611, 333, 333, -1, -1, + -1, 333, -1, -1, -1, 611, -1, 556, -1, -1, -1, -1, 611, 556, 556, -1, -1, -1, 167, 611, -1, 611, 611, 611, -1, + 333, 584, 549, 556, 556, 333, 333, 611, -1, 333, 333, -1, -1, 278, 278, 278, 278, 278, 278, -1, -1, -1, -1, -1, + -1, 278, -1, -1, 278, 556, -1, 556, 278, 278, -1, 400, 278, 584, 549, -1, 584, -1, 494, 278, -1, 889, 333, 584, + -1, -1, 611, 584, 611, 611, 611, 611, 556, -1, -1, -1, -1, 549, -1, -1, 611, -1, 556, 611, 611, 611, 611, 944, + 333, 611, 611, 611, -1, -1, -1, 556, -1, -1, -1, 834, -1, -1, 834, 333, -1, 370, 365, 611, -1, 611, 611, 556, + 333, -1, -1, -1, -1, -1, 333, -1, -1, -1, -1, -1, 494, 889, 278, 278, -1, -1, -1, 1000, -1, -1, -1, 584, 584, + -1, -1, -1, -1, -1, 611, 611, 611, -1, -1, 474, 500, 500, 500, 278, 278, 278, 238, 389, 389, 549, -1, 389, 389, + -1, -1, 737, -1, -1, -1, 333, -1, -1, 556, 556, 556, 556, 556, -1, 556, 333, 556, -1, -1, -1, -1, -1, -1, -1, + 556, -1, -1, -1, 278, 278, -1, -1, 556, -1, 600, 333, -1, 389, 333, -1, -1, -1, 611, 556, -1, -1, -1, 834, -1, + 333, 333, 1000, -1, -1, -1, 556, -1, -1, -1, 333, -1, 611, 611, 611, 611, 611, 611, 611, 556, -1, -1, 611, -1, + 611, 556, 778, -1, 556, -1, 556, 556, 556, 556, 500, 500, 500, 500, 556, -1, -1, -1, -1, 667, 1000, -1, 667, + -1, 667, 667, -1, -1, 667, -1, 667, -1, -1, 667, 667, 667, -1, -1, 667, -1, 667, -1, -1, -1, 722, 722, -1, 722, + 722, -1, -1, -1, -1, -1, 722, 722, 722, 612, -1, -1, -1, 667, 667, -1, 667, 667, -1, 667, -1, 667, 667, -1, + 667, 667, -1, -1, -1, 722, -1, 556, 611, -1, 778, -1, 778, 778, -1, -1, 722, -1, -1, 278, 278, -1, 278, -1, + 278, -1, 278, -1, 278, -1, 278, 278, -1, -1, 500, -1, 667, -1, 667, -1, 556, 556, -1, 556, 556, 556, -1, -1, + 833, -1, -1, -1, 722, 722, 722, 722, -1, 722, -1, -1, 778, 1000, -1, 778, -1, 778, -1, 778, -1, -1, 778, -1, + 778, 778, -1, -1, 778, -1, -1, 778, -1, 667, -1, -1, -1, -1, 778, -1, 722, 722, 722, 722, -1, -1, -1, -1, 667, + 667, 667, -1, 667, 667, -1, -1, 611, -1, 611, 611, -1, 667, -1, -1, -1, 722, 722, -1, 722, -1, 722, -1, 722, + -1, 722, 722, 722, -1, -1, 722, -1, 667, -1, 944, -1, 667, -1, -1, 667, 667, -1, 667, -1, -1, 611, 611, 611, + -1, 611, -1, -1, 556, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 556, 556, 556, 333, 556, 889, 556, -1, -1, 556, 667, -1, -1, -1, + -1, 556, -1, -1, 556, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 469, 584, 389, -1, -1, 1015, 556, 556, + 278, 260, -1, -1, 334, -1, -1, -1, 334, -1, -1, -1, 278, -1, -1, -1, 278, -1, -1, -1, 333, 260, -1, 350, 500, + 500, 333, -1, 500, 500, 333, 556, -1, -1, -1, -1, -1, -1, 333, -1, 278, -1, 278, 250, -1, -1, -1, 737, -1, -1, + 556, 556, 556, 556, 643, 556, 400, -1, -1, 333, 584, 556, -1, -1, -1, 333, 278, -1, -1, 556, 556, 556, 556, + 556, 556, 556, 556, -1, -1, -1, -1, 1000, 556, 1000, -1, 556, 556, -1, 584, -1, -1, -1, 556, 278, 333, -1, -1, + -1, 278, -1, -1, -1, 500, -1, 556, -1, -1, -1, -1, 500, 556, 556, -1, -1, -1, 167, 556, -1, 556, 556, 611, -1, + 333, 584, 549, 556, 556, 333, 333, 556, -1, 333, 333, -1, -1, 222, 278, 278, 278, 278, 278, -1, -1, -1, -1, -1, + -1, 222, -1, -1, 222, 500, -1, 500, 222, 222, -1, 299, 222, 584, 549, -1, 584, -1, 471, 222, -1, 833, 333, 584, + -1, -1, 556, 584, 556, 556, 556, 556, 556, -1, -1, -1, -1, 549, -1, -1, 556, -1, 556, 556, 556, 556, 556, 944, + 333, 556, 556, 556, -1, -1, -1, 556, -1, -1, -1, 834, -1, -1, 834, 333, -1, 370, 365, 611, -1, 556, 556, 537, + 333, -1, -1, -1, -1, -1, 333, -1, -1, -1, -1, -1, 476, 889, 278, 278, -1, -1, -1, 1000, -1, -1, -1, 584, 584, + -1, -1, -1, -1, -1, 556, 556, 611, -1, -1, 355, 333, 333, 333, 222, 222, 222, 191, 333, 333, 453, -1, 333, 333, + -1, -1, 737, -1, -1, -1, 333, -1, -1, 500, 500, 500, 500, 500, -1, 556, 278, 556, -1, -1, -1, -1, -1, -1, -1, + 556, -1, -1, -1, 278, 278, -1, -1, 556, -1, 600, 278, -1, 317, 278, -1, -1, -1, 556, 556, -1, -1, -1, 834, -1, + 333, 333, 1000, -1, -1, -1, 556, -1, -1, -1, 333, -1, 556, 556, 556, 556, 556, 556, 556, 556, -1, -1, 556, -1, + 556, 500, 722, -1, 500, -1, 500, 500, 500, 556, 500, 500, 500, 500, 556, -1, -1, -1, -1, 722, 1000, -1, 722, + -1, 722, 722, -1, -1, 722, -1, 722, -1, -1, 722, 722, 722, -1, -1, 722, -1, 722, -1, -1, -1, 722, 722, -1, 722, + 722, -1, -1, -1, -1, -1, 722, 722, 722, 612, -1, -1, -1, 667, 667, -1, 667, 667, -1, 667, -1, 667, 667, -1, + 667, 667, -1, -1, -1, 722, -1, 556, 611, -1, 778, -1, 778, 778, -1, -1, 722, -1, -1, 278, 278, -1, 278, -1, + 278, -1, 278, -1, 278, -1, 278, 278, -1, -1, 556, -1, 722, -1, 722, -1, 611, 611, -1, 611, 611, 611, -1, -1, + 833, -1, -1, -1, 722, 722, 722, 722, -1, 722, -1, -1, 778, 1000, -1, 778, -1, 778, -1, 778, -1, -1, 778, -1, + 778, 778, -1, -1, 778, -1, -1, 778, -1, 667, -1, -1, -1, -1, 778, -1, 722, 722, 722, 722, -1, -1, -1, -1, 667, + 667, 667, -1, 667, 667, -1, -1, 611, -1, 611, 611, -1, 667, -1, -1, -1, 722, 722, -1, 722, -1, 722, -1, 722, + -1, 722, 722, 722, -1, -1, 722, -1, 667, -1, 944, -1, 667, -1, -1, 667, 667, -1, 667, -1, -1, 611, 611, 611, + -1, 611, -1, -1, 556, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 556, 556, 556, 333, 556, 889, 556, -1, -1, 556, 722, -1, -1, -1, + -1, 556, -1, -1, 556, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 584, 584, 389, -1, -1, 975, 556, 611, + 278, 280, -1, -1, 389, -1, -1, -1, 389, -1, -1, -1, 333, -1, -1, -1, 333, -1, -1, -1, 333, 280, -1, 350, 556, + 556, 333, -1, 556, 556, 333, 556, -1, -1, -1, -1, -1, -1, 333, -1, 333, -1, 278, 250, -1, -1, -1, 737, -1, -1, + 556, 611, 556, 556, 743, 611, 400, -1, -1, 333, 584, 556, -1, -1, -1, 333, 278, -1, -1, 556, 556, 556, 556, + 556, 556, 556, 556, -1, -1, -1, -1, 1000, 556, 1000, -1, 556, 556, -1, 584, -1, -1, -1, 611, 333, 333, -1, -1, + -1, 333, -1, -1, -1, 611, -1, 556, -1, -1, -1, -1, 611, 556, 556, -1, -1, -1, 167, 611, -1, 611, 611, 611, -1, + 333, 584, 549, 556, 556, 333, 333, 611, -1, 333, 333, -1, -1, 278, 278, 278, 278, 278, 278, -1, -1, -1, -1, -1, + -1, 278, -1, -1, 278, 556, -1, 556, 278, 278, -1, 400, 278, 584, 549, -1, 584, -1, 494, 278, -1, 889, 333, 584, + -1, -1, 611, 584, 611, 611, 611, 611, 556, -1, -1, -1, -1, 549, -1, -1, 611, -1, 556, 611, 611, 611, 611, 944, + 333, 611, 611, 611, -1, -1, -1, 556, -1, -1, -1, 834, -1, -1, 834, 333, -1, 370, 365, 611, -1, 611, 611, 556, + 333, -1, -1, -1, -1, -1, 333, -1, -1, -1, -1, -1, 494, 889, 278, 278, -1, -1, -1, 1000, -1, -1, -1, 584, 584, + -1, -1, -1, -1, -1, 611, 611, 611, -1, -1, 474, 500, 500, 500, 278, 278, 278, 238, 389, 389, 549, -1, 389, 389, + -1, -1, 737, -1, -1, -1, 333, -1, -1, 556, 556, 556, 556, 556, -1, 556, 333, 556, -1, -1, -1, -1, -1, -1, -1, + 556, -1, -1, -1, 278, 278, -1, -1, 556, -1, 600, 333, -1, 389, 333, -1, -1, -1, 611, 556, -1, -1, -1, 834, -1, + 333, 333, 1000, -1, -1, -1, 556, -1, -1, -1, 333, -1, 611, 611, 611, 611, 611, 611, 611, 556, -1, -1, 611, -1, + 611, 556, 778, -1, 556, -1, 556, 556, 556, 556, 500, 500, 500, 500, 556, -1, -1, -1, -1, 722, 889, -1, 722, -1, + 722, 722, -1, -1, 722, -1, 722, -1, -1, 722, 722, 722, -1, -1, 722, -1, 667, -1, -1, -1, 667, 667, -1, 667, + 667, -1, -1, -1, -1, -1, 722, 722, 722, 612, -1, -1, -1, 611, 611, -1, 611, 611, -1, 611, -1, 611, 611, -1, + 611, 611, -1, -1, -1, 722, -1, 500, 556, -1, 722, -1, 722, 722, -1, -1, 722, -1, -1, 333, 333, -1, 333, -1, + 333, -1, 333, -1, 333, -1, 333, 333, -1, -1, 389, -1, 722, -1, 722, -1, 611, 611, -1, 611, 611, 611, -1, -1, + 889, -1, -1, -1, 722, 722, 722, 722, -1, 722, -1, -1, 722, 889, -1, 722, -1, 722, -1, 722, -1, -1, 722, -1, + 722, 722, -1, -1, 722, -1, -1, 722, -1, 556, -1, -1, -1, -1, 722, -1, 667, 667, 667, 667, -1, -1, -1, -1, 556, + 556, 556, -1, 556, 556, -1, -1, 611, -1, 611, 611, -1, 556, -1, -1, -1, 722, 722, -1, 722, -1, 722, -1, 722, + -1, 722, 722, 722, -1, -1, 722, -1, 722, -1, 944, -1, 722, -1, -1, 722, 722, -1, 722, -1, -1, 611, 611, 611, + -1, 611, -1, -1, 444, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 444, 444, 444, 333, 444, 667, 444, -1, -1, 444, 778, -1, -1, -1, + -1, 444, -1, -1, 444, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 469, 541, 500, -1, -1, 921, 444, 500, + 278, 200, -1, -1, 480, -1, -1, -1, 480, -1, -1, -1, 333, -1, -1, -1, 333, -1, -1, -1, 333, 200, -1, 350, 444, + 444, 333, -1, 444, 444, 333, 500, -1, -1, -1, -1, -1, -1, 333, -1, 278, -1, 250, 250, -1, -1, -1, 760, -1, -1, + 500, 500, 500, 500, 588, 500, 400, -1, -1, 333, 564, 500, -1, -1, -1, 333, 278, -1, -1, 444, 444, 444, 444, + 444, 444, 444, 500, -1, -1, -1, -1, 1000, 444, 1000, -1, 500, 444, -1, 564, -1, -1, -1, 500, 333, 333, -1, -1, + -1, 333, -1, -1, -1, 556, -1, 500, -1, -1, -1, -1, 556, 500, 500, -1, -1, -1, 167, 500, -1, 500, 500, 500, -1, + 333, 564, 549, 500, 500, 333, 333, 500, -1, 333, 333, -1, -1, 278, 278, 278, 278, 278, 278, -1, -1, -1, -1, -1, + -1, 278, -1, -1, 278, 500, -1, 500, 278, 278, -1, 344, 278, 564, 549, -1, 564, -1, 471, 278, -1, 778, 333, 564, + -1, -1, 500, 564, 500, 500, 500, 500, 500, -1, -1, -1, -1, 549, -1, -1, 500, -1, 500, 500, 500, 500, 500, 722, + 333, 500, 500, 500, -1, -1, -1, 500, -1, -1, -1, 750, -1, -1, 750, 300, -1, 276, 310, 500, -1, 500, 500, 453, + 333, -1, -1, -1, -1, -1, 333, -1, -1, -1, -1, -1, 476, 833, 250, 250, -1, -1, -1, 1000, -1, -1, -1, 564, 564, + -1, -1, -1, -1, -1, 500, 444, 444, -1, -1, 408, 444, 444, 444, 333, 333, 333, 180, 333, 333, 453, -1, 333, 333, + -1, -1, 760, -1, -1, -1, 333, -1, -1, 389, 389, 389, 389, 389, -1, 500, 278, 500, -1, -1, -1, -1, -1, -1, -1, + 500, -1, -1, -1, 278, 250, -1, -1, 500, -1, 600, 278, -1, 326, 278, -1, -1, -1, 500, 500, -1, -1, -1, 750, -1, + 300, 333, 980, -1, -1, -1, 500, -1, -1, -1, 300, -1, 500, 500, 500, 500, 500, 500, 500, 500, -1, -1, 500, -1, + 500, 500, 722, -1, 500, -1, 500, 500, 500, 500, 444, 444, 444, 444, 500, -1, -1, -1, -1, 722, 1000, -1, 722, + -1, 722, 722, -1, -1, 722, -1, 722, -1, -1, 722, 722, 722, -1, -1, 722, -1, 667, -1, -1, -1, 722, 722, -1, 722, + 722, -1, -1, -1, -1, -1, 722, 722, 722, 612, -1, -1, -1, 667, 667, -1, 667, 667, -1, 667, -1, 667, 667, -1, + 667, 667, -1, -1, -1, 722, -1, 500, 611, -1, 778, -1, 778, 778, -1, -1, 778, -1, -1, 389, 389, -1, 389, -1, + 389, -1, 389, -1, 389, -1, 389, 389, -1, -1, 500, -1, 778, -1, 778, -1, 667, 667, -1, 667, 667, 667, -1, -1, + 944, -1, -1, -1, 722, 722, 722, 722, -1, 722, -1, -1, 778, 1000, -1, 778, -1, 778, -1, 778, -1, -1, 778, -1, + 778, 778, -1, -1, 778, -1, -1, 778, -1, 611, -1, -1, -1, -1, 778, -1, 722, 722, 722, 722, -1, -1, -1, -1, 556, + 556, 556, -1, 556, 556, -1, -1, 667, -1, 667, 667, -1, 611, -1, -1, -1, 722, 722, -1, 722, -1, 722, -1, 722, + -1, 722, 722, 722, -1, -1, 722, -1, 722, -1, 1000, -1, 722, -1, -1, 722, 722, -1, 722, -1, -1, 667, 667, 667, + -1, 667, -1, -1, 500, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 500, 500, 500, 333, 500, 722, 500, -1, -1, 500, 833, -1, -1, -1, + -1, 500, -1, -1, 500, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 581, 520, 500, -1, -1, 930, 500, 556, + 278, 220, -1, -1, 394, -1, -1, -1, 394, -1, -1, -1, 333, -1, -1, -1, 333, -1, -1, -1, 333, 220, -1, 350, 444, + 444, 333, -1, 444, 444, 333, 500, -1, -1, -1, -1, -1, -1, 333, -1, 333, -1, 250, 250, -1, -1, -1, 747, -1, -1, + 500, 556, 500, 500, 672, 556, 400, -1, -1, 333, 570, 500, -1, -1, -1, 333, 278, -1, -1, 444, 444, 444, 444, + 444, 444, 444, 500, -1, -1, -1, -1, 1000, 444, 1000, -1, 500, 444, -1, 570, -1, -1, -1, 500, 333, 333, -1, -1, + -1, 333, -1, -1, -1, 556, -1, 500, -1, -1, -1, -1, 556, 500, 500, -1, -1, -1, 167, 500, -1, 500, 500, 556, -1, + 333, 570, 549, 500, 500, 333, 333, 556, -1, 333, 333, -1, -1, 278, 278, 278, 278, 278, 278, -1, -1, -1, -1, -1, + -1, 278, -1, -1, 333, 556, -1, 556, 278, 278, -1, 394, 278, 570, 549, -1, 570, -1, 494, 278, -1, 833, 333, 570, + -1, -1, 556, 570, 556, 556, 556, 556, 500, -1, -1, -1, -1, 549, -1, -1, 556, -1, 500, 500, 500, 500, 500, 722, + 333, 500, 500, 500, -1, -1, -1, 500, -1, -1, -1, 750, -1, -1, 750, 300, -1, 300, 330, 500, -1, 500, 556, 540, + 333, -1, -1, -1, -1, -1, 333, -1, -1, -1, -1, -1, 494, 1000, 250, 250, -1, -1, -1, 1000, -1, -1, -1, 570, 570, + -1, -1, -1, -1, -1, 556, 500, 500, -1, -1, 555, 500, 500, 500, 333, 333, 333, 278, 444, 444, 549, -1, 444, 444, + -1, -1, 747, -1, -1, -1, 333, -1, -1, 389, 389, 389, 389, 389, -1, 500, 333, 500, -1, -1, -1, -1, -1, -1, -1, + 500, -1, -1, -1, 278, 250, -1, -1, 500, -1, 600, 333, -1, 416, 333, -1, -1, -1, 556, 500, -1, -1, -1, 750, -1, + 300, 333, 1000, -1, -1, -1, 500, -1, -1, -1, 300, -1, 556, 556, 556, 556, 556, 556, 556, 500, -1, -1, 556, -1, + 556, 500, 722, -1, 500, -1, 500, 500, 500, 500, 444, 444, 444, 444, 500, -1, -1, -1, -1, 611, 889, -1, 611, -1, + 611, 611, -1, -1, 611, -1, 611, -1, -1, 611, 611, 611, -1, -1, 611, -1, 611, -1, -1, -1, 667, 667, -1, 667, + 667, -1, -1, -1, -1, -1, 722, 722, 722, 612, -1, -1, -1, 611, 611, -1, 611, 611, -1, 611, -1, 611, 611, -1, + 611, 611, -1, -1, -1, 722, -1, 500, 611, -1, 722, -1, 722, 722, -1, -1, 722, -1, -1, 333, 333, -1, 333, -1, + 333, -1, 333, -1, 333, -1, 333, 333, -1, -1, 444, -1, 667, -1, 667, -1, 556, 556, -1, 611, 556, 556, -1, -1, + 833, -1, -1, -1, 667, 667, 667, 667, -1, 667, -1, -1, 722, 944, -1, 722, -1, 722, -1, 722, -1, -1, 722, -1, + 722, 722, -1, -1, 722, -1, -1, 722, -1, 611, -1, -1, -1, -1, 722, -1, 611, 611, 611, 611, -1, -1, -1, -1, 500, + 500, 500, -1, 500, 500, -1, -1, 556, -1, 556, 556, -1, 611, -1, -1, -1, 722, 722, -1, 722, -1, 722, -1, 722, + -1, 722, 722, 722, -1, -1, 722, -1, 611, -1, 833, -1, 611, -1, -1, 556, 556, -1, 556, -1, -1, 556, 556, 556, + -1, 556, -1, -1, 500, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 500, 500, 500, 333, 500, 667, 500, -1, -1, 500, 778, -1, -1, -1, + -1, 500, -1, -1, 500, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 422, 541, 500, -1, -1, 920, 500, 500, + 278, 275, -1, -1, 400, -1, -1, -1, 400, -1, -1, -1, 389, -1, -1, -1, 389, -1, -1, -1, 333, 275, -1, 350, 444, + 444, 333, -1, 444, 444, 333, 500, -1, -1, -1, -1, -1, -1, 333, -1, 333, -1, 250, 250, -1, -1, -1, 760, -1, -1, + 500, 500, 500, 500, 544, 500, 400, -1, -1, 333, 675, 500, -1, -1, -1, 333, 278, -1, -1, 444, 444, 444, 444, + 444, 444, 444, 500, -1, -1, -1, -1, 889, 444, 889, -1, 500, 444, -1, 675, -1, -1, -1, 500, 333, 389, -1, -1, + -1, 278, -1, -1, -1, 500, -1, 500, -1, -1, -1, -1, 500, 500, 500, -1, -1, -1, 167, 500, -1, 500, 500, 500, -1, + 333, 675, 549, 500, 500, 333, 333, 500, -1, 333, 333, -1, -1, 278, 278, 278, 278, 278, 278, -1, -1, -1, -1, -1, + -1, 278, -1, -1, 278, 444, -1, 444, 278, 278, -1, 300, 278, 675, 549, -1, 675, -1, 471, 278, -1, 722, 333, 675, + -1, -1, 500, 675, 500, 500, 500, 500, 500, -1, -1, -1, -1, 549, -1, -1, 500, -1, 500, 500, 500, 500, 500, 667, + 333, 500, 500, 500, -1, -1, -1, 500, -1, -1, -1, 750, -1, -1, 750, 300, -1, 276, 310, 500, -1, 500, 500, 523, + 333, -1, -1, -1, -1, -1, 333, -1, -1, -1, -1, -1, 476, 833, 250, 250, -1, -1, -1, 1000, -1, -1, -1, 675, 675, + -1, -1, -1, -1, -1, 500, 500, 500, -1, -1, 420, 556, 556, 556, 333, 333, 333, 214, 389, 389, 453, -1, 389, 389, + -1, -1, 760, -1, -1, -1, 333, -1, -1, 389, 389, 389, 389, 389, -1, 500, 333, 500, -1, -1, -1, -1, -1, -1, -1, + 500, -1, -1, -1, 278, 250, -1, -1, 500, -1, 600, 278, -1, 300, 278, -1, -1, -1, 500, 500, -1, -1, -1, 750, -1, + 300, 333, 980, -1, -1, -1, 500, -1, -1, -1, 300, -1, 500, 500, 500, 500, 500, 500, 500, 500, -1, -1, 500, -1, + 500, 444, 667, -1, 444, -1, 444, 444, 444, 500, 389, 389, 389, 389, 500, -1, -1, -1, -1, 667, 944, -1, 667, -1, + 667, 667, -1, -1, 667, -1, 667, -1, -1, 667, 667, 667, -1, -1, 667, -1, 667, -1, -1, -1, 667, 667, -1, 667, + 667, -1, -1, -1, -1, -1, 722, 722, 722, 612, -1, -1, -1, 667, 667, -1, 667, 667, -1, 667, -1, 667, 667, -1, + 667, 667, -1, -1, -1, 722, -1, 500, 667, -1, 722, -1, 722, 722, -1, -1, 778, -1, -1, 389, 389, -1, 389, -1, + 389, -1, 389, -1, 389, -1, 389, 389, -1, -1, 500, -1, 667, -1, 667, -1, 611, 611, -1, 611, 611, 611, -1, -1, + 889, -1, -1, -1, 722, 722, 722, 722, -1, 722, -1, -1, 722, 944, -1, 722, -1, 722, -1, 722, -1, -1, 722, -1, + 722, 722, -1, -1, 722, -1, -1, 722, -1, 611, -1, -1, -1, -1, 722, -1, 667, 667, 667, 667, -1, -1, -1, -1, 556, + 556, 556, -1, 556, 556, -1, -1, 611, -1, 611, 611, -1, 611, -1, -1, -1, 722, 722, -1, 722, -1, 722, -1, 722, + -1, 722, 722, 722, -1, -1, 722, -1, 667, -1, 889, -1, 667, -1, -1, 611, 611, -1, 611, -1, -1, 611, 611, 611, + -1, 611, -1, -1, 500, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 500, 500, 500, 333, 500, 722, 500, -1, -1, 500, 778, -1, -1, -1, + -1, 500, -1, -1, 500, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 570, 570, 500, -1, -1, 832, 500, 500, + 278, 220, -1, -1, 348, -1, -1, -1, 348, -1, -1, -1, 333, -1, -1, -1, 333, -1, -1, -1, 333, 220, -1, 350, 444, + 444, 333, -1, 444, 444, 333, 500, -1, -1, -1, -1, -1, -1, 333, -1, 333, -1, 250, 250, -1, -1, -1, 747, -1, -1, + 500, 500, 500, 500, 608, 500, 400, -1, -1, 333, 570, 500, -1, -1, -1, 333, 278, -1, -1, 444, 444, 444, 444, + 444, 444, 444, 500, -1, -1, -1, -1, 1000, 444, 1000, -1, 500, 444, -1, 570, -1, -1, -1, 500, 389, 389, -1, -1, + -1, 333, -1, -1, -1, 556, -1, 500, -1, -1, -1, -1, 556, 500, 500, -1, -1, -1, 167, 500, -1, 500, 500, 500, -1, + 333, 570, 549, 500, 500, 333, 333, 556, -1, 333, 333, -1, -1, 278, 278, 278, 278, 278, 278, -1, -1, -1, -1, -1, + -1, 278, -1, -1, 278, 500, -1, 500, 278, 278, -1, 382, 278, 570, 549, -1, 606, -1, 494, 278, -1, 778, 333, 606, + -1, -1, 576, 570, 556, 556, 556, 556, 500, -1, -1, -1, -1, 549, -1, -1, 556, -1, 500, 500, 500, 500, 500, 722, + 333, 500, 500, 500, -1, -1, -1, 500, -1, -1, -1, 750, -1, -1, 750, 300, -1, 266, 300, 500, -1, 500, 500, 500, + 333, -1, -1, -1, -1, -1, 333, -1, -1, -1, -1, -1, 494, 833, 250, 250, -1, -1, -1, 1000, -1, -1, -1, 570, 570, + -1, -1, -1, -1, -1, 500, 500, 500, -1, -1, 555, 500, 500, 500, 333, 333, 333, 278, 389, 389, 549, -1, 389, 389, + -1, -1, 747, -1, -1, -1, 333, -1, -1, 389, 389, 389, 389, 389, -1, 500, 333, 500, -1, -1, -1, -1, -1, -1, -1, + 500, -1, -1, -1, 278, 250, -1, -1, 500, -1, 600, 278, -1, 366, 278, -1, -1, -1, 500, 500, -1, -1, -1, 750, -1, + 300, 333, 1000, -1, -1, -1, 500, -1, -1, -1, 300, -1, 556, 556, 556, 556, 556, 556, 556, 500, -1, -1, 556, -1, + 556, 444, 667, -1, 500, -1, 444, 444, 444, 500, 389, 389, 389, 389, 500, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, 722, -1, -1, -1, -1, -1, -1, -1, -1, 667, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 722, -1, -1, -1, -1, -1, 612, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 611, -1, 722, -1, + -1, 750, -1, -1, -1, 603, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 686, -1, -1, -1, -1, 333, + -1, -1, -1, -1, 722, -1, -1, -1, -1, 686, -1, -1, -1, -1, -1, -1, -1, -1, 889, -1, -1, -1, -1, -1, -1, -1, 722, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 768, 722, -1, -1, -1, -1, -1, -1, 763, 768, 795, -1, + -1, -1, -1, -1, -1, -1, 795, 556, -1, -1, -1, -1, -1, -1, -1, -1, 592, -1, -1, 611, -1, -1, 741, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 690, 620, -1, -1, -1, -1, -1, -1, -1, 645, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, 611, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 823, 631, -1, + 778, -1, 768, 329, 329, -1, 790, 549, -1, 1042, 1042, 603, 987, 987, 603, 603, 1000, 987, 987, 603, 603, -1, + -1, -1, 500, -1, -1, -1, -1, -1, 200, 549, 494, 480, 494, 494, 494, 480, 494, 494, 494, 333, 384, 384, 384, + 333, 384, 384, 384, -1, -1, -1, 460, -1, -1, -1, 658, -1, -1, -1, -1, -1, -1, -1, 549, 768, 768, -1, 753, 278, + -1, 250, -1, -1, -1, 549, -1, 790, 790, -1, -1, -1, -1, -1, -1, 400, 494, 753, -1, 549, -1, -1, -1, -1, -1, -1, + 250, -1, -1, -1, -1, -1, -1, -1, -1, 500, -1, -1, -1, 713, 1000, -1, -1, 823, -1, -1, 439, 549, 549, -1, 603, + -1, 333, -1, -1, -1, 549, -1, -1, -1, -1, -1, -1, 500, -1, -1, -1, -1, -1, 500, 500, -1, -1, -1, 167, -1, 411, + -1, -1, -1, 713, -1, 549, 549, -1, -1, -1, -1, -1, 753, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 713, 274, 686, + 686, 686, 768, -1, 329, -1, -1, -1, 549, -1, -1, -1, 549, -1, -1, 549, 549, 603, 713, 603, 494, -1, -1, -1, -1, + 549, 247, -1, 576, 549, -1, -1, -1, -1, 500, -1, -1, -1, 713, 549, 713, -1, -1, 521, 500, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 686, 713, 549, 500, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 333, 384, + 384, -1, -1, 384, 333, 384, 384, -1, -1, 384, 494, 833, 250, -1, -1, -1, 658, -1, 521, 603, 549, 549, 549, 823, + 713, 713, 713, 686, -1, 444, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 549, 500, -1, -1, 713, 713, + -1, 790, 790, 549, -1, -1, -1, -1, -1, -1, -1, -1, 411, -1, 278, 500, -1, -1, -1, -1, 603, 439, 549, 500, -1, + -1, -1, 278, 250, 753, -1, -1, 439, 713, -1, 439, -1, -1, 863, 521, 631, -1, 500, -1, -1, -1, -1, -1, -1, -1, + -1, 786, 890, -1, 500, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 500, 768, 713, -1, 576, -1, -1, -1, 987, + -1, 493, -1, -1, -1, -1, -1, -1, -1, -1, 500, -1, -1, -1, 494, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 974, 692, 668, 732, + 544, 544, 910, 911, 667, 760, 760, 626, 960, 694, 595, 776, 690, 791, 790, 939, 788, 788, 788, 788, 788, 788, + 788, 788, 788, 788, 549, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 855, 788, 788, 788, 788, 788, 788, + 788, 788, 788, 788, 911, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 933, 894, 838, 924, 1016, 458, 924, + 918, 927, 928, 928, 945, 834, 873, 828, 924, 917, 930, 931, 463, 883, 836, 974, 867, 696, 874, 760, 946, 865, + 967, 831, 873, 927, 755, 970, 918, 748, 836, 771, 888, 748, 771, 888, 867, 961, 846, 696, 874, 974, 762, 759, + 509, 410, 762, 761, 571, 677, 763, 760, 759, 754, 786, 980, 788, 788, 790, 793, 794, 816, 823, 789, 841, 823, + 719, 833, 816, 831, 923, 744, 723, 749, 790, 792, 695, 789, 776, 768, 792, 759, 707, 708, 682, 701, 826, 815, + 494, 789, 789, 707, 687, 696, 689, 786, 787, 713, 791, 552, 785, 791, 873, 761, 762, 759, 892, 892, 788, 784, + 537, 438, 138, 277, 415, 509, 410, 234, 234, 390, 577, 390, 276, 276, 317, 317, 334, 334, 392, 392, 668, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 278, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, + ]; + + /// For each font: FontBBox (4 values), ItalicAngle x 10, CapHeight, XHeight, Ascent, Descent, StdVW, StdHW and the ISO 32000-2 Table 121 flags. + internal static ReadOnlySpan FontMetrics => + [ + -23, -250, 715, 805, 0, 562, 426, 629, -157, 51, 51, 33, -113, -250, 749, 801, 0, 562, 439, 629, -157, 106, 84, + 33, -27, -250, 849, 805, -120, 562, 426, 629, -157, 51, 51, 97, -57, -250, 869, 801, -120, 562, 439, 629, -157, + 106, 84, 97, -166, -225, 1000, 931, 0, 718, 523, 718, -207, 88, 76, 32, -170, -228, 1003, 962, 0, 718, 532, + 718, -207, 140, 118, 32, -170, -225, 1116, 931, -120, 718, 523, 718, -207, 88, 76, 96, -174, -228, 1114, 962, + -120, 718, 532, 718, -207, 140, 118, 96, -168, -218, 1000, 898, 0, 662, 450, 683, -217, 84, 28, 34, -168, -218, + 1000, 935, 0, 676, 461, 683, -217, 139, 44, 34, -169, -217, 1010, 883, -155, 653, 441, 683, -217, 76, 32, 98, + -200, -218, 996, 921, -150, 669, 462, 683, -217, 121, 42, 98, -180, -293, 1090, 1010, 0, 1010, 0, 1010, -293, + 85, 92, 4, -1, -143, 981, 820, 0, 820, 0, 820, -143, 90, 28, 4, + ]; + + /// Unicode values of the Latin character set's glyphs, ascending; parallel to . + internal static ReadOnlySpan LatinUnicodes => + [ + 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, + 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, + 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 161, 162, 163, 164, 165, 166, 167, + 168, 169, 170, 171, 172, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, + 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, + 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, + 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, + 257, 258, 259, 260, 261, 262, 263, 268, 269, 270, 271, 272, 273, 274, 275, 278, 279, 280, 281, 282, 283, 286, + 287, 290, 291, 298, 299, 302, 303, 304, 305, 310, 311, 313, 314, 315, 316, 317, 318, 321, 322, 323, 324, 325, + 326, 327, 328, 332, 333, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 350, 351, 352, 353, 354, + 355, 356, 357, 362, 363, 366, 367, 368, 369, 370, 371, 376, 377, 378, 379, 380, 381, 382, 402, 536, 537, 710, + 711, 728, 729, 730, 731, 732, 733, 8211, 8212, 8216, 8217, 8218, 8220, 8221, 8222, 8224, 8225, 8226, 8230, + 8240, 8249, 8250, 8260, 8364, 8482, 8706, 8710, 8721, 8722, 8730, 8800, 8804, 8805, 9674, 63171, 64257, 64258, + ]; + + /// For each value of , the index of the glyph's name in . + internal static ReadOnlySpan LatinUnicodeNames => + [ + 740, 536, 696, 631, 504, 674, 414, 703, 661, 667, 437, 684, 485, 575, 675, 739, 798, 644, 766, 754, 554, 547, + 735, 727, 519, 621, 483, 726, 602, 531, 566, 692, 440, 0, 21, 25, 35, 42, 61, 63, 69, 72, 87, 89, 93, 101, 105, + 113, 134, 139, 141, 149, 157, 166, 182, 184, 186, 189, 195, 455, 443, 459, 435, 779, 565, 202, 442, 467, 494, + 512, 541, 559, 572, 578, 593, 594, 597, 610, 617, 632, 659, 691, 704, 719, 746, 772, 785, 786, 788, 790, 794, + 447, 444, 451, 436, 537, 474, 743, 493, 793, 464, 725, 502, 490, 654, 568, 605, 712, 611, 499, 685, 770, 760, + 407, 615, 660, 676, 473, 652, 655, 569, 651, 648, 758, 693, 11, 3, 6, 19, 9, 16, 1, 29, 51, 43, 46, 48, 81, 73, + 75, 77, 58, 110, 123, 116, 118, 132, 120, 616, 129, 173, 167, 169, 171, 190, 162, 563, 410, 404, 406, 441, 408, + 422, 409, 472, 518, 513, 515, 516, 582, 579, 580, 581, 535, 629, 638, 633, 634, 658, 635, 503, 656, 776, 773, + 774, 775, 791, 753, 792, 14, 413, 5, 405, 15, 419, 26, 468, 28, 471, 36, 497, 37, 498, 53, 525, 50, 517, 54, + 529, 45, 514, 65, 561, 66, 562, 83, 583, 84, 590, 79, 509, 91, 596, 94, 598, 97, 601, 96, 600, 98, 608, 106, + 618, 108, 620, 107, 619, 126, 640, 125, 639, 114, 636, 142, 705, 144, 709, 143, 708, 150, 720, 153, 722, 151, + 721, 160, 749, 159, 748, 176, 778, 180, 784, 175, 777, 177, 782, 192, 196, 795, 199, 797, 197, 796, 553, 154, + 723, 481, 469, 463, 508, 716, 637, 761, 574, 528, 526, 700, 701, 702, 698, 699, 697, 495, 496, 466, 524, 680, + 570, 571, 558, 60, 762, 673, 38, 745, 612, 706, 626, 603, 567, 607, 486, 545, 552, + ]; + + /// Unicode values of the Symbol character set's glyphs, ascending; parallel to . + internal static ReadOnlySpan SymbolUnicodes => + [ + 32, 33, 35, 37, 38, 40, 41, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 91, + 93, 95, 123, 124, 125, 172, 176, 177, 181, 215, 247, 402, 913, 914, 915, 917, 918, 919, 920, 921, 922, 923, + 924, 925, 926, 927, 928, 929, 931, 932, 933, 934, 935, 936, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, + 955, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 977, 978, 981, 982, 8226, 8230, 8242, + 8243, 8260, 8364, 8465, 8472, 8476, 8486, 8501, 8592, 8593, 8594, 8595, 8596, 8629, 8656, 8657, 8658, 8659, + 8660, 8704, 8706, 8707, 8709, 8710, 8711, 8712, 8713, 8715, 8719, 8721, 8722, 8727, 8730, 8733, 8734, 8736, + 8743, 8744, 8745, 8746, 8747, 8756, 8764, 8773, 8776, 8800, 8801, 8804, 8805, 8834, 8835, 8836, 8838, 8839, + 8853, 8855, 8869, 8901, 8992, 8993, 9001, 9002, 9674, 9824, 9827, 9829, 9830, 63193, 63194, 63195, 63717, + 63718, 63719, 63720, 63721, 63722, 63723, 63724, 63725, 63726, 63727, 63728, 63729, 63730, 63731, 63732, 63733, + 63734, 63735, 63736, 63737, 63738, 63739, 63740, 63741, 63742, 63743, + ]; + + /// For each value of , the index of the glyph's name in . + internal static ReadOnlySpan SymbolUnicodeNames => + [ + 740, 536, 631, 674, 414, 661, 667, 684, 485, 675, 739, 798, 644, 766, 754, 554, 547, 735, 727, 519, 621, 483, + 726, 602, 531, 566, 692, 455, 459, 779, 447, 444, 451, 605, 499, 685, 615, 616, 503, 553, 13, 22, 64, 55, 200, + 57, 161, 85, 90, 95, 104, 112, 187, 128, 136, 146, 155, 158, 178, 135, 32, 137, 412, 445, 560, 500, 530, 802, + 534, 751, 591, 595, 599, 630, 789, 643, 683, 715, 733, 732, 747, 783, 681, 478, 690, 641, 752, 179, 682, 642, + 466, 524, 613, 724, 558, 60, 80, 787, 145, 127, 411, 431, 433, 432, 429, 423, 470, 426, 428, 427, 425, 424, + 781, 673, 540, 527, 38, 564, 523, 625, 744, 686, 745, 612, 438, 706, 689, 584, 416, 604, 606, 589, 780, 585, + 750, 734, 489, 421, 626, 532, 603, 567, 687, 688, 627, 710, 711, 480, 479, 679, 510, 588, 586, 417, 418, 607, + 741, 482, 573, 501, 492, 714, 764, 707, 434, 430, 713, 491, 763, 666, 663, 662, 458, 457, 456, 450, 449, 448, + 446, 587, 672, 669, 668, 462, 461, 460, 454, 453, 452, 420, + ]; + + /// Unicode values of the ZapfDingbats character set's glyphs, ascending; parallel to . + internal static ReadOnlySpan ZapfDingbatsUnicodes => + [ + 8594, 8596, 8597, 9312, 9313, 9314, 9315, 9316, 9317, 9318, 9319, 9320, 9321, 9632, 9650, 9660, 9670, 9679, + 9687, 9733, 9742, 9755, 9758, 9824, 9827, 9829, 9830, 9985, 9986, 9987, 9988, 9990, 9991, 9992, 9993, 9996, + 9997, 9998, 9999, 10000, 10001, 10002, 10003, 10004, 10005, 10006, 10007, 10008, 10009, 10010, 10011, 10012, + 10013, 10014, 10015, 10016, 10017, 10018, 10019, 10020, 10021, 10022, 10023, 10025, 10026, 10027, 10028, 10029, + 10030, 10031, 10032, 10033, 10034, 10035, 10036, 10037, 10038, 10039, 10040, 10041, 10042, 10043, 10044, 10045, + 10046, 10047, 10048, 10049, 10050, 10051, 10052, 10053, 10054, 10055, 10056, 10057, 10058, 10059, 10061, 10063, + 10064, 10065, 10066, 10070, 10072, 10073, 10074, 10075, 10076, 10077, 10078, 10081, 10082, 10083, 10084, 10085, + 10086, 10087, 10088, 10089, 10090, 10091, 10092, 10093, 10094, 10095, 10096, 10097, 10098, 10099, 10100, 10101, + 10102, 10103, 10104, 10105, 10106, 10107, 10108, 10109, 10110, 10111, 10112, 10113, 10114, 10115, 10116, 10117, + 10118, 10119, 10120, 10121, 10122, 10123, 10124, 10125, 10126, 10127, 10128, 10129, 10130, 10131, 10132, 10136, + 10137, 10138, 10139, 10140, 10141, 10142, 10143, 10144, 10145, 10146, 10147, 10148, 10149, 10150, 10151, 10152, + 10153, 10154, 10155, 10156, 10157, 10158, 10159, 10161, 10162, 10163, 10164, 10165, 10166, 10167, 10168, 10169, + 10170, 10171, 10172, 10173, 10174, + ]; + + /// For each value of , the index of the glyph's name in . + internal static ReadOnlySpan ZapfDingbatsUnicodeNames => + [ + 268, 270, 271, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 376, 379, 380, 381, 374, 384, 334, 339, 215, + 222, 214, 218, 216, 217, 203, 310, 314, 328, 350, 221, 220, 219, 233, 244, 255, 266, 210, 277, 288, 299, 311, + 319, 320, 321, 322, 323, 324, 325, 326, 361, 372, 383, 393, 204, 327, 329, 330, 331, 332, 333, 335, 336, 337, + 338, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 362, + 363, 364, 365, 366, 367, 368, 369, 370, 371, 373, 375, 377, 315, 378, 316, 382, 385, 386, 387, 401, 402, 403, + 205, 206, 207, 208, 209, 211, 212, 213, 392, 394, 397, 398, 395, 396, 317, 388, 318, 389, 390, 391, 399, 400, + 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 256, 257, + 258, 259, 260, 261, 262, 263, 264, 265, 267, 306, 272, 302, 273, 274, 275, 276, 278, 279, 280, 281, 269, 282, + 283, 284, 285, 286, 287, 303, 289, 309, 290, 312, 291, 313, 292, 293, 307, 294, 304, 308, 295, 305, 296, 297, + 298, 300, 301, + ]; +} diff --git a/src/Broadside/Fonts/Standard14Font.cs b/src/Broadside/Fonts/Standard14Font.cs new file mode 100644 index 00000000..96d219b7 --- /dev/null +++ b/src/Broadside/Fonts/Standard14Font.cs @@ -0,0 +1,51 @@ +namespace Broadside.Fonts; + +/// One of the fourteen Standard 14 fonts, whose metrics every PDF processor provides. +/// +/// ISO 32000-2 §9.6.2.2. The metrics are those of the Adobe Core 14 AFM files (Adobe Technical Note #5004), which ship in the core +/// package; the glyphs ship separately (ADR 0007). +/// +public enum Standard14Font +{ + /// Courier. + Courier = 0, + + /// Courier-Bold. + CourierBold = 1, + + /// Courier-Oblique. + CourierOblique = 2, + + /// Courier-BoldOblique. + CourierBoldOblique = 3, + + /// Helvetica. + Helvetica = 4, + + /// Helvetica-Bold. + HelveticaBold = 5, + + /// Helvetica-Oblique. + HelveticaOblique = 6, + + /// Helvetica-BoldOblique. + HelveticaBoldOblique = 7, + + /// Times-Roman. + TimesRoman = 8, + + /// Times-Bold. + TimesBold = 9, + + /// Times-Italic. + TimesItalic = 10, + + /// Times-BoldItalic. + TimesBoldItalic = 11, + + /// Symbol, a symbolic font with its own built-in encoding (Annex D.5). + Symbol = 12, + + /// ZapfDingbats, a symbolic font with its own built-in encoding (Annex D.6). + ZapfDingbats = 13, +} diff --git a/src/Broadside/Objects/CosArray.cs b/src/Broadside/Objects/CosArray.cs index 7a9e9367..0718b971 100644 --- a/src/Broadside/Objects/CosArray.cs +++ b/src/Broadside/Objects/CosArray.cs @@ -54,6 +54,12 @@ public override bool IsDirty } } + /// + /// Gets a number that changes on every mutation through the public API: caches of state derived from this array (the + /// font model's encoding and width tables) compare it to know they are stale. Loading (ReplaceLoaded) does not change it. + /// + internal int Version { get; private set; } + /// Gets the number of elements. public int Count => _items.Count; @@ -69,7 +75,7 @@ public CosObject this[int index] { ArgumentNullException.ThrowIfNull(value); _items[index] = value; - _changed = true; + Changed(); } } @@ -79,7 +85,7 @@ public void Add(CosObject item) { ArgumentNullException.ThrowIfNull(item); _items.Add(item); - _changed = true; + Changed(); } /// Inserts an element and marks the array dirty. @@ -89,7 +95,7 @@ public void Insert(int index, CosObject item) { ArgumentNullException.ThrowIfNull(item); _items.Insert(index, item); - _changed = true; + Changed(); } /// Removes the element at and marks the array dirty. @@ -97,7 +103,7 @@ public void Insert(int index, CosObject item) public void RemoveAt(int index) { _items.RemoveAt(index); - _changed = true; + Changed(); } /// Removes the first element equal to ; marks the array dirty when one was removed. @@ -106,14 +112,22 @@ public void RemoveAt(int index) public bool Remove(CosObject item) { bool removed = _items.Remove(item); - _changed |= removed; + if (removed) + { + Changed(); + } + return removed; } /// Removes every element; marks the array dirty when it was not already empty. public void Clear() { - _changed |= _items.Count > 0; + if (_items.Count > 0) + { + Changed(); + } + _items.Clear(); } @@ -139,4 +153,11 @@ public void Clear() /// Wraps a list the caller gives up ownership of, without copying it and without marking the array dirty. internal static CosArray FromOwnedList(List items) => new(items, owned: true); + + /// Marks the array dirty and moves on. + private void Changed() + { + _changed = true; + Version++; + } } diff --git a/src/Broadside/Objects/CosDictionary.cs b/src/Broadside/Objects/CosDictionary.cs index b9157f57..90024a84 100644 --- a/src/Broadside/Objects/CosDictionary.cs +++ b/src/Broadside/Objects/CosDictionary.cs @@ -45,6 +45,12 @@ public override bool IsDirty } } + /// + /// Gets a number that changes on every mutation through the public API: caches of state derived from this dictionary (the + /// font model's encoding and width tables) compare it to know they are stale. Loading (ReplaceLoaded) does not change it. + /// + internal int Version { get; private set; } + /// Gets the number of entries. public int Count => _entries.Count; @@ -84,7 +90,7 @@ public CosObject this[CosName key] } _entries[key] = value; - _changed = true; + Changed(); } } @@ -107,7 +113,7 @@ public void Add(CosName key, CosObject value) } _entries.Add(key, value); - _changed = true; + Changed(); } /// Removes the entry for ; marks the dictionary dirty when one was removed. @@ -116,14 +122,22 @@ public void Add(CosName key, CosObject value) public bool Remove(CosName key) { bool removed = _entries.Remove(key); - _changed |= removed; + if (removed) + { + Changed(); + } + return removed; } /// Removes every entry; marks the dictionary dirty when it was not already empty. public void Clear() { - _changed |= _entries.Count > 0; + if (_entries.Count > 0) + { + Changed(); + } + _entries.Clear(); } @@ -155,7 +169,11 @@ void ICollection>.CopyTo(KeyValuePair>.Remove(KeyValuePair item) { bool removed = ((ICollection>)_entries).Remove(item); - _changed |= removed; + if (removed) + { + Changed(); + } + return removed; } @@ -171,4 +189,11 @@ bool ICollection>.Remove(KeyValuePairWraps entries the caller gives up ownership of, without copying them and without marking the dictionary dirty. internal static CosDictionary FromOwnedEntries(OrderedDictionary entries) => new(entries); + + /// Marks the dictionary dirty and moves on. + private void Changed() + { + _changed = true; + Version++; + } } diff --git a/src/Broadside/Parsing/DiagnosticCodes.cs b/src/Broadside/Parsing/DiagnosticCodes.cs index 38370fe5..03cb5f66 100644 --- a/src/Broadside/Parsing/DiagnosticCodes.cs +++ b/src/Broadside/Parsing/DiagnosticCodes.cs @@ -132,4 +132,20 @@ internal static class DiagnosticCodes public const string PageResourcesMissing = nameof(PageResourcesMissing); public const string PageResourcesInvalid = nameof(PageResourcesInvalid); public const string PageUserUnitInvalid = nameof(PageUserUnitInvalid); + + // Fonts: font dictionaries, simple-font encodings and widths, font descriptors (§9.5, §9.6, §9.8; issue #49). + public const string FontTypeInvalid = nameof(FontTypeInvalid); + public const string FontSubtypeInvalid = nameof(FontSubtypeInvalid); + public const string FontBaseFontMissing = nameof(FontBaseFontMissing); + public const string FontStandard14Alias = nameof(FontStandard14Alias); + public const string FontStandard14EntriesIncomplete = nameof(FontStandard14EntriesIncomplete); + public const string FontDescriptorMissing = nameof(FontDescriptorMissing); + public const string FontDescriptorInvalid = nameof(FontDescriptorInvalid); + public const string FontWidthsMissing = nameof(FontWidthsMissing); + public const string FontWidthsInvalid = nameof(FontWidthsInvalid); + public const string FontEncodingInvalid = nameof(FontEncodingInvalid); + public const string FontEncodingIgnored = nameof(FontEncodingIgnored); + public const string FontDifferencesInvalid = nameof(FontDifferencesInvalid); + public const string FontBuiltInEncodingUnavailable = nameof(FontBuiltInEncodingUnavailable); + public const string FontGlyphMissing = nameof(FontGlyphMissing); } diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 5c0e9ec2..0bc50888 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -1,6 +1,8 @@ using System.Buffers; +using System.Runtime.CompilerServices; using Broadside.Diagnostics; using Broadside.Filters; +using Broadside.Fonts; using Broadside.IO; using Broadside.Objects; using Broadside.Parsing; @@ -54,6 +56,7 @@ public sealed class PdfDocument : IDisposable private readonly DiagnosticSink _diagnostics; private readonly ObjectLoader _loader; private readonly StreamDecoder _streams; + private readonly ConditionalWeakTable _fonts = []; private PdfDocument( PdfSource source, @@ -371,9 +374,37 @@ public void DecodeStream(CosStream stream, IBufferWriter output) _streams.Decode(stream, output); } + /// Returns the font view over a font dictionary of this document. + /// A font dictionary, or an indirect reference to one, such as an entry of a resource dictionary's Font subdictionary. + /// + /// The view, of the type the dictionary's Subtype selects; when is not a + /// dictionary and does not refer to one. The same dictionary always gives the same view instance. + /// + /// In strict mode, when the dictionary's Type or Subtype is not a font's. + /// ISO 32000-2 §9.5, Table 108, and §7.8.3. + public PdfFont? GetFont(CosObject? font) + { + if (Resolve(font) is not CosDictionary dictionary) + { + return null; + } + + if (_fonts.TryGetValue(dictionary, out PdfFont? existing)) + { + return existing; + } + + // Two threads may create a view each; the first one added is the one everybody gets. + PdfFont created = PdfFont.Create(this, dictionary, font as CosReference); + return _fonts.TryAdd(dictionary, created) || !_fonts.TryGetValue(dictionary, out PdfFont? winner) ? created : winner; + } + /// public void Dispose() => _source.Dispose(); + /// Gets the sink this document records diagnostics in. + internal DiagnosticSink DiagnosticSink => _diagnostics; + /// Builds the bytes of a new one-page document and opens them (issue #44). /// The engine's configuration. /// The document. diff --git a/src/Broadside/PdfPage.cs b/src/Broadside/PdfPage.cs index b7d9ae5b..3cbbc645 100644 --- a/src/Broadside/PdfPage.cs +++ b/src/Broadside/PdfPage.cs @@ -1,3 +1,5 @@ +using Broadside.Diagnostics; +using Broadside.Fonts; using Broadside.Objects; namespace Broadside; @@ -73,6 +75,22 @@ internal PdfPage(PdfDocument document, CosDictionary dictionary, CosReference? r /// ISO 32000-2 §7.7.3.3, Table 31 (PDF 1.6). public double UserUnit => ReadUserUnit(out double value) == PageAttributeState.Valid ? value : 1.0; + /// Returns the font the page's resources name , as the Tf operator selects it. + /// The key in the Font subdictionary of the page's (possibly inherited) resource dictionary, without the slash. + /// The font view, or when the resources have no font of that name. + /// In strict mode, when the font dictionary's Type or Subtype is not a font's. + /// ISO 32000-2 §7.8.3, Table 34 (Font), and §9.5. The same font dictionary always gives the same view. + public PdfFont? GetFont(string resourceName) + { + ArgumentNullException.ThrowIfNull(resourceName); + return Resources is { } resources + && resources.TryGetValue(FontNames.Font, out CosObject? fonts) + && _document.Resolve(fonts) is CosDictionary fontResources + && fontResources.TryGetValue(new CosName(resourceName), out CosObject? font) + ? _document.GetFont(font) + : null; + } + /// Reads a page boundary; for an inheritable one, from the nearest node that has it. internal PageAttributeState ReadBox(CosName key, bool inheritable, out PdfRectangle box) { diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index a576dc7d..b05e77a8 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -404,3 +404,88 @@ Broadside.Security.PublicKeySecurityHandler.Filter.get -> Broadside.Objects.CosN Broadside.Security.PublicKeySecurityHandler.PublicKeySecurityHandler() -> void Broadside.Security.PublicKeySecurityHandler.SubFilters.get -> System.Collections.Generic.IReadOnlyCollection! override Broadside.Security.PdfCertificateCredentials.ToString() -> string! +Broadside.Fonts.PdfFont +Broadside.Fonts.PdfFont.BaseFont.get -> string? +Broadside.Fonts.PdfFont.Descriptor.get -> Broadside.Fonts.PdfFontDescriptor? +Broadside.Fonts.PdfFont.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Fonts.PdfFont.FontType.get -> Broadside.Fonts.PdfFontType +Broadside.Fonts.PdfFont.IsEmbedded.get -> bool +Broadside.Fonts.PdfFont.Reference.get -> Broadside.Objects.CosReference? +Broadside.Fonts.PdfFontDescriptor +Broadside.Fonts.PdfFontDescriptor.Ascent.get -> double +Broadside.Fonts.PdfFontDescriptor.AvgWidth.get -> double +Broadside.Fonts.PdfFontDescriptor.CapHeight.get -> double +Broadside.Fonts.PdfFontDescriptor.CharSet.get -> string? +Broadside.Fonts.PdfFontDescriptor.Descent.get -> double +Broadside.Fonts.PdfFontDescriptor.Dictionary.get -> Broadside.Objects.CosDictionary? +Broadside.Fonts.PdfFontDescriptor.Flags.get -> Broadside.Fonts.PdfFontFlags +Broadside.Fonts.PdfFontDescriptor.FontBBox.get -> Broadside.PdfRectangle +Broadside.Fonts.PdfFontDescriptor.FontFamily.get -> string? +Broadside.Fonts.PdfFontDescriptor.FontFile.get -> Broadside.Objects.CosStream? +Broadside.Fonts.PdfFontDescriptor.FontFile2.get -> Broadside.Objects.CosStream? +Broadside.Fonts.PdfFontDescriptor.FontFile3.get -> Broadside.Objects.CosStream? +Broadside.Fonts.PdfFontDescriptor.FontName.get -> string? +Broadside.Fonts.PdfFontDescriptor.FontStretch.get -> Broadside.Fonts.PdfFontStretch? +Broadside.Fonts.PdfFontDescriptor.FontWeight.get -> int? +Broadside.Fonts.PdfFontDescriptor.IsSynthesized.get -> bool +Broadside.Fonts.PdfFontDescriptor.ItalicAngle.get -> double +Broadside.Fonts.PdfFontDescriptor.Leading.get -> double +Broadside.Fonts.PdfFontDescriptor.MaxWidth.get -> double +Broadside.Fonts.PdfFontDescriptor.MissingWidth.get -> double +Broadside.Fonts.PdfFontDescriptor.Reference.get -> Broadside.Objects.CosReference? +Broadside.Fonts.PdfFontDescriptor.StemH.get -> double +Broadside.Fonts.PdfFontDescriptor.StemV.get -> double +Broadside.Fonts.PdfFontDescriptor.XHeight.get -> double +Broadside.Fonts.PdfFontFlags +Broadside.Fonts.PdfFontFlags.AllCap = 65536 -> Broadside.Fonts.PdfFontFlags +Broadside.Fonts.PdfFontFlags.FixedPitch = 1 -> Broadside.Fonts.PdfFontFlags +Broadside.Fonts.PdfFontFlags.ForceBold = 262144 -> Broadside.Fonts.PdfFontFlags +Broadside.Fonts.PdfFontFlags.Italic = 64 -> Broadside.Fonts.PdfFontFlags +Broadside.Fonts.PdfFontFlags.None = 0 -> Broadside.Fonts.PdfFontFlags +Broadside.Fonts.PdfFontFlags.Nonsymbolic = 32 -> Broadside.Fonts.PdfFontFlags +Broadside.Fonts.PdfFontFlags.Script = 8 -> Broadside.Fonts.PdfFontFlags +Broadside.Fonts.PdfFontFlags.Serif = 2 -> Broadside.Fonts.PdfFontFlags +Broadside.Fonts.PdfFontFlags.SmallCap = 131072 -> Broadside.Fonts.PdfFontFlags +Broadside.Fonts.PdfFontFlags.Symbolic = 4 -> Broadside.Fonts.PdfFontFlags +Broadside.Fonts.PdfFontStretch +Broadside.Fonts.PdfFontStretch.Condensed = 2 -> Broadside.Fonts.PdfFontStretch +Broadside.Fonts.PdfFontStretch.Expanded = 6 -> Broadside.Fonts.PdfFontStretch +Broadside.Fonts.PdfFontStretch.ExtraCondensed = 1 -> Broadside.Fonts.PdfFontStretch +Broadside.Fonts.PdfFontStretch.ExtraExpanded = 7 -> Broadside.Fonts.PdfFontStretch +Broadside.Fonts.PdfFontStretch.Normal = 4 -> Broadside.Fonts.PdfFontStretch +Broadside.Fonts.PdfFontStretch.SemiCondensed = 3 -> Broadside.Fonts.PdfFontStretch +Broadside.Fonts.PdfFontStretch.SemiExpanded = 5 -> Broadside.Fonts.PdfFontStretch +Broadside.Fonts.PdfFontStretch.UltraCondensed = 0 -> Broadside.Fonts.PdfFontStretch +Broadside.Fonts.PdfFontStretch.UltraExpanded = 8 -> Broadside.Fonts.PdfFontStretch +Broadside.Fonts.PdfFontType +Broadside.Fonts.PdfFontType.MMType1 = 1 -> Broadside.Fonts.PdfFontType +Broadside.Fonts.PdfFontType.TrueType = 2 -> Broadside.Fonts.PdfFontType +Broadside.Fonts.PdfFontType.Type0 = 4 -> Broadside.Fonts.PdfFontType +Broadside.Fonts.PdfFontType.Type1 = 0 -> Broadside.Fonts.PdfFontType +Broadside.Fonts.PdfFontType.Type3 = 3 -> Broadside.Fonts.PdfFontType +Broadside.Fonts.PdfSimpleFont +Broadside.Fonts.PdfSimpleFont.GetGlyphName(byte code) -> string! +Broadside.Fonts.PdfSimpleFont.GetWidth(byte code) -> double +Broadside.Fonts.PdfSimpleFont.Standard14.get -> Broadside.Fonts.Standard14Font? +Broadside.Fonts.PdfTrueTypeFont +Broadside.Fonts.PdfType0Font +Broadside.Fonts.PdfType1Font +Broadside.Fonts.PdfType1Font.IsMultipleMaster.get -> bool +Broadside.Fonts.PdfType3Font +Broadside.Fonts.Standard14Font +Broadside.Fonts.Standard14Font.Courier = 0 -> Broadside.Fonts.Standard14Font +Broadside.Fonts.Standard14Font.CourierBold = 1 -> Broadside.Fonts.Standard14Font +Broadside.Fonts.Standard14Font.CourierBoldOblique = 3 -> Broadside.Fonts.Standard14Font +Broadside.Fonts.Standard14Font.CourierOblique = 2 -> Broadside.Fonts.Standard14Font +Broadside.Fonts.Standard14Font.Helvetica = 4 -> Broadside.Fonts.Standard14Font +Broadside.Fonts.Standard14Font.HelveticaBold = 5 -> Broadside.Fonts.Standard14Font +Broadside.Fonts.Standard14Font.HelveticaBoldOblique = 7 -> Broadside.Fonts.Standard14Font +Broadside.Fonts.Standard14Font.HelveticaOblique = 6 -> Broadside.Fonts.Standard14Font +Broadside.Fonts.Standard14Font.Symbol = 12 -> Broadside.Fonts.Standard14Font +Broadside.Fonts.Standard14Font.TimesBold = 9 -> Broadside.Fonts.Standard14Font +Broadside.Fonts.Standard14Font.TimesBoldItalic = 11 -> Broadside.Fonts.Standard14Font +Broadside.Fonts.Standard14Font.TimesItalic = 10 -> Broadside.Fonts.Standard14Font +Broadside.Fonts.Standard14Font.TimesRoman = 8 -> Broadside.Fonts.Standard14Font +Broadside.Fonts.Standard14Font.ZapfDingbats = 13 -> Broadside.Fonts.Standard14Font +Broadside.PdfDocument.GetFont(Broadside.Objects.CosObject? font) -> Broadside.Fonts.PdfFont? +Broadside.PdfPage.GetFont(string! resourceName) -> Broadside.Fonts.PdfFont? diff --git a/src/Broadside/THIRD-PARTY-NOTICES.txt b/src/Broadside/THIRD-PARTY-NOTICES.txt new file mode 100644 index 00000000..5271b4b1 --- /dev/null +++ b/src/Broadside/THIRD-PARTY-NOTICES.txt @@ -0,0 +1,109 @@ +Broadside (core package) third-party notices +============================================= + +Broadside is licensed under the MIT License (LICENSE). The core package also carries data derived from the third-party +sources below, each under its own terms. The source files are in the repository under src/Broadside/Fonts/Data/; the +generated C# tables (src/Broadside/Fonts/*.g.cs, produced by src/Broadside/Fonts/Data/generate.py) carry the same notices. + + +1. Adobe Core 14 AFM files (Standard 14 font metrics) +------------------------------------------------------ + +Source: https://github.com/apache/pdfbox, commit 8712d47b075511a4c5a2829c3713ba2d538999bb, + pdfbox/src/main/resources/org/apache/pdfbox/resources/afm/ +Licence: the notice in MustRead.html (SPDX: APAFML), shipped in this package as licenses/adobe-core14-afm/MustRead.html +Used as: per-glyph widths, font-wide metrics and the Symbol and ZapfDingbats built-in encodings, in + src/Broadside/Fonts/Standard14Data.g.cs and src/Broadside/Fonts/GlyphNameTable.g.cs. +Modified: yes. The AFM files were converted to C# tables; kerning, ligature and glyph bounding-box data were removed. + The unmodified files are in the repository. + +Notice (MustRead.html, verbatim): + + This file and the 14 PostScript(R) AFM files it accompanies may be used, copied, and distributed for any purpose and + without charge, with or without modification, provided that all copyright notices are retained; that the AFM files + are not distributed without this file; that all modifications to this file or any of the AFM files are prominently + noted in the modified file(s); and that this paragraph is not modified. Adobe Systems has no responsibility or + obligation to support the use of the AFM files. + +Copyright notices of the AFM files: + + Courier, Courier-Bold, Courier-Oblique, Courier-BoldOblique: + Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. + Copyright (c) 1989, 1990, 1991, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. + Helvetica, Helvetica-Bold, Helvetica-Oblique, Helvetica-BoldOblique: + Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved. + Helvetica is a trademark of Linotype-Hell AG and/or its subsidiaries. + Times-Roman, Times-Bold, Times-Italic, Times-BoldItalic: + Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved. + Times is a trademark of Linotype-Hell AG and/or its subsidiaries. + Symbol: + Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All rights reserved. + ZapfDingbats: + Copyright (c) 1985, 1987, 1988, 1989, 1997 Adobe Systems Incorporated. All Rights Reserved. + ITC Zapf Dingbats is a registered trademark of International Typeface Corporation. + +SHA-256 of the source files: + + e72833dda79161e3aaf385adfeb59c61c89a4a3e184f27d21c178056eea30e17 Courier.afm + 1e86f0a949e316c08df32adc2fc2e2a92ed9902ffd54e3516e5a66a32db856da Courier-Bold.afm + 9e3494b4abb127a6586c095a377924514dd6956973f8f3b0bd7d6d00fcc89ea6 Courier-Oblique.afm + e1349f5f306b16338972eaf7f43d7913535cc075a15189b5f3efc841aee3d02e Courier-BoldOblique.afm + 5654761eab868ccb3080122accf13b4fb79edf37af09e1c57a881c35c334ee03 Helvetica.afm + 59ac93091bc7e76eb6baf60210526a4df88fe107dd5e13eb0ae70c9fc6d91fb9 Helvetica-Bold.afm + 8c00ac46ca5963df22d4fc1153ea1246c8778475820378640c8d54d4fd3a46fe Helvetica-Oblique.afm + 1f848276efd76c0e5020ef98ccb459005f5a022f56cb8579e52c98e33ffab03b Helvetica-BoldOblique.afm + b6dbde33196ff61f051f8468fb81a0dece63997a80b7fba058e8295f49480026 Times-Roman.afm + 37efa084183acfb06f45ad73bd75f6dd09b20d1e498c66ce1b9aa72b00db4ac7 Times-Bold.afm + 2f34d3bc49530532daa690aec165b68368162d4c27d24fbe6a3fb24aae49a74a Times-Italic.afm + 1bf83cee5300d4de1ce90681a2a2d70fd1876c664e91c1c4c6b6b5b12873b6da Times-BoldItalic.afm + 13eeef80def2f9a8d3a31a980731376823e8b48340ff3891ffc1cc0299c0b4fe Symbol.afm + d3e7b9f6366ab0df06acbb217c8586c5962ff2efbd4e1b5566c7eaf5b745dd41 ZapfDingbats.afm + b226bfc00e1b8b8a80c7b3cfbbc322d13b4b0401f94cdeafdd93b2210ad802eb MustRead.html + + +2. Adobe Glyph List and ITC Zapf Dingbats Glyph List +----------------------------------------------------- + +Source: https://github.com/adobe-type-tools/agl-aglfn, commit 4036a9ca80a62f64f9de4f7321a9a045ad0ecfd6 + (glyphlist.txt, zapfdingbats.txt, LICENSE.md) +Licence: BSD-3-Clause, shipped in this package as licenses/adobe-glyph-list/LICENSE.md +Used as: glyph name to Unicode tables in src/Broadside/Fonts/AdobeGlyphList.g.cs and Standard14Data.g.cs. +Modified: converted to C# tables. + +SHA-256 of the source files: + + a3b2f61ced9f3644cc0d4ecde5c59df34ca286c689d9484a43a710a81c466789 glyphlist.txt + f6394e3cb8a447e84a1dad75d4baaf2aa7f45dc104faf369f4720e1a774ef2dc zapfdingbats.txt + 58147d341e7a34aa2196862395a34d2fd95716c41d5ed26efb59ab0e12f92089 LICENSE.md + +Licence text: + + Copyright 2002-2019 Adobe (http://www.adobe.com/). + + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of conditions and the following + disclaimer. + + Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided with the distribution. + + Neither the name of Adobe nor the names of its contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +3. Font encodings (ISO 32000-2:2020 Annex D) +--------------------------------------------- + +StandardEncoding, WinAnsiEncoding, MacRomanEncoding, MacExpertEncoding and the Mac OS Roman additions of Table 113 +(src/Broadside/Fonts/Data/encodings.txt) are the code-to-glyph-name assignments of ISO 32000-2:2020 Annex D and +§9.6.5.4, cross-checked against the AFM files above and pdf.js (Apache-2.0); no pdf.js code or data is included. diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 4a3ab467..4ce646ab 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -1,6 +1,7 @@ using System.Buffers; using Broadside.Diagnostics; using Broadside.Filters; +using Broadside.Fonts; using Broadside.IO; using Broadside.Objects; using Broadside.Parsing; @@ -40,6 +41,7 @@ internal static class FuzzTargets }; private static readonly CosName ContentsKey = new("Contents"); + private static readonly CosName FontKey = new("Font"); private static readonly CosName InfoKey = new("Info"); /// @@ -91,7 +93,7 @@ private static void Document(ReadOnlySpan data) throw new InvalidOperationException($"Rotation {page.Rotation} or user unit {page.UserUnit} is out of range."); } - _ = page.Resources; + ReadFonts(document, page); if (page.Dictionary.TryGetValue(ContentsKey, out CosObject? contents) && document.Resolve(contents) is CosStream stream) { _ = document.DecodeStream(stream); @@ -99,6 +101,37 @@ private static void Document(ReadOnlySpan data) } } + /// Reads every font of a page's resources through the font model (#49): each simple font's 256 names and widths, and its descriptor. + private static void ReadFonts(PdfDocument document, PdfPage page) + { + if (page.Resources is not { } resources + || !resources.TryGetValue(FontKey, out CosObject? value) + || document.Resolve(value) is not CosDictionary fonts) + { + return; + } + + foreach (KeyValuePair entry in fonts) + { + PdfFont? font = document.GetFont(entry.Value); + if (font?.Descriptor is { } descriptor) + { + _ = (descriptor.Flags, descriptor.FontBBox, descriptor.FontStretch, descriptor.FontWeight, descriptor.MissingWidth, descriptor.FontFamily); + } + + if (font is PdfSimpleFont simple) + { + for (int code = 0; code < 256; code++) + { + if (simple.GetGlyphName((byte)code) is not { Length: > 0 } || !double.IsFinite(simple.GetWidth((byte)code))) + { + throw new InvalidOperationException($"Code {code} of font {entry.Key.Value} has no glyph name or a width that is not finite."); + } + } + } + } + } + /// /// Opens the input twice, from memory (the whole file in one view) and through a seekable stream (read in place, in windows that /// grow while an object does not end inside them), and requires the two to read the same: the same outcome when the file cannot diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index 1a3db895..36229e6e 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters, and reads every font of each page's resources through the font model (each simple font's 256 glyph names and widths, which must be non-empty and finite, and its descriptor); a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. diff --git a/tests/Broadside.TestSupport/Corpus.cs b/tests/Broadside.TestSupport/Corpus.cs index e98e5c47..078fa169 100644 --- a/tests/Broadside.TestSupport/Corpus.cs +++ b/tests/Broadside.TestSupport/Corpus.cs @@ -12,6 +12,15 @@ public static class Corpus "pdf20-header.pdf", "text-standard14.pdf", "text-truetype-embedded.pdf", + "text-standard14-differences.pdf", + "text-standard14-winansi-quirks.pdf", + "text-standard14-macroman.pdf", + "text-standard14-symbol.pdf", + "text-standard14-symbol-differences.pdf", + "text-standard14-zapfdingbats.pdf", + "text-standard14-widths.pdf", + "text-standard14-alias.pdf", + "text-type1-symbolic-noencoding.pdf", "xref-stream.pdf", "object-stream.pdf", "incremental-update.pdf", diff --git a/tests/Broadside.Tests/Fonts/EncodingTests.cs b/tests/Broadside.Tests/Fonts/EncodingTests.cs new file mode 100644 index 00000000..7c338bbb --- /dev/null +++ b/tests/Broadside.Tests/Fonts/EncodingTests.cs @@ -0,0 +1,198 @@ +using Broadside.Diagnostics; +using Broadside.Fonts; + +namespace Broadside.Tests.Fonts; + +/// +/// Simple-font encodings: the predefined encodings of Annex D (rows checked against Tables D.2 and D.4), encoding dictionaries with +/// BaseEncoding and Differences, and how malformed entries are repaired. ISO 32000-2 §9.6.5.1, §9.6.5.2, Annex D. +/// +public class EncodingTests +{ + public static TheoryData PredefinedRows => new() + { + // Table D.2, STD column (octal 047 quoteright, 140 quoteleft, 256 fi, 341 AE, 350 Lslash). + { "", 0x27, "quoteright" }, + { "", 0x60, "quoteleft" }, + { "", 0xAE, "fi" }, + { "", 0xE1, "AE" }, + { "", 0xE8, "Lslash" }, + { "", 0x80, ".notdef" }, + + // Table D.2, WIN column and notes 1 to 3 (0x18 is defined in PDFDocEncoding only). + { "/Encoding /WinAnsiEncoding", 0x18, ".notdef" }, + { "/Encoding /WinAnsiEncoding", 0x80, "Euro" }, + { "/Encoding /WinAnsiEncoding", 0x8A, "Scaron" }, + { "/Encoding /WinAnsiEncoding", 0x92, "quoteright" }, + { "/Encoding /WinAnsiEncoding", 0x9F, "Ydieresis" }, + { "/Encoding /WinAnsiEncoding", 0x9D, "bullet" }, + { "/Encoding /WinAnsiEncoding", 0xFF, "ydieresis" }, + + // Table D.2, MAC column and note 6; 0xF0 apple and 0xDB Euro are Mac OS Roman only (§9.6.5.4 Table 113). + { "/Encoding /MacRomanEncoding", 0x8A, "adieresis" }, + { "/Encoding /MacRomanEncoding", 0xD8, "ydieresis" }, + { "/Encoding /MacRomanEncoding", 0xDE, "fi" }, + { "/Encoding /MacRomanEncoding", 0xDB, "currency" }, + { "/Encoding /MacRomanEncoding", 0xF0, ".notdef" }, + { "/Encoding /MacRomanEncoding", 0xCA, "space" }, + + // Table D.4 (octal 047 Acutesmall, 064 fouroldstyle, 276 AEsmall, 330 Ydieresissmall). + { "/Encoding /MacExpertEncoding", 0x27, "Acutesmall" }, + { "/Encoding /MacExpertEncoding", 0x34, "fouroldstyle" }, + { "/Encoding /MacExpertEncoding", 0xBE, "AEsmall" }, + { "/Encoding /MacExpertEncoding", 0xD8, "Ydieresissmall" }, + { "/Encoding /MacExpertEncoding", 0x41, ".notdef" }, + }; + + [Theory] + [MemberData(nameof(PredefinedRows))] + public void A_predefined_encoding_gives_the_name_annex_D_lists(string encoding, int code, string expected) + { + using PdfDocument document = FontPdf.Open($"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica {encoding} >>"); + Assert.Equal(expected, FontPdf.SimpleFont(document).GetGlyphName((byte)code)); + + // Helvetica has no glyphs for the expert set: those widths are 0, recorded as information only. + Assert.All(document.Diagnostics, diagnostic => Assert.Equal(DiagnosticSeverity.Information, diagnostic.Severity)); + } + + [Fact] + public void The_example_of_annex_D_maps_codes_to_the_no_break_space_and_soft_hyphen_names_whose_widths_are_the_space_and_hyphen() + { + using PdfDocument document = FontPdf.Open( + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding << /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences [ 160 /nonbreakingspace 173 /softhyphen ] >> >>"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + Assert.Equal("nonbreakingspace", font.GetGlyphName(160)); + Assert.Equal("softhyphen", font.GetGlyphName(173)); + Assert.Equal(278, font.GetWidth(160)); + Assert.Equal(333, font.GetWidth(173)); + Assert.Equal("Euro", font.GetGlyphName(0x80)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_glyph_name_the_metrics_do_not_use_is_measured_through_its_Unicode_value() + { + using PdfDocument document = FontPdf.Open( + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding << /Differences [ 1 /uni00C4 /nbspace /afii10017 /u1F600 /Aogonek ] >> >>"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + Assert.Equal(667, font.GetWidth(1)); + Assert.Equal(278, font.GetWidth(2)); + Assert.Equal(0, font.GetWidth(3)); + Assert.Equal(0, font.GetWidth(4)); + Assert.Equal(667, font.GetWidth(5)); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("FontGlyphMissing", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Information, diagnostic.Severity); + } + + [Fact] + public void Differences_take_codes_as_integers_or_whole_reals_and_later_runs_win() + { + using PdfDocument document = FontPdf.Open( + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding << /Differences [ 65 /X /Y 66.0 /Z 200 /Adieresis ] >> >>"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + Assert.Equal(["X", "Z", "C", "Adieresis"], new[] { font.GetGlyphName(65), font.GetGlyphName(66), font.GetGlyphName(67), font.GetGlyphName(200) }); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Malformed_differences_are_skipped_with_a_diagnostic() + { + using PdfDocument document = FontPdf.Open( + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding << /Differences [ /Orphan 65 (text) /B 300 /Far 254 /thorn /ydieresis /Beyond ] >> >>"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + Assert.Equal("B", font.GetGlyphName(65)); + Assert.Equal("thorn", font.GetGlyphName(254)); + Assert.Equal("ydieresis", font.GetGlyphName(255)); + Assert.Equal(".notdef", font.GetGlyphName(0)); + Assert.Equal(["FontDifferencesInvalid"], FontPdf.Codes(document)); + } + + [Fact] + public void An_encoding_dictionary_with_a_base_encoding_applies_its_differences_to_it() + { + using PdfDocument document = FontPdf.Open( + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding 5 0 R >>", + "<< /Type /Encoding /BaseEncoding /MacRomanEncoding /Differences 6 0 R >>", + "[ 128 /Euro ]"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + Assert.Equal("Euro", font.GetGlyphName(0x80)); + Assert.Equal("Aring", font.GetGlyphName(0x81)); + Assert.Equal(556, font.GetWidth(0x80)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void StandardEncoding_by_name_is_used_with_a_diagnostic_since_it_is_not_a_predefined_name() + { + using PdfDocument document = FontPdf.Open("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /StandardEncoding >>"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + Assert.Equal("quoteright", font.GetGlyphName(0x27)); + Assert.Equal(["FontEncodingInvalid"], FontPdf.Codes(document)); + } + + [Theory] + [InlineData("/Encoding /SymbolEncoding")] + [InlineData("/Encoding 12")] + [InlineData("/Encoding << /BaseEncoding (WinAnsiEncoding) >>")] + [InlineData("/Encoding << /BaseEncoding /PDFDocEncoding >>")] + public void An_unknown_or_malformed_encoding_falls_back_to_the_built_in_encoding_with_a_diagnostic(string encoding) + { + using PdfDocument document = FontPdf.Open($"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica {encoding} >>"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + Assert.Equal("quoteright", font.GetGlyphName(0x27)); + Assert.Equal(["FontEncodingInvalid"], FontPdf.Codes(document)); + } + + [Fact] + public void An_embedded_font_without_an_encoding_uses_StandardEncoding_until_its_program_is_read() + { + using PdfDocument document = FontPdf.Open( + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /FirstChar 32 /LastChar 32 /Widths [ 300 ] /FontDescriptor 5 0 R >>", + "<< /Type /FontDescriptor /FontName /Helvetica /Flags 32 /FontBBox [ 0 0 1000 1000 ] /ItalicAngle 0 /Ascent 800 /Descent -200 /CapHeight 700 /StemV 80 /FontFile 6 0 R >>", + "<< /Length 0 >>\nstream\n\nendstream"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + Assert.True(font.IsEmbedded); + Assert.Null(font.Standard14); + Assert.Equal("quoteright", font.GetGlyphName(0x27)); + Assert.Equal(300, font.GetWidth(0x20)); + Assert.Equal(0, font.GetWidth(0x41)); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("FontBuiltInEncodingUnavailable", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Information, diagnostic.Severity); + } + + [Fact] + public void A_type_3_font_has_only_the_glyph_names_its_encoding_dictionary_gives() + { + using PdfDocument document = FontPdf.Open( + "<< /Type /Font /Subtype /Type3 /FontBBox [ 0 0 1 1 ] /FontMatrix [ 0.001 0 0 0.001 0 0 ] /CharProcs << >> /Encoding << /Type /Encoding /Differences [ 65 /square /circle ] >> /FirstChar 65 /LastChar 66 /Widths [ 1000 500 ] >>"); + PdfType3Font font = Assert.IsType(FontPdf.Font(document)); + + Assert.Equal(["square", "circle", ".notdef"], new[] { font.GetGlyphName(65), font.GetGlyphName(66), font.GetGlyphName(0x20) }); + Assert.Equal([1000.0, 500, 0], new[] { font.GetWidth(65), font.GetWidth(66), font.GetWidth(67) }); + Assert.Null(font.Standard14); + Assert.Null(font.Descriptor); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_type_3_font_without_an_encoding_dictionary_has_no_glyph_names_and_a_diagnostic() + { + using PdfDocument document = FontPdf.Open( + "<< /Type /Font /Subtype /Type3 /BaseFont /Helvetica /FontBBox [ 0 0 1 1 ] /FontMatrix [ 0.001 0 0 0.001 0 0 ] /CharProcs << >> /FirstChar 65 /LastChar 65 /Widths [ 1000 ] >>"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + Assert.Equal(".notdef", font.GetGlyphName(65)); + Assert.Null(font.Standard14); + Assert.Equal(["FontEncodingInvalid"], FontPdf.Codes(document)); + } +} diff --git a/tests/Broadside.Tests/Fonts/FontModelTests.cs b/tests/Broadside.Tests/Fonts/FontModelTests.cs new file mode 100644 index 00000000..88e294ec --- /dev/null +++ b/tests/Broadside.Tests/Fonts/FontModelTests.cs @@ -0,0 +1,199 @@ +using Broadside.Diagnostics; +using Broadside.Fonts; +using Broadside.Objects; + +namespace Broadside.Tests.Fonts; + +/// +/// Font dictionaries and font descriptors as typed, live views: the type each Subtype selects, the descriptor's Table 120 +/// entries and Table 121 flags, Standard 14 name matching, and the diagnostics of malformed dictionaries. ISO 32000-2 §9.5 +/// Table 108, §9.6.1, §9.6.2, §9.8. +/// +public class FontModelTests +{ + private const string Descriptor = + "<< /Type /FontDescriptor /FontName /Plain /Flags 32 /FontBBox [ 0 -200 1000 800 ] /ItalicAngle 0 /Ascent 800 /Descent -200 /CapHeight 700 /StemV 80 >>"; + + [Theory] + [InlineData("Type1", typeof(PdfType1Font), PdfFontType.Type1)] + [InlineData("MMType1", typeof(PdfType1Font), PdfFontType.MMType1)] + [InlineData("TrueType", typeof(PdfTrueTypeFont), PdfFontType.TrueType)] + [InlineData("Type3", typeof(PdfType3Font), PdfFontType.Type3)] + [InlineData("Type0", typeof(PdfType0Font), PdfFontType.Type0)] + public void The_subtype_selects_the_type_of_the_view(string subtype, Type expectedType, PdfFontType expectedFontType) + { + using PdfDocument document = FontPdf.Open($"<< /Type /Font /Subtype /{subtype} /BaseFont /Plain >>"); + PdfFont font = FontPdf.Font(document); + + Assert.IsType(expectedType, font); + Assert.Equal(expectedFontType, font.FontType); + Assert.Equal(new CosReference(4, 0), font.Reference); + Assert.Same(document.Resolve(new CosReference(4, 0)), font.Dictionary); + Assert.Equal("Plain", font.BaseFont); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_multiple_master_instance_is_a_type_1_font() + { + using PdfDocument document = FontPdf.Open("<< /Type /Font /Subtype /MMType1 /BaseFont /MinionMM_366_465_11_ /FirstChar 32 /LastChar 32 /Widths [ 187 ] /FontDescriptor 5 0 R >>", Descriptor); + PdfType1Font font = Assert.IsType(FontPdf.Font(document)); + + Assert.True(font.IsMultipleMaster); + Assert.Equal(187, font.GetWidth(32)); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [InlineData("<< /Type /Font /Subtype /CIDFontType2 /BaseFont /Helvetica >>", "FontSubtypeInvalid")] + [InlineData("<< /Type /Font /BaseFont /Helvetica >>", "FontSubtypeInvalid")] + [InlineData("<< /Type /XObject /Subtype /Type1 /BaseFont /Helvetica >>", "FontTypeInvalid")] + [InlineData("<< /Subtype /Type1 /BaseFont /Helvetica >>", "FontTypeInvalid")] + public void A_dictionary_that_is_not_quite_a_font_is_read_as_a_type_1_font_with_a_diagnostic(string dictionary, string expectedCode) + { + using PdfDocument document = FontPdf.Open(dictionary); + PdfType1Font font = Assert.IsType(FontPdf.Font(document)); + + Assert.Equal(PdfFontType.Type1, font.FontType); + Assert.Equal(278, font.GetWidth((byte)' ')); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal(expectedCode, diagnostic.Code); + Assert.Equal(new CosReference(4, 0), diagnostic.ObjectReference); + } + + [Fact] + public void The_same_dictionary_gives_the_same_view_and_a_non_dictionary_none() + { + using PdfDocument document = FontPdf.Open("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"); + PdfPage page = Assert.Single(document.Pages); + + Assert.Same(page.GetFont("F1"), page.GetFont("F1")); + Assert.Same(page.GetFont("F1"), document.GetFont(new CosReference(4, 0))); + Assert.Same(page.GetFont("F1"), document.GetFont(document.Resolve(new CosReference(4, 0)))); + Assert.Null(page.GetFont("F2")); + Assert.Null(document.GetFont(new CosInteger(1))); + Assert.Null(document.GetFont(null)); + } + + [Fact] + public void The_descriptor_view_reads_every_entry_of_table_120() + { + using PdfDocument document = FontPdf.Open( + "<< /Type /Font /Subtype /TrueType /BaseFont /AGaramond-Semibold /FirstChar 32 /LastChar 32 /Widths [ 255 ] /FontDescriptor 5 0 R >>", + "<< /Type /FontDescriptor /FontName /AGaramond-Semibold /FontFamily (Adobe Garamond) /FontStretch /SemiCondensed /FontWeight 600 /Flags 262178 /FontBBox [ 1123 866 -177 -269 ] /MissingWidth 255 /StemV 105 /StemH 45 /CapHeight 660 /XHeight 394 /Ascent 720 /Descent -270 /Leading 83 /MaxWidth 1212 /AvgWidth 478 /ItalicAngle -12.5 /CharSet (/a/b) /FontFile2 6 0 R >>", + "<< /Length 0 >>\nstream\n\nendstream"); + PdfFont font = FontPdf.Font(document); + PdfFontDescriptor descriptor = font.Descriptor!; + + Assert.False(descriptor.IsSynthesized); + Assert.Equal(new CosReference(5, 0), descriptor.Reference); + Assert.Equal("AGaramond-Semibold", descriptor.FontName); + Assert.Equal("Adobe Garamond", descriptor.FontFamily); + Assert.Equal(PdfFontStretch.SemiCondensed, descriptor.FontStretch); + Assert.Equal(600, descriptor.FontWeight); + Assert.Equal(PdfFontFlags.Serif | PdfFontFlags.Nonsymbolic | PdfFontFlags.ForceBold, descriptor.Flags); + Assert.Equal(new PdfRectangle(-177, -269, 1123, 866), descriptor.FontBBox); + Assert.Equal(-12.5, descriptor.ItalicAngle); + Assert.Equal([720, -270, 83, 660, 394, 105, 45, 478, 1212, 255], new[] + { + descriptor.Ascent, descriptor.Descent, descriptor.Leading, descriptor.CapHeight, descriptor.XHeight, descriptor.StemV, + descriptor.StemH, descriptor.AvgWidth, descriptor.MaxWidth, descriptor.MissingWidth, + }); + Assert.Equal("/a/b", descriptor.CharSet); + Assert.NotNull(descriptor.FontFile2); + Assert.Null(descriptor.FontFile); + Assert.Null(descriptor.FontFile3); + Assert.True(font.IsEmbedded); + Assert.Same(descriptor, font.Descriptor); + } + + [Fact] + public void Optional_descriptor_entries_default_and_the_view_follows_changes() + { + using PdfDocument document = FontPdf.Open("<< /Type /Font /Subtype /Type1 /BaseFont /Plain /FirstChar 32 /LastChar 32 /Widths [ 250 ] /FontDescriptor 5 0 R >>", Descriptor); + PdfFontDescriptor descriptor = FontPdf.Font(document).Descriptor!; + + Assert.Null(descriptor.FontFamily); + Assert.Null(descriptor.FontStretch); + Assert.Null(descriptor.FontWeight); + Assert.Null(descriptor.CharSet); + Assert.Equal(0, descriptor.Leading + descriptor.XHeight + descriptor.StemH + descriptor.AvgWidth + descriptor.MaxWidth + descriptor.MissingWidth); + Assert.False(FontPdf.Font(document).IsEmbedded); + + descriptor.Dictionary![new CosName("FontWeight")] = new CosReal(350); + descriptor.Dictionary[new CosName("FontStretch")] = new CosName("Wide"); + descriptor.Dictionary[new CosName("XHeight")] = new CosInteger(450); + Assert.Null(descriptor.FontWeight); + Assert.Null(descriptor.FontStretch); + Assert.Equal(450, descriptor.XHeight); + } + + [Fact] + public void A_descriptor_missing_required_entries_or_with_two_programs_is_reported_once() + { + using PdfDocument document = FontPdf.Open( + "<< /Type /Font /Subtype /Type1 /BaseFont /Plain /FirstChar 32 /LastChar 32 /Widths [ 250 ] /FontDescriptor 5 0 R >>", + "<< /FontName /Plain /Flags 4.5 /FontFile 6 0 R /FontFile3 6 0 R >>", + "<< /Length 0 >>\nstream\n\nendstream"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + Assert.Equal(250, font.GetWidth(32)); + Assert.Equal(PdfFontFlags.None, font.Descriptor!.Flags); + Assert.Equal(default, font.Descriptor.FontBBox); + Diagnostic diagnostic = Assert.Single(document.Diagnostics, d => d.Code == "FontDescriptorInvalid"); + Assert.Contains("Type", diagnostic.Message, StringComparison.Ordinal); + Assert.Contains("FontBBox", diagnostic.Message, StringComparison.Ordinal); + Assert.Contains("FontFile", diagnostic.Message, StringComparison.Ordinal); + } + + [Fact] + public void A_simple_font_that_is_not_a_standard_14_font_needs_a_descriptor_and_a_base_font() + { + using PdfDocument document = FontPdf.Open("<< /Type /Font /Subtype /Type1 /FirstChar 32 /LastChar 32 /Widths [ 250 ] >>"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + Assert.Equal(250, font.GetWidth(32)); + Assert.Null(font.Descriptor); + Assert.Null(font.BaseFont); + Assert.Equal(["FontBaseFontMissing", "FontDescriptorMissing"], FontPdf.Codes(document)); + } + + [Theory] + [InlineData("Helvetica", Standard14Font.Helvetica, false)] + [InlineData("Times-BoldItalic", Standard14Font.TimesBoldItalic, false)] + [InlineData("ZapfDingbats", Standard14Font.ZapfDingbats, false)] + [InlineData("TimesNewRomanPS-BoldItalicMT", Standard14Font.TimesBoldItalic, true)] + [InlineData("TimesNewRoman,Italic", Standard14Font.TimesItalic, true)] + [InlineData("Times,Bold", Standard14Font.TimesBold, true)] + [InlineData("CourierNew", Standard14Font.Courier, true)] + [InlineData("CourierNewPS-BoldItalicMT", Standard14Font.CourierBoldOblique, true)] + [InlineData("Arial-ItalicMT", Standard14Font.HelveticaOblique, true)] + [InlineData("Helvetica-BoldItalic", Standard14Font.HelveticaBoldOblique, true)] + [InlineData("Symbol,Bold", Standard14Font.Symbol, true)] + [InlineData("helvetica", Standard14Font.Helvetica, true)] + [InlineData("ABCDEF+Courier", Standard14Font.Courier, true)] + public void A_non_embedded_font_named_after_a_standard_14_font_takes_its_metrics(string baseFont, Standard14Font expected, bool isAlias) + { + using PdfDocument document = FontPdf.Open($"<< /Type /Font /Subtype /Type1 /BaseFont /{baseFont.Replace(",", "#2C", StringComparison.Ordinal)} >>"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + string[] expectedCodes = isAlias ? ["FontStandard14Alias"] : []; + Assert.Equal(expected, font.Standard14); + Assert.Equal(expectedCodes, FontPdf.Codes(document)); + } + + [Theory] + [InlineData("ArialNarrow")] + [InlineData("Arial-Black")] + [InlineData("Helvetica-Narrow")] + [InlineData("ABCDE+Helvetica")] + public void Fonts_whose_metrics_differ_from_the_standard_14_are_not_matched(string baseFont) + { + using PdfDocument document = FontPdf.Open($"<< /Type /Font /Subtype /Type1 /BaseFont /{baseFont} >>"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + Assert.Null(font.Standard14); + Assert.Equal(0, font.GetWidth(65)); + Assert.Equal(["FontWidthsMissing", "FontDescriptorMissing"], FontPdf.Codes(document)); + } +} diff --git a/tests/Broadside.Tests/Fonts/FontPdf.cs b/tests/Broadside.Tests/Fonts/FontPdf.cs new file mode 100644 index 00000000..be54881b --- /dev/null +++ b/tests/Broadside.Tests/Fonts/FontPdf.cs @@ -0,0 +1,36 @@ +using Broadside.Fonts; +using Broadside.Tests.Document; + +namespace Broadside.Tests.Fonts; + +/// +/// Builds a one-page file in memory whose resources name one font, /F1, object 4; extra objects are numbered from 5. For +/// font dictionary variations the corpus does not need a file for. +/// +internal static class FontPdf +{ + /// Opens a file whose font F1 has the given dictionary body. + public static PdfDocument Open(string fontDictionary, params string[] objects) => Open(fontDictionary, new PdfOptions(), objects); + + /// Opens a file whose font F1 has the given dictionary body, with options. + public static PdfDocument Open(string fontDictionary, PdfOptions options, params string[] objects) => + PdfDocument.Open( + new TestPdf().Build( + [ + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 4 0 R >> >> >>", + fontDictionary, + .. objects, + ]), + options); + + /// Gets font F1 of the file's page. + public static PdfFont Font(PdfDocument document) => Assert.IsAssignableFrom(Assert.Single(document.Pages).GetFont("F1")); + + /// Gets font F1 of the file's page as a simple font. + public static PdfSimpleFont SimpleFont(PdfDocument document) => Assert.IsAssignableFrom(Font(document)); + + /// The codes of the diagnostics recorded so far. + public static string[] Codes(PdfDocument document) => [.. document.Diagnostics.Select(diagnostic => diagnostic.Code)]; +} diff --git a/tests/Broadside.Tests/Fonts/RealWorldFontTests.cs b/tests/Broadside.Tests/Fonts/RealWorldFontTests.cs new file mode 100644 index 00000000..3690c184 --- /dev/null +++ b/tests/Broadside.Tests/Fonts/RealWorldFontTests.cs @@ -0,0 +1,107 @@ +using Broadside.Fonts; +using Broadside.Objects; +using Broadside.Security; +using Broadside.Tests.Document; +using Broadside.TestSupport; + +namespace Broadside.Tests.Fonts; + +/// +/// Every font in the fetched real-world corpora reads through the font model in lenient mode: each simple font gives a glyph +/// name and a finite width for all 256 codes, and every descriptor entry reads, without an exception. Skips when the corpora are +/// not fetched. ISO 32000-2 §9.5, §9.6, §9.8. +/// +[Trait("Category", "Corpus")] +public class RealWorldFontTests(ITestOutputHelper output) +{ + public static TheoryData CorpusIds => new(RealWorldCorpusTests.CorpusIds); + + [Theory] + [MemberData(nameof(CorpusIds))] + public void Every_font_of_a_real_world_corpus_reads_leniently_without_an_exception(string corpusId) + { + IReadOnlyList files = RealWorldCorpus.Files(corpusId); + if (files.Count == 0) + { + Assert.Skip($"Corpus '{corpusId}' not fetched; run tools/CorpusFetcher (or set {RealWorldCorpus.EnvironmentVariable})."); + } + + int fonts = 0; + int standard14 = 0; + foreach (string file in files) + { + if (RealWorldCorpusTests.Unreadable.ContainsKey(file)) + { + continue; + } + + using PdfDocument? document = OpenOrNull(file); + if (document is null) + { + continue; + } + + var seen = new HashSet(ReferenceEqualityComparer.Instance); + foreach (PdfPage page in document.Pages) + { + if (page.Resources is not { } resources + || !resources.TryGetValue(new CosName("Font"), out CosObject? value) + || document.Resolve(value) is not CosDictionary fontResources) + { + continue; + } + + foreach (KeyValuePair entry in fontResources) + { + if (document.GetFont(entry.Value) is not { } font || !seen.Add(font.Dictionary)) + { + continue; + } + + fonts++; + Read(font, file); + if (font is PdfSimpleFont { Standard14: not null }) + { + standard14++; + } + } + } + } + + output.WriteLine($"{corpusId}: {fonts} fonts read, {standard14} with Standard 14 metrics."); + } + + private static void Read(PdfFont font, string file) + { + _ = font.BaseFont; + _ = font.IsEmbedded; + if (font.Descriptor is { } descriptor) + { + _ = (descriptor.FontName, descriptor.FontFamily, descriptor.FontStretch, descriptor.FontWeight, descriptor.Flags, descriptor.FontBBox); + _ = descriptor.ItalicAngle + descriptor.Ascent + descriptor.Descent + descriptor.Leading + descriptor.CapHeight + descriptor.XHeight + + descriptor.StemV + descriptor.StemH + descriptor.AvgWidth + descriptor.MaxWidth + descriptor.MissingWidth; + _ = (descriptor.FontFile, descriptor.FontFile2, descriptor.FontFile3, descriptor.CharSet); + } + + if (font is PdfSimpleFont simple) + { + for (int code = 0; code < 256; code++) + { + Assert.False(string.IsNullOrEmpty(simple.GetGlyphName((byte)code)), file); + Assert.True(double.IsFinite(simple.GetWidth((byte)code)), file); + } + } + } + + private static PdfDocument? OpenOrNull(string file) + { + try + { + return PdfDocument.Open(File.ReadAllBytes(RealWorldCorpus.PathOf(file))); + } + catch (Exception exception) when (exception is PdfPasswordException or PdfCertificateException or NotSupportedException) + { + return null; + } + } +} diff --git a/tests/Broadside.Tests/Fonts/SimpleFontCorpusTests.cs b/tests/Broadside.Tests/Fonts/SimpleFontCorpusTests.cs new file mode 100644 index 00000000..caccd1b9 --- /dev/null +++ b/tests/Broadside.Tests/Fonts/SimpleFontCorpusTests.cs @@ -0,0 +1,161 @@ +using Broadside.Diagnostics; +using Broadside.Fonts; +using Broadside.TestSupport; + +namespace Broadside.Tests.Fonts; + +/// +/// The glyph name and width of each code of the simple-font corpus files. Expected widths are the AFM WX values of the Adobe Core +/// 14 files; expected names come from ISO 32000-2 Annex D. ISO 32000-2 §9.6.2.1, §9.6.2.2, §9.6.5.1, §9.8, Annex D.2, D.5, D.6. +/// +public class SimpleFontCorpusTests +{ + [Fact] + public void Differences_without_a_base_encoding_change_StandardEncoding_for_a_nonsymbolic_font() + { + using PdfDocument document = Open("text-standard14-differences.pdf"); + PdfSimpleFont font = Font(document, "F1"); + + Assert.Equal(["quotesingle", "quoteleft", "Euro", "bullet", "Adieresis"], Names(font, 0x27, 0x60, 0x80, 0x81, 0xC8)); + Assert.Equal([191, 222, 556, 350, 667], Widths(font, 0x27, 0x60, 0x80, 0x81, 0xC8)); + Assert.Equal("A", font.GetGlyphName(0x41)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void WinAnsiEncoding_applies_the_notes_of_table_D2() + { + using PdfDocument document = Open("text-standard14-winansi-quirks.pdf"); + PdfSimpleFont font = Font(document, "F1"); + + int[] codes = [0x27, 0x60, 0x7F, 0x81, 0x80, 0xA0, 0xAD, 0x8E]; + Assert.Equal(["quotesingle", "grave", "bullet", "bullet", "Euro", "space", "hyphen", "Zcaron"], Names(font, codes)); + Assert.Equal([191, 333, 350, 350, 556, 278, 333, 611], Widths(font, codes)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void MacRomanEncoding_is_table_D2_and_not_Mac_OS_Roman() + { + using PdfDocument document = Open("text-standard14-macroman.pdf"); + PdfSimpleFont font = Font(document, "F1"); + + int[] codes = [0x80, 0xCA, 0xDB, 0xA5, 0xAD]; + Assert.Equal(["Adieresis", "space", "currency", "bullet", ".notdef"], Names(font, codes)); + Assert.Equal([722, 250, 500, 350, 250], Widths(font, codes)); + Assert.Equal(Standard14Font.TimesRoman, font.Standard14); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void The_Symbol_font_uses_its_built_in_encoding_and_ignores_a_named_encoding() + { + using PdfDocument document = Open("text-standard14-symbol.pdf"); + PdfSimpleFont plain = Font(document, "F1"); + PdfSimpleFont named = Font(document, "F2"); + + foreach (PdfSimpleFont font in new[] { plain, named }) + { + Assert.Equal(["alpha", "beta", "gamma", "Euro"], Names(font, 0x61, 0x62, 0x67, 0xA0)); + Assert.Equal([631, 549, 411, 750], Widths(font, 0x61, 0x62, 0x67, 0xA0)); + Assert.Equal(Standard14Font.Symbol, font.Standard14); + } + + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("FontEncodingIgnored", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Information, diagnostic.Severity); + Assert.Equal(named.Reference, diagnostic.ObjectReference); + } + + [Fact] + public void Differences_on_the_Symbol_font_apply_to_its_built_in_encoding() + { + using PdfDocument document = Open("text-standard14-symbol-differences.pdf"); + PdfSimpleFont font = Font(document, "F1"); + + Assert.Equal(["alpha", "Gamma"], Names(font, 0x61, 0x42)); + Assert.Equal([631, 603], Widths(font, 0x61, 0x42)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void The_ZapfDingbats_font_encodes_the_codes_its_metrics_list_beyond_table_D6() + { + using PdfDocument document = Open("text-standard14-zapfdingbats.pdf"); + PdfSimpleFont font = Font(document, "F1"); + + Assert.Equal(["a1", "a71", "a89", "a96"], Names(font, 0x21, 0x6C, 0x80, 0x8D)); + Assert.Equal([974, 791, 390, 334], Widths(font, 0x21, 0x6C, 0x80, 0x8D)); + Assert.Equal(".notdef", font.GetGlyphName(0x7F)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Widths_override_the_standard_14_metrics_and_other_codes_take_MissingWidth() + { + using PdfDocument document = Open("text-standard14-widths.pdf"); + PdfSimpleFont font = Font(document, "F1"); + + Assert.Equal([500, 700, 777], Widths(font, 0x41, 0x42, 0x43)); + Assert.Equal(777, font.GetWidth(0x20)); + Assert.Equal(Standard14Font.Courier, font.Standard14); + Assert.False(font.Descriptor!.IsSynthesized); + Assert.Equal(777, font.Descriptor.MissingWidth); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_non_embedded_Arial_bold_takes_the_Helvetica_bold_metrics_with_an_information_diagnostic() + { + using PdfDocument document = Open("text-standard14-alias.pdf"); + PdfTrueTypeFont font = Assert.IsType(document.Pages[0].GetFont("F1")); + + Assert.Equal(Standard14Font.HelveticaBold, font.Standard14); + Assert.Equal("Arial,Bold", font.BaseFont); + Assert.Equal([722, 278, 333], Widths(font, 'H', 'i', '!')); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("FontStandard14Alias", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Information, diagnostic.Severity); + } + + [Fact] + public void A_symbolic_font_without_its_program_or_an_encoding_reads_names_from_StandardEncoding_with_a_diagnostic() + { + using PdfDocument document = Open("text-type1-symbolic-noencoding.pdf"); + PdfSimpleFont font = Font(document, "F1"); + + Assert.Equal([600, 650, 700], Widths(font, 0x41, 0x42, 0x43)); + Assert.Equal(["A", "B", "C"], Names(font, 0x41, 0x42, 0x43)); + Assert.Null(font.Standard14); + Assert.Equal(PdfFontFlags.Symbolic, font.Descriptor!.Flags); + Assert.Equal(0, font.GetWidth(0x44)); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("FontBuiltInEncodingUnavailable", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Information, diagnostic.Severity); + } + + [Fact] + public void Strict_mode_does_not_reject_the_compatibility_choices_on_legal_files() + { + foreach (string name in new[] { "text-standard14-symbol.pdf", "text-standard14-alias.pdf", "text-type1-symbolic-noencoding.pdf" }) + { + using PdfDocument document = PdfDocument.Open(Path.Combine(Corpus.Directory, name), new PdfOptions().UseStrict()); + foreach (string resource in new[] { "F1", "F2" }) + { + if (document.Pages[0].GetFont(resource) is PdfSimpleFont font) + { + _ = font.GetWidth(0x41); + } + } + } + } + + private static PdfDocument Open(string name) => PdfDocument.Open(Path.Combine(Corpus.Directory, name)); + + private static PdfSimpleFont Font(PdfDocument document, string resource) => + Assert.IsAssignableFrom(Assert.Single(document.Pages).GetFont(resource)); + + private static string[] Names(PdfSimpleFont font, params int[] codes) => [.. codes.Select(code => font.GetGlyphName((byte)code))]; + + private static double[] Widths(PdfSimpleFont font, params int[] codes) => [.. codes.Select(code => font.GetWidth((byte)code))]; +} diff --git a/tests/Broadside.Tests/Fonts/Standard14FontTests.cs b/tests/Broadside.Tests/Fonts/Standard14FontTests.cs new file mode 100644 index 00000000..e1907955 --- /dev/null +++ b/tests/Broadside.Tests/Fonts/Standard14FontTests.cs @@ -0,0 +1,32 @@ +using Broadside.Fonts; +using Broadside.TestSupport; + +namespace Broadside.Tests.Fonts; + +/// +/// Non-embedded Standard 14 fonts: glyph names from the encoding, widths from the AFM metrics. ISO 32000-2 §9.6.2.1 (Table 109 +/// and the paragraph after it), §9.6.2.2, §9.6.5. +/// +public class Standard14FontTests +{ + [Fact] + public void Text_standard14_pdf_gives_each_code_its_glyph_name_and_its_Helvetica_width() + { + using PdfDocument document = PdfDocument.Open(Path.Combine(Corpus.Directory, "text-standard14.pdf")); + PdfPage page = Assert.Single(document.Pages); + PdfType1Font font = Assert.IsType(page.GetFont("F1")); + + string[] expectedNames = ["H", "e", "l", "l", "o", "comma", "space", "B", "r", "o", "a", "d", "s", "i", "d", "e"]; + double[] expectedWidths = [722, 556, 222, 222, 556, 278, 278, 667, 333, 556, 556, 556, 500, 222, 556, 556]; + byte[] codes = "Hello, Broadside"u8.ToArray(); + + Assert.Equal(expectedNames, codes.Select(font.GetGlyphName)); + Assert.Equal(expectedWidths, codes.Select(font.GetWidth)); + Assert.Equal(7336, codes.Sum(font.GetWidth)); + Assert.Equal(Standard14Font.Helvetica, font.Standard14); + Assert.Equal("Helvetica", font.BaseFont); + Assert.Equal(PdfFontType.Type1, font.FontType); + Assert.False(font.IsEmbedded); + Assert.Empty(document.Diagnostics); + } +} diff --git a/tests/Broadside.Tests/Fonts/Standard14MetricsTests.cs b/tests/Broadside.Tests/Fonts/Standard14MetricsTests.cs new file mode 100644 index 00000000..930e4a72 --- /dev/null +++ b/tests/Broadside.Tests/Fonts/Standard14MetricsTests.cs @@ -0,0 +1,172 @@ +using System.Globalization; +using System.Text; +using Broadside.Fonts; +using Broadside.TestSupport; + +namespace Broadside.Tests.Fonts; + +/// +/// The Standard 14 metrics in the core against the Adobe Core 14 AFM files they were generated from, read here independently +/// (Adobe Technical Note #5004 §8, C, WX and N of each StartCharMetrics line). Every glyph of every +/// font is reached through a Differences array, so the whole table is checked through the public font model. +/// ISO 32000-2 §9.6.2.2, §9.6.5.1, Annex D.2, D.5, D.6. +/// +public class Standard14MetricsTests +{ + public static TheoryData Fonts => new() + { + { "Courier", Standard14Font.Courier }, + { "Courier-Bold", Standard14Font.CourierBold }, + { "Courier-Oblique", Standard14Font.CourierOblique }, + { "Courier-BoldOblique", Standard14Font.CourierBoldOblique }, + { "Helvetica", Standard14Font.Helvetica }, + { "Helvetica-Bold", Standard14Font.HelveticaBold }, + { "Helvetica-Oblique", Standard14Font.HelveticaOblique }, + { "Helvetica-BoldOblique", Standard14Font.HelveticaBoldOblique }, + { "Times-Roman", Standard14Font.TimesRoman }, + { "Times-Bold", Standard14Font.TimesBold }, + { "Times-Italic", Standard14Font.TimesItalic }, + { "Times-BoldItalic", Standard14Font.TimesBoldItalic }, + { "Symbol", Standard14Font.Symbol }, + { "ZapfDingbats", Standard14Font.ZapfDingbats }, + }; + + [Theory] + [MemberData(nameof(Fonts))] + public void Every_glyph_of_every_font_has_its_AFM_width(string fontName, Standard14Font expectedFont) + { + AfmFile afm = AfmFile.Read(fontName); + foreach (AfmGlyph[] chunk in afm.Glyphs.Chunk(255)) + { + string differences = string.Join(' ', chunk.Select(glyph => "/" + glyph.Name)); + using PdfDocument document = FontPdf.Open($"<< /Type /Font /Subtype /Type1 /BaseFont /{fontName} /Encoding << /Differences [1 {differences}] >> >>"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + Assert.Equal(expectedFont, font.Standard14); + for (int index = 0; index < chunk.Length; index++) + { + byte code = (byte)(index + 1); + Assert.Equal(chunk[index].Name, font.GetGlyphName(code)); + Assert.Equal(chunk[index].Width, font.GetWidth(code)); + } + + Assert.Empty(document.Diagnostics); + } + } + + [Theory] + [MemberData(nameof(Fonts))] + public void Without_an_encoding_each_code_has_the_glyph_the_AFM_file_encodes_and_other_codes_are_notdef(string fontName, Standard14Font expectedFont) + { + AfmFile afm = AfmFile.Read(fontName); + using PdfDocument document = FontPdf.Open($"<< /Type /Font /Subtype /Type1 /BaseFont /{fontName} >>"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + double notDefWidth = fontName.StartsWith("Courier", StringComparison.Ordinal) ? 600 : 250; + + Assert.Equal(expectedFont, font.Standard14); + for (int code = 0; code < 256; code++) + { + AfmGlyph? glyph = afm.Glyphs.SingleOrDefault(candidate => candidate.Code == code); + Assert.Equal(glyph?.Name ?? ".notdef", font.GetGlyphName((byte)code)); + Assert.Equal(glyph?.Width ?? notDefWidth, font.GetWidth((byte)code)); + } + + Assert.Empty(document.Diagnostics); + } + + [Theory] + [MemberData(nameof(Fonts))] + public void A_font_without_a_descriptor_gets_one_synthesized_from_its_AFM_file(string fontName, Standard14Font expectedFont) + { + AfmFile afm = AfmFile.Read(fontName); + using PdfDocument document = FontPdf.Open($"<< /Type /Font /Subtype /Type1 /BaseFont /{fontName} >>"); + PdfFontDescriptor descriptor = FontPdf.Font(document).Descriptor!; + + Assert.True(descriptor.IsSynthesized); + Assert.Null(descriptor.Dictionary); + Assert.Equal(fontName, descriptor.FontName); + double[] box = afm.Numbers("FontBBox"); + Assert.Equal(new PdfRectangle(box[0], box[1], box[2], box[3]), descriptor.FontBBox); + Assert.Equal(afm.Numbers("ItalicAngle")[0], descriptor.ItalicAngle); + Assert.Equal(afm.Numbers("StdVW")[0], descriptor.StemV); + Assert.Equal(afm.Numbers("StdHW")[0], descriptor.StemH); + bool symbolic = expectedFont is Standard14Font.Symbol or Standard14Font.ZapfDingbats; + Assert.Equal(symbolic ? box[3] : afm.Numbers("Ascender")[0], descriptor.Ascent); + Assert.Equal(symbolic ? box[1] : afm.Numbers("Descender")[0], descriptor.Descent); + Assert.Equal(symbolic ? box[3] : afm.Numbers("CapHeight")[0], descriptor.CapHeight); + Assert.Equal(symbolic ? 0 : afm.Numbers("XHeight")[0], descriptor.XHeight); + Assert.Equal(0, descriptor.MissingWidth); + Assert.Null(descriptor.FontFile); + } + + [Fact] + public void Synthesized_flags_follow_the_AFM_files() + { + // Courier 33 (FixedPitch, Nonsymbolic), Helvetica 32, Times 34 (Serif), +64 for a slanted font, Symbol and ZapfDingbats 4. + (string Name, PdfFontFlags Flags)[] expected = + [ + ("Courier", (PdfFontFlags)33), ("Courier-BoldOblique", (PdfFontFlags)97), ("Helvetica", (PdfFontFlags)32), + ("Helvetica-Oblique", (PdfFontFlags)96), ("Times-Bold", (PdfFontFlags)34), ("Times-Italic", (PdfFontFlags)98), + ("Symbol", PdfFontFlags.Symbolic), ("ZapfDingbats", PdfFontFlags.Symbolic), + ]; + foreach ((string name, PdfFontFlags flags) in expected) + { + using PdfDocument document = FontPdf.Open($"<< /Type /Font /Subtype /Type1 /BaseFont /{name} >>"); + Assert.Equal(flags, FontPdf.Font(document).Descriptor!.Flags); + } + } + + private sealed record AfmGlyph(int Code, double Width, string Name); + + private sealed class AfmFile + { + private readonly Dictionary _keys = []; + + public List Glyphs { get; } = []; + + public static AfmFile Read(string fontName) + { + string path = Path.Combine(Corpus.Directory, "..", "..", "src", "Broadside", "Fonts", "Data", "Afm", fontName + ".afm"); + var file = new AfmFile(); + bool inMetrics = false; + foreach (string raw in File.ReadLines(path, Encoding.ASCII)) + { + string line = raw.Trim(); + if (line.Length == 0) + { + continue; + } + + string key = line.Split(' ', 2)[0]; + if (key == "StartCharMetrics") + { + inMetrics = true; + } + else if (key == "EndCharMetrics") + { + inMetrics = false; + } + else if (inMetrics) + { + Dictionary fields = line.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Select(field => field.Split(' ', 2)) + .GroupBy(parts => parts[0]) + .ToDictionary(group => group.Key, group => group.First()[1]); + file.Glyphs.Add(new AfmGlyph( + int.Parse(fields["C"], CultureInfo.InvariantCulture), + double.Parse(fields["WX"], CultureInfo.InvariantCulture), + fields["N"])); + } + else + { + file._keys.TryAdd(key, line.Length > key.Length ? line[(key.Length + 1)..] : string.Empty); + } + } + + return file; + } + + public double[] Numbers(string key) => + [.. _keys[key].Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(value => double.Parse(value, CultureInfo.InvariantCulture))]; + } +} diff --git a/tests/Broadside.Tests/Fonts/WidthTests.cs b/tests/Broadside.Tests/Fonts/WidthTests.cs new file mode 100644 index 00000000..96206ceb --- /dev/null +++ b/tests/Broadside.Tests/Fonts/WidthTests.cs @@ -0,0 +1,162 @@ +using Broadside.Diagnostics; +using Broadside.Fonts; +using Broadside.Objects; + +namespace Broadside.Tests.Fonts; + +/// +/// Widths of simple fonts: FirstChar, LastChar, Widths, MissingWidth, and the repairs of malformed +/// entries. ISO 32000-2 §9.6.2.1 Table 109, §9.8.1 Table 120, §9.2.4. +/// +public class WidthTests +{ + private const string Descriptor = + "<< /Type /FontDescriptor /FontName /Plain /Flags 32 /FontBBox [ 0 -200 1000 800 ] /ItalicAngle 0 /Ascent 800 /Descent -200 /CapHeight 700 /StemV 80 /MissingWidth 99 >>"; + + [Fact] + public void Codes_in_range_take_their_widths_and_the_others_take_MissingWidth() + { + using PdfDocument document = FontPdf.Open("<< /Type /Font /Subtype /Type1 /BaseFont /Plain /FirstChar 65 /LastChar 67 /Widths [ 500 600.5 6 0 R ] /FontDescriptor 5 0 R >>", Descriptor, "650"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + Assert.Equal([99.0, 500, 600.5, 650, 99], new[] { font.GetWidth(64), font.GetWidth(65), font.GetWidth(66), font.GetWidth(67), font.GetWidth(68) }); + Assert.Null(font.Standard14); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_missing_FirstChar_is_read_as_0_and_a_missing_LastChar_from_the_number_of_widths() + { + using PdfDocument document = FontPdf.Open("<< /Type /Font /Subtype /Type1 /BaseFont /Plain /Widths [ 10 20 ] /FontDescriptor 5 0 R >>", Descriptor); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + Assert.Equal([10.0, 20, 99], new[] { font.GetWidth(0), font.GetWidth(1), font.GetWidth(2) }); + Assert.Equal(["FontWidthsInvalid"], FontPdf.Codes(document)); + } + + [Fact] + public void A_widths_array_shorter_than_its_range_or_with_a_non_number_falls_back_to_MissingWidth() + { + using PdfDocument document = FontPdf.Open("<< /Type /Font /Subtype /Type1 /BaseFont /Plain /FirstChar 65 /LastChar 68 /Widths [ 500 /Bad 700 ] /FontDescriptor 5 0 R >>", Descriptor); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + Assert.Equal([500.0, 99, 700, 99], new[] { font.GetWidth(65), font.GetWidth(66), font.GetWidth(67), font.GetWidth(68) }); + Assert.Equal(["FontWidthsInvalid"], FontPdf.Codes(document)); + } + + [Fact] + public void A_font_without_widths_that_is_not_a_standard_14_font_has_zero_widths_and_a_diagnostic() + { + using PdfDocument document = FontPdf.Open("<< /Type /Font /Subtype /TrueType /BaseFont /Plain /Widths 12 /FontDescriptor 5 0 R >>", Descriptor); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + Assert.Equal(0, font.GetWidth(65)); + Assert.Equal(["FontWidthsInvalid", "FontWidthsMissing"], FontPdf.Codes(document)); + } + + [Fact] + public void A_standard_14_font_with_widths_but_no_descriptor_takes_its_metrics_outside_the_range_with_a_diagnostic() + { + using PdfDocument document = FontPdf.Open("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /FirstChar 65 /LastChar 65 /Widths [ 1000 ] >>"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + Assert.Equal(1000, font.GetWidth(65)); + Assert.Equal(667, font.GetWidth(66)); + Assert.True(font.Descriptor!.IsSynthesized); + Assert.Equal(["FontStandard14EntriesIncomplete"], FontPdf.Codes(document)); + } + + [Fact] + public void Widths_follow_changes_to_the_widths_array_and_the_font_dictionary() + { + using PdfDocument document = FontPdf.Open("<< /Type /Font /Subtype /Type1 /BaseFont /Plain /FirstChar 65 /LastChar 65 /Widths [ 500 ] /FontDescriptor 5 0 R >>", Descriptor); + PdfSimpleFont font = FontPdf.SimpleFont(document); + Assert.Equal(500, font.GetWidth(65)); + + var widths = (CosArray)document.Resolve(font.Dictionary[new CosName("Widths")]); + widths[0] = new CosInteger(321); + Assert.Equal(321, font.GetWidth(65)); + + font.Dictionary[new CosName("FirstChar")] = new CosInteger(66); + font.Dictionary[new CosName("LastChar")] = new CosInteger(66); + Assert.Equal(99, font.GetWidth(65)); + Assert.Equal(321, font.GetWidth(66)); + + var descriptor = (CosDictionary)document.Resolve(font.Dictionary[new CosName("FontDescriptor")]); + descriptor[new CosName("MissingWidth")] = new CosInteger(5); + Assert.Equal(5, font.GetWidth(65)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Glyph_names_follow_changes_to_the_differences_array() + { + using PdfDocument document = FontPdf.Open("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding << /Differences [ 65 /B ] >> >>"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + Assert.Equal("B", font.GetGlyphName(65)); + Assert.Equal(667, font.GetWidth(65)); + + var encoding = (CosDictionary)font.Dictionary[new CosName("Encoding")]; + ((CosArray)encoding[new CosName("Differences")])[1] = new CosName("i"); + Assert.Equal("i", font.GetGlyphName(65)); + Assert.Equal(222, font.GetWidth(65)); + + font.Dictionary[new CosName("Encoding")] = new CosName("WinAnsiEncoding"); + Assert.Equal("A", font.GetGlyphName(65)); + } + + [Fact] + public void Strict_mode_throws_from_the_first_lookup_of_a_font_with_malformed_widths() + { + using PdfDocument document = FontPdf.Open("<< /Type /Font /Subtype /Type1 /BaseFont /Plain /Widths [ 1 ] /FontDescriptor 5 0 R >>", new PdfOptions().UseStrict(), Descriptor); + PdfSimpleFont font = FontPdf.SimpleFont(document); + + DiagnosticException exception = Assert.Throws(() => font.GetWidth(0)); + Assert.Equal("FontWidthsInvalid", exception.Diagnostic.Code); + Assert.Equal(new CosReference(4, 0), exception.Diagnostic.ObjectReference); + } + + [Fact] + public void Concurrent_lookups_on_a_new_font_agree() + { + using PdfDocument document = FontPdf.Open("<< /Type /Font /Subtype /Type1 /BaseFont /Times-Roman /Encoding /WinAnsiEncoding >>"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + double[][] results = new double[64][]; + + Parallel.For(0, results.Length, index => results[index] = [.. Enumerable.Range(0, 256).Select(code => font.GetWidth((byte)code))]); + + Assert.All(results, widths => Assert.Equal(results[0], widths)); + Assert.Equal(250, results[0][' ']); + Assert.Equal(722, results[0]['A']); + } + + [Fact] + public void Looking_up_a_glyph_name_and_width_allocates_nothing() + { + using PdfDocument document = FontPdf.Open("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding << /Differences [ 65 /B ] >> >>"); + PdfSimpleFont font = FontPdf.SimpleFont(document); + double total = 0; + for (int warmUp = 0; warmUp < 50; warmUp++) + { + total += Sum(font); + } + + long before = GC.GetAllocatedBytesForCurrentThread(); + total += Sum(font); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.Equal(0, allocated); + Assert.True(total > 0); + } + + private static double Sum(PdfSimpleFont font) + { + double sum = 0; + for (int code = 0; code < 256; code++) + { + sum += font.GetWidth((byte)code) + font.GetGlyphName((byte)code).Length; + } + + return sum; + } +} diff --git a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt index f9e9b5e1..0c4cc049 100644 --- a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt +++ b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt @@ -37,8 +37,17 @@ png-predictor.pdf, runlength-stream.pdf, startxref-wrong.pdf, + text-standard14-alias.pdf, + text-standard14-differences.pdf, + text-standard14-macroman.pdf, + text-standard14-symbol-differences.pdf, + text-standard14-symbol.pdf, + text-standard14-widths.pdf, + text-standard14-winansi-quirks.pdf, + text-standard14-zapfdingbats.pdf, text-standard14.pdf, text-truetype-embedded.pdf, + text-type1-symbolic-noencoding.pdf, wrong-stream-length.pdf, xref-stream.pdf ] \ No newline at end of file diff --git a/tests/Corpus/README.md b/tests/Corpus/README.md index f693ab10..5f01612e 100644 --- a/tests/Corpus/README.md +++ b/tests/Corpus/README.md @@ -36,6 +36,15 @@ Verification was run with qpdf 12.4.2 (`qpdf --check`), poppler (`pdfinfo`, `pdf | `pdf20-header.pdf` | `%PDF-2.0` header and catalog `/Version /2.0`; the trailer carries the `/ID` a PDF 2.0 file requires (Table 15). | 7.5.2, 7.5.5 Table 15, 7.7.2 Table 29 | `pdfinfo` shows `PDF version: 2.0`; `qpdf --check` | clean | | `text-standard14.pdf` | One line of text in non-embedded Helvetica with `/WinAnsiEncoding`. | 9.6.2, 9.6.5, 9.4.3 | `pdftotext` prints `Hello, Broadside` | clean | | `text-truetype-embedded.pdf` | One line of text in an embedded TrueType font (`/FontFile2`, `/Length1`). The font program is synthesized by the script: `.notdef`, `H` and `I` drawn as rectangles, tables `head hhea maxp OS/2 hmtx cmap(3,1 format 4) loca glyf name post`. It is not a real typeface and carries no license. | 9.6.3, 9.8.2, 9.9 Table 125 | `pdftotext` prints `HI`; `pdffonts` shows `TrueType WinAnsi emb=yes`; `fc-scan` on the extracted stream reports `Broadside Minimal Regular TrueType charset=48-49`; `pdftoppm` renders two block glyphs | clean | +| `text-standard14-differences.pdf` | Non-embedded Helvetica with an encoding dictionary without `/BaseEncoding`: `/Differences [39 /quotesingle 128 /Euro /bullet 200 /Adieresis]` over StandardEncoding. Shows codes 0x27 0x60 0x80 0x81 0xC8. Expected: quotesingle 191, quoteleft 222 (StandardEncoding, not WinAnsi's grave), Euro 556, bullet 350, Adieresis 667. | 9.6.5.1 Table 112, Annex D.2 | `pdftotext` prints `'‘€•Ä`; `pdffonts` shows `Type 1 Custom emb=no` | clean | +| `text-standard14-winansi-quirks.pdf` | Non-embedded Helvetica with `/WinAnsiEncoding` showing the codes where WinAnsi differs from StandardEncoding or shares a name: 0x27 0x60 0x7F 0x81 0x80 0xA0 0xAD 0x8E. Expected: quotesingle 191, grave 333, bullet 350 twice, Euro 556, space 278, hyphen 333, Zcaron 611. | Annex D.2 and notes 1, 2, 3, 5, 6 | `pdftotext` prints `` '`••€ -Ž `` | clean | +| `text-standard14-macroman.pdf` | Non-embedded Times-Roman with `/MacRomanEncoding` showing 0x80 0xCA 0xDB 0xA5 0xAD. Expected: Adieresis 722, space 250, currency 500 (MacRomanEncoding, not Mac OS Roman's Euro), bullet 350, `.notdef` 250 at 0xAD (Mac OS Roman's notequal is not in MacRomanEncoding). | Annex D.2 note 6, 9.6.5.4 Table 113 | `pdftotext` prints `Ä ¤•≠`: poppler, like pdf.js, reads MacRomanEncoding as Mac OS Roman at 0xAD | clean | +| `text-standard14-symbol.pdf` | Non-embedded Symbol twice, no font descriptor: `F1` without `/Encoding` and `F2` with `/WinAnsiEncoding`, each showing `abg` and 0xA0. Expected for both: alpha 631, beta 549, gamma 411, Euro 750 (Symbol's built-in encoding; the named encoding of `F2` is ignored, as pdf.js does for issue16464.pdf). | 9.6.5.1, 9.6.2.2, Annex D.5 | `pdftotext` prints `abg` then `αβγ`; `pdffonts` shows `Symbol` and `WinAnsi` encodings | clean | +| `text-standard14-symbol-differences.pdf` | Non-embedded Symbol, no font descriptor, `/Differences [66 /Gamma]` without `/BaseEncoding`. Expected: the base is Symbol's built-in encoding (the font is symbolic), so 0x61 is alpha (631) and 0x42 is Gamma (603). | 9.6.5.1 Table 112, 9.8.2 | `pdftotext` prints `αΓ` | clean | +| `text-standard14-zapfdingbats.pdf` | Non-embedded ZapfDingbats showing 0x21 0x6C 0x80 0x8D. Expected: a1 974, a71 791, a89 390, a96 334. 0x80-0x8D are encoded by the font's AFM file but missing from Table D.6. | Annex D.6 | `pdftotext` prints `✁●`: poppler, following Table D.6, has no glyph names for 0x80 and 0x8D | clean | +| `text-standard14-widths.pdf` | Non-embedded Courier with all four of `/FirstChar 65 /LastChar 66 /Widths [500 700]` and a font descriptor with `/MissingWidth 777`, showing `ABC`. Expected: A 500, B 700, C 777 (not Courier's 600). | 9.6.2.1 Table 109, 9.8.1 Table 120 | `pdftotext` prints `ABC` | clean | +| `text-standard14-alias.pdf` | Non-embedded `/TrueType` font `/BaseFont /Arial,Bold` with `/WinAnsiEncoding`, no widths, no font descriptor, showing `Hi!`. Expected: Helvetica-Bold metrics H 722, i 278, exclam 333. | 9.6.2.2, 9.6.3 | `pdftotext` prints `Hi!`; `pdffonts` shows `Arial,Bold TrueType WinAnsi emb=no` | clean | +| `text-type1-symbolic-noencoding.pdf` | Non-embedded Type 1 font `/BroadsideSymbolic` (not a standard 14 font), descriptor `/Flags 4` (Symbolic), `/Widths [600 650 700]` for 65-67, no `/Encoding`, showing `ABC`. Expected: widths 600 650 700; glyph names A B C from StandardEncoding, standing in for the unknown built-in encoding, with a diagnostic. | 9.6.5.1, 9.8.2 Table 121 | `pdftotext` prints `ABC`; `pdffonts` shows `Type 1 Standard emb=no` | clean | | `xref-stream.pdf` | Cross-reference stream (`/Type /XRef`, `/W [1 2 1]`, uncompressed), no classic table, no `trailer` keyword. | 7.5.8.2, 7.5.8.3 | `qpdf --check`; `qpdf --qdf --object-streams=disable` | clean | | `object-stream.pdf` | Catalog, page tree and page stored in an object stream (`/Type /ObjStm`, `/N 3`, `/First`), located through type 2 entries in a cross-reference stream. | 7.5.7, 7.5.8.3 Table 18 | `qpdf --qdf --object-streams=disable` lists objects 1-3 as ordinary objects | clean | | `incremental-update.pdf` | `empty-page.pdf` followed by one update section that replaces object 3 with an A4 `/MediaBox`; update trailer carries `/Prev`. | 7.5.6 | `pdfinfo` shows `595 x 842 pts (A4)` | clean | diff --git a/tests/Corpus/generate.py b/tests/Corpus/generate.py index 88922f6c..b9ba4032 100644 --- a/tests/Corpus/generate.py +++ b/tests/Corpus/generate.py @@ -704,6 +704,96 @@ def gen_text_truetype_embedded() -> bytes: ], binary=True) +def codes_content(lines: list[tuple[str, bytes]]) -> bytes: + """One text line per (font resource, codes); codes as a hexadecimal string so any byte can be shown.""" + out = b"BT /%s 24 Tf 72 700 Td <%s> Tj" % (lines[0][0].encode(), lines[0][1].hex().upper().encode()) + for font, codes in lines[1:]: + out += b" /%s 24 Tf 0 -36 Td <%s> Tj" % (font.encode(), codes.hex().upper().encode()) + return out + b" ET" + + +def font_file(fonts: list[bytes], codes: list[bytes], extra: list[tuple[int, bytes]] | None = None) -> bytes: + """A page showing ``codes[i]`` in font ``F{i+1}`` (object 5 + i); ``extra`` objects follow the fonts.""" + refs = b" ".join(b"/F%d %d 0 R" % (i + 1, 5 + i) for i in range(len(fonts))) + objects = [ + (1, catalog()), + (2, pages()), + (3, b"<< /Type /Page /Parent 2 0 R /MediaBox %s /Contents 4 0 R /Resources << /Font << %s >> >> >>" % (LETTER, refs)), + (4, stream(b"", codes_content([("F%d" % (i + 1), c) for i, c in enumerate(codes)]))), + ] + objects += [(5 + i, body) for i, body in enumerate(fonts)] + objects += extra or [] + return simple_file(objects) + + +def std14(base_font: bytes, entries: bytes = b"", subtype: bytes = b"Type1") -> bytes: + """9.6.2.2: a non-embedded standard 14 font dictionary without FirstChar, LastChar, Widths or FontDescriptor.""" + return b"<< /Type /Font /Subtype /%s /BaseFont /%s%s >>" % (subtype, base_font, b" " + entries if entries else b"") + + +def gen_text_standard14_differences() -> bytes: + """9.6.5.1 Table 112: an encoding dictionary without BaseEncoding on a non-embedded nonsymbolic font differs from + StandardEncoding; codes 0x27 0x60 0x80 0x81 0xC8.""" + enc = b"/Encoding << /Type /Encoding /Differences [39 /quotesingle 128 /Euro /bullet 200 /Adieresis] >>" + return font_file([std14(b"Helvetica", enc)], [b"\x27\x60\x80\x81\xc8"]) + + +def gen_text_standard14_winansi_quirks() -> bytes: + """Annex D.2 and its notes 1, 2, 3, 5, 6: the WinAnsiEncoding codes that differ from StandardEncoding or are + shared by two names.""" + return font_file([HELVETICA], [b"\x27\x60\x7f\x81\x80\xa0\xad\x8e"]) + + +def gen_text_standard14_macroman() -> bytes: + """Annex D.2: MacRomanEncoding, its note 6 (0xCA space) and its differences from Mac OS Roman (9.6.5.4 Table 113: + 0xDB is currency, 0xAD is unused).""" + return font_file([std14(b"Times-Roman", b"/Encoding /MacRomanEncoding")], [b"\x80\xca\xdb\xa5\xad"]) + + +def gen_text_standard14_symbol() -> bytes: + """9.6.5.1 and Annex D.5: the Symbol font's built-in encoding; F2 names WinAnsiEncoding, which a reader ignores for + the non-embedded symbolic font (as pdf.js does, issue16464).""" + return font_file([std14(b"Symbol"), std14(b"Symbol", b"/Encoding /WinAnsiEncoding")], [b"abg\xa0", b"abg\xa0"]) + + +def gen_text_standard14_symbol_differences() -> bytes: + """9.6.5.1 Table 112: without BaseEncoding the differences of a symbolic font apply to its built-in encoding, + so 0x61 stays alpha.""" + enc = b"/Encoding << /Type /Encoding /Differences [66 /Gamma] >>" + return font_file([std14(b"Symbol", enc)], [b"aB"]) + + +def gen_text_standard14_zapfdingbats() -> bytes: + """Annex D.6: the ZapfDingbats built-in encoding, including 0x80-0x8D, which its AFM file encodes but Table D.6 + does not list.""" + return font_file([std14(b"ZapfDingbats")], [b"\x21\x6c\x80\x8d"]) + + +def gen_text_standard14_widths() -> bytes: + """9.6.2.1 Table 109: a standard 14 font with all four of FirstChar, LastChar, Widths and FontDescriptor; the + Widths override the font's metrics and other codes take MissingWidth (9.8.1 Table 120).""" + font = std14(b"Courier", b"/FirstChar 65 /LastChar 66 /Widths [500 700] /Encoding /WinAnsiEncoding /FontDescriptor 6 0 R") + descriptor = (b"<< /Type /FontDescriptor /FontName /Courier /Flags 33 /FontBBox [-23 -250 715 805] /ItalicAngle 0 " + b"/Ascent 629 /Descent -157 /CapHeight 562 /XHeight 426 /StemV 51 /StemH 51 /MissingWidth 777 >>") + return font_file([font], [b"ABC"], [(6, descriptor)]) + + +def gen_text_standard14_alias() -> bytes: + """9.6.2.2 and 9.6.3: a non-embedded TrueType font named /Arial,Bold, which readers take as Helvetica-Bold + (PDFBox Standard14Fonts, pdf.js getStdFontMap).""" + return font_file([std14(b"Arial,Bold", b"/Encoding /WinAnsiEncoding", subtype=b"TrueType")], [b"Hi!"]) + + +def gen_text_type1_symbolic_noencoding() -> bytes: + """9.6.5.1 and 9.8.2: a non-embedded symbolic Type 1 font that is not a standard 14 font and has no Encoding; its + built-in encoding is unknown without its program, and its widths come from Widths.""" + font = (b"<< /Type /Font /Subtype /Type1 /BaseFont /BroadsideSymbolic /FirstChar 65 /LastChar 67 " + b"/Widths [600 650 700] /FontDescriptor 6 0 R >>") + descriptor = (b"<< /Type /FontDescriptor /FontName /BroadsideSymbolic /Flags 4 /FontBBox [0 -200 1000 800] " + b"/ItalicAngle 0 /Ascent 800 /Descent -200 /CapHeight 700 /StemV 80 >>") + return font_file([font], [b"ABC"], [(6, descriptor)]) + + def gen_xref_stream() -> bytes: f = File("1.5", binary=True) f.add(1, catalog()) @@ -1211,6 +1301,15 @@ def gen_metadata_xmp() -> bytes: "pdf20-header.pdf": gen_pdf20_header, "text-standard14.pdf": gen_text_standard14, "text-truetype-embedded.pdf": gen_text_truetype_embedded, + "text-standard14-differences.pdf": gen_text_standard14_differences, + "text-standard14-winansi-quirks.pdf": gen_text_standard14_winansi_quirks, + "text-standard14-macroman.pdf": gen_text_standard14_macroman, + "text-standard14-symbol.pdf": gen_text_standard14_symbol, + "text-standard14-symbol-differences.pdf": gen_text_standard14_symbol_differences, + "text-standard14-zapfdingbats.pdf": gen_text_standard14_zapfdingbats, + "text-standard14-widths.pdf": gen_text_standard14_widths, + "text-standard14-alias.pdf": gen_text_standard14_alias, + "text-type1-symbolic-noencoding.pdf": gen_text_type1_symbolic_noencoding, "xref-stream.pdf": gen_xref_stream, "object-stream.pdf": gen_object_stream, "incremental-update.pdf": gen_incremental_update, diff --git a/tests/Corpus/text-standard14-alias.pdf b/tests/Corpus/text-standard14-alias.pdf new file mode 100644 index 0000000000000000000000000000000000000000..1ee56caee57c0aabc24c3e8be9d8abf9292f427a GIT binary patch literal 613 zcmZXSO>e?542JLd6~1uWmL~lI300yST()TlD(!%F2sE&uE}4>4V*B+=(hADRskI;b zb>4Wid|KR-ha3@zKy8m`It5()d~?8$%(6xu0592r8=wwYK~W$sYY+PW>w=EM&!RT4 zi9P<|x~NuKAcI1mxh?cEnme@9!LPg)tW+o1M2^o0g?vIoKWQCiAn^i#SKO#p@7#cX z@`Z98!Uusg07c=X2kO48R|ovU<-vYJoO{4n&Dj?!E7yhqO`zIC?qs6~sv4%rIGa#X zKy`$9eP9xky7ge=HQEFIs(2yr9(GvH|A*5F?(rh|S~GtqDzwqz}S bIb`kyl=2VUZ-=o=+c0MmM`$#fzb()o0PLap literal 0 HcmV?d00001 diff --git a/tests/Corpus/text-standard14-differences.pdf b/tests/Corpus/text-standard14-differences.pdf new file mode 100644 index 0000000000000000000000000000000000000000..4c0ceb6661cde69b03a51b45bcd5433c76c97e5a GIT binary patch literal 682 zcmZWn!A|2a6ujpv=F;QhIBD8Msv>PmtCawOAh(Kx+q`sLWn(sW5b*Upy9HYCDS2<^ z&AhQkcbBVQ@?siE#4wwEG@C(GuTKQAP)@aG2XUu%WRWo79%UI(S9_rUKPMb;;!4*R z>(s*^d5Rf22YEvDou5Q6(-T7vI^u?Et>)$h>zMHqnP6HZVP5ALW-;~x5cg!w&~MqG zcfK+_A$&+=0Z^7KeWLDZM|Fs6>UQog#=)L-J*j`uyy7tu$rx3GDa*z&sv5IoI*Ic* zmy5hawa2pZK^!^9NW9|tX2Fkm7&b0M>VuUKb7kq!`9tk9IlWa7%Wi9G-R*+?!wr0v z#HDT;;&}X?>$HIQKNv@r;VnTXIn#&UKx~G#CC-pNi{G_oiq-bRs?TE{bS0THdarcUwia-2eap literal 0 HcmV?d00001 diff --git a/tests/Corpus/text-standard14-macroman.pdf b/tests/Corpus/text-standard14-macroman.pdf new file mode 100644 index 0000000000000000000000000000000000000000..410fda0e469706f614c0c7a1f0ab3f71a3ac9487 GIT binary patch literal 616 zcmZWn%WlFj5WM><=E9LW&Vz@9A`u>!78OBms0Tv~4FbDLj70nOU7M6g@hO>|-5Jli zH6Ksg;-$+30+{ul4F=%(_m=`6Nh=R#2R@fORU;(A0%^*WE*#PQKQ>%={Ix7LG!0AHxuoT?2Obk3)S zCioA5#1qn#r0>*STcZyCru5E!BKG!bTPb;DSx#dF!Wj7$U6Ks~4QW*cSD59PH@oXi_gR1;PS(ZNv a9a@4hZpY07sjaN6_ZdeKYqcitQ}zqQ^P-&q literal 0 HcmV?d00001 diff --git a/tests/Corpus/text-standard14-symbol-differences.pdf b/tests/Corpus/text-standard14-symbol-differences.pdf new file mode 100644 index 0000000000000000000000000000000000000000..0a16004df13eb716dd8b34ceaeeaee9e86822e3a GIT binary patch literal 634 zcmZWn%WlFj5WM><=EAXc9P%g<%7Fqsv{e!0hBz4Fq(LOE5+gyszH1XfC_Xu}vpcgB z4;It;lX#AqfCs(Zv+)=_J^v{1S83!y7vKw7s1`mEmPit&>dX@D_kF{K$KT7W#d>Jz z8=9hzwSnk0+R9_2m1z`FFFO2FWu=_x6V@K_BjF<+`EFiqh}I&o0^m#4>SMDbgVy<6 z(*$=B2pu6wNV=zP+d6gd4^46Aj&lXJpX$E|T;+DHZXM7FA{oU5%qfY0ik&dR!Qt}nq~AwDhhTu~}^y>%3U zzsahSoBNGUjmjBC#JuZ46o#}^jvF?DtD?SP;mZRi1Z`qZkLL&UHvVBlKfYn6k>x=( g?&++`Uj;I{)Y|^_?#Z-9Hpcl3Lcs=u+1H%?0WYbihX4Qo literal 0 HcmV?d00001 diff --git a/tests/Corpus/text-standard14-symbol.pdf b/tests/Corpus/text-standard14-symbol.pdf new file mode 100644 index 0000000000000000000000000000000000000000..cf91af8501180e5ec6a2957e08377a1ebf60c55a GIT binary patch literal 738 zcmbV~J#WG=5QcaEidz_|Kk`*16bV|gv{eyA>VP^JVrUT9Rcs{audmNUkiu3^_TA&x zukWrmeJ=X^AtM|ZnB|rXhd|5Iw*vYko!prX(5c)g3&I04$aA7}g&>~)UO02~rLHV2 zBE&zviaBTpymJvV_ZRV*MtSu74t-NqEyv~v3+DNh3&;i{=xOIM3o$+bbf&C1G%Ifq zofpO{gbjz}3={&=u*-9AqT>SvS|31PmEO27$OHn`HA?Quxb%V?L=5E`GZ|x0RxnI? zD$;DkawxZ+5G}!=AEo!eq{ND~l5OqK+TRic<8*#lx=?%U00%mjR<)Vaera|c_xPuO zNzjR2nX1;lu^+V_XC69M8&i!|BbvTju wdAo^4neWI=ERH*zYh=AsO&HO6{i7iB?KcLes~t`2WaEN&ZqjbX<2F8t z)Fa>HqcwWCU5@!x9&w1FdwGo}6JX`vg9dh^yxMgQum{y>2Lb^rm`)?z)&!*ZbHNG6 zzMI;?Q$p}(?9v@u4}4HaHLogJnUZAM$Nl7c#099aRGTDLci7{%t1;7z*gFI zM_ZvlQoii4LpX4d0Wh5+^?;qqdUjwxbldnXBsl?`w_5F^d5LW}h!n~V zc`DLm3gs&-N;09x_jVB5=c$4gwm!c2U?-W%fz6fEryF#}8f}rySm$rH%0ebllX?#_ zV2`HuTXa*R2o!?zFWRcBO^a)JH0`W)=A59mx7tK|yfur`pr* zKeX*s;~+^+*3QF1#v*~Skf?}DxQ->N`i8%Xsb+1n)5yYRuA)_Dq5wt&6pXpd>8Co} zY13>y$V>qH(+8=*Vb@;oe}hDm=yVrO_r^J#HuwN}9v0O*{$}+iLJ?8?@u7h-k+6Yt zu7Ge0?Kvl}FLE3w`HB-Mz6tsUwFyr2HJ26xoVUvCv<=T_ZT@M%nO9v$FQ9)u&MWJK O_N*wP(P;5&8T|)m`Sqm$ literal 0 HcmV?d00001 diff --git a/tests/Corpus/text-standard14-winansi-quirks.pdf b/tests/Corpus/text-standard14-winansi-quirks.pdf new file mode 100644 index 0000000000000000000000000000000000000000..782ad5f35c6c8213505eece789674ae8485397bc GIT binary patch literal 619 zcmZWn%WlFj5WM><_QJ8Xoi`GS1SL_Wwkm>1J)j;8G1Q3Km2E28udi()2*sylc6Mex z-ob2I-_iRVQ6QjJJ2V;rZhpQv;0I>eUTp!-*p?fJ9AOS+iMVV%(f?mJoOt+2v<8;3 zr@uQDb&wWluhCa-8@-L@j(YOJFT53OqK>d6j-Sy8@?jM8q;)g{i8lZ|=SCg$+70L@ zua#2>9~9C+C`)JEbN6kXJK$$7xAp^)+!Kt|oPDB6<76mA2{aqXoh>2Iv@nYDjO2Ae z3o<6-X;GEX?4W9V99?G@jQ731UziFn4l5gi_3=``6K43S^2qn!+=?{=T*0QemP|B9hCCV-0g_5OxrML5@%>Is9tOI2L$w@;{X5v literal 0 HcmV?d00001 diff --git a/tests/Corpus/text-standard14-zapfdingbats.pdf b/tests/Corpus/text-standard14-zapfdingbats.pdf new file mode 100644 index 0000000000000000000000000000000000000000..91b16cac08838b6f915631ee17971118444852ae GIT binary patch literal 587 zcmZWn%WlFj5WM><=EAXcoEIRW9C%&Yst9r_>cKQl8bo6h8;SPoyEah?#iwL;W@mTo z!D_yI5RXG95J2ztY%&4QzmE!hCapZ^3VbCiWe^f!jVxoTDIC%L-wG}~{!|wR+sM)1 zsf#`}7NRF~m3yJHX%$f~KKw-$wVdiRwgK@|5n?zFeZR&M%^-FL;A>^{sr{e<-Q-J6 z9sGwt;t5$s);)J8>)gSgRa4ndL}N!VwpH?rO>=4^5XQ($49PYKkQbPQBAtzb(L6)G z$0Bzzbc!wz=Xbl8pN4NvJL>~=u?q01H0n}$lgDyiH`PwkKG$T=ttuJq%!0pzG)bZa zC9c>QzKZ6GC8Ik`2pY?s9xsgPvj1UG)Wd8m>w{|jTiDb;3Mu8RwY$dd4Hzq1>*tJv Lm<GlY*zxlo?SPHK=C1py|Xj3 zyY}SqVs^xj^MFGLdifSir@*R@tps*1oal55>`}DRLWF=h6h$EWhJdvHov_ET8`W5N zi3$FSEPB^F;G;x}943;CkqF)Eushi(QR;Vi2@#+12=dd&^Ysp477`KwHkVfKOpOM~ z`Aj2&|KX5&KvAIdNS)FKbzrx$Z`~T=oB-AtDKz^zb086UKS(SsDkE$>qZ=_yQ%i=du6* literal 0 HcmV?d00001 From 238e9c3a77c939d92e65df1feb600d38291b7581 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:27:41 -0500 Subject: [PATCH 026/152] feat(model): associated files and object-level metadata at every location (#76) PdfDocument.AssociatedFiles, ReadAssociatedFiles(owner), ReadMarkedContentAssociatedFiles (MCAF and bare array), PdfPage.AssociatedFiles, EnumerateAssociatedFiles(deep) and EnumerateObjectMetadata(deep) over a one-visited-set walk of the catalog, OCGs, threads, structure tree, document parts, embedded files, pages, resources (recursively) and annotations; deep scans every object. AF repairs (single dict, strings, non-filespecs) and embedded AF checks (Subtype, Params ModDate); metadata stream Type/Subtype check. New corpus files associated-files.pdf and object-metadata.pdf. Co-Authored-By: Claude Opus 5.5 --- src/Broadside/AssociatedFileReader.cs | 268 ++++++++++ src/Broadside/DocumentObjectWalker.cs | 480 ++++++++++++++++++ src/Broadside/PdfAssociatedFile.cs | 79 +++ src/Broadside/PdfDocument.cs | 77 ++- src/Broadside/PdfObjectMetadata.cs | 110 ++++ src/Broadside/PdfPage.cs | 4 + src/Broadside/PublicAPI.Unshipped.txt | 54 ++ tests/Broadside.TestSupport/Corpus.cs | 2 + .../Files/AssociatedFileTests.cs | 142 ++++++ .../Files/ObjectMetadataTests.cs | 104 ++++ ...pus_file_names_match_snapshot.verified.txt | 2 + tests/Corpus/README.md | 2 + tests/Corpus/associated-files.pdf | Bin 0 -> 4008 bytes tests/Corpus/generate.py | 101 ++++ tests/Corpus/object-metadata.pdf | Bin 0 -> 9881 bytes 15 files changed, 1424 insertions(+), 1 deletion(-) create mode 100644 src/Broadside/AssociatedFileReader.cs create mode 100644 src/Broadside/DocumentObjectWalker.cs create mode 100644 src/Broadside/PdfAssociatedFile.cs create mode 100644 src/Broadside/PdfObjectMetadata.cs create mode 100644 tests/Broadside.Tests/Files/AssociatedFileTests.cs create mode 100644 tests/Broadside.Tests/Files/ObjectMetadataTests.cs create mode 100644 tests/Corpus/associated-files.pdf create mode 100644 tests/Corpus/object-metadata.pdf diff --git a/src/Broadside/AssociatedFileReader.cs b/src/Broadside/AssociatedFileReader.cs new file mode 100644 index 00000000..bc9c8df2 --- /dev/null +++ b/src/Broadside/AssociatedFileReader.cs @@ -0,0 +1,268 @@ +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// +/// Reads AF arrays and object-level Metadata entries, and enumerates them over the document (issue #76). Every read is +/// lenient: malformed entries are repaired or skipped with a diagnostic, nothing is written. +/// +internal static class AssociatedFileReader +{ + /// Reads an AF value (ISO 32000-2 §14.13.2): an array of file specification dictionaries. + public static IReadOnlyList Read(PdfDocument document, CosObject? value, CosReference? owner, bool requireRelationship = false) + { + var files = new List(); + switch (document.Resolve(value)) + { + case CosNull: + break; + case CosDictionary: + Warn("An AF entry is a single file specification, not an array; it is read as an array of one."); + Add(value!, wrapped: true); + break; + case CosArray array: + foreach (CosObject entry in array) + { + Add(entry, wrapped: false); + } + + break; + default: + Warn("An AF entry is neither an array nor a file specification; it is ignored."); + break; + } + + return files; + + void Add(CosObject entry, bool wrapped) + { + CosObject resolved = document.Resolve(entry); + if (resolved is CosNull) + { + return; + } + + if (PdfFileSpecification.Create(document, entry) is not { } file) + { + Warn("An AF array entry is not a file specification; it is skipped."); + return; + } + + if (resolved is CosString) + { + Warn("An AF array entry is a file specification string; associated files shall be file specification dictionaries. It is read as one."); + } + else if (!wrapped) + { + Check(document, file, owner, requireRelationship); + } + + files.Add(file); + } + + void Warn(string message) => ViewReading.Warn(document, DiagnosticCodes.AssociatedFilesInvalid, message, owner); + } + + /// Reads the associated files of a marked-content property list (§14.13.5): an MCAF entry, or the array itself. + public static IReadOnlyList ReadMarkedContent(PdfDocument document, CosObject? properties, CosReference? owner) => + document.Resolve(properties) switch + { + CosArray array => Read(document, array, owner), + CosDictionary dictionary when dictionary.TryGetValue(FileAndLayerNames.MCAF, out CosObject? files) => Read(document, files, owner, requireRelationship: true), + _ => [], + }; + + /// Walks the known locations (and, when , every object) for AF entries. + public static IEnumerable Enumerate(PdfDocument document, bool deep) + { + var seen = new HashSet(ReferenceEqualityComparer.Instance); + foreach (ObjectVisit visit in new DocumentObjectWalker(document).Walk()) + { + seen.Add(visit.Value); + if (visit.Role == ObjectRole.PropertyList) + { + foreach (PdfFileSpecification file in ReadMarkedContent(document, visit.Value, visit.Reference)) + { + yield return new PdfAssociatedFile(file, PdfAssociatedFileLocation.MarkedContent, visit.Value, visit.Reference, visit.PageIndex, visit.PropertyName); + } + } + else + { + foreach (PdfAssociatedFile file in FromOwner(document, visit.Value, visit.Dictionary!, visit.Reference, LocationOf(visit.Role), visit.PageIndex)) + { + yield return file; + } + } + + if (visit.Dictionary is { } owner && MetadataOf(document, owner, visit.Reference) is { } metadata && seen.Add(metadata.Stream)) + { + foreach (PdfAssociatedFile file in FromOwner(document, metadata.Stream, metadata.Stream.Dictionary, metadata.Reference, PdfAssociatedFileLocation.MetadataStream, visit.PageIndex)) + { + yield return file; + } + } + } + + if (!deep) + { + yield break; + } + + foreach (CosReference reference in document.EnumerateObjectReferences()) + { + CosObject value = document.Resolve(reference); + CosDictionary? dictionary = value switch + { + CosStream stream => stream.Dictionary, + CosDictionary plain => plain, + _ => null, + }; + if (dictionary is null || !seen.Add(value)) + { + continue; + } + + PdfAssociatedFileLocation location = ViewReading.HasType(document, dictionary, FileAndLayerNames.Metadata) + ? PdfAssociatedFileLocation.MetadataStream + : PdfAssociatedFileLocation.Other; + foreach (PdfAssociatedFile file in FromOwner(document, value, dictionary, reference, location, pageIndex: null)) + { + yield return file; + } + } + } + + /// Walks the known locations (and, when , every object) for Metadata entries. + public static IEnumerable EnumerateMetadata(PdfDocument document, bool deep) + { + var seen = new HashSet(ReferenceEqualityComparer.Instance); + foreach (ObjectVisit visit in new DocumentObjectWalker(document).Walk()) + { + seen.Add(visit.Value); + if (visit.Dictionary is { } owner && MetadataOf(document, owner, visit.Reference) is { } metadata) + { + seen.Add(metadata.Stream); + yield return new PdfObjectMetadata(document, metadata.Stream, metadata.Reference, MetadataLocationOf(visit.Role), visit.Value, visit.Reference, visit.PageIndex); + } + } + + if (!deep) + { + yield break; + } + + foreach (CosReference reference in document.EnumerateObjectReferences()) + { + CosObject value = document.Resolve(reference); + CosDictionary? dictionary = value switch + { + CosStream stream => stream.Dictionary, + CosDictionary plain => plain, + _ => null, + }; + if (dictionary is not null && seen.Add(value) && MetadataOf(document, dictionary, reference) is { } metadata) + { + yield return new PdfObjectMetadata(document, metadata.Stream, metadata.Reference, PdfMetadataLocation.Other, value, reference, null); + } + } + } + + /// The metadata stream in 's Metadata entry, checked against Table 347. + public static (CosStream Stream, CosReference? Reference)? MetadataOf(PdfDocument document, CosDictionary owner, CosReference? ownerReference) + { + if (!owner.TryGetValue(FileAndLayerNames.Metadata, out CosObject? entry)) + { + return null; + } + + CosReference? reference = entry as CosReference; + switch (document.Resolve(entry)) + { + case CosNull: + return null; + case CosStream stream: + if (!ViewReading.HasType(document, stream.Dictionary, FileAndLayerNames.Metadata) + || ViewReading.Name(document, stream.Dictionary, FileAndLayerNames.Subtype) is not { Value: "XML" }) + { + ViewReading.Warn(document, DiagnosticCodes.MetadataStreamInvalid, "A metadata stream shall have Type Metadata and Subtype XML; it is read as XMP anyway.", reference ?? ownerReference); + } + + return (stream, reference); + default: + ViewReading.Warn(document, DiagnosticCodes.MetadataStreamInvalid, "A Metadata entry is not a stream; it is ignored.", ownerReference); + return null; + } + } + + private static IEnumerable FromOwner(PdfDocument document, CosObject owner, CosDictionary dictionary, CosReference? reference, PdfAssociatedFileLocation location, int? pageIndex) + { + if (!dictionary.TryGetValue(FileAndLayerNames.AF, out CosObject? value)) + { + return []; + } + + return Read(document, value, reference).Select(file => new PdfAssociatedFile(file, location, owner, reference, pageIndex, null)); + } + + /// The checks §14.13.2 makes of an embedded associated file: Subtype shall be present; Params with ModDate. + private static void Check(PdfDocument document, PdfFileSpecification file, CosReference? owner, bool requireRelationship) + { + CosReference? where = file.Reference ?? owner; + if (requireRelationship && file.Dictionary is { } dictionary && !dictionary.ContainsKey(FileAndLayerNames.AFRelationship)) + { + ViewReading.Warn(document, DiagnosticCodes.AssociatedFilesInvalid, "A file specification in a marked-content MCAF array shall have an AFRelationship entry; Unspecified is used.", where); + } + + if (file.EmbeddedFile is not { } embedded) + { + return; + } + + if (embedded.Subtype is null) + { + ViewReading.Warn(document, DiagnosticCodes.EmbeddedFileSubtypeMissing, "An embedded file used as an associated file shall have a Subtype (MIME type); application/octet-stream is assumed.", embedded.Reference ?? where); + } + + if (embedded.Parameters is { } parameters && parameters.ModificationDate is null) + { + ViewReading.Warn(document, DiagnosticCodes.EmbeddedFileParamsInvalid, "The parameters of an embedded file used as an associated file shall have a ModDate.", embedded.Reference ?? where); + } + } + + private static PdfAssociatedFileLocation LocationOf(ObjectRole role) => role switch + { + ObjectRole.Catalog => PdfAssociatedFileLocation.Catalog, + ObjectRole.Page => PdfAssociatedFileLocation.Page, + ObjectRole.FormXObject => PdfAssociatedFileLocation.FormXObject, + ObjectRole.ImageXObject => PdfAssociatedFileLocation.ImageXObject, + ObjectRole.Annotation => PdfAssociatedFileLocation.Annotation, + ObjectRole.StructureTreeRoot => PdfAssociatedFileLocation.StructureTreeRoot, + ObjectRole.StructureElement => PdfAssociatedFileLocation.StructureElement, + ObjectRole.DocumentPart => PdfAssociatedFileLocation.DocumentPart, + ObjectRole.PropertyList => PdfAssociatedFileLocation.MarkedContent, + _ => PdfAssociatedFileLocation.Other, + }; + + private static PdfMetadataLocation MetadataLocationOf(ObjectRole role) => role switch + { + ObjectRole.Catalog => PdfMetadataLocation.Document, + ObjectRole.OptionalContentGroup => PdfMetadataLocation.OptionalContentGroup, + ObjectRole.Thread => PdfMetadataLocation.Thread, + ObjectRole.StructureElement => PdfMetadataLocation.StructureElement, + ObjectRole.DocumentPart => PdfMetadataLocation.DocumentPart, + ObjectRole.EmbeddedFile => PdfMetadataLocation.EmbeddedFile, + ObjectRole.Page => PdfMetadataLocation.Page, + ObjectRole.FormXObject => PdfMetadataLocation.FormXObject, + ObjectRole.ImageXObject => PdfMetadataLocation.ImageXObject, + ObjectRole.IccProfile => PdfMetadataLocation.IccProfile, + ObjectRole.FontProgram => PdfMetadataLocation.FontProgram, + ObjectRole.Type3Font => PdfMetadataLocation.Type3Font, + ObjectRole.TilingPattern => PdfMetadataLocation.TilingPattern, + ObjectRole.Shading => PdfMetadataLocation.Shading, + ObjectRole.PropertyList => PdfMetadataLocation.MarkedContent, + ObjectRole.Annotation => PdfMetadataLocation.Annotation, + ObjectRole.ThreeD => PdfMetadataLocation.ThreeD, + _ => PdfMetadataLocation.Other, + }; +} diff --git a/src/Broadside/DocumentObjectWalker.cs b/src/Broadside/DocumentObjectWalker.cs new file mode 100644 index 00000000..e0e6c4be --- /dev/null +++ b/src/Broadside/DocumentObjectWalker.cs @@ -0,0 +1,480 @@ +using Broadside.Objects; + +namespace Broadside; + +/// What a visited object is, by where the walk found it. +internal enum ObjectRole : byte +{ + Catalog, + OptionalContentGroup, + Thread, + StructureTreeRoot, + StructureElement, + DocumentPart, + EmbeddedFile, + Page, + FormXObject, + ImageXObject, + IccProfile, + FontProgram, + Type3Font, + TilingPattern, + Shading, + PropertyList, + Annotation, + ThreeD, +} + +/// One object the walk found. +/// The dictionary or stream. +/// Its indirect reference, when it was reached through one. +/// What it is. +/// The page it was found under, or for document-level objects. +/// For a marked-content property list, its name in the Properties resource. +internal readonly record struct ObjectVisit(CosObject Value, CosReference? Reference, ObjectRole Role, int? PageIndex, string? PropertyName = null) +{ + /// Gets the dictionary of the object (a stream's dictionary for a stream); for a property list that is an array. + public CosDictionary? Dictionary => Value switch + { + CosStream stream => stream.Dictionary, + CosDictionary dictionary => dictionary, + _ => null, + }; +} + +/// +/// Walks the places of a document where associated files (ISO 32000-2 §14.13, PDF 2.0 Application Note 002) and object-level +/// metadata (§14.3.2, Application Note 003) can be: the catalog, optional content groups, threads, the structure tree, document +/// parts, embedded files, then each page with its resources (recursively through forms, patterns and Type 3 fonts) and annotations. +/// Every object is visited once (one visited set for the whole walk); recursion uses an explicit stack. Lazy; reads only. +/// +internal sealed class DocumentObjectWalker(PdfDocument document) +{ + private const int MaxColorSpaceDepth = 8; + + private readonly HashSet _visited = new(ReferenceEqualityComparer.Instance); + + public IEnumerable Walk() + { + CosDictionary catalog = document.Catalog; + _visited.Add(catalog); + yield return new ObjectVisit(catalog, RootReference(), ObjectRole.Catalog, null); + + if (document.OptionalContent is { } optionalContent) + { + foreach (PdfOptionalContentGroup group in optionalContent.Groups) + { + if (_visited.Add(group.Dictionary)) + { + yield return new ObjectVisit(group.Dictionary, group.Reference, ObjectRole.OptionalContentGroup, null); + } + } + } + + if (Get(catalog, Names.Threads) is CosArray threads) + { + foreach (CosObject thread in threads) + { + if (Visit(thread, ObjectRole.Thread, null) is { } visit) + { + yield return visit; + } + } + } + + foreach (ObjectVisit visit in WalkStructure(catalog)) + { + yield return visit; + } + + foreach (ObjectVisit visit in WalkDocumentParts(catalog)) + { + yield return visit; + } + + foreach (PdfEmbeddedFileEntry entry in document.EmbeddedFiles) + { + if (entry.File.EmbeddedFile is { } file && _visited.Add(file.Stream)) + { + yield return new ObjectVisit(file.Stream, file.Reference, ObjectRole.EmbeddedFile, null); + } + } + + for (int index = 0; index < document.Pages.Count; index++) + { + PdfPage page = document.Pages[index]; + if (!_visited.Add(page.Dictionary)) + { + continue; + } + + yield return new ObjectVisit(page.Dictionary, page.Reference, ObjectRole.Page, index); + foreach (ObjectVisit visit in WalkResources(page.Resources, index)) + { + yield return visit; + } + + if (Get(page.Dictionary, FileAndLayerNames.Annots) is CosArray annotations) + { + foreach (CosObject entry in annotations) + { + if (Visit(entry, ObjectRole.Annotation, index) is not { } annotation) + { + continue; + } + + yield return annotation; + foreach (ObjectVisit visit in WalkAnnotation(annotation.Dictionary!, index)) + { + yield return visit; + } + } + } + } + } + + private CosReference? RootReference() => + document.Trailer.TryGetValue(KnownNames.Root, out CosObject? root) ? root as CosReference : null; + + private CosObject? Get(CosDictionary dictionary, CosName key) => ViewReading.Get(document, dictionary, key); + + /// Visits when it resolves to a dictionary or stream not visited yet. + private ObjectVisit? Visit(CosObject entry, ObjectRole role, int? page, string? propertyName = null) + { + CosObject resolved = document.Resolve(entry); + return resolved is CosDictionary or CosStream && _visited.Add(resolved) + ? new ObjectVisit(resolved, entry as CosReference, role, page, propertyName) + : null; + } + + private IEnumerable WalkStructure(CosDictionary catalog) + { + if (!catalog.TryGetValue(Names.StructTreeRoot, out CosObject? rootEntry) || Visit(rootEntry, ObjectRole.StructureTreeRoot, null) is not { } root) + { + yield break; + } + + yield return root; + var pending = new Stack(); + PushChildren(root.Dictionary!, pending); + while (pending.TryPop(out CosObject? entry)) + { + CosObject resolved = document.Resolve(entry); + if (resolved is CosArray array) + { + if (_visited.Add(array)) + { + for (int index = array.Count - 1; index >= 0; index--) + { + pending.Push(array[index]); + } + } + + continue; + } + + if (resolved is not CosDictionary element + || ViewReading.Name(document, element, KnownNames.Type) is { Value: "MCR" or "OBJR" } + || Visit(entry, ObjectRole.StructureElement, null) is not { } visit) + { + continue; + } + + yield return visit; + PushChildren(element, pending); + } + + static void PushChildren(CosDictionary node, Stack pending) + { + if (node.TryGetValue(Names.K, out CosObject? kids)) + { + pending.Push(kids); + } + } + } + + private IEnumerable WalkDocumentParts(CosDictionary catalog) + { + if (Get(catalog, Names.DPartRoot) is not CosDictionary partRoot || !partRoot.TryGetValue(Names.DPartRootNode, out CosObject? node)) + { + yield break; + } + + var pending = new Stack(); + pending.Push(node); + while (pending.TryPop(out CosObject? entry)) + { + if (Visit(entry, ObjectRole.DocumentPart, null) is not { } part) + { + continue; + } + + yield return part; + if (Get(part.Dictionary!, Names.DParts) is CosArray levels) + { + var children = new List(); + foreach (CosObject level in levels) + { + if (document.Resolve(level) is CosArray parts) + { + children.AddRange(parts); + } + } + + for (int index = children.Count - 1; index >= 0; index--) + { + pending.Push(children[index]); + } + } + } + } + + private IEnumerable WalkAnnotation(CosDictionary annotation, int page) + { + if (Get(annotation, Names.FS) is { } fileSpecification + && PdfFileSpecification.Create(document, fileSpecification) is { Dictionary: not null } spec + && spec.EmbeddedFile is { } file + && _visited.Add(file.Stream)) + { + yield return new ObjectVisit(file.Stream, file.Reference, ObjectRole.EmbeddedFile, page); + } + + if (annotation.TryGetValue(Names.ThreeDD, out CosObject? artwork) && Visit(artwork, ObjectRole.ThreeD, page) is { } threeD) + { + yield return threeD; + } + + if (Get(annotation, Names.AP) is CosDictionary appearances) + { + foreach (KeyValuePair appearance in appearances) + { + IEnumerable streams = document.Resolve(appearance.Value) switch + { + CosStream => [appearance.Value], + CosDictionary states => states.Values, + _ => [], + }; + foreach (CosObject stream in streams) + { + if (document.Resolve(stream) is CosStream && Visit(stream, ObjectRole.FormXObject, page) is { } form) + { + yield return form; + foreach (ObjectVisit visit in WalkResources(Get(form.Dictionary!, KnownNames.Resources) as CosDictionary, page)) + { + yield return visit; + } + } + } + } + } + } + + /// Walks a resource dictionary and every resource dictionary it leads to, with an explicit stack. + private IEnumerable WalkResources(CosDictionary? resources, int page) + { + var pending = new Stack(); + if (resources is not null && _visited.Add(resources)) + { + pending.Push(resources); + } + + while (pending.TryPop(out CosDictionary? current)) + { + var found = new List(); + if (Get(current, FileAndLayerNames.XObject) is CosDictionary xobjects) + { + foreach (CosObject entry in xobjects.Values) + { + if (document.Resolve(entry) is not CosStream stream) + { + continue; + } + + CosName? subtype = ViewReading.Name(document, stream.Dictionary, FileAndLayerNames.Subtype); + ObjectRole? role = subtype?.Value switch + { + "Image" => ObjectRole.ImageXObject, + "Form" => ObjectRole.FormXObject, + _ => null, + }; + if (role is { } known && Visit(entry, known, page) is { } visit) + { + found.Add(visit); + if (known == ObjectRole.ImageXObject) + { + AddColorSpace(Get(stream.Dictionary, Names.ColorSpace), page, found, 0); + } + } + } + } + + if (Get(current, Names.ColorSpace) is CosDictionary colorSpaces) + { + foreach (CosObject entry in colorSpaces.Values) + { + AddColorSpace(entry, page, found, 0); + } + } + + if (Get(current, Names.Font) is CosDictionary fonts) + { + foreach (CosObject entry in fonts.Values) + { + AddFont(entry, page, found); + } + } + + if (Get(current, Names.Pattern) is CosDictionary patterns) + { + foreach (CosObject entry in patterns.Values) + { + switch (document.Resolve(entry)) + { + case CosStream when Visit(entry, ObjectRole.TilingPattern, page) is { } tiling: + found.Add(tiling); + break; + case CosDictionary shadingPattern when _visited.Add(shadingPattern) && shadingPattern.TryGetValue(Names.Shading, out CosObject? shading): + if (Visit(shading, ObjectRole.Shading, page) is { } visit) + { + found.Add(visit); + } + + break; + } + } + } + + if (Get(current, Names.Shading) is CosDictionary shadings) + { + foreach (CosObject entry in shadings.Values) + { + if (Visit(entry, ObjectRole.Shading, page) is { } visit) + { + found.Add(visit); + } + } + } + + if (Get(current, FileAndLayerNames.Properties) is CosDictionary properties) + { + foreach (KeyValuePair entry in properties) + { + CosObject resolved = document.Resolve(entry.Value); + if (resolved is CosArray array && _visited.Add(array)) + { + found.Add(new ObjectVisit(array, entry.Value as CosReference, ObjectRole.PropertyList, page, entry.Key.Value)); + } + else if (resolved is CosDictionary && Visit(entry.Value, ObjectRole.PropertyList, page, entry.Key.Value) is { } visit) + { + found.Add(visit); + } + } + } + + foreach (ObjectVisit visit in found) + { + yield return visit; + if (visit.Role is ObjectRole.FormXObject or ObjectRole.TilingPattern or ObjectRole.Type3Font + && Get(visit.Dictionary!, KnownNames.Resources) is CosDictionary nested && _visited.Add(nested)) + { + pending.Push(nested); + } + } + } + } + + private void AddColorSpace(CosObject? entry, int page, List found, int depth) + { + if (depth >= MaxColorSpaceDepth || document.Resolve(entry) is not CosArray array || array.Count == 0) + { + return; + } + + if (document.Resolve(array[0]) is CosName { Value: "ICCBased" } && array.Count > 1) + { + if (document.Resolve(array[1]) is CosStream && Visit(array[1], ObjectRole.IccProfile, page) is { } visit) + { + found.Add(visit); + } + + return; + } + + for (int index = 1; index < array.Count; index++) + { + AddColorSpace(array[index], page, found, depth + 1); + } + } + + private void AddFont(CosObject entry, int page, List found) + { + if (document.Resolve(entry) is not CosDictionary font || _visited.Contains(font)) + { + return; + } + + CosName? subtype = ViewReading.Name(document, font, FileAndLayerNames.Subtype); + if (subtype is { Value: "Type3" }) + { + if (Visit(entry, ObjectRole.Type3Font, page) is { } visit) + { + found.Add(visit); + } + + return; + } + + _visited.Add(font); + AddFontProgram(font); + if (subtype is { Value: "Type0" } && Get(font, Names.DescendantFonts) is CosArray descendants) + { + foreach (CosObject descendant in descendants) + { + if (document.Resolve(descendant) is CosDictionary cidFont && _visited.Add(cidFont)) + { + AddFontProgram(cidFont); + } + } + } + + void AddFontProgram(CosDictionary dictionary) + { + if (Get(dictionary, Names.FontDescriptor) is not CosDictionary descriptor) + { + return; + } + + foreach (CosName key in (ReadOnlySpan)[Names.FontFile, Names.FontFile2, Names.FontFile3]) + { + if (descriptor.TryGetValue(key, out CosObject? program) && document.Resolve(program) is CosStream + && Visit(program, ObjectRole.FontProgram, page) is { } visit) + { + found.Add(visit); + } + } + } + } + + /// Names only this walk looks up. + private static class Names + { + public static readonly CosName Threads = new("Threads"); + public static readonly CosName StructTreeRoot = new("StructTreeRoot"); + public static readonly CosName K = new("K"); + public static readonly CosName DPartRoot = new("DPartRoot"); + public static readonly CosName DPartRootNode = new("DPartRootNode"); + public static readonly CosName DParts = new("DParts"); + public static readonly CosName FS = new("FS"); + public static readonly CosName ThreeDD = new("3DD"); + public static readonly CosName AP = new("AP"); + public static readonly CosName ColorSpace = new("ColorSpace"); + public static readonly CosName Font = new("Font"); + public static readonly CosName Pattern = new("Pattern"); + public static readonly CosName Shading = new("Shading"); + public static readonly CosName DescendantFonts = new("DescendantFonts"); + public static readonly CosName FontDescriptor = new("FontDescriptor"); + public static readonly CosName FontFile = new("FontFile"); + public static readonly CosName FontFile2 = new("FontFile2"); + public static readonly CosName FontFile3 = new("FontFile3"); + } +} diff --git a/src/Broadside/PdfAssociatedFile.cs b/src/Broadside/PdfAssociatedFile.cs new file mode 100644 index 00000000..a6530f63 --- /dev/null +++ b/src/Broadside/PdfAssociatedFile.cs @@ -0,0 +1,79 @@ +using Broadside.Objects; + +namespace Broadside; + +/// Where an associated file was found: the kind of object whose AF entry (or marked-content property list) lists it. +/// ISO 32000-2 §14.13.3-§14.13.9 and PDF 2.0 Application Note 002 §3.1 and §6.2 (the list of locations is open). +public enum PdfAssociatedFileLocation +{ + /// The document catalog: files associated with the whole document (§14.13.3). + Catalog, + + /// A page (§14.13.4). + Page, + + /// A form XObject (§14.13.7), including an annotation's appearance stream. + FormXObject, + + /// An image XObject (§14.13.7). + ImageXObject, + + /// An annotation (§14.13.9), including widgets and merged fields. + Annotation, + + /// The structure tree root (Table 354). + StructureTreeRoot, + + /// A structure element (§14.13.6). + StructureElement, + + /// A document part (§14.13.8). + DocumentPart, + + /// A metadata stream (§14.13.1). + MetadataStream, + + /// A marked-content sequence: a property list in a Properties resource (§14.13.5, errata Table 409a). + MarkedContent, + + /// Any other object: found by a deep scan, or an object kind the walk does not classify (Application Note 002 §3.2). + Other, +} + +/// An associated file together with the object it is associated with. +/// ISO 32000-2 §14.13 (PDF 2.0) and PDF 2.0 Application Note 002. +public sealed class PdfAssociatedFile +{ + internal PdfAssociatedFile(PdfFileSpecification file, PdfAssociatedFileLocation location, CosObject owner, CosReference? ownerReference, int? pageIndex, string? propertyName) + { + File = file; + Location = location; + Owner = owner; + OwnerReference = ownerReference; + PageIndex = pageIndex; + PropertyName = propertyName; + } + + /// Gets the file specification of the associated file. + /// ISO 32000-2 §14.13.2 and §7.11.3. + public PdfFileSpecification File { get; } + + /// Gets the kind of object the file is associated with. + public PdfAssociatedFileLocation Location { get; } + + /// Gets the object whose AF entry lists the file: a dictionary or a stream, or for marked content the property list (a dictionary or an array). + public CosObject Owner { get; } + + /// Gets the indirect reference to , when it has one. + public CosReference? OwnerReference { get; } + + /// Gets the index of the page the owner was found under, or for document-level objects. + public int? PageIndex { get; } + + /// Gets, for , the property list's name in the Properties resource. + /// ISO 32000-2 §14.13.5: the name a /AF /name BDC operator uses. + public string? PropertyName { get; } + + /// + public override string ToString() => $"{Location}: {File.FileName}"; +} diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 9768d35e..4a53e34d 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -452,7 +452,7 @@ public PdfOptionalContentProperties? OptionalContent /// /// ISO 32000-2 §7.7.4, Table 32 (PDF 1.4), and §7.11.4. Read on every call. An entry whose value is not a file specification is /// skipped with a FileSpecificationInvalid diagnostic. Files attached only to annotations or associated files are not - /// listed here (PDF 2.0 Application Note 002 §6.2): see EnumerateAssociatedFiles. + /// listed here (PDF 2.0 Application Note 002 §6.2): see . /// public IReadOnlyList EmbeddedFiles { @@ -487,6 +487,81 @@ public IReadOnlyList EmbeddedFiles ? new PdfCollection(this, dictionary, entry as CosReference) : null; + /// Gets the files associated with the whole document (the catalog's AF). + /// ISO 32000-2 §7.7.2, Table 29 (PDF 2.0), and §14.13.3. Read on every call. + public IReadOnlyList AssociatedFiles => ReadAssociatedFiles(Catalog, CatalogReference); + + /// Returns the associated files listed in the AF entry of . + /// Any dictionary or stream dictionary of this document: a structure element, an annotation, a form field. + /// The owner's indirect reference, for diagnostics. + /// The file specifications, in order. + /// + /// ISO 32000-2 §14.13.2 (PDF 2.0): AF is an array of file specification dictionaries. A single dictionary is read as an + /// array of one and a file specification string is accepted, both with an AssociatedFilesInvalid diagnostic. An embedded + /// associated file without Subtype, or with Params but no ModDate, is reported. A missing + /// AFRelationship means Unspecified and is not reported. + /// + public IReadOnlyList ReadAssociatedFiles(CosDictionary owner, CosReference? ownerReference = null) + { + ArgumentNullException.ThrowIfNull(owner); + return owner.TryGetValue(FileAndLayerNames.AF, out CosObject? value) ? AssociatedFileReader.Read(this, value, ownerReference) : []; + } + + /// Returns the associated files of a marked-content sequence, from the property list of its /AF tag. + /// The property list operand of /AF ... BDC, resolved from the Properties resource, or a reference to it. + /// The file specifications. + /// + /// ISO 32000-2 §14.13.5 and errata Table 409a: a property list dictionary whose MCAF array lists the files (each shall + /// have AFRelationship), or, as in the original text's Example 2, a resource that is the array itself. Both are accepted. + /// + public IReadOnlyList ReadMarkedContentAssociatedFiles(CosObject? properties) => + AssociatedFileReader.ReadMarkedContent(this, properties, properties as CosReference); + + /// Enumerates every associated file of the document with the object it is associated with. + /// + /// walks the known locations: the catalog and its metadata, the structure tree, document parts, and every + /// page with its resources (form and image XObjects, marked-content property lists, recursively through forms) and annotations. + /// also scans every object of the file for an AF entry (Application Note 002 §3.2: AF may appear on + /// any object), reporting those as . + /// + /// A lazy sequence; each object is reported once. Nothing is cached. + /// ISO 32000-2 §14.13 and PDF 2.0 Application Note 002 §6.2. + public IEnumerable EnumerateAssociatedFiles(bool deep = false) => AssociatedFileReader.Enumerate(this, deep); + + /// Enumerates every object-level metadata stream of the document with the object it describes. + /// + /// walks the locations Application Note 003 lists: the catalog, optional content groups, threads, + /// structure elements, document parts, embedded files, pages, XObjects, ICC profiles, embedded font programs, Type 3 fonts, tiling + /// patterns, shadings, marked-content property lists, annotations and 3D artwork. also scans every object + /// of the file for a Metadata entry, reporting those as . + /// + /// A lazy sequence; each object is reported once. Nothing is cached. + /// + /// ISO 32000-2 §14.3.2 (PDF 1.4), Tables 347 and 348, and PDF 2.0 Application Note 003. A metadata stream without Type + /// Metadata and Subtype XML is still reported, with a MetadataStreamInvalid diagnostic. + /// + public IEnumerable EnumerateObjectMetadata(bool deep = false) => AssociatedFileReader.EnumerateMetadata(this, deep); + + /// Gets the catalog's indirect reference, from the trailer. + internal CosReference? CatalogReference => Trailer.TryGetValue(KnownNames.Root, out CosObject? root) ? root as CosReference : null; + + /// Enumerates the reference of every object the cross-reference information lists as in use, by object number. + internal IEnumerable EnumerateObjectReferences() + { + foreach (KeyValuePair entry in _loader.CrossReference.Entries.OrderBy(entry => entry.Key)) + { + switch (entry.Value.Kind) + { + case XrefEntryKind.InUse: + yield return new CosReference(entry.Key, entry.Value.Generation); + break; + case XrefEntryKind.Compressed: + yield return new CosReference(entry.Key, 0); + break; + } + } + } + /// Returns a view over a file specification held by , resolving it first. /// A file specification string or dictionary, or a reference to one, of this document. /// The view, or when the value is neither a string nor a dictionary. diff --git a/src/Broadside/PdfObjectMetadata.cs b/src/Broadside/PdfObjectMetadata.cs new file mode 100644 index 00000000..9e5c7c4f --- /dev/null +++ b/src/Broadside/PdfObjectMetadata.cs @@ -0,0 +1,110 @@ +using Broadside.Objects; + +namespace Broadside; + +/// The kind of object a metadata stream describes. +/// ISO 32000-2 §14.3.2, Table 348, and PDF 2.0 Application Note 003 Tables 1-5 and "Other locations". +public enum PdfMetadataLocation +{ + /// The whole document: the catalog's Metadata (Table 29). + Document, + + /// A page (Table 31). + Page, + + /// An ICC profile stream of an ICCBased colour space (Table 65). + IccProfile, + + /// An image XObject (Table 87). + ImageXObject, + + /// A form XObject (Table 93). + FormXObject, + + /// An article thread (Table 162, PDF 2.0). + Thread, + + /// A document part (Table 409, PDF 2.0). + DocumentPart, + + /// An embedded font program stream (FontFile, FontFile2, FontFile3), not the font or its descriptor (Application Note 003 Table 2). + FontProgram, + + /// A Type 3 font dictionary (Application Note 003, other locations). + Type3Font, + + /// A tiling pattern stream (Application Note 003 Table 3). + TilingPattern, + + /// A shading dictionary or stream, not a shading pattern (Application Note 003 Table 4). + Shading, + + /// A marked-content property list in a Properties resource (§14.3.2). + MarkedContent, + + /// A structure element (§14.7.2, Table 355; Application Note 003 Table 5). + StructureElement, + + /// An embedded file stream (Table 44; Application Note 003, other locations). + EmbeddedFile, + + /// An annotation (Application Note 003, other locations). + Annotation, + + /// An optional content group (Application Note 003, other locations). + OptionalContentGroup, + + /// A 3D artwork stream (Application Note 003, other locations). + ThreeD, + + /// Any other object: found by a deep scan (§14.3.2 NOTE 2). + Other, +} + +/// A metadata stream attached to an object, together with that object. +/// +/// ISO 32000-2 §14.3.2 (PDF 1.4), Tables 347 and 348: a stream with Type Metadata and Subtype XML holding +/// an XMP packet (ISO 16684-1), in the Metadata entry of the object it describes. PDF 2.0 Application Note 003. +/// +public sealed class PdfObjectMetadata +{ + private readonly PdfDocument _document; + + internal PdfObjectMetadata(PdfDocument document, CosStream stream, CosReference? reference, PdfMetadataLocation location, CosObject owner, CosReference? ownerReference, int? pageIndex) + { + _document = document; + Stream = stream; + Reference = reference; + Location = location; + Owner = owner; + OwnerReference = ownerReference; + PageIndex = pageIndex; + } + + /// Gets the metadata stream. + /// ISO 32000-2 §14.3.2, Table 347. + public CosStream Stream { get; } + + /// Gets the indirect reference to the metadata stream, when it has one. + public CosReference? Reference { get; } + + /// Gets the kind of object the metadata describes. + public PdfMetadataLocation Location { get; } + + /// Gets the object whose Metadata entry holds the stream: a dictionary or a stream. + public CosObject Owner { get; } + + /// Gets the indirect reference to , when it has one. + public CosReference? OwnerReference { get; } + + /// Gets the index of the page the owner was found under, or for document-level objects. + public int? PageIndex { get; } + + /// Returns the XMP packet: the stream data decoded through its filters. + /// The decoded bytes. + /// ISO 32000-2 §14.3.2. Nothing is cached. + public ReadOnlyMemory Decode() => _document.DecodeStream(Stream); + + /// + public override string ToString() => Location.ToString(); +} diff --git a/src/Broadside/PdfPage.cs b/src/Broadside/PdfPage.cs index b7d9ae5b..65f798fa 100644 --- a/src/Broadside/PdfPage.cs +++ b/src/Broadside/PdfPage.cs @@ -73,6 +73,10 @@ internal PdfPage(PdfDocument document, CosDictionary dictionary, CosReference? r /// ISO 32000-2 §7.7.3.3, Table 31 (PDF 1.6). public double UserUnit => ReadUserUnit(out double value) == PageAttributeState.Valid ? value : 1.0; + /// Gets the files associated with the page (AF). + /// ISO 32000-2 §7.7.3.3, Table 31 (PDF 2.0), and §14.13.4. Read on every call; see . + public IReadOnlyList AssociatedFiles => _document.ReadAssociatedFiles(Dictionary, Reference); + /// Reads a page boundary; for an inheritable one, from the nearest node that has it. internal PageAttributeState ReadBox(CosName key, bool inheritable, out PdfRectangle box) { diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index 129dc950..e1f8b0e8 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -65,6 +65,25 @@ Broadside.Objects.CosString.CosString(System.ReadOnlySpan bytes, bool hexa Broadside.Objects.CosString.DecodeText() -> string! Broadside.Objects.CosString.Equals(Broadside.Objects.CosString? other) -> bool Broadside.Objects.CosString.IsHexadecimal.get -> bool +Broadside.PdfAssociatedFile +Broadside.PdfAssociatedFile.File.get -> Broadside.PdfFileSpecification! +Broadside.PdfAssociatedFile.Location.get -> Broadside.PdfAssociatedFileLocation +Broadside.PdfAssociatedFile.Owner.get -> Broadside.Objects.CosObject! +Broadside.PdfAssociatedFile.OwnerReference.get -> Broadside.Objects.CosReference? +Broadside.PdfAssociatedFile.PageIndex.get -> int? +Broadside.PdfAssociatedFile.PropertyName.get -> string? +Broadside.PdfAssociatedFileLocation +Broadside.PdfAssociatedFileLocation.Annotation = 4 -> Broadside.PdfAssociatedFileLocation +Broadside.PdfAssociatedFileLocation.Catalog = 0 -> Broadside.PdfAssociatedFileLocation +Broadside.PdfAssociatedFileLocation.DocumentPart = 7 -> Broadside.PdfAssociatedFileLocation +Broadside.PdfAssociatedFileLocation.FormXObject = 2 -> Broadside.PdfAssociatedFileLocation +Broadside.PdfAssociatedFileLocation.ImageXObject = 3 -> Broadside.PdfAssociatedFileLocation +Broadside.PdfAssociatedFileLocation.MarkedContent = 9 -> Broadside.PdfAssociatedFileLocation +Broadside.PdfAssociatedFileLocation.MetadataStream = 8 -> Broadside.PdfAssociatedFileLocation +Broadside.PdfAssociatedFileLocation.Other = 10 -> Broadside.PdfAssociatedFileLocation +Broadside.PdfAssociatedFileLocation.Page = 1 -> Broadside.PdfAssociatedFileLocation +Broadside.PdfAssociatedFileLocation.StructureElement = 6 -> Broadside.PdfAssociatedFileLocation +Broadside.PdfAssociatedFileLocation.StructureTreeRoot = 5 -> Broadside.PdfAssociatedFileLocation Broadside.PdfCheckSumStatus Broadside.PdfCheckSumStatus.Absent = 0 -> Broadside.PdfCheckSumStatus Broadside.PdfCheckSumStatus.DoesNotMatch = 2 -> Broadside.PdfCheckSumStatus @@ -160,10 +179,15 @@ Broadside.PdfCollectionView.Details = 0 -> Broadside.PdfCollectionView Broadside.PdfCollectionView.Hidden = 2 -> Broadside.PdfCollectionView Broadside.PdfCollectionView.Navigator = 3 -> Broadside.PdfCollectionView Broadside.PdfCollectionView.Tile = 1 -> Broadside.PdfCollectionView +Broadside.PdfDocument.AssociatedFiles.get -> System.Collections.Generic.IReadOnlyList! Broadside.PdfDocument.Collection.get -> Broadside.PdfCollection? Broadside.PdfDocument.EmbeddedFiles.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfDocument.EnumerateAssociatedFiles(bool deep = false) -> System.Collections.Generic.IEnumerable! +Broadside.PdfDocument.EnumerateObjectMetadata(bool deep = false) -> System.Collections.Generic.IEnumerable! Broadside.PdfDocument.GetFileSpecification(Broadside.Objects.CosObject? value) -> Broadside.PdfFileSpecification? Broadside.PdfDocument.OptionalContent.get -> Broadside.PdfOptionalContentProperties? +Broadside.PdfDocument.ReadAssociatedFiles(Broadside.Objects.CosDictionary! owner, Broadside.Objects.CosReference? ownerReference = null) -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfDocument.ReadMarkedContentAssociatedFiles(Broadside.Objects.CosObject? properties) -> System.Collections.Generic.IReadOnlyList! Broadside.PdfEmbeddedFile Broadside.PdfEmbeddedFile.Decode() -> System.ReadOnlyMemory Broadside.PdfEmbeddedFile.Decode(System.Buffers.IBufferWriter! output) -> void @@ -217,7 +241,34 @@ Broadside.PdfFileSpecification.RelationshipName.get -> Broadside.Objects.CosName Broadside.PdfFileSpecification.SafeFileName.get -> string? Broadside.PdfFileSpecification.Thumbnail.get -> Broadside.Objects.CosStream? Broadside.PdfFileSpecification.Value.get -> Broadside.Objects.CosObject! +Broadside.PdfMetadataLocation +Broadside.PdfMetadataLocation.Annotation = 14 -> Broadside.PdfMetadataLocation +Broadside.PdfMetadataLocation.Document = 0 -> Broadside.PdfMetadataLocation +Broadside.PdfMetadataLocation.DocumentPart = 6 -> Broadside.PdfMetadataLocation +Broadside.PdfMetadataLocation.EmbeddedFile = 13 -> Broadside.PdfMetadataLocation +Broadside.PdfMetadataLocation.FontProgram = 7 -> Broadside.PdfMetadataLocation +Broadside.PdfMetadataLocation.FormXObject = 4 -> Broadside.PdfMetadataLocation +Broadside.PdfMetadataLocation.IccProfile = 2 -> Broadside.PdfMetadataLocation +Broadside.PdfMetadataLocation.ImageXObject = 3 -> Broadside.PdfMetadataLocation +Broadside.PdfMetadataLocation.MarkedContent = 11 -> Broadside.PdfMetadataLocation +Broadside.PdfMetadataLocation.OptionalContentGroup = 15 -> Broadside.PdfMetadataLocation +Broadside.PdfMetadataLocation.Other = 17 -> Broadside.PdfMetadataLocation +Broadside.PdfMetadataLocation.Page = 1 -> Broadside.PdfMetadataLocation +Broadside.PdfMetadataLocation.Shading = 10 -> Broadside.PdfMetadataLocation +Broadside.PdfMetadataLocation.StructureElement = 12 -> Broadside.PdfMetadataLocation +Broadside.PdfMetadataLocation.Thread = 5 -> Broadside.PdfMetadataLocation +Broadside.PdfMetadataLocation.ThreeD = 16 -> Broadside.PdfMetadataLocation +Broadside.PdfMetadataLocation.TilingPattern = 9 -> Broadside.PdfMetadataLocation +Broadside.PdfMetadataLocation.Type3Font = 8 -> Broadside.PdfMetadataLocation Broadside.PdfNameDictionary.EmbeddedFiles.get -> Broadside.PdfNameTree? +Broadside.PdfObjectMetadata +Broadside.PdfObjectMetadata.Decode() -> System.ReadOnlyMemory +Broadside.PdfObjectMetadata.Location.get -> Broadside.PdfMetadataLocation +Broadside.PdfObjectMetadata.Owner.get -> Broadside.Objects.CosObject! +Broadside.PdfObjectMetadata.OwnerReference.get -> Broadside.Objects.CosReference? +Broadside.PdfObjectMetadata.PageIndex.get -> int? +Broadside.PdfObjectMetadata.Reference.get -> Broadside.Objects.CosReference? +Broadside.PdfObjectMetadata.Stream.get -> Broadside.Objects.CosStream! Broadside.PdfOptionalContentBaseState Broadside.PdfOptionalContentBaseState.Off = 1 -> Broadside.PdfOptionalContentBaseState Broadside.PdfOptionalContentBaseState.On = 0 -> Broadside.PdfOptionalContentBaseState @@ -315,6 +366,7 @@ Broadside.PdfOptionalContentUsageContext.UserNames.get -> System.Collections.Gen Broadside.PdfOptionalContentUsageContext.UserNames.init -> void Broadside.PdfOptionalContentUsageContext.Zoom.get -> double? Broadside.PdfOptionalContentUsageContext.Zoom.init -> void +Broadside.PdfPage.AssociatedFiles.get -> System.Collections.Generic.IReadOnlyList! Broadside.PdfRelatedFile Broadside.PdfRelatedFile.File.get -> Broadside.PdfEmbeddedFile! Broadside.PdfRelatedFile.Name.get -> string! @@ -352,6 +404,7 @@ override Broadside.Objects.CosReference.GetHashCode() -> int override Broadside.Objects.CosStream.IsDirty.get -> bool override Broadside.Objects.CosString.Equals(object? obj) -> bool override Broadside.Objects.CosString.GetHashCode() -> int +override Broadside.PdfAssociatedFile.ToString() -> string! override Broadside.PdfCollectionColor.Equals(object? obj) -> bool override Broadside.PdfCollectionColor.GetHashCode() -> int override Broadside.PdfCollectionColor.ToString() -> string! @@ -361,6 +414,7 @@ override Broadside.PdfCollectionIdRange.Equals(object? obj) -> bool override Broadside.PdfCollectionIdRange.GetHashCode() -> int override Broadside.PdfCollectionIdRange.ToString() -> string! override Broadside.PdfEmbeddedFileEntry.ToString() -> string! +override Broadside.PdfObjectMetadata.ToString() -> string! override Broadside.PdfOptionalContentConfiguration.ToString() -> string! override Broadside.PdfOptionalContentGroup.ToString() -> string! override Broadside.PdfOptionalContentOrderItem.ToString() -> string! diff --git a/tests/Broadside.TestSupport/Corpus.cs b/tests/Broadside.TestSupport/Corpus.cs index ab81c0bc..e6a0de0f 100644 --- a/tests/Broadside.TestSupport/Corpus.cs +++ b/tests/Broadside.TestSupport/Corpus.cs @@ -45,6 +45,8 @@ public static class Corpus "optional-content.pdf", "embedded-files.pdf", "collection-portfolio.pdf", + "associated-files.pdf", + "object-metadata.pdf", ]; private static readonly string[] Malformed = diff --git a/tests/Broadside.Tests/Files/AssociatedFileTests.cs b/tests/Broadside.Tests/Files/AssociatedFileTests.cs new file mode 100644 index 00000000..7a6c4549 --- /dev/null +++ b/tests/Broadside.Tests/Files/AssociatedFileTests.cs @@ -0,0 +1,142 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Tests.Document; +using Broadside.TestSupport; + +namespace Broadside.Tests.Files; + +/// Associated files at every location ISO 32000-2 §14.13 and PDF 2.0 Application Note 002 list. +public class AssociatedFileTests +{ + [Fact] + public void Enumeration_finds_each_associated_file_with_its_location() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("associated-files.pdf")); + + var found = document.EnumerateAssociatedFiles().Select(file => (file.Location, file.File.FileName, file.File.Relationship)).ToList(); + + Assert.Equal( + [ + (PdfAssociatedFileLocation.Catalog, "source.txt", PdfFileRelationship.Source), + (PdfAssociatedFileLocation.MetadataStream, "schema.xsd", PdfFileRelationship.Schema), + (PdfAssociatedFileLocation.StructureTreeRoot, "tree.txt", PdfFileRelationship.Alternative), + (PdfAssociatedFileLocation.StructureElement, "element.txt", PdfFileRelationship.Alternative), + (PdfAssociatedFileLocation.DocumentPart, "part.txt", PdfFileRelationship.Source), + (PdfAssociatedFileLocation.Page, "page-data.csv", PdfFileRelationship.Data), + (PdfAssociatedFileLocation.FormXObject, "equation.mml", PdfFileRelationship.Supplement), + (PdfAssociatedFileLocation.ImageXObject, "image-data.csv", PdfFileRelationship.Data), + (PdfAssociatedFileLocation.MarkedContent, "marked.csv", PdfFileRelationship.Data), + (PdfAssociatedFileLocation.MarkedContent, "marked-legacy.txt", PdfFileRelationship.Supplement), + (PdfAssociatedFileLocation.Annotation, "annotation.txt", PdfFileRelationship.Unspecified), + ], + found); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Each_associated_file_knows_its_owner_and_page() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("associated-files.pdf")); + + List files = [.. document.EnumerateAssociatedFiles()]; + + PdfAssociatedFile form = files.Single(file => file.Location == PdfAssociatedFileLocation.FormXObject); + Assert.Equal(new CosReference(11, 0), form.OwnerReference); + Assert.IsType(form.Owner); + Assert.Equal(0, form.PageIndex); + Assert.Equal("application/mathml+xml", form.File.EmbeddedFile!.Subtype); + Assert.Null(files.Single(file => file.Location == PdfAssociatedFileLocation.Catalog).PageIndex); + Assert.Equal("MF1", files.First(file => file.Location == PdfAssociatedFileLocation.MarkedContent).PropertyName); + } + + [Fact] + public void A_deep_scan_also_finds_associated_files_in_unlisted_places() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>", + "<< /Type /Custom /AF [5 0 R] >>", + "<< /Type /Filespec /F (hidden.txt) /AFRelationship /Data >>"); + using PdfDocument document = PdfDocument.Open(file); + + Assert.Empty(document.EnumerateAssociatedFiles()); + PdfAssociatedFile found = Assert.Single(document.EnumerateAssociatedFiles(deep: true)); + Assert.Equal(PdfAssociatedFileLocation.Other, found.Location); + Assert.Equal(new CosReference(4, 0), found.OwnerReference); + Assert.Equal("hidden.txt", found.File.FileName); + } + + [Fact] + public void Catalog_and_page_accessors_read_AF_directly() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("associated-files.pdf")); + + Assert.Equal("source.txt", Assert.Single(document.AssociatedFiles).FileName); + Assert.Equal("page-data.csv", Assert.Single(document.Pages[0].AssociatedFiles).FileName); + var annotation = (CosDictionary)document.Resolve(new CosReference(5, 0)); + Assert.Equal("annotation.txt", Assert.Single(document.ReadAssociatedFiles(annotation)).FileName); + } + + [Fact] + public void A_marked_content_property_list_gives_its_files_from_MCAF_or_a_bare_array() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("associated-files.pdf")); + var properties = (CosDictionary)document.Resolve(document.Pages[0].Resources![new CosName("Properties")]); + + Assert.Equal("marked.csv", Assert.Single(document.ReadMarkedContentAssociatedFiles(properties[new CosName("MF1")])).FileName); + Assert.Equal("marked-legacy.txt", Assert.Single(document.ReadMarkedContentAssociatedFiles(properties[new CosName("MF2")])).FileName); + } + + [Theory] + [MemberData(nameof(MalformedAssociatedFiles))] + public void A_malformed_AF_entry_is_repaired_with_a_diagnostic(string pageEntries, string[] extraObjects, string expectedCode, int expectedFiles) + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build( + [ + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + $"<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] {pageEntries} >>", + .. extraObjects, + ])); + + Assert.Equal(expectedFiles, document.Pages[0].AssociatedFiles.Count); + Assert.Contains(expectedCode, document.Diagnostics.Select(diagnostic => diagnostic.Code)); + } + + public static TheoryData MalformedAssociatedFiles => new() + { + { "/AF 4 0 R", ["<< /Type /Filespec /F (single.txt) >>"], "AssociatedFilesInvalid", 1 }, + { "/AF [(plain.txt)]", [], "AssociatedFilesInvalid", 1 }, + { "/AF [42]", [], "AssociatedFilesInvalid", 0 }, + { "/AF [4 0 R]", ["<< /Type /Filespec /F (a.txt) /EF << /F 5 0 R >> >>", "<< /Params << /ModDate (D:2024) >> /Length 1 >>\nstream\nx\nendstream"], "EmbeddedFileSubtypeMissing", 1 }, + { "/AF [4 0 R]", ["<< /Type /Filespec /F (a.txt) /EF << /F 5 0 R >> >>", "<< /Subtype /text#2Fplain /Params << /Size 1 >> /Length 1 >>\nstream\nx\nendstream"], "EmbeddedFileParamsInvalid", 1 }, + }; + + [Fact] + public void Strict_mode_throws_for_an_AF_entry_that_is_not_an_array() + { + using PdfDocument document = PdfDocument.Open( + TestPdf.OnePage("/MediaBox [0 0 612 792] /AF << /F (x.txt) >>"), + new PdfOptions().UseStrict()); + + DiagnosticException exception = Assert.Throws(() => document.Pages[0].AssociatedFiles); + Assert.Equal("AssociatedFilesInvalid", exception.Diagnostic.Code); + } + + [Fact] + public void Reading_associated_files_leaves_every_object_clean() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("associated-files.pdf")); + + foreach (PdfAssociatedFile file in document.EnumerateAssociatedFiles(deep: true)) + { + _ = (file.File.FileName, file.File.EmbeddedFile?.Parameters?.ModificationDate); + } + + for (int number = 1; number <= 32; number++) + { + Assert.False(document.Resolve(new CosReference(number, 0)).IsDirty); + } + } +} diff --git a/tests/Broadside.Tests/Files/ObjectMetadataTests.cs b/tests/Broadside.Tests/Files/ObjectMetadataTests.cs new file mode 100644 index 00000000..fb4800bf --- /dev/null +++ b/tests/Broadside.Tests/Files/ObjectMetadataTests.cs @@ -0,0 +1,104 @@ +using System.Xml.Linq; +using Broadside.Objects; +using Broadside.Tests.Document; +using Broadside.TestSupport; + +namespace Broadside.Tests.Files; + +/// Metadata streams at the object-level locations of ISO 32000-2 §14.3.2 and PDF 2.0 Application Note 003. +public class ObjectMetadataTests +{ + private static readonly XNamespace Dc = "http://purl.org/dc/elements/1.1/"; + + private static string Title(PdfObjectMetadata metadata) => + XDocument.Parse(System.Text.Encoding.UTF8.GetString(metadata.Decode().Span).TrimStart('').Split("?>", 2)[1].Split(" (metadata.Location, Title(metadata))).ToList(); + + Assert.Equal( + [ + (PdfMetadataLocation.Document, "Document"), + (PdfMetadataLocation.OptionalContentGroup, "Optional content"), + (PdfMetadataLocation.EmbeddedFile, "Embedded file"), + (PdfMetadataLocation.Page, "Page"), + (PdfMetadataLocation.ImageXObject, "Image"), + (PdfMetadataLocation.FormXObject, "Form"), + (PdfMetadataLocation.IccProfile, "ICC profile"), + (PdfMetadataLocation.FontProgram, "Font program"), + (PdfMetadataLocation.TilingPattern, "Tiling pattern"), + (PdfMetadataLocation.Shading, "Shading"), + (PdfMetadataLocation.MarkedContent, "Marked content"), + (PdfMetadataLocation.Annotation, "Annotation"), + ], + found); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Each_metadata_stream_knows_its_owner() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("object-metadata.pdf")); + + PdfObjectMetadata font = document.EnumerateObjectMetadata().Single(metadata => metadata.Location == PdfMetadataLocation.FontProgram); + + Assert.Equal(new CosReference(13, 0), font.OwnerReference); + Assert.Equal(0, font.PageIndex); + Assert.IsType(font.Owner); + Assert.Equal(new CosReference(45, 0), font.Reference); + } + + [Fact] + public void Structure_elements_threads_and_document_parts_carry_metadata_too() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 4 0 R /Threads [6 0 R] /DPartRoot 7 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>", + "<< /Type /StructTreeRoot /K [5 0 R] >>", + "<< /Type /StructElem /S /Document /P 4 0 R /Metadata 9 0 R >>", + "<< /Type /Thread /Metadata 9 0 R >>", + "<< /Type /DPartRoot /DPartRootNode 8 0 R >>", + "<< /Type /DPart /Parent 7 0 R /Metadata 9 0 R >>", + "<< /Type /Metadata /Subtype /XML /Length 3 >>\nstream\n\nendstream"); + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal( + [PdfMetadataLocation.Thread, PdfMetadataLocation.StructureElement, PdfMetadataLocation.DocumentPart], + document.EnumerateObjectMetadata().Select(metadata => metadata.Location)); + } + + [Fact] + public void A_deep_scan_finds_metadata_anywhere_else() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>", + "<< /Type /Custom /Metadata 5 0 R >>", + "<< /Type /Metadata /Subtype /XML /Length 3 >>\nstream\n\nendstream"); + using PdfDocument document = PdfDocument.Open(file); + + Assert.Empty(document.EnumerateObjectMetadata()); + PdfObjectMetadata found = Assert.Single(document.EnumerateObjectMetadata(deep: true)); + Assert.Equal((PdfMetadataLocation.Other, new CosReference(4, 0)), (found.Location, found.OwnerReference)); + } + + [Fact] + public void A_metadata_stream_without_Type_Metadata_and_Subtype_XML_is_reported() + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] /Metadata 4 0 R >>", + "<< /Length 3 >>\nstream\n\nendstream")); + + Assert.Single(document.EnumerateObjectMetadata()); + Assert.Equal(["MetadataStreamInvalid"], document.Diagnostics.Select(diagnostic => diagnostic.Code)); + } +} diff --git a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt index 4a978aa4..9d3357aa 100644 --- a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt +++ b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt @@ -2,6 +2,7 @@ annotations-link.pdf, ascii85-stream.pdf, asciihex-stream.pdf, + associated-files.pdf, broken-xref-offsets.pdf, collection-portfolio.pdf, embedded-files.pdf, @@ -35,6 +36,7 @@ name-tree-dests.pdf, no-xref.pdf, number-tree-deep.pdf, + object-metadata.pdf, object-stream.pdf, optional-content.pdf, outline.pdf, diff --git a/tests/Corpus/README.md b/tests/Corpus/README.md index ee28e3c3..90964978 100644 --- a/tests/Corpus/README.md +++ b/tests/Corpus/README.md @@ -69,6 +69,8 @@ Verification was run with qpdf 12.4.2 (`qpdf --check`), poppler (`pdfinfo`, `pdf | `optional-content.pdf` | `/OCProperties` with groups A, B (OFF in `D`), C (`/Intent /Design`) and D2 (`/Usage /View /ViewState /OFF`, no `AS`); OCMD `/OCGs [A B] /P /AllOff` and OCMD `/VE [/Or A [/Not B]]`; `/OC` sections `/a`, `/m1`, `/m2`, `/a` nested in `/b`; a form XObject with `/OC B`; a Square annotation with `/OC C`; `D` with `Order` (label and unlabelled nesting), `RBGroups`, `Locked`; one alternate configuration (`/BaseState /OFF /ON [C] /Intent /All`). Expected default: A ON, B OFF, C ON (no effect under View), D2 ON; sections a visible, m1 hidden, m2 visible, nested hidden, form hidden, annotation visible. | 8.11 | `qpdf --check`, `pdfinfo` | clean; one Letter page | | `embedded-files.pdf` | `/Names /EmbeddedFiles` with two file specifications: `hello.txt` (`/Subtype /text#2Fplain`, `Params` `Size 13`, `CreationDate`, `ModDate`, `CheckSum` = MD5 of the data) and `data.csv` (`UF` `dätä.csv` as UTF-16BE, `Desc`, Flate-encoded, `Subtype /text#2Fcsv`, `RF` with one related file `data.schema`). | 7.7.4, 7.11.3, 7.11.4 | `qpdf --check`, `qpdf --list-attachments --verbose`, `pdfdetach -list` | clean; qpdf shows preferred name `dätä.csv`, checksum `6cd3556deb0da54bca060b4c39479839`; pdfdetach lists `dätä.csv`, `hello.txt` | | `collection-portfolio.pdf` | Portable collection: `/Collection` with `View /D`, initial document `D (notes.txt)`, `Schema` (fields `name` S, `date` D, `pages` N with `V false`, `fname` F with `E true`, `size` Size, each with `O`), `Sort /S [/date /name] /A [false]`, `Colors`, `Split /V 30`, `Folders` root (ID 0, `Free [2 10]`) with one child (ID 1, `Reports`); EmbeddedFiles keys `<1>report.txt` and `notes.txt`; collection items with a subitem (`D`, `P`). | 7.11.6, 12.3.5 | `qpdf --check`, `pdfdetach -list` | clean; pdfdetach lists `report.txt`, `notes.txt` | +| `associated-files.pdf` | PDF 2.0 (trailer `ID`): `AF` on the catalog (`Source`, embedded `text/plain` with `Params` `ModDate`), the page (`Data`), a form XObject (`Supplement`, embedded `application/mathml+xml`), an image XObject (`Data`), a Square annotation (no `AFRelationship`), the structure tree root and a `Document` structure element (`Alternative`), a `DPart` (`Source`), the catalog metadata stream (`Schema`); marked content `/AF /MF1 BDC` with an `MCAF` property list (errata Table 409a) and `/AF /MF2 BDC` whose resource is the bare array (§14.13.5 Example 2). | 14.13, 7.11.3 | `qpdf --check`, `pdfinfo` | clean; one Letter page | +| `object-metadata.pdf` | `Metadata` streams (each XMP packet with its own `dc:title`) on the catalog, a page, an image XObject, a form XObject, an ICCBased colour space stream, an embedded TrueType program (`FontFile2`, `minimal_truetype()`), a tiling pattern, a shading dictionary, a marked-content property list, an optional content group, a Square annotation and an embedded file stream. | 14.3.2 | `qpdf --check`, `pdfinfo`, `pdftotext` | clean; `pdftotext` prints `HI` | The crypt filter `/Length` entries in the R4 and R6 files are `16` and `32` (bytes), the form Acrobat and qpdf write and that Table 25 describes for the standard security handler; the same table also says the key "shall have the value of 128/256". Readers should accept both forms. diff --git a/tests/Corpus/associated-files.pdf b/tests/Corpus/associated-files.pdf new file mode 100644 index 0000000000000000000000000000000000000000..1a37e774f022c345c8f9fe7f073240d1c892655d GIT binary patch literal 4008 zcmcIn+m72d5PkPo5Do&QC~QiU@30;0+UsPIIN7dKBO()N zzt9OnCG=uJ?wEtmp9x)wVjqYP1?RU}CP=T^GQaT)Aq9g)h;H&IxUJ5M<=%l4@tu67Vt?1LCc!C|Y4WXZ$G zzswHg4!!ERjP!>Lf|_NifNdq|paB&z!h;dZ*vL?=q-h5G?z(F6mY3PS2mmaM>(l%7 z7aj=tyhw;ERSxH2%nWx*gwWmp2Eg^0eX5D9(D)2-N% zK^HfaqTqhgz(j!xmt4+gu-8HC;jiFiL#~#y<2sY;6#ScKQvR(I(z~sIgxQNu$-bJ-|-rEn;!!I;hzptojE;C7~oBpSAdqN~Yc#*XSG4 zhdsyqC^DSMgNsioxQaOhw1P}#!9GDc(3>N1r7JS)x+_RxQ`4E?6(5l6@3N39UYwmk zo;-2%#6(peD***VRNAl7@c1bGQRF%+l|^J~Jr&p)_D{>V3R_u~0JLI>H-qHm40TF2c>|cD_)1;BC^}36YN|y}!S2-+S$>*iv^m98!l- z##*qWRX(J`KeW>F8LFss%y}6UQ7)n^C8*P1XL~VeHkINqIO)yzMJ%<30p*ZstYhl7 zUFi>K3xkn}M9insw~JU*4{?O5MzNo6C(T1E-iComZZ{TPMNeOy9c^Ju%nRt!Bf&WaT<3zp~ndlc|jh5rDq zMxwmo#VkwmEXCp*D3Z!b(45se*`H5%r+4_}OxB6)$$H(&?qwplh+2h-I;IcP zz_gjAt{8@XRj--}Q}UBm?1^Mp$)VM1CbZYOewA@80DCAIs>@)<6Tf{Z!y}<|fu&w9 z>iF0r%TUi@kRl)3NfIjqHIZdvpXXH*)OlN7K9KQV^=R_e9(RTp5!QU2xR$W)Nu9a& zU^I**@=B;xh9UTYa#@XL-CreZ9)>(bBihwO@Pl~97J2MPshr7vQeEAaSqL6;@?t(> z4(m8B{K}s{0Qgn($l=C-w>LFX@#T2$s=A8ZvgAe1^y-O_TQT4I!GlK7Dsod^2Viy1 z^O>zOxu(JYfWZfrM1kZMppp1um&CuqJp5@$G$@#-VKGKs({U0_4`T|S@PPswoI}Ak z4TpGMqk bytes: ]) +def xmp_titled(title: bytes) -> bytes: + """A minimal XMP packet (14.3.2) whose dc:title is ``title``.""" + return XMP.replace(b">Broadside<", b">" + title + b"<") + + +def af_filespec(name: bytes, relationship: bytes | None, ef: int | None = None) -> bytes: + """7.11.3 file specification for an associated file (14.13): embedded when ``ef`` is given, else external.""" + body = b"<< /Type /Filespec /F (%s) /UF (%s)" % (name, name) + if relationship is not None: + body += b" /AFRelationship /" + relationship + if ef is not None: + body += b" /EF << /F %d 0 R /UF %d 0 R >>" % (ef, ef) + return body + b" >>" + + +def gen_associated_files() -> bytes: + """14.13 associated files at every location: catalog (Source, embedded), page (Data), form XObject + (Supplement, embedded application/mathml+xml), image XObject (Data), annotation (no AFRelationship: + Unspecified), structure tree root (Alternative), structure element (Alternative), DPart (Source), + metadata stream (Schema), marked content /AF /MF1 with an MCAF property list (errata Table 409a) and + /AF /MF2 with a bare array resource (14.13.5 Example 2). PDF 2.0 with a trailer ID (7.5.5).""" + id0 = file_id("associated-files").hex().encode() + content = b"/AF /MF1 BDC 0 0 10 10 re f EMC\n/AF /MF2 BDC /Fm Do EMC\nq 10 0 0 10 20 0 cm /Im Do Q\n" + return simple_file([ + (1, catalog(b" /AF [20 0 R] /StructTreeRoot 6 0 R /DPartRoot 8 0 R /Metadata 10 0 R /MarkInfo << /Marked true >>")), + (2, pages()), + (3, page(contents=4, resources=False, + extra=b" /AF [21 0 R] /DPart 9 0 R /Annots [5 0 R] /Resources << /XObject << /Fm 11 0 R /Im 12 0 R >>" + b" /Properties << /MF1 13 0 R /MF2 [31 0 R] >> >>")), + (4, stream(b"", content)), + (5, b"<< /Type /Annot /Subtype /Square /Rect [100 100 200 200] /AF [22 0 R] >>"), + (6, b"<< /Type /StructTreeRoot /K 7 0 R /AF [23 0 R] >>"), + (7, b"<< /Type /StructElem /S /Document /P 6 0 R /AF [24 0 R] >>"), + (8, b"<< /Type /DPartRoot /DPartRootNode 9 0 R >>"), + (9, b"<< /Type /DPart /Parent 8 0 R /Start 3 0 R /End 3 0 R /AF [25 0 R] >>"), + (10, stream(b"/Type /Metadata /Subtype /XML /AF [26 0 R]", XMP)), + (11, stream(b"/Type /XObject /Subtype /Form /BBox [0 0 10 10] /AF [27 0 R]", b"40 0 10 10 re f")), + (12, stream(b"/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /AF [28 0 R]", b"\x80")), + (13, b"<< /MCAF [29 0 R] >>"), + (20, af_filespec(b"source.txt", b"Source", ef=30)), + (21, af_filespec(b"page-data.csv", b"Data")), + (22, af_filespec(b"annotation.txt", None)), + (23, af_filespec(b"tree.txt", b"Alternative")), + (24, af_filespec(b"element.txt", b"Alternative")), + (25, af_filespec(b"part.txt", b"Source")), + (26, af_filespec(b"schema.xsd", b"Schema")), + (27, af_filespec(b"equation.mml", b"Supplement", ef=32)), + (28, af_filespec(b"image-data.csv", b"Data")), + (29, af_filespec(b"marked.csv", b"Data")), + (30, stream(b"/Type /EmbeddedFile /Subtype /text#2Fplain /Params << /ModDate (D:20240101000000Z) /Size 6 >>", b"source")), + (31, af_filespec(b"marked-legacy.txt", b"Supplement")), + (32, stream(b"/Type /EmbeddedFile /Subtype /application#2Fmathml+xml /Params << /ModDate (D:20240101000000Z) >>", + b"x")), + ], version="2.0", trailer_extra=b" /ID [<%s> <%s>]" % (id0, id0)) + + +def gen_object_metadata() -> bytes: + """14.3.2 and PDF 2.0 Application Note 003: a Metadata stream, each with a distinct dc:title, on the catalog + (Document), a page, an image XObject, a form XObject, an ICCBased colour space stream, an embedded TrueType + font program (FontFile2), a tiling pattern, a shading dictionary, a marked-content property list, an + optional content group, an annotation and an embedded file stream.""" + font, widths = minimal_truetype() + first, last = min(widths), max(widths) + w = b" ".join(b"%d" % widths[c] for c in range(first, last + 1)) + titles = [b"Document", b"Page", b"Image", b"Form", b"ICC profile", b"Font program", b"Tiling pattern", + b"Shading", b"Marked content", b"Optional content", b"Annotation", b"Embedded file"] + meta = {title: 40 + i for i, title in enumerate(titles)} + objects = [ + (1, catalog(b" /Metadata %d 0 R /OCProperties << /OCGs [15 0 R] /D << >> >>" + b" /Names << /EmbeddedFiles << /Names [(attached.txt) 16 0 R] >> >>" % meta[b"Document"])), + (2, pages()), + (3, page(contents=4, resources=False, + extra=b" /Metadata %d 0 R /Annots [14 0 R] /Resources << /XObject << /Im 5 0 R /Fm 6 0 R >>" + b" /ColorSpace << /CS0 [/ICCBased 7 0 R] >> /Font << /F1 8 0 R >> /Pattern << /P0 10 0 R >>" + b" /Shading << /Sh0 11 0 R >> /Properties << /MC0 12 0 R /OC0 15 0 R >> >>" % meta[b"Page"])), + (4, stream(b"", b"/Im Do /Fm Do /Span /MC0 BDC EMC /OC /OC0 BDC EMC BT /F1 24 Tf 72 700 Td (HI) Tj ET\n")), + (5, stream(b"/Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Metadata %d 0 R" + % meta[b"Image"], b"\x80")), + (6, stream(b"/Type /XObject /Subtype /Form /BBox [0 0 10 10] /Metadata %d 0 R" % meta[b"Form"], b"0 0 10 10 re f")), + (7, stream(b"/N 1 /Alternate /DeviceGray /Metadata %d 0 R" % meta[b"ICC profile"], b"ICC")), + (8, b"<< /Type /Font /Subtype /TrueType /BaseFont /BroadsideMinimal /FirstChar %d /LastChar %d " + b"/Widths [%s] /Encoding /WinAnsiEncoding /FontDescriptor 9 0 R >>" % (first, last, w)), + (9, b"<< /Type /FontDescriptor /FontName /BroadsideMinimal /Flags 32 /FontBBox [0 0 700 700] " + b"/ItalicAngle 0 /Ascent 800 /Descent -200 /CapHeight 700 /StemV 200 /FontFile2 13 0 R >>"), + (10, stream(b"/Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10" + b" /Resources << >> /Metadata %d 0 R" % meta[b"Tiling pattern"], b"0 0 5 5 re f")), + (11, b"<< /ShadingType 2 /ColorSpace /DeviceGray /Coords [0 0 1 0] /Function << /FunctionType 2 /Domain [0 1]" + b" /C0 [0] /C1 [1] /N 1 >> /Metadata %d 0 R >>" % meta[b"Shading"]), + (12, b"<< /Metadata %d 0 R >>" % meta[b"Marked content"]), + (13, stream(b"/Length1 %d /Metadata %d 0 R" % (len(font), meta[b"Font program"]), font)), + (14, b"<< /Type /Annot /Subtype /Square /Rect [100 100 200 200] /Metadata %d 0 R >>" % meta[b"Annotation"]), + (15, b"<< /Type /OCG /Name (Layer) /Metadata %d 0 R >>" % meta[b"Optional content"]), + (16, b"<< /Type /Filespec /F (attached.txt) /UF (attached.txt) /EF << /F 17 0 R /UF 17 0 R >> >>"), + (17, stream(b"/Type /EmbeddedFile /Subtype /text#2Fplain /Metadata %d 0 R" % meta[b"Embedded file"], b"attached")), + ] + objects += [(meta[title], stream(b"/Type /Metadata /Subtype /XML", xmp_titled(title))) for title in titles] + return simple_file(objects, binary=True) + + FILES = { "empty-page.pdf": gen_empty_page, "pdf20-header.pdf": gen_pdf20_header, @@ -1439,6 +1538,8 @@ def gen_collection_portfolio() -> bytes: "optional-content.pdf": gen_optional_content, "embedded-files.pdf": gen_embedded_files, "collection-portfolio.pdf": gen_collection_portfolio, + "associated-files.pdf": gen_associated_files, + "object-metadata.pdf": gen_object_metadata, } diff --git a/tests/Corpus/object-metadata.pdf b/tests/Corpus/object-metadata.pdf new file mode 100644 index 0000000000000000000000000000000000000000..eaa00a93c7a3621cb02d3bf76490e74fb11b7ca9 GIT binary patch literal 9881 zcmeHN&2J+~6|a2kiuDX1#}(pGco{S!P0}C!j*={i9d9DWlPEU3vkEKdbXV-2X?Hj6 zHgQHA=1)LK`~gTD_P{@YScxk)4shatR&e3Qg*`6e_o_eKb`R_91#@uAZTEZi>ec(I zSFfu5;H=f&(za`b2Y>tfAOBR)xXQiD=Y`!}uJmqv!Ih>F8jjcJ%9+s@Bd&wsoGTp> z8Wvi3S&a~<&9lJsMG)E`qTZ*?_eT6et5EYtTxk(hY zlD5X{a&$8B8SEzlS2mofT#LL!E!}}(*=}F9bO&gPM3$XqJ=kfYHMYblJx6lR`+!u8 zP05uf!tI9xUN4iaM`0k0VL^e4El=u4KTyhr$-wZi)#OK=CdCTfQ^a8p)Ed{zym!TG zu)3=9p2Z&?pFHBd=lrNwAV0?J<4_>sW<8o%S?P{1LmA5_L&PvwKCmswsBz_3*!=+o z20WUYTWN`(+NO9fFmAYVXosUS5j4G_@3|Bi^{lsJ<90l8jzVkAH* z_8jI_9RX2R$udW->B)G8SKR}5WKR*qza>UyVEdsL@CKwiCl%s=AviB>rh`HZC?CNi zc_AI6KjI|_NK{jgQK;gEWGBd*wt3+89f6UQgOMrY2ko$S1Z?R9H4Q%wMCz<`Los}x z%NAlysZr-zJ2Nx4k|XW!g#Pk8_fg3KsouldfSd2 z*8%$jfmQe~&0hij7;tp}#2bHI{~_Q{0e@#O3@2~?n*D*X^-aL{9nUn_cNzMwe*^GW zhQ`EaZ?LZcej6}%5$*SW@vW}{CjKA$-YA4zxYj?#7iSx5|62PwdNBMxCVcYC^av(g ze34%1b$H(DvhT5DcCx{5!Fz*~R8n{FSpOs?T*G+O^FG_ecnsg05;{QM^4?3^94fO*WoI3s4`TL9a^lZ$%@yaO7+ z`fQ9R1GJ0j^AxlEWc*~so_)@*BeH5rW|W-GQ9*^=n5^X8pNvtdQC)>H>Ow=_q??i^ zZp`jl0PC!MbOLII^}RFv|EPmCK8Jj(Ph&o3LY6rB}LRqpYn`NwW)fWQJ_LoUukICgD4J+jl76Wpt0L(Kzj7lTK1z=Z!B5`dR%_ zV@~b=tn(x-LP`xalg@VEouF!cAwqsB`nJ1Q{O9j}U*xv6SNx#TQ9FK94D92Vf#|+` z+B09iFdJ6!-TlJuWM?w;huBr{$k!Lf!*(+X?L38zSIlr}A zJQ@LAQf>ZNn6APWXny7b8z_i0&f=@GtB=Nc0 zBA+(0+wEzFUoEQnMHPn;+z-4f?39<_+I&5^(6!l9o0V&$O6c|V5}kmMZ~K9ufRVuz~Dvpk#xE~!=FJb29_g9O&TW_qYr#n_p@tNKd+?qdzUgXxsYSP|y(sqpC z1ztdz$ji&w#^#Uh7kW2)@UdEMzi7EV_31PnFJYGEUwK~lC6Ax7Zyi?t{UZO$_tFOW z_@jw|87_lapb-oL$f)5LX42SM-9KUc6eVlq&p+r#Sit0bSfpaT*Sf z=W%)&mDwC!rG{mF4p*aBZ*#bM4O{J59NrA%=rnp=Fi)qyrf<2L=U1&@UobaDUBkjO zkE`Tl)@y1WS64ALX8Y>(YR*=Aqn4wSy`sJuJEyv>aB4RG{(tOJQn8ho^LeRK&H1;i z>N&b{xsi*Za-*7y$x4~d{AGls^R3dLH%+s+Y6*FE9#_xvtCh;RxlpU)Pdamb>v~qc tFfec~6Ucv*b?uh|IRdZkJdgf%6aOJ&6dFM&Gf2Hws}vqQI67??{sTqcBm4jW literal 0 HcmV?d00001 From ceacfe36c34b7f90b35a65e83f55ee49f167ab37 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:34:49 -0500 Subject: [PATCH 027/152] feat(structure): structure tree, role maps, namespaces, attributes and marked content (#75) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Logical structure per ISO 32000-2 §14.6-§14.8 and ISO/TS 32005 §5-§6, in the new Broadside.Structure namespace: - PdfDocument.StructureTree (PdfStructureTreeRoot) and PdfDocument.MarkInfo. - Live element views (PdfStructureElement) with K children (elements, MCIDs/MCRs, OBJRs), effective page, language and phonetic alphabet. - Role resolution through RoleMap chains and RoleMapNS (name lands in the default 1.7 namespace, [name ns] in the named one), cycles legal, standard type sets for PDF 1.7, PDF 2.0 (Annex M, Hn) and MathML. - Attribute objects typed by owner (Layout, List, Table, PrintField, Artifact, UserProperties), revision numbers, ClassMap, A-over-C precedence, inheritance and defaults (errata Table 377). - Per-content-stream MCID index through the ParentTree (#70's number-tree reader), IDTree lookups (#70's name-tree reader), object content items via StructParent, each checked against K with a K-walk fallback. - Typed marked-content property lists (PdfPropertyList) for #56's events. - Repairs are diagnostics (lenient) or throws (strict): ParentTreeMissing, ParentTreeEntryInvalid, McidDuplicate, StructElemPageMissing, StructElemParentMismatch, IdTreeDuplicate/EntryInvalid, StructTreeCycle, StructTreeDepthExceeded, StructElemTypeUnknown, NamespaceNotDeclared, StructureTypeUnresolved, attribute and MarkInfo codes. New corpus file tagged-structure.pdf, fuzz target structure-tree, benchmark StructureTreeBenchmarks, conformance rows 14.6-14.8 split to third level and ISO/TS 32005 rows 4-6 updated. Co-Authored-By: Claude Opus 5.5 --- .../StructureTreeBenchmarks.cs | 85 ++++ docs/conformance/iso-32000-2.md | 18 +- docs/conformance/iso-ts-32005.md | 16 +- src/Broadside/Caching/OnceCache.cs | 9 +- .../Parsing/DiagnosticCodes.Structure.cs | 25 + src/Broadside/PdfDocument.cs | 50 ++ src/Broadside/PdfPageCollection.cs | 22 +- src/Broadside/PublicAPI.Unshipped.txt | 186 ++++++++ src/Broadside/Structure/AttributeReader.cs | 179 ++++++++ src/Broadside/Structure/KidReader.cs | 155 +++++++ src/Broadside/Structure/MarkedContentIndex.cs | 111 +++++ .../Structure/PdfArtifactAttributes.cs | 25 + src/Broadside/Structure/PdfAttributeObject.cs | 112 +++++ .../Structure/PdfLayoutAttributes.cs | 211 +++++++++ src/Broadside/Structure/PdfListAttributes.cs | 39 ++ src/Broadside/Structure/PdfMarkInfo.cs | 54 +++ .../Structure/PdfMarkedContentReference.cs | 62 +++ src/Broadside/Structure/PdfObjectReference.cs | 38 ++ .../Structure/PdfPrintFieldAttributes.cs | 30 ++ src/Broadside/Structure/PdfPropertyList.cs | 106 +++++ .../Structure/PdfStructureElement.cs | 433 ++++++++++++++++++ src/Broadside/Structure/PdfStructureItem.cs | 16 + .../Structure/PdfStructureNamespace.cs | 140 ++++++ .../Structure/PdfStructureNamespaceKind.cs | 18 + .../Structure/PdfStructureTreeRoot.cs | 196 ++++++++ src/Broadside/Structure/PdfStructureType.cs | 39 ++ src/Broadside/Structure/PdfTableAttributes.cs | 68 +++ .../Structure/PdfUserPropertiesAttributes.cs | 48 ++ src/Broadside/Structure/PdfUserProperty.cs | 36 ++ src/Broadside/Structure/RoleResolver.cs | 119 +++++ src/Broadside/Structure/StandardAttributes.cs | 77 ++++ .../Structure/StandardStructureTypes.cs | 61 +++ src/Broadside/Structure/StructureContext.cs | 209 +++++++++ src/Broadside/Structure/StructureNames.cs | 77 ++++ .../StructureNamespaceSuppression.cs | 8 + src/Broadside/Structure/StructureValues.cs | 68 +++ src/Broadside/Structure/StructureWalk.cs | 161 +++++++ tests/Broadside.Fuzz/FuzzTargets.cs | 1 + tests/Broadside.Fuzz/README.md | 2 +- tests/Broadside.Fuzz/StructureTree.cs | 153 +++++++ tests/Broadside.TestSupport/Corpus.cs | 1 + .../LogicalStructure/AttributeTests.cs | 185 ++++++++ .../LogicalStructure/ContentItemTests.cs | 141 ++++++ .../LogicalStructure/RoleMappingTests.cs | 190 ++++++++ ..._summary_matches_the_snapshot.verified.txt | 19 + ...file_yields_the_expected_tree.verified.txt | 36 ++ .../LogicalStructure/StructureCorpusTests.cs | 114 +++++ .../LogicalStructure/StructureProjection.cs | 120 +++++ .../LogicalStructure/StructureRepairTests.cs | 249 ++++++++++ .../LogicalStructure/StructureWalker.cs | 68 +++ .../LogicalStructure/TaggedPdf.cs | 54 +++ .../TaggedStructureCorpusTests.cs | 220 +++++++++ ...pus_file_names_match_snapshot.verified.txt | 1 + tests/Corpus/README.md | 1 + tests/Corpus/generate.py | 62 +++ tests/Corpus/tagged-structure.pdf | Bin 0 -> 4518 bytes 56 files changed, 4910 insertions(+), 14 deletions(-) create mode 100644 bench/Broadside.Benchmarks/StructureTreeBenchmarks.cs create mode 100644 src/Broadside/Parsing/DiagnosticCodes.Structure.cs create mode 100644 src/Broadside/Structure/AttributeReader.cs create mode 100644 src/Broadside/Structure/KidReader.cs create mode 100644 src/Broadside/Structure/MarkedContentIndex.cs create mode 100644 src/Broadside/Structure/PdfArtifactAttributes.cs create mode 100644 src/Broadside/Structure/PdfAttributeObject.cs create mode 100644 src/Broadside/Structure/PdfLayoutAttributes.cs create mode 100644 src/Broadside/Structure/PdfListAttributes.cs create mode 100644 src/Broadside/Structure/PdfMarkInfo.cs create mode 100644 src/Broadside/Structure/PdfMarkedContentReference.cs create mode 100644 src/Broadside/Structure/PdfObjectReference.cs create mode 100644 src/Broadside/Structure/PdfPrintFieldAttributes.cs create mode 100644 src/Broadside/Structure/PdfPropertyList.cs create mode 100644 src/Broadside/Structure/PdfStructureElement.cs create mode 100644 src/Broadside/Structure/PdfStructureItem.cs create mode 100644 src/Broadside/Structure/PdfStructureNamespace.cs create mode 100644 src/Broadside/Structure/PdfStructureNamespaceKind.cs create mode 100644 src/Broadside/Structure/PdfStructureTreeRoot.cs create mode 100644 src/Broadside/Structure/PdfStructureType.cs create mode 100644 src/Broadside/Structure/PdfTableAttributes.cs create mode 100644 src/Broadside/Structure/PdfUserPropertiesAttributes.cs create mode 100644 src/Broadside/Structure/PdfUserProperty.cs create mode 100644 src/Broadside/Structure/RoleResolver.cs create mode 100644 src/Broadside/Structure/StandardAttributes.cs create mode 100644 src/Broadside/Structure/StandardStructureTypes.cs create mode 100644 src/Broadside/Structure/StructureContext.cs create mode 100644 src/Broadside/Structure/StructureNames.cs create mode 100644 src/Broadside/Structure/StructureNamespaceSuppression.cs create mode 100644 src/Broadside/Structure/StructureValues.cs create mode 100644 src/Broadside/Structure/StructureWalk.cs create mode 100644 tests/Broadside.Fuzz/StructureTree.cs create mode 100644 tests/Broadside.Tests/LogicalStructure/AttributeTests.cs create mode 100644 tests/Broadside.Tests/LogicalStructure/ContentItemTests.cs create mode 100644 tests/Broadside.Tests/LogicalStructure/RoleMappingTests.cs create mode 100644 tests/Broadside.Tests/LogicalStructure/Snapshots/StructureCorpusTests.Every_real_world_structure_tree_walks_leniently_and_the_summary_matches_the_snapshot.verified.txt create mode 100644 tests/Broadside.Tests/LogicalStructure/Snapshots/TaggedStructureCorpusTests.The_tagged_file_yields_the_expected_tree.verified.txt create mode 100644 tests/Broadside.Tests/LogicalStructure/StructureCorpusTests.cs create mode 100644 tests/Broadside.Tests/LogicalStructure/StructureProjection.cs create mode 100644 tests/Broadside.Tests/LogicalStructure/StructureRepairTests.cs create mode 100644 tests/Broadside.Tests/LogicalStructure/StructureWalker.cs create mode 100644 tests/Broadside.Tests/LogicalStructure/TaggedPdf.cs create mode 100644 tests/Broadside.Tests/LogicalStructure/TaggedStructureCorpusTests.cs create mode 100644 tests/Corpus/tagged-structure.pdf diff --git a/bench/Broadside.Benchmarks/StructureTreeBenchmarks.cs b/bench/Broadside.Benchmarks/StructureTreeBenchmarks.cs new file mode 100644 index 00000000..28243784 --- /dev/null +++ b/bench/Broadside.Benchmarks/StructureTreeBenchmarks.cs @@ -0,0 +1,85 @@ +using System.Globalization; +using System.Text; +using BenchmarkDotNet.Attributes; +using Broadside.Structure; +using Broadside.TestSupport; + +namespace Broadside.Benchmarks; + +/// +/// Builds the per-page MCID index of a tagged page (ISO 32000-2 §14.7.5.4): open the file from memory, read the structure tree root +/// and map every MCID of page 1 to its element through the page's StructParents parent-tree entry, checking each against the +/// element's K. This is what text extraction and the layout tree pay once per page. Mcids 10 is the corpus file +/// tagged-structure.pdf; 1000 and 10000 are synthetic pages with one paragraph element per 10 MCIDs. Building the index +/// allocates (one dictionary per page, one view per element), so Allocated is a baseline to watch, not a zero to assert. +/// +[MemoryDiagnoser] +public class StructureTreeBenchmarks +{ + private byte[] _bytes = []; + + /// The number of MCIDs on the page. + [Params(10, 1000, 10000)] + public int Mcids { get; set; } + + [GlobalSetup] + public void Setup() => _bytes = Mcids == 10 + ? File.ReadAllBytes(Path.Combine(CorpusLocator.CorpusDirectory, "tagged-structure.pdf")) + : TaggedPage(Mcids); + + [Benchmark] + public int BuildPageMcidIndex() + { + using PdfDocument document = PdfDocument.Open(_bytes); + PdfStructureTreeRoot root = document.StructureTree!; + return root.GetMarkedContentElements(document.Pages[0]).Count; + } + + /// One page whose parent tree lists MCIDs, ten per paragraph element. + private static byte[] TaggedPage(int mcids) + { + int paragraphs = mcids / 10; + var objects = new List + { + "<< /Type /Catalog /Pages 2 0 R /MarkInfo << /Marked true >> /StructTreeRoot 4 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] /StructParents 0 >>", + }; + var kids = new StringBuilder(); + var parents = new StringBuilder(); + for (int index = 0; index < paragraphs; index++) + { + kids.Append(CultureInfo.InvariantCulture, $"{6 + index} 0 R "); + for (int item = 0; item < 10; item++) + { + parents.Append(CultureInfo.InvariantCulture, $"{6 + index} 0 R "); + } + } + + objects.Add($"<< /Type /StructTreeRoot /K [5 0 R] /ParentTree << /Nums [0 [{parents}]] >> /ParentTreeNextKey 1 >>"); + objects.Add($"<< /Type /StructElem /S /Document /P 4 0 R /K [{kids}] >>"); + for (int index = 0; index < paragraphs; index++) + { + string items = string.Join(' ', Enumerable.Range(index * 10, 10)); + objects.Add($"<< /Type /StructElem /S /P /P 5 0 R /Pg 3 0 R /K [{items}] >>"); + } + + var text = new StringBuilder("%PDF-2.0\n"); + var offsets = new List(); + for (int index = 0; index < objects.Count; index++) + { + offsets.Add(text.Length); + text.Append(CultureInfo.InvariantCulture, $"{index + 1} 0 obj\n{objects[index]}\nendobj\n"); + } + + int xref = text.Length; + text.Append(CultureInfo.InvariantCulture, $"xref\n0 {objects.Count + 1}\n0000000000 65535 f \n"); + foreach (int offset in offsets) + { + text.Append(CultureInfo.InvariantCulture, $"{offset:D10} 00000 n \n"); + } + + text.Append(CultureInfo.InvariantCulture, $"trailer\n<< /Size {objects.Count + 1} /Root 1 0 R /ID [<00> <00>] >>\nstartxref\n{xref}\n%%EOF\n"); + return Encoding.Latin1.GetBytes(text.ToString()); + } +} diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index f18429c5..ca81b8eb 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -120,9 +120,21 @@ Clause numbers at the second level; split rows to the third level as clauses are | 14.3 | Metadata | not started | | | | | 14.4 | File identifiers | partial | `FileWriter` | `Broadside.Tests.Writing.SaveTests.Saving_twice_writes_the_same_bytes_and_keeps_the_first_file_identifier`, `Broadside.Tests.Writing.SaveTests.A_file_without_identifiers_gets_two_equal_ones_when_saved`, `Broadside.Tests.Writing.CreateTests.A_saved_created_document_reopens_with_two_equal_file_identifiers` | written on save: the first identifier is kept, the second is the first 16 bytes of SHA-256 of the bytes before the cross-reference information (deterministic; MD5 is unavailable on browser-wasm); a file without identifiers gets two equal ones; incremental updates are Phase 4 | | 14.5 | Page-piece dictionaries | not started | | | | -| 14.6 | Marked content | not started | | | | -| 14.7 | Logical structure | not started | | | | -| 14.8 | Tagged PDF | not started | | | | +| 14.6.1 | General | partial | `PdfPropertyList` | `Broadside.Tests.LogicalStructure.ContentItemTests.A_property_list_is_typed_for_mcid_artifacts_and_span_entries`, `Broadside.Tests.LogicalStructure.TaggedStructureCorpusTests.Every_marked_content_sequence_of_the_page_maps_to_the_element_tagged_like_it_through_the_parent_tree` | Tags defined in 2.0 (errata Table 352a) typed for Artifact and Span; the operators MP/DP/BMC/BDC/EMC, their nesting and stream scope are the content interpreter's (#56), OC and AF tags #76's | +| 14.6.2 | Property lists | partial | `PdfPropertyList` | `Broadside.Tests.LogicalStructure.ContentItemTests.A_property_list_is_typed_for_mcid_artifacts_and_span_entries` | Typed view of a resolved property list (MCID, artifact entries, Lang/Alt/ActualText/E); resolving the inline-dictionary or /Properties-name form is the content interpreter's (#56) | +| 14.7.1 | General | done | `PdfMarkInfo` | `Broadside.Tests.LogicalStructure.TaggedStructureCorpusTests.Mark_information_says_the_document_is_tagged`, `Broadside.Tests.LogicalStructure.StructureRepairTests.Mark_information_that_is_not_boolean_reads_false_with_a_diagnostic`, `Broadside.Tests.LogicalStructure.StructureRepairTests.An_untagged_document_has_no_structure_tree_and_no_diagnostic` | Table 353; non-boolean entries read false with `MarkInfoInvalid` | +| 14.7.2 | Structure hierarchy | done | `PdfStructureTreeRoot`, `PdfStructureElement`, `PdfStructureItem` | `Broadside.Tests.LogicalStructure.TaggedStructureCorpusTests.The_tagged_file_yields_the_expected_tree`, `Broadside.Tests.LogicalStructure.TaggedStructureCorpusTests.Lookups_return_elements_that_know_their_parents`, `Broadside.Tests.LogicalStructure.StructureRepairTests.A_damaged_tree_is_read_with_exactly_one_kind_of_diagnostic`, `Broadside.Tests.LogicalStructure.StructureRepairTests.A_cycle_through_k_is_cut_so_a_recursive_walk_of_the_children_ends`, `Broadside.Tests.LogicalStructure.StructureRepairTests.A_hierarchy_deeper_than_the_limit_is_cut_with_a_diagnostic`, `Broadside.Tests.LogicalStructure.StructureRepairTests.A_k_dictionary_without_type_is_read_by_what_it_holds`, `Broadside.Tests.LogicalStructure.StructureCorpusTests.Every_real_world_structure_tree_walks_leniently_and_the_summary_matches_the_snapshot` | Tables 354-355; corpus `tagged-structure.pdf`. Tree shape from K (P mismatch, cycles, depth 256, Type repairs are diagnostics); IDTree through #70's name-tree reader with K-walk fallback; PronunciationLexicon and AF exposed as COS until #76 types them. Fuzz target `structure-tree` | +| 14.7.3 | Structure types | done | `PdfStructureType`, `PdfStructureElement` | `Broadside.Tests.LogicalStructure.RoleMappingTests.The_role_map_is_followed_as_a_chain_and_maps_even_standard_types`, `Broadside.Tests.LogicalStructure.RoleMappingTests.A_role_map_cycle_ends_the_chain_at_the_first_standard_type_after_the_start` | RoleMap followed as a chain, standard types mapped too, cycles legal (NOTE 2); pdf.js and PDFBox apply one step | +| 14.7.4 | Namespaces | done | `PdfStructureNamespace`, `PdfStructureNamespaceKind` | `Broadside.Tests.LogicalStructure.RoleMappingTests.A_namespace_role_map_lands_a_name_in_the_default_namespace_and_an_array_in_the_named_namespace`, `Broadside.Tests.LogicalStructure.RoleMappingTests.Two_namespace_dictionaries_with_a_standard_name_are_the_same_namespace`, `Broadside.Tests.LogicalStructure.TaggedStructureCorpusTests.Role_mapping_follows_the_root_role_map_and_the_custom_namespace_role_map` | 14.7.4.1-14.7.4.2, Table 356; Schema exposed as COS until #76 types file specifications | +| 14.7.5 | Structure content | done | `PdfMarkedContentReference`, `PdfObjectReference`, `PdfStructureTreeRoot` | `Broadside.Tests.LogicalStructure.ContentItemTests.Mcids_are_scoped_to_their_content_stream_so_a_form_and_its_page_both_have_mcid_0`, `Broadside.Tests.LogicalStructure.ContentItemTests.An_mcr_page_overrides_the_element_page_and_an_objr_falls_back_to_the_annotation_page`, `Broadside.Tests.LogicalStructure.ContentItemTests.An_mcid_with_no_page_anywhere_takes_the_page_whose_parent_tree_entry_lists_its_element`, `Broadside.Tests.LogicalStructure.TaggedStructureCorpusTests.Every_marked_content_sequence_of_the_page_maps_to_the_element_tagged_like_it_through_the_parent_tree`, `Broadside.Tests.LogicalStructure.TaggedStructureCorpusTests.The_link_annotation_finds_its_paragraph_through_its_struct_parent`, `Broadside.Tests.LogicalStructure.StructureRepairTests.The_parent_tree_finds_an_element_the_root_does_not_reach`, `Broadside.Tests.LogicalStructure.TaggedStructureCorpusTests.Concurrent_first_lookups_build_each_index_once_and_agree` | 14.7.5.1-14.7.5.4, Tables 357-359. MCID index per content stream (page or form StructParents) through #70's number-tree reader, built once per stream, each entry checked against the element's K, K-walk fallback with `ParentTreeMissing`/`ParentTreeEntryInvalid`. Benchmark `StructureTreeBenchmarks` | +| 14.7.6 | Structure attributes | done | `PdfAttributeObject`, `PdfUserPropertiesAttributes`, `PdfUserProperty` | `Broadside.Tests.LogicalStructure.AttributeTests.Revision_numbers_follow_the_object_or_class_they_belong_to_and_later_entries_win`, `Broadside.Tests.LogicalStructure.AttributeTests.A_legacy_attribute_stream_is_read_through_its_dictionary`, `Broadside.Tests.LogicalStructure.AttributeTests.An_attribute_object_owned_by_a_namespace_or_another_owner_is_read_generically`, `Broadside.Tests.LogicalStructure.AttributeTests.List_table_print_field_artifact_and_user_property_attributes_are_typed` | 14.7.6.1-14.7.6.4, Tables 360-362; A over C, later over earlier, revisions attach to the preceding object | +| 14.7.7 | Example of logical structure | n/a | | | Informative example; `tagged-structure.pdf` exercises the same constructs (ParentTree, IDTree, RoleMap, ClassMap) | +| 14.8.1 | General | partial | `PdfMarkInfo`, `PdfStructureElement` | `Broadside.Tests.LogicalStructure.RoleMappingTests.An_unresolved_type_in_an_untagged_document_is_not_a_diagnostic`, `Broadside.Tests.LogicalStructure.RoleMappingTests.An_element_without_ns_is_in_the_pdf_1_7_namespace_even_in_a_pdf_2_0_file` | Tagged PDF is recognised (Marked) and an unresolved type in it is `StructureTypeUnresolved`; full tagged-PDF conformance checking is PDF/UA validation (later phase) | +| 14.8.2 | Tagged PDF and page content | partial | `PdfPropertyList` | `Broadside.Tests.LogicalStructure.ContentItemTests.A_property_list_is_typed_for_mcid_artifacts_and_span_entries` | 14.8.2.2.2 artifact property lists typed (Table 363); K order exposed as logical order (14.8.2.5); soft hyphens, hidden content, reverse-order show strings and Unicode mapping are text extraction (Phase 5) | +| 14.8.3 | Basic layout model | not started | | | Consumed by the layout tree (Phase 5); the layout attributes themselves are 14.8.5.4 | +| 14.8.4 | Standard structure types | partial | `PdfStructureNamespace`, `PdfStructureType` | `Broadside.Tests.LogicalStructure.RoleMappingTests.Standard_types_differ_between_the_pdf_1_7_and_pdf_2_0_namespaces`, `Broadside.Tests.LogicalStructure.RoleMappingTests.Mathml_elements_are_standard_in_their_own_namespace_without_a_role_map` | Tables 364-375 and Annex M type sets (Hn for n >= 1 in 2.0, H1-H6 in 1.7); nesting rules (14.8.4.2, Annex L) are not validated (PDF/UA work) | +| 14.8.5 | Standard structure attributes | partial | `PdfLayoutAttributes`, `PdfListAttributes`, `PdfTableAttributes`, `PdfPrintFieldAttributes`, `PdfArtifactAttributes`, `PdfStructureElement` | `Broadside.Tests.LogicalStructure.AttributeTests.Layout_attributes_are_typed`, `Broadside.Tests.LogicalStructure.AttributeTests.List_table_print_field_artifact_and_user_property_attributes_are_typed`, `Broadside.Tests.LogicalStructure.AttributeTests.Inheritable_attributes_pass_through_every_ancestor_and_others_stop_at_the_element`, `Broadside.Tests.LogicalStructure.TaggedStructureCorpusTests.Attributes_resolve_with_a_over_c_inheritance_and_defaults` | Tables 376-385 with errata Table 377; inheritance and defaults through `GetAttributeValue`. Missing: format owners (14.8.5.3 step 1), element-dependent defaults (Placement, Color, computed Scope), TextDecorationType's ILSE-only inheritance, the Table 371 header algorithm | +| 14.8.6 | Standard structure namespaces | done | `PdfStructureNamespace`, `PdfStructureElement` | `Broadside.Tests.LogicalStructure.RoleMappingTests.An_element_without_ns_is_in_the_pdf_1_7_namespace_even_in_a_pdf_2_0_file`, `Broadside.Tests.LogicalStructure.RoleMappingTests.A_name_landing_in_the_default_namespace_continues_through_the_root_role_map`, `Broadside.Tests.LogicalStructure.RoleMappingTests.Mathml_elements_are_standard_in_their_own_namespace_without_a_role_map`, `Broadside.Tests.LogicalStructure.StructureRepairTests.A_damaged_tree_is_read_with_exactly_one_kind_of_diagnostic` | 14.8.6.1-14.8.6.3: default namespace PDF 1.7 even in 2.0 files; root RoleMap for the default namespace only; namespace not in Namespaces is `NamespaceNotDeclared`; MathML names not checked against the MathML schema | | 14.9 | Repurposing and accessibility support | not started | | | | | 14.10 | Web capture | not started | | | | | 14.11.1 | General | n/a | | | Introductory text | diff --git a/docs/conformance/iso-ts-32005.md b/docs/conformance/iso-ts-32005.md index 440698ec..453c8b6c 100644 --- a/docs/conformance/iso-ts-32005.md +++ b/docs/conformance/iso-ts-32005.md @@ -4,13 +4,13 @@ Clause titles verified against the document's table of contents. Split rows to d | Clause | Title | Status | Implementing types | Tests | Notes | |---|---|---|---|---|---| -| 4 | Declaration of conformance | not started | | | | -| 5.1 | Using the PDF 1.7 namespace with PDF 2.0: general | not started | | | | -| 5.2 | PDF 1.7 as a standalone namespace | not started | | | | -| 5.3 | Elements defined in both namespaces | not started | | | | -| 5.4 | Elements defined solely in the PDF 2.0 namespace | not started | | | | -| 5.5 | Elements defined solely in the PDF 1.7 namespace | not started | | | | -| 5.6 | Role mapping | not started | | | | -| 6 | Attributes (owners, namespaces) | not started | | | | +| 4 | Declaration of conformance | not started | | | The declaration URI `https://pdfa.org/declarations#iso32005` lives in the XMP PDF Declarations, which #76 reads; nothing here checks it | +| 5.1 | Using the PDF 1.7 namespace with PDF 2.0: general | partial | `PdfStructureNamespace` | `Broadside.Tests.LogicalStructure.RoleMappingTests.An_element_without_ns_is_in_the_pdf_1_7_namespace_even_in_a_pdf_2_0_file` | Both namespaces read in one document; the PDF 2.0 version requirement is not checked (validator work) | +| 5.2 | PDF 1.7 as a standalone namespace | partial | `PdfStructureNamespace`, `PdfStructureType` | `Broadside.Tests.LogicalStructure.RoleMappingTests.The_role_map_is_followed_as_a_chain_and_maps_even_standard_types` | Elements in or mapped to the default namespace resolve to 1.7 types; the exemption is a validator rule | +| 5.3 | Elements defined in both namespaces | partial | `PdfStructureNamespace` | `Broadside.Tests.LogicalStructure.RoleMappingTests.Standard_types_differ_between_the_pdf_1_7_and_pdf_2_0_namespaces` | Common types are standard in both; the "shall use the PDF 2.0 namespace" rule is not checked | +| 5.4 | Elements defined solely in the PDF 2.0 namespace | partial | `PdfStructureNamespace` | `Broadside.Tests.LogicalStructure.RoleMappingTests.Standard_types_differ_between_the_pdf_1_7_and_pdf_2_0_namespaces` | 2.0-only types (Annex M) are standard only in the 2.0 namespace | +| 5.5 | Elements defined solely in the PDF 1.7 namespace | partial | `PdfStructureNamespace` | `Broadside.Tests.LogicalStructure.RoleMappingTests.Standard_types_differ_between_the_pdf_1_7_and_pdf_2_0_namespaces` | Tables 2-3 (Art, BlockQuote, TOC, TOCI, Index, Private, Quote, Note, Reference, BibEntry, Code) are standard only in the 1.7 namespace | +| 5.6 | Role mapping | partial | `PdfStructureElement`, `PdfStructureType` | `Broadside.Tests.LogicalStructure.RoleMappingTests.A_namespace_role_map_lands_a_name_in_the_default_namespace_and_an_array_in_the_named_namespace` | RoleMap and RoleMapNS resolution done; "custom types shall have an explicit namespace" is a TS conformance rule left to a validator, not a reading diagnostic | +| 6 | Attributes (owners, namespaces) | partial | `PdfAttributeObject` | `Broadside.Tests.LogicalStructure.AttributeTests.An_attribute_object_owned_by_a_namespace_or_another_owner_is_read_generically` | Owners and NSO namespaces read on any element; restricting attributes to element types (6.2) is validator work | | 7 | Parent-child relationships between standard structure elements | not started | | | | | Annex | Hierarchical inclusion rules tables | not started | | | | diff --git a/src/Broadside/Caching/OnceCache.cs b/src/Broadside/Caching/OnceCache.cs index 01a1a4a7..4a3d2b84 100644 --- a/src/Broadside/Caching/OnceCache.cs +++ b/src/Broadside/Caching/OnceCache.cs @@ -40,7 +40,14 @@ namespace Broadside.Caching; internal sealed class OnceCache where TKey : notnull { - private readonly ConcurrentDictionary _entries = new(); + private readonly ConcurrentDictionary _entries; + + /// Creates an empty cache comparing keys with their default equality. + public OnceCache() => _entries = new(); + + /// Creates an empty cache comparing keys with (for instance by reference, for COS containers). + /// The key comparer. + public OnceCache(IEqualityComparer comparer) => _entries = new(comparer); /// Returns the cached value for , when one has been computed. /// The key. diff --git a/src/Broadside/Parsing/DiagnosticCodes.Structure.cs b/src/Broadside/Parsing/DiagnosticCodes.Structure.cs new file mode 100644 index 00000000..ee0a8317 --- /dev/null +++ b/src/Broadside/Parsing/DiagnosticCodes.Structure.cs @@ -0,0 +1,25 @@ +namespace Broadside.Parsing; + +/// Diagnostic codes of the logical structure and tagged PDF views (ISO 32000-2 §14.6-§14.8, issue #75). +internal static partial class DiagnosticCodes +{ + public const string MarkInfoInvalid = nameof(MarkInfoInvalid); + public const string StructTreeRootInvalid = nameof(StructTreeRootInvalid); + public const string StructElemInvalid = nameof(StructElemInvalid); + public const string StructElemTypeUnknown = nameof(StructElemTypeUnknown); + public const string StructElemParentMismatch = nameof(StructElemParentMismatch); + public const string StructElemPageMissing = nameof(StructElemPageMissing); + public const string StructTreeCycle = nameof(StructTreeCycle); + public const string StructTreeDepthExceeded = nameof(StructTreeDepthExceeded); + public const string ParentTreeMissing = nameof(ParentTreeMissing); + public const string ParentTreeEntryInvalid = nameof(ParentTreeEntryInvalid); + public const string McidDuplicate = nameof(McidDuplicate); + public const string IdTreeDuplicate = nameof(IdTreeDuplicate); + public const string IdTreeEntryInvalid = nameof(IdTreeEntryInvalid); + public const string NamespaceInvalid = nameof(NamespaceInvalid); + public const string NamespaceNotDeclared = nameof(NamespaceNotDeclared); + public const string StructureTypeUnresolved = nameof(StructureTypeUnresolved); + public const string AttributeObjectInvalid = nameof(AttributeObjectInvalid); + public const string AttributeOwnerInvalid = nameof(AttributeOwnerInvalid); + public const string AttributeRevisionInvalid = nameof(AttributeRevisionInvalid); +} diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index da14fec4..a38e3cc7 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -6,6 +6,7 @@ using Broadside.Objects; using Broadside.Parsing; using Broadside.Security; +using Broadside.Structure; using Broadside.Writing; namespace Broadside; @@ -57,6 +58,7 @@ public sealed class PdfDocument : IDisposable private readonly StreamDecoder _streams; private readonly ConditionalWeakTable _nameTrees = []; private readonly ConditionalWeakTable _numberTrees = []; + private StructureContext? _structure; private PdfDocument( PdfSource source, @@ -186,6 +188,54 @@ public PdfNameDictionary? Names /// ISO 32000-2 §7.6.4.2, Table 22, and §7.6.5.2, Table 24. Readers are expected to respect them; PDF does not enforce them. public PdfPermissions Permissions => Security?.Permissions ?? PdfPermissions.All; + /// Gets the document's mark information: whether it is a tagged PDF () and which conventions it uses. + /// ISO 32000-2 §7.7.2, Table 29 (MarkInfo), §14.7.1, Table 353. Never : without the dictionary every flag is false. + public PdfMarkInfo MarkInfo => new(this); + + /// Gets the root of the document's structure tree, or when the document has none. + /// + /// ISO 32000-2 §7.7.2, Table 29 (StructTreeRoot), §14.7.2. Read when first asked for; an untagged document has no structure + /// tree and no diagnostic. A StructTreeRoot that is not a dictionary is ignored with a StructTreeRootInvalid diagnostic. + /// The views share indexes built on first use (see ); they are rebuilt when the catalog's + /// StructTreeRoot entry is replaced. + /// + public PdfStructureTreeRoot? StructureTree + { + get + { + if (!Catalog.TryGetValue(StructureNames.StructTreeRoot, out CosObject? value)) + { + return null; + } + + CosReference? reference = value as CosReference; + if (Resolve(value) is not CosDictionary root) + { + if (Resolve(value) is not CosNull) + { + _diagnostics.Report(DiagnosticCodes.StructTreeRootInvalid, DiagnosticSeverity.Warning, "The catalog's StructTreeRoot is not a dictionary (Table 29); the document is read without a structure tree.", offset: null, reference); + } + + return null; + } + + StructureContext? current = Volatile.Read(ref _structure); + if (current is null || !ReferenceEquals(current.Root, root)) + { + if (root.TryGetValue(KnownNames.Type, out CosObject? type) && !StructureNames.StructTreeRoot.Equals(Resolve(type))) + { + _diagnostics.Report(DiagnosticCodes.StructTreeRootInvalid, DiagnosticSeverity.Warning, "The structure tree root's Type is not StructTreeRoot (Table 354); read as the root.", offset: null, reference); + } + + var created = new StructureContext(this, root, reference); + StructureContext? previous = Interlocked.CompareExchange(ref _structure, created, current); + current = ReferenceEquals(previous, current) ? created : previous!; + } + + return new PdfStructureTreeRoot(current); + } + } + /// Gets the deviations found so far, in the order they were found. Empty for a well-formed file. /// /// ADR 0005. A snapshot: objects load lazily, so reading more of the document can add diagnostics, which a later call returns. diff --git a/src/Broadside/PdfPageCollection.cs b/src/Broadside/PdfPageCollection.cs index 18ea55a5..929a5c1f 100644 --- a/src/Broadside/PdfPageCollection.cs +++ b/src/Broadside/PdfPageCollection.cs @@ -1,4 +1,6 @@ using System.Collections; +using System.Diagnostics.CodeAnalysis; +using Broadside.Objects; namespace Broadside; @@ -11,9 +13,13 @@ namespace Broadside; public sealed class PdfPageCollection : IReadOnlyList { private readonly Lazy> _pages; + private readonly Lazy> _byObject; - internal PdfPageCollection(Func> walk) => + internal PdfPageCollection(Func> walk) + { _pages = new Lazy>(walk, LazyThreadSafetyMode.ExecutionAndPublication); + _byObject = new Lazy>(IndexPages, LazyThreadSafetyMode.ExecutionAndPublication); + } /// Gets the number of pages. public int Count => _pages.Value.Count; @@ -29,4 +35,18 @@ internal PdfPageCollection(Func> walk) => /// IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + /// Finds the page whose page object is (by identity), for references such as a structure element's Pg. + internal bool TryGetPage(CosDictionary pageObject, [MaybeNullWhen(false)] out PdfPage page) => _byObject.Value.TryGetValue(pageObject, out page); + + private Dictionary IndexPages() + { + var index = new Dictionary(ReferenceEqualityComparer.Instance); + foreach (PdfPage page in _pages.Value) + { + index.TryAdd(page.Dictionary, page); + } + + return index; + } } diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index feb3fcc7..8f43c317 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -426,3 +426,189 @@ Broadside.PdfNumberTree.Root.get -> Broadside.Objects.CosDictionary! Broadside.PdfNumberTree.RootReference.get -> Broadside.Objects.CosReference? Broadside.PdfNumberTree.TryGetFloor(int key, out int floorKey, out Broadside.Objects.CosObject! value) -> bool Broadside.PdfNumberTree.TryGetValue(int key, out Broadside.Objects.CosObject! value) -> bool +Broadside.PdfDocument.MarkInfo.get -> Broadside.Structure.PdfMarkInfo! +Broadside.PdfDocument.StructureTree.get -> Broadside.Structure.PdfStructureTreeRoot? +Broadside.Structure.PdfArtifactAttributes +Broadside.Structure.PdfArtifactAttributes.ArtifactSubtype.get -> string? +Broadside.Structure.PdfArtifactAttributes.ArtifactType.get -> string? +Broadside.Structure.PdfArtifactAttributes.BoundingBox.get -> Broadside.PdfRectangle? +Broadside.Structure.PdfAttributeObject +Broadside.Structure.PdfAttributeObject.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Structure.PdfAttributeObject.GetValue(Broadside.Objects.CosName! name) -> Broadside.Objects.CosObject? +Broadside.Structure.PdfAttributeObject.Namespace.get -> Broadside.Structure.PdfStructureNamespace? +Broadside.Structure.PdfAttributeObject.Owner.get -> Broadside.Objects.CosName? +Broadside.Structure.PdfAttributeObject.Reference.get -> Broadside.Objects.CosReference? +Broadside.Structure.PdfAttributeObject.Revision.get -> int +Broadside.Structure.PdfAttributeObject.Stream.get -> Broadside.Objects.CosStream? +Broadside.Structure.PdfLayoutAttributes +Broadside.Structure.PdfLayoutAttributes.BackgroundColor.get -> System.Collections.Generic.IReadOnlyList? +Broadside.Structure.PdfLayoutAttributes.BaselineShift.get -> double? +Broadside.Structure.PdfLayoutAttributes.BlockAlign.get -> string? +Broadside.Structure.PdfLayoutAttributes.BorderStyle.get -> System.Collections.Generic.IReadOnlyList? +Broadside.Structure.PdfLayoutAttributes.BorderThickness.get -> System.Collections.Generic.IReadOnlyList? +Broadside.Structure.PdfLayoutAttributes.BoundingBox.get -> Broadside.PdfRectangle? +Broadside.Structure.PdfLayoutAttributes.Color.get -> System.Collections.Generic.IReadOnlyList? +Broadside.Structure.PdfLayoutAttributes.ColumnCount.get -> int? +Broadside.Structure.PdfLayoutAttributes.ColumnGap.get -> System.Collections.Generic.IReadOnlyList? +Broadside.Structure.PdfLayoutAttributes.ColumnWidths.get -> System.Collections.Generic.IReadOnlyList? +Broadside.Structure.PdfLayoutAttributes.EndIndent.get -> double? +Broadside.Structure.PdfLayoutAttributes.GlyphOrientationVertical.get -> double? +Broadside.Structure.PdfLayoutAttributes.Height.get -> double? +Broadside.Structure.PdfLayoutAttributes.InlineAlign.get -> string? +Broadside.Structure.PdfLayoutAttributes.LineHeight.get -> double? +Broadside.Structure.PdfLayoutAttributes.Padding.get -> System.Collections.Generic.IReadOnlyList? +Broadside.Structure.PdfLayoutAttributes.Placement.get -> string? +Broadside.Structure.PdfLayoutAttributes.RubyAlign.get -> string? +Broadside.Structure.PdfLayoutAttributes.RubyPosition.get -> string? +Broadside.Structure.PdfLayoutAttributes.SpaceAfter.get -> double? +Broadside.Structure.PdfLayoutAttributes.SpaceBefore.get -> double? +Broadside.Structure.PdfLayoutAttributes.StartIndent.get -> double? +Broadside.Structure.PdfLayoutAttributes.TableBorderStyle.get -> System.Collections.Generic.IReadOnlyList? +Broadside.Structure.PdfLayoutAttributes.TablePadding.get -> System.Collections.Generic.IReadOnlyList? +Broadside.Structure.PdfLayoutAttributes.TextAlign.get -> string? +Broadside.Structure.PdfLayoutAttributes.TextDecorationColor.get -> System.Collections.Generic.IReadOnlyList? +Broadside.Structure.PdfLayoutAttributes.TextDecorationThickness.get -> double? +Broadside.Structure.PdfLayoutAttributes.TextDecorationType.get -> string? +Broadside.Structure.PdfLayoutAttributes.TextIndent.get -> double? +Broadside.Structure.PdfLayoutAttributes.TextPosition.get -> string? +Broadside.Structure.PdfLayoutAttributes.Width.get -> double? +Broadside.Structure.PdfLayoutAttributes.WritingMode.get -> string? +Broadside.Structure.PdfListAttributes +Broadside.Structure.PdfListAttributes.ContinuedFrom.get -> Broadside.Objects.CosString? +Broadside.Structure.PdfListAttributes.ContinuedList.get -> bool? +Broadside.Structure.PdfListAttributes.IsOrdered.get -> bool +Broadside.Structure.PdfListAttributes.ListNumbering.get -> string? +Broadside.Structure.PdfMarkedContentReference +Broadside.Structure.PdfMarkedContentReference.ContentStream.get -> Broadside.Objects.CosStream? +Broadside.Structure.PdfMarkedContentReference.ContentStreamOwner.get -> Broadside.Objects.CosObject? +Broadside.Structure.PdfMarkedContentReference.Dictionary.get -> Broadside.Objects.CosDictionary? +Broadside.Structure.PdfMarkedContentReference.Mcid.get -> int +Broadside.Structure.PdfMarkedContentReference.Page.get -> Broadside.PdfPage? +Broadside.Structure.PdfMarkInfo +Broadside.Structure.PdfMarkInfo.Dictionary.get -> Broadside.Objects.CosDictionary? +Broadside.Structure.PdfMarkInfo.Marked.get -> bool +Broadside.Structure.PdfMarkInfo.Suspects.get -> bool +Broadside.Structure.PdfMarkInfo.UserProperties.get -> bool +Broadside.Structure.PdfObjectReference +Broadside.Structure.PdfObjectReference.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Structure.PdfObjectReference.ObjectReference.get -> Broadside.Objects.CosReference? +Broadside.Structure.PdfObjectReference.Page.get -> Broadside.PdfPage? +Broadside.Structure.PdfObjectReference.ReferencedObject.get -> Broadside.Objects.CosObject! +Broadside.Structure.PdfPrintFieldAttributes +Broadside.Structure.PdfPrintFieldAttributes.Checked.get -> string? +Broadside.Structure.PdfPrintFieldAttributes.Description.get -> string? +Broadside.Structure.PdfPrintFieldAttributes.Role.get -> string? +Broadside.Structure.PdfPropertyList +Broadside.Structure.PdfPropertyList.ActualText.get -> string? +Broadside.Structure.PdfPropertyList.AlternateDescription.get -> string? +Broadside.Structure.PdfPropertyList.ArtifactAttachments.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Structure.PdfPropertyList.ArtifactBoundingBox.get -> Broadside.PdfRectangle? +Broadside.Structure.PdfPropertyList.ArtifactSubtype.get -> string? +Broadside.Structure.PdfPropertyList.ArtifactType.get -> string? +Broadside.Structure.PdfPropertyList.Expansion.get -> string? +Broadside.Structure.PdfPropertyList.IsArtifact.get -> bool +Broadside.Structure.PdfPropertyList.Language.get -> string? +Broadside.Structure.PdfPropertyList.Mcid.get -> int? +Broadside.Structure.PdfPropertyList.PdfPropertyList(Broadside.Objects.CosName! tag, Broadside.Objects.CosDictionary? properties, Broadside.PdfDocument? document) -> void +Broadside.Structure.PdfPropertyList.Properties.get -> Broadside.Objects.CosDictionary? +Broadside.Structure.PdfPropertyList.Tag.get -> Broadside.Objects.CosName! +Broadside.Structure.PdfStructureElement +Broadside.Structure.PdfStructureElement.ActualText.get -> string? +Broadside.Structure.PdfStructureElement.AlternateDescription.get -> string? +Broadside.Structure.PdfStructureElement.AssociatedFiles.get -> Broadside.Objects.CosArray? +Broadside.Structure.PdfStructureElement.Attributes.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Structure.PdfStructureElement.Children.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Structure.PdfStructureElement.ClassAttributes.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Structure.PdfStructureElement.ClassNames.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Structure.PdfStructureElement.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Structure.PdfStructureElement.EffectiveLanguage.get -> string? +Broadside.Structure.PdfStructureElement.Equals(Broadside.Structure.PdfStructureElement? other) -> bool +Broadside.Structure.PdfStructureElement.Expansion.get -> string? +Broadside.Structure.PdfStructureElement.GetAttributeValue(Broadside.Objects.CosName! owner, Broadside.Objects.CosName! name) -> Broadside.Objects.CosObject? +Broadside.Structure.PdfStructureElement.GetContentItems() -> System.Collections.Generic.IReadOnlyList! +Broadside.Structure.PdfStructureElement.Id.get -> Broadside.Objects.CosString? +Broadside.Structure.PdfStructureElement.Language.get -> string? +Broadside.Structure.PdfStructureElement.Namespace.get -> Broadside.Structure.PdfStructureNamespace! +Broadside.Structure.PdfStructureElement.Page.get -> Broadside.PdfPage? +Broadside.Structure.PdfStructureElement.PhoneticAlphabet.get -> string! +Broadside.Structure.PdfStructureElement.Phoneme.get -> string? +Broadside.Structure.PdfStructureElement.Reference.get -> Broadside.Objects.CosReference? +Broadside.Structure.PdfStructureElement.References.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Structure.PdfStructureElement.Revision.get -> int +Broadside.Structure.PdfStructureElement.RoleMapping.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Structure.PdfStructureElement.StandardType.get -> Broadside.Structure.PdfStructureType? +Broadside.Structure.PdfStructureElement.StructureType.get -> Broadside.Objects.CosName? +Broadside.Structure.PdfStructureElement.Title.get -> string? +Broadside.Structure.PdfStructureItem +Broadside.Structure.PdfStructureNamespace +Broadside.Structure.PdfStructureNamespace.Dictionary.get -> Broadside.Objects.CosDictionary? +Broadside.Structure.PdfStructureNamespace.Equals(Broadside.Structure.PdfStructureNamespace? other) -> bool +Broadside.Structure.PdfStructureNamespace.IsDefault.get -> bool +Broadside.Structure.PdfStructureNamespace.IsStandardType(string! type) -> bool +Broadside.Structure.PdfStructureNamespace.Kind.get -> Broadside.Structure.PdfStructureNamespaceKind +Broadside.Structure.PdfStructureNamespace.Name.get -> string! +Broadside.Structure.PdfStructureNamespace.Reference.get -> Broadside.Objects.CosReference? +Broadside.Structure.PdfStructureNamespace.RoleMap.get -> Broadside.Objects.CosDictionary? +Broadside.Structure.PdfStructureNamespace.Schema.get -> Broadside.Objects.CosObject? +Broadside.Structure.PdfStructureNamespaceKind +Broadside.Structure.PdfStructureNamespaceKind.Custom = 0 -> Broadside.Structure.PdfStructureNamespaceKind +Broadside.Structure.PdfStructureNamespaceKind.MathML = 3 -> Broadside.Structure.PdfStructureNamespaceKind +Broadside.Structure.PdfStructureNamespaceKind.Pdf17 = 1 -> Broadside.Structure.PdfStructureNamespaceKind +Broadside.Structure.PdfStructureNamespaceKind.Pdf20 = 2 -> Broadside.Structure.PdfStructureNamespaceKind +Broadside.Structure.PdfStructureTreeRoot +Broadside.Structure.PdfStructureTreeRoot.AssociatedFiles.get -> Broadside.Objects.CosArray? +Broadside.Structure.PdfStructureTreeRoot.Children.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Structure.PdfStructureTreeRoot.ClassMap.get -> Broadside.Objects.CosDictionary? +Broadside.Structure.PdfStructureTreeRoot.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Structure.PdfStructureTreeRoot.Elements.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Structure.PdfStructureTreeRoot.FindElement(Broadside.Objects.CosStream! contentStream, int mcid) -> Broadside.Structure.PdfStructureElement? +Broadside.Structure.PdfStructureTreeRoot.FindElement(Broadside.PdfPage! page, int mcid) -> Broadside.Structure.PdfStructureElement? +Broadside.Structure.PdfStructureTreeRoot.FindElementById(System.ReadOnlySpan id) -> Broadside.Structure.PdfStructureElement? +Broadside.Structure.PdfStructureTreeRoot.FindElementForObject(Broadside.Objects.CosObject! contentItem) -> Broadside.Structure.PdfStructureElement? +Broadside.Structure.PdfStructureTreeRoot.GetMarkedContentElements(Broadside.Objects.CosStream! contentStream) -> System.Collections.Generic.IReadOnlyDictionary! +Broadside.Structure.PdfStructureTreeRoot.GetMarkedContentElements(Broadside.PdfPage! page) -> System.Collections.Generic.IReadOnlyDictionary! +Broadside.Structure.PdfStructureTreeRoot.Namespaces.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Structure.PdfStructureTreeRoot.ParentTreeNextKey.get -> int? +Broadside.Structure.PdfStructureTreeRoot.PronunciationLexicon.get -> Broadside.Objects.CosArray? +Broadside.Structure.PdfStructureTreeRoot.Reference.get -> Broadside.Objects.CosReference? +Broadside.Structure.PdfStructureTreeRoot.RoleMap.get -> Broadside.Objects.CosDictionary? +Broadside.Structure.PdfStructureType +Broadside.Structure.PdfStructureType.Equals(Broadside.Structure.PdfStructureType? other) -> bool +Broadside.Structure.PdfStructureType.IsStandard.get -> bool +Broadside.Structure.PdfStructureType.Name.get -> string! +Broadside.Structure.PdfStructureType.Namespace.get -> Broadside.Structure.PdfStructureNamespace! +Broadside.Structure.PdfStructureType.PdfStructureType(string! name, Broadside.Structure.PdfStructureNamespace! namespace) -> void +Broadside.Structure.PdfTableAttributes +Broadside.Structure.PdfTableAttributes.ColumnSpan.get -> int? +Broadside.Structure.PdfTableAttributes.Headers.get -> System.Collections.Generic.IReadOnlyList? +Broadside.Structure.PdfTableAttributes.RowSpan.get -> int? +Broadside.Structure.PdfTableAttributes.Scope.get -> string? +Broadside.Structure.PdfTableAttributes.ShortForm.get -> string? +Broadside.Structure.PdfTableAttributes.Summary.get -> string? +Broadside.Structure.PdfUserPropertiesAttributes +Broadside.Structure.PdfUserPropertiesAttributes.Properties.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Structure.PdfUserProperty +Broadside.Structure.PdfUserProperty.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Structure.PdfUserProperty.FormattedValue.get -> string? +Broadside.Structure.PdfUserProperty.IsHidden.get -> bool +Broadside.Structure.PdfUserProperty.Name.get -> string! +Broadside.Structure.PdfUserProperty.Value.get -> Broadside.Objects.CosObject! +abstract Broadside.Structure.PdfStructureItem.Parent.get -> Broadside.Structure.PdfStructureElement? +const Broadside.Structure.PdfStructureNamespace.MathMLName = "http://www.w3.org/1998/Math/MathML" -> string! +const Broadside.Structure.PdfStructureNamespace.Pdf17Name = "http://iso.org/pdf/ssn" -> string! +const Broadside.Structure.PdfStructureNamespace.Pdf20Name = "http://iso.org/pdf2/ssn" -> string! +override Broadside.Structure.PdfMarkedContentReference.Parent.get -> Broadside.Structure.PdfStructureElement! +override Broadside.Structure.PdfObjectReference.Parent.get -> Broadside.Structure.PdfStructureElement! +override Broadside.Structure.PdfStructureElement.Equals(object? obj) -> bool +override Broadside.Structure.PdfStructureElement.GetHashCode() -> int +override Broadside.Structure.PdfStructureElement.Parent.get -> Broadside.Structure.PdfStructureElement? +override Broadside.Structure.PdfStructureElement.ToString() -> string! +override Broadside.Structure.PdfStructureNamespace.Equals(object? obj) -> bool +override Broadside.Structure.PdfStructureNamespace.GetHashCode() -> int +override Broadside.Structure.PdfStructureNamespace.ToString() -> string! +override Broadside.Structure.PdfStructureType.Equals(object? obj) -> bool +override Broadside.Structure.PdfStructureType.GetHashCode() -> int +override Broadside.Structure.PdfStructureType.ToString() -> string! +static Broadside.Structure.PdfStructureNamespace.MathML.get -> Broadside.Structure.PdfStructureNamespace! +static Broadside.Structure.PdfStructureNamespace.Pdf17.get -> Broadside.Structure.PdfStructureNamespace! +static Broadside.Structure.PdfStructureNamespace.Pdf20.get -> Broadside.Structure.PdfStructureNamespace! diff --git a/src/Broadside/Structure/AttributeReader.cs b/src/Broadside/Structure/AttributeReader.cs new file mode 100644 index 00000000..31592c5f --- /dev/null +++ b/src/Broadside/Structure/AttributeReader.cs @@ -0,0 +1,179 @@ +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Structure; + +/// Reads a structure element's A and C entries and the root's ClassMap into attribute objects. +/// +/// +/// ISO 32000-2 §14.7.6 (Tables 355, 360) and §14.7.6.3: in an A or C array, an integer is the revision number of the +/// object (or class) BEFORE it; an attribute object is never an integer, so the two are told apart by type (p.738 NOTE 3). A leading +/// integer, or two in a row, is ignored with an AttributeRevisionInvalid diagnostic (PDFBox's model; pdf.js drops every +/// integer). An entry that is neither an attribute object nor a revision is skipped with AttributeObjectInvalid. +/// +/// +/// An attribute object whose O is missing, is NSO without NS, or has NS with another owner, is still +/// read (generically, by its owner name) with an AttributeOwnerInvalid diagnostic (Table 360). +/// +/// +internal static class AttributeReader +{ + public static List ReadObjects(StructureContext context, CosObject? value, CosReference? where) + { + var objects = new List(); + if (value is null) + { + return objects; + } + + CosObject resolved = context.Resolve(value); + if (resolved is CosArray array) + { + CosObject? pending = null; + CosReference? pendingReference = null; + bool revisionSeen = false; + foreach (CosObject item in array) + { + CosObject entry = context.Resolve(item); + if (entry is CosInteger revision) + { + if (pending is null || revisionSeen || revision.Value is < 0 or > int.MaxValue) + { + context.Report(DiagnosticCodes.AttributeRevisionInvalid, "A revision number in an A array does not follow an attribute object (§14.7.6.3); ignored.", where); + continue; + } + + objects.Add(Create(context, pending, pendingReference, (int)revision.Value, where)); + pending = null; + revisionSeen = true; + continue; + } + + if (pending is not null) + { + objects.Add(Create(context, pending, pendingReference, 0, where)); + pending = null; + } + + revisionSeen = false; + if (entry is CosDictionary or CosStream) + { + pending = entry; + pendingReference = item as CosReference; + } + else if (entry is not CosNull) + { + context.Report(DiagnosticCodes.AttributeObjectInvalid, "An A entry is neither an attribute object (a dictionary or a stream) nor a revision number (Table 355); skipped.", where); + } + } + + if (pending is not null) + { + objects.Add(Create(context, pending, pendingReference, 0, where)); + } + } + else if (resolved is CosDictionary or CosStream) + { + objects.Add(Create(context, resolved, value as CosReference, 0, where)); + } + else if (resolved is not CosNull) + { + context.Report(DiagnosticCodes.AttributeObjectInvalid, "An A entry is neither an attribute object nor an array of them (Table 355); ignored.", where); + } + + return objects; + } + + /// Reads C: class names, each optionally followed by its revision number. + public static List<(CosName Name, int Revision)> ReadClassNames(StructureContext context, CosObject? value, CosReference? where) + { + var names = new List<(CosName, int)>(); + if (value is null) + { + return names; + } + + switch (context.Resolve(value)) + { + case CosName single: + names.Add((single, 0)); + break; + case CosArray array: + bool revisionAllowed = false; + foreach (CosObject item in array) + { + switch (context.Resolve(item)) + { + case CosName name: + names.Add((name, 0)); + revisionAllowed = true; + break; + case CosInteger { Value: >= 0 and <= int.MaxValue } revision when revisionAllowed: + names[^1] = (names[^1].Item1, (int)revision.Value); + revisionAllowed = false; + break; + case CosInteger: + context.Report(DiagnosticCodes.AttributeRevisionInvalid, "A revision number in a C array does not follow a class name (§14.7.6.3); ignored.", where); + break; + default: + context.Report(DiagnosticCodes.AttributeObjectInvalid, "A C entry is not a class name (Table 355); skipped.", where); + revisionAllowed = false; + break; + } + } + + break; + case CosNull: + break; + default: + context.Report(DiagnosticCodes.AttributeObjectInvalid, "C is neither a class name nor an array of them (Table 355); ignored.", where); + break; + } + + return names; + } + + /// The attribute objects of class in the root's ClassMap, carrying . + public static List ReadClass(StructureContext context, CosName name, int revision, CosReference? where) + { + if (StructureValues.Get(context.Document, context.Root, StructureNames.ClassMap) is not CosDictionary classMap + || !classMap.TryGetValue(name, out CosObject? value)) + { + return []; + } + + List objects = ReadObjects(context, value, where); + if (revision == 0) + { + return objects; + } + + for (int index = 0; index < objects.Count; index++) + { + PdfAttributeObject attributes = objects[index]; + objects[index] = PdfAttributeObject.Create(context, (CosObject?)attributes.Stream ?? attributes.Dictionary, attributes.Reference, revision); + } + + return objects; + } + + private static PdfAttributeObject Create(StructureContext context, CosObject source, CosReference? reference, int revision, CosReference? where) + { + PdfAttributeObject attributes = PdfAttributeObject.Create(context, source, reference, revision); + bool isNamespaceOwner = StructureNames.NSO.Equals(attributes.Owner); + bool hasNamespace = attributes.Dictionary.ContainsKey(StructureNames.NS); + if (attributes.Owner is null) + { + context.Report(DiagnosticCodes.AttributeOwnerInvalid, "An attribute object has no owner (O, Table 360); read without one.", reference ?? where); + } + else if (isNamespaceOwner != hasNamespace) + { + context.Report( + DiagnosticCodes.AttributeOwnerInvalid, + isNamespaceOwner ? "An attribute object owned by NSO has no NS entry (Table 360)." : "An attribute object has NS but its owner is not NSO (Table 360).", + reference ?? where); + } + + return attributes; + } +} diff --git a/src/Broadside/Structure/KidReader.cs b/src/Broadside/Structure/KidReader.cs new file mode 100644 index 00000000..9ec2803b --- /dev/null +++ b/src/Broadside/Structure/KidReader.cs @@ -0,0 +1,155 @@ +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Structure; + +/// What one entry of a structure element's K is. +internal enum KidKind +{ + /// Not a valid child: skipped (a diagnostic was recorded). + Invalid, + + /// A structure element dictionary. + Element, + + /// A marked-content sequence: an integer MCID or an MCR dictionary. + MarkedContent, + + /// A whole object: an OBJR dictionary. + Object, +} + +/// One entry of K, classified. +/// What it is. +/// The element, MCR or OBJR dictionary; for an integer MCID. +/// The indirect reference the entry was, if it was one. +/// The MCID of a marked-content item. +internal readonly record struct Kid(KidKind Kind, CosDictionary? Dictionary, CosReference? Reference, int Mcid); + +/// Reads and classifies the entries of K (ISO 32000-2 §14.7.2, Table 355; §14.7.5). +/// +/// +/// K is one object or an array of them: a structure element dictionary, an integer MCID, an MCR dictionary (Table 357) or an +/// OBJR dictionary (Table 358). "If the value of K is a dictionary containing no Type entry, it shall be assumed to be a structure +/// element dictionary" (Table 355). +/// +/// +/// Repairs (pdf.js and PDFBox treat these as structure elements, then fail on them): a dictionary without Type and without +/// S that holds an integer MCID is read as an MCR, one that holds Obj as an OBJR; a dictionary whose +/// Type is something else is read by the same rule (an element when it has S). Each is a +/// StructElemTypeUnknown diagnostic; anything else in K is skipped with StructElemInvalid. +/// +/// +internal static class KidReader +{ + /// The raw entries of 's K, references kept. + public static IReadOnlyList Entries(StructureContext context, CosDictionary owner) + { + if (!owner.TryGetValue(StructureNames.K, out CosObject? value)) + { + return []; + } + + return context.Resolve(value) switch + { + CosArray array => array, + CosNull => [], + _ => [value], + }; + } + + public static Kid Classify(StructureContext context, CosObject entry, CosReference? ownerReference) + { + CosReference? reference = entry as CosReference; + CosObject value = context.Resolve(entry); + CosReference? where = reference ?? ownerReference; + switch (value) + { + case CosInteger { Value: >= 0 and <= int.MaxValue } integer: + return new Kid(KidKind.MarkedContent, null, reference, (int)integer.Value); + case CosDictionary dictionary: + return ClassifyDictionary(context, dictionary, reference, where); + default: + context.Report(DiagnosticCodes.StructElemInvalid, $"A K entry is {Describe(value)}, not a structure element, an MCID, an MCR or an OBJR (Table 355); skipped.", where); + return default; + } + } + + private static Kid ClassifyDictionary(StructureContext context, CosDictionary dictionary, CosReference? reference, CosReference? where) + { + CosName? type = StructureValues.Name(context.Document, dictionary, KnownNames.Type); + bool hasStructureType = dictionary.ContainsKey(StructureNames.S); + CosObject? mcid = StructureValues.Get(context.Document, dictionary, StructureNames.MCID); + bool hasObject = dictionary.ContainsKey(StructureNames.Obj); + if (type is null || StructureNames.StructElem.Equals(type)) + { + if (type is not null || hasStructureType || (mcid is null && !hasObject)) + { + return new Kid(KidKind.Element, dictionary, reference, 0); + } + } + else if (StructureNames.MCR.Equals(type)) + { + return Mcr(context, dictionary, reference, where, mcid); + } + else if (StructureNames.OBJR.Equals(type)) + { + return Objr(context, dictionary, reference, where, hasObject); + } + else if (hasStructureType) + { + context.Report(DiagnosticCodes.StructElemTypeUnknown, $"A K entry has Type /{type.Value} and an S entry; read as a structure element (Table 355).", where); + return new Kid(KidKind.Element, dictionary, reference, 0); + } + + if (mcid is not null) + { + context.Report(DiagnosticCodes.StructElemTypeUnknown, "A K entry without Type MCR holds an MCID; read as a marked-content reference (Table 357).", where); + return Mcr(context, dictionary, reference, where, mcid); + } + + if (hasObject) + { + context.Report(DiagnosticCodes.StructElemTypeUnknown, "A K entry without Type OBJR holds Obj; read as an object reference (Table 358).", where); + return Objr(context, dictionary, reference, where, hasObject); + } + + context.Report(DiagnosticCodes.StructElemTypeUnknown, $"A K entry has Type /{type!.Value} and is neither a structure element, an MCR nor an OBJR; skipped.", where); + return default; + } + + private static Kid Mcr(StructureContext context, CosDictionary dictionary, CosReference? reference, CosReference? where, CosObject? mcid) + { + if (mcid is CosInteger { Value: >= 0 and <= int.MaxValue } integer) + { + return new Kid(KidKind.MarkedContent, dictionary, reference, (int)integer.Value); + } + + context.Report(DiagnosticCodes.StructElemInvalid, "A marked-content reference has no non-negative integer MCID (Table 357); skipped.", where); + return default; + } + + private static Kid Objr(StructureContext context, CosDictionary dictionary, CosReference? reference, CosReference? where, bool hasObject) + { + if (hasObject) + { + return new Kid(KidKind.Object, dictionary, reference, 0); + } + + context.Report(DiagnosticCodes.StructElemInvalid, "An object reference has no Obj entry (Table 358); skipped.", where); + return default; + } + + private static string Describe(CosObject value) => value switch + { + CosNull => "null", + CosInteger => "a negative or too large integer", + CosReal => "a real number", + CosBoolean => "a boolean", + CosString => "a string", + CosName => "a name", + CosArray => "an array", + CosStream => "a stream", + _ => "an object of another kind", + }; +} diff --git a/src/Broadside/Structure/MarkedContentIndex.cs b/src/Broadside/Structure/MarkedContentIndex.cs new file mode 100644 index 00000000..77bb32e6 --- /dev/null +++ b/src/Broadside/Structure/MarkedContentIndex.cs @@ -0,0 +1,111 @@ +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Structure; + +/// The MCID-to-element map of one content stream (a page or a form XObject), built once per stream. +/// +/// +/// ISO 32000-2 §14.7.5.4, Table 359: the stream's StructParents is a key of the parent tree, whose value is an array indexed +/// by MCID of the elements owning the stream's marked-content sequences (null entries are gaps). The map is keyed by the content +/// stream, because MCIDs are unique per stream, not per page (§14.7.5.2). Building it reads one number-tree entry; it does not walk +/// the whole structure tree. +/// +/// +/// Each entry is checked against the element it names: the element's K must hold that MCID for that stream. An entry that +/// does not, a parent-tree value that is not an array, or a stream with content items but no usable entry, is a +/// ParentTreeEntryInvalid diagnostic, and the answer comes from the K walk instead. Arrays longer than +/// are read up to that length. +/// +/// +internal sealed class MarkedContentIndex +{ + private static readonly Dictionary NoElements = []; + + private MarkedContentIndex(IReadOnlyDictionary elements) => Elements = elements; + + public static MarkedContentIndex Empty { get; } = new(NoElements); + + public IReadOnlyDictionary Elements { get; } + + public static MarkedContentIndex Build(StructureContext context, CosObject owner) + { + CosDictionary? ownerDictionary = owner as CosDictionary ?? (owner as CosStream)?.Dictionary; + int? key = ownerDictionary is null ? null : StructureValues.Integer(context.Document, ownerDictionary, StructureNames.StructParents); + if (context.ParentTree is not { } tree) + { + StructureWalk walk = context.Walk; + return From(walk.MarkedContent(owner)); + } + + if (key is not { } structParents || !tree.TryGetValue(structParents, out CosObject? value) || value is not CosArray array) + { + IReadOnlyDictionary? fromWalk = context.Walk.MarkedContent(owner); + if (fromWalk is { Count: > 0 }) + { + context.Report( + DiagnosticCodes.ParentTreeEntryInvalid, + key is null + ? "A content stream holds content items but has no StructParents entry (Table 359); its MCIDs are mapped through K." + : $"The parent tree entry {key} of a content stream is missing or not an array of elements (§14.7.5.4); its MCIDs are mapped through K.", + owner is CosDictionary page && context.Document.Pages.TryGetPage(page, out PdfPage? found) ? found.Reference : null); + } + + return From(fromWalk); + } + + var elements = new Dictionary(); + var owned = new Dictionary>(ReferenceEqualityComparer.Instance); + int count = Math.Min(array.Count, StructureContext.MaxParentTreeArray); + for (int mcid = 0; mcid < count; mcid++) + { + CosObject entry = array[mcid]; + CosObject resolved = context.Resolve(entry); + if (resolved is CosNull) + { + continue; + } + + if (resolved is CosDictionary dictionary && Owns(context, owned, dictionary, entry as CosReference, owner).Contains(mcid)) + { + elements[mcid] = new PdfStructureElement(context, dictionary, entry as CosReference, null, parentKnown: false, depth: 0); + continue; + } + + context.Report( + DiagnosticCodes.ParentTreeEntryInvalid, + $"The parent tree names an element for MCID {mcid} whose K does not hold that MCID (§14.7.5.4); the element whose K holds it is used.", + entry as CosReference); + if (context.Walk.MarkedContent(owner) is { } fromWalk && fromWalk.TryGetValue(mcid, out PdfStructureElement? element)) + { + elements[mcid] = element; + } + } + + return new MarkedContentIndex(elements); + } + + private static MarkedContentIndex From(IReadOnlyDictionary? elements) => elements is null ? Empty : new MarkedContentIndex(elements); + + /// The MCIDs of 's content that 's K holds, read once per element. + private static HashSet Owns(StructureContext context, Dictionary> owned, CosDictionary dictionary, CosReference? reference, CosObject owner) + { + if (owned.TryGetValue(dictionary, out HashSet? mcids)) + { + return mcids; + } + + mcids = []; + var element = new PdfStructureElement(context, dictionary, reference, null, parentKnown: false, depth: 0); + foreach (PdfStructureItem item in element.Children) + { + if (item is PdfMarkedContentReference content && (content.StreamKey is null || ReferenceEquals(content.StreamKey, owner))) + { + mcids.Add(content.Mcid); + } + } + + owned.Add(dictionary, mcids); + return mcids; + } +} diff --git a/src/Broadside/Structure/PdfArtifactAttributes.cs b/src/Broadside/Structure/PdfArtifactAttributes.cs new file mode 100644 index 00000000..429af8c6 --- /dev/null +++ b/src/Broadside/Structure/PdfArtifactAttributes.cs @@ -0,0 +1,25 @@ +using Broadside.Objects; + +namespace Broadside.Structure; + +/// An attribute object owned by Artifact, on an Artifact structure element (PDF 2.0). +/// ISO 32000-2 §14.8.5.8, Table 385. +public sealed class PdfArtifactAttributes : PdfAttributeObject +{ + internal PdfArtifactAttributes(StructureContext context, CosObject source, CosReference? reference, int revision) + : base(context, source, reference, revision) + { + } + + /// Gets the artifact type (Type): Pagination, Layout, Page or Inline. + /// ISO 32000-2 Table 385. + public string? ArtifactType => NameValue(Objects.KnownNames.Type); + + /// Gets the artifact's bounding box (BBox). + /// ISO 32000-2 Table 385. + public PdfRectangle? BoundingBox => RectangleValue(StructureNames.BBox); + + /// Gets the artifact subtype (Subtype): Header, Footer, Watermark, PageNum, Bates, LineNum or Redaction. + /// ISO 32000-2 Table 385. + public string? ArtifactSubtype => NameValue(StructureNames.Subtype); +} diff --git a/src/Broadside/Structure/PdfAttributeObject.cs b/src/Broadside/Structure/PdfAttributeObject.cs new file mode 100644 index 00000000..b2c1249b --- /dev/null +++ b/src/Broadside/Structure/PdfAttributeObject.cs @@ -0,0 +1,112 @@ +using Broadside.Objects; + +namespace Broadside.Structure; + +/// +/// An attribute object of a structure element: a dictionary (or, in the legacy form, a stream) whose O entry names the owner +/// of the attributes it holds. Owners with typed attributes have a derived view: , +/// , , , +/// and ; any other owner (an NSO namespace owner, +/// a format owner such as CSS-3, or a second-class name) is read through this class. +/// +/// +/// +/// ISO 32000-2 §14.7.6.1, Table 360 (O, and NS when O is NSO); §14.8.5.2, Table 376 (standard owners). +/// A view over its dictionary (ADR 0004): every value is read when asked for. is the revision number that +/// follows the object in the element's A array or its class in C (§14.7.6.3, deprecated in PDF 2.0; 0 when absent). +/// +/// +/// Values are the object's own, as written. The value that applies to an element, after class attributes, inheritance and +/// defaults, comes from . +/// +/// +public class PdfAttributeObject +{ + private readonly StructureContext _context; + + private protected PdfAttributeObject(StructureContext context, CosObject source, CosReference? reference, int revision) + { + _context = context; + Stream = source as CosStream; + Dictionary = StructureValues.DictionaryOf(source) ?? new CosDictionary(); + Reference = reference; + Revision = revision; + } + + /// Gets the attribute object's dictionary (a stream's dictionary for the legacy stream form). + /// ISO 32000-2 §14.7.6.1, Table 360. + public CosDictionary Dictionary { get; } + + /// Gets the stream when the attribute object is the legacy stream form, else . + /// ISO 32000-2 §14.7.6.1: "Each attribute object shall be either a dictionary or a stream." + public CosStream? Stream { get; } + + /// Gets the indirect reference the attribute object was reached through, if any. + public CosReference? Reference { get; } + + /// Gets the owner (O), or when the entry is missing. + /// ISO 32000-2 §14.7.6.1, Table 360 (required); Table 376 lists the standard owners. + public CosName? Owner => StructureValues.Name(Document, Dictionary, StructureNames.O); + + /// Gets the namespace that owns the attributes when is NSO, else . + /// ISO 32000-2 §14.7.6.1, Table 360 (NS, PDF 2.0, an indirect reference to a namespace dictionary). + public PdfStructureNamespace? Namespace => + StructureNames.NSO.Equals(Owner) && Dictionary.TryGetValue(StructureNames.NS, out CosObject? value) && Context.Resolve(value) is CosDictionary ns + ? Context.Namespace(ns, value as CosReference) + : null; + + /// Gets the revision number of the attribute object (deprecated in PDF 2.0); 0 when none was given. + /// ISO 32000-2 §14.7.6.3. + public int Revision { get; } + + /// Gets the document the attribute object belongs to. + private protected PdfDocument Document => _context.Document; + + /// Gets the shared structure state. + private protected StructureContext Context => _context; + + /// Returns the value of the attribute in this object, resolved, or when absent. + /// The attribute name. + /// The value. + /// ISO 32000-2 §14.7.6.1. + public CosObject? GetValue(CosName name) + { + ArgumentNullException.ThrowIfNull(name); + return StructureValues.Get(Document, Dictionary, name); + } + + /// Creates the view for an attribute object, typed by its owner. + internal static PdfAttributeObject Create(StructureContext context, CosObject source, CosReference? reference, int revision) + { + CosDictionary dictionary = StructureValues.DictionaryOf(source) ?? new CosDictionary(); + CosName? owner = StructureValues.Name(context.Document, dictionary, StructureNames.O); + return owner switch + { + _ when StructureNames.Layout.Equals(owner) => new PdfLayoutAttributes(context, source, reference, revision), + _ when StructureNames.List.Equals(owner) => new PdfListAttributes(context, source, reference, revision), + _ when StructureNames.Table.Equals(owner) => new PdfTableAttributes(context, source, reference, revision), + _ when StructureNames.PrintField.Equals(owner) => new PdfPrintFieldAttributes(context, source, reference, revision), + _ when StructureNames.Artifact.Equals(owner) => new PdfArtifactAttributes(context, source, reference, revision), + _ when StructureNames.UserProperties.Equals(owner) => new PdfUserPropertiesAttributes(context, source, reference, revision), + _ => new PdfAttributeObject(context, source, reference, revision), + }; + } + + /// A name-valued attribute as a string. + private protected string? NameValue(CosName name) => StructureValues.Name(Document, Dictionary, name)?.Value; + + /// A number-valued attribute. + private protected double? NumberValue(CosName name) => StructureValues.Number(Document, Dictionary, name); + + /// An integer-valued attribute. + private protected int? IntegerValue(CosName name) => StructureValues.Integer(Document, Dictionary, name); + + /// A text-string-valued attribute. + private protected string? TextValue(CosName name) => StructureValues.Text(Document, Dictionary, name); + + /// An array of numbers. + private protected IReadOnlyList? NumbersValue(CosName name) => StructureValues.Numbers(Document, Dictionary, name); + + /// A rectangle. + private protected PdfRectangle? RectangleValue(CosName name) => StructureValues.Rectangle(Document, Dictionary, name); +} diff --git a/src/Broadside/Structure/PdfLayoutAttributes.cs b/src/Broadside/Structure/PdfLayoutAttributes.cs new file mode 100644 index 00000000..4f574385 --- /dev/null +++ b/src/Broadside/Structure/PdfLayoutAttributes.cs @@ -0,0 +1,211 @@ +using Broadside.Objects; + +namespace Broadside.Structure; + +/// An attribute object owned by Layout: how an element's content is laid out. +/// +/// +/// ISO 32000-2 §14.8.5.4, Tables 377-381 (with the corrected Table 377 of the 2020 errata). Each property is this object's own value, +/// when absent or of the wrong type; it is not inherited and has no default applied. For the value in effect on +/// an element use . +/// +/// +/// Attributes with several forms read as follows: a side value (BorderStyle, TBorderStyle, BorderThickness, +/// Padding, TPadding) is four entries in the order before, after, start, end, a single value repeated; Width, +/// Height, LineHeight and GlyphOrientationVertical read for their name forms (Auto, +/// Normal). BorderColor and other forms are available through . +/// +/// +public sealed class PdfLayoutAttributes : PdfAttributeObject +{ + private static readonly CosName PlacementName = new("Placement"); + private static readonly CosName WritingModeName = new("WritingMode"); + private static readonly CosName BackgroundColorName = new("BackgroundColor"); + private static readonly CosName BorderStyleName = new("BorderStyle"); + private static readonly CosName BorderThicknessName = new("BorderThickness"); + private static readonly CosName PaddingName = new("Padding"); + private static readonly CosName ColorName = new("Color"); + private static readonly CosName SpaceBeforeName = new("SpaceBefore"); + private static readonly CosName SpaceAfterName = new("SpaceAfter"); + private static readonly CosName StartIndentName = new("StartIndent"); + private static readonly CosName EndIndentName = new("EndIndent"); + private static readonly CosName TextIndentName = new("TextIndent"); + private static readonly CosName TextAlignName = new("TextAlign"); + private static readonly CosName WidthName = new("Width"); + private static readonly CosName HeightName = new("Height"); + private static readonly CosName BlockAlignName = new("BlockAlign"); + private static readonly CosName InlineAlignName = new("InlineAlign"); + private static readonly CosName TBorderStyleName = new("TBorderStyle"); + private static readonly CosName TPaddingName = new("TPadding"); + private static readonly CosName BaselineShiftName = new("BaselineShift"); + private static readonly CosName LineHeightName = new("LineHeight"); + private static readonly CosName TextPositionName = new("TextPosition"); + private static readonly CosName TextDecorationColorName = new("TextDecorationColor"); + private static readonly CosName TextDecorationThicknessName = new("TextDecorationThickness"); + private static readonly CosName TextDecorationTypeName = new("TextDecorationType"); + private static readonly CosName RubyAlignName = new("RubyAlign"); + private static readonly CosName RubyPositionName = new("RubyPosition"); + private static readonly CosName GlyphOrientationVerticalName = new("GlyphOrientationVertical"); + private static readonly CosName ColumnCountName = new("ColumnCount"); + private static readonly CosName ColumnGapName = new("ColumnGap"); + private static readonly CosName ColumnWidthsName = new("ColumnWidths"); + + internal PdfLayoutAttributes(StructureContext context, CosObject source, CosReference? reference, int revision) + : base(context, source, reference, revision) + { + } + + /// Gets Placement: Block, Inline, Before, Start or End. + /// ISO 32000-2 Table 378. + public string? Placement => NameValue(PlacementName); + + /// Gets WritingMode: LrTb, RlTb, TbRl, TbLr, LrBt, RlBt, BtRl or BtLr. + /// ISO 32000-2 Table 378. + public string? WritingMode => NameValue(WritingModeName); + + /// Gets BackgroundColor, three RGB components (PDF 1.5). + /// ISO 32000-2 Table 378. + public IReadOnlyList? BackgroundColor => NumbersValue(BackgroundColorName) is { Count: 3 } rgb ? rgb : null; + + /// Gets BorderStyle per side (before, after, start, end): None, Hidden, Dotted, Dashed, Solid, Double, Groove, Ridge, Inset, Outset; a side may be null. + /// ISO 32000-2 Table 378 (PDF 1.5). + public IReadOnlyList? BorderStyle => Sides(BorderStyleName); + + /// Gets BorderThickness per side (before, after, start, end) (PDF 1.5). + /// ISO 32000-2 Table 378. + public IReadOnlyList? BorderThickness => SideNumbers(BorderThicknessName); + + /// Gets Padding per side (before, after, start, end) (PDF 1.5). + /// ISO 32000-2 Table 378. + public IReadOnlyList? Padding => SideNumbers(PaddingName); + + /// Gets Color, three RGB components (PDF 1.5). + /// ISO 32000-2 Table 378. + public IReadOnlyList? Color => NumbersValue(ColorName) is { Count: 3 } rgb ? rgb : null; + + /// Gets SpaceBefore. + /// ISO 32000-2 Table 379. + public double? SpaceBefore => NumberValue(SpaceBeforeName); + + /// Gets SpaceAfter. + /// ISO 32000-2 Table 379. + public double? SpaceAfter => NumberValue(SpaceAfterName); + + /// Gets StartIndent. + /// ISO 32000-2 Table 379. + public double? StartIndent => NumberValue(StartIndentName); + + /// Gets EndIndent. + /// ISO 32000-2 Table 379. + public double? EndIndent => NumberValue(EndIndentName); + + /// Gets TextIndent. + /// ISO 32000-2 Table 379. + public double? TextIndent => NumberValue(TextIndentName); + + /// Gets TextAlign: Start, Center, End or Justify. + /// ISO 32000-2 Table 379. + public string? TextAlign => NameValue(TextAlignName); + + /// Gets BBox, the element's bounding box (Figure, Form, Formula, Table, Artifact). + /// ISO 32000-2 Table 379 (errata Table 377). + public PdfRectangle? BoundingBox => RectangleValue(StructureNames.BBox); + + /// Gets Width when it is a number; for Auto or absent. + /// ISO 32000-2 Table 379. + public double? Width => NumberValue(WidthName); + + /// Gets Height when it is a number; for Auto or absent. + /// ISO 32000-2 Table 379. + public double? Height => NumberValue(HeightName); + + /// Gets BlockAlign (table cells): Before, Middle, After or Justify. + /// ISO 32000-2 Table 379. + public string? BlockAlign => NameValue(BlockAlignName); + + /// Gets InlineAlign (table cells): Start, Center or End. + /// ISO 32000-2 Table 379. + public string? InlineAlign => NameValue(InlineAlignName); + + /// Gets TBorderStyle per side (table cells, PDF 1.5). + /// ISO 32000-2 Table 379. + public IReadOnlyList? TableBorderStyle => Sides(TBorderStyleName); + + /// Gets TPadding per side (table cells, PDF 1.5). + /// ISO 32000-2 Table 379. + public IReadOnlyList? TablePadding => SideNumbers(TPaddingName); + + /// Gets BaselineShift. + /// ISO 32000-2 Table 380. + public double? BaselineShift => NumberValue(BaselineShiftName); + + /// Gets LineHeight when it is a number; for Normal, Auto or absent. + /// ISO 32000-2 Table 380. + public double? LineHeight => NumberValue(LineHeightName); + + /// Gets TextPosition: Sup, Sub or Normal (PDF 2.0). + /// ISO 32000-2 Table 380. + public string? TextPosition => NameValue(TextPositionName); + + /// Gets TextDecorationColor, three RGB components (PDF 1.5). + /// ISO 32000-2 Table 380. + public IReadOnlyList? TextDecorationColor => NumbersValue(TextDecorationColorName) is { Count: 3 } rgb ? rgb : null; + + /// Gets TextDecorationThickness (PDF 1.5). + /// ISO 32000-2 Table 380. + public double? TextDecorationThickness => NumberValue(TextDecorationThicknessName); + + /// Gets TextDecorationType: None, Underline, Overline or LineThrough. + /// ISO 32000-2 Table 380. + public string? TextDecorationType => NameValue(TextDecorationTypeName); + + /// Gets RubyAlign: Start, Center, End, Justify or Distribute (PDF 1.5). + /// ISO 32000-2 Table 380. + public string? RubyAlign => NameValue(RubyAlignName); + + /// Gets RubyPosition: Before, After, Warichu or Inline (PDF 1.5). + /// ISO 32000-2 Table 380. + public string? RubyPosition => NameValue(RubyPositionName); + + /// Gets GlyphOrientationVertical in degrees; for Auto or absent (PDF 1.5). + /// ISO 32000-2 Table 380. + public double? GlyphOrientationVertical => NumberValue(GlyphOrientationVerticalName); + + /// Gets ColumnCount (PDF 1.6). + /// ISO 32000-2 Table 381. + public int? ColumnCount => IntegerValue(ColumnCountName); + + /// Gets ColumnGap: one gap, or one per pair of columns (the last repeats) (PDF 1.6). + /// ISO 32000-2 Table 381. + public IReadOnlyList? ColumnGap => NumberOrNumbers(ColumnGapName); + + /// Gets ColumnWidths: one width, or one per column (the last repeats) (PDF 1.6). + /// ISO 32000-2 Table 381. + public IReadOnlyList? ColumnWidths => NumberOrNumbers(ColumnWidthsName); + + private IReadOnlyList? NumberOrNumbers(CosName name) => + NumberValue(name) is { } single ? [single] : NumbersValue(name); + + private IReadOnlyList? SideNumbers(CosName name) => NumberValue(name) is { } single + ? [single, single, single, single] + : NumbersValue(name) is { Count: 4 } sides ? sides : null; + + private string?[]? Sides(CosName name) + { + switch (GetValue(name)) + { + case CosName single: + return [single.Value, single.Value, single.Value, single.Value]; + case CosArray { Count: 4 } array: + string?[] sides = new string?[4]; + for (int index = 0; index < 4; index++) + { + sides[index] = (Document.Resolve(array[index]) as CosName)?.Value; + } + + return sides; + default: + return null; + } + } +} diff --git a/src/Broadside/Structure/PdfListAttributes.cs b/src/Broadside/Structure/PdfListAttributes.cs new file mode 100644 index 00000000..b0f83bcc --- /dev/null +++ b/src/Broadside/Structure/PdfListAttributes.cs @@ -0,0 +1,39 @@ +using Broadside.Objects; + +namespace Broadside.Structure; + +/// An attribute object owned by List, on an L element. +/// +/// ISO 32000-2 §14.8.5.5, Table 382. Each property is this object's own value, when absent; the value in effect +/// (ListNumbering is inheritable, default None) comes from . +/// +public sealed class PdfListAttributes : PdfAttributeObject +{ + private static readonly CosName ListNumberingName = new("ListNumbering"); + private static readonly CosName ContinuedListName = new("ContinuedList"); + private static readonly CosName ContinuedFromName = new("ContinuedFrom"); + + internal PdfListAttributes(StructureContext context, CosObject source, CosReference? reference, int revision) + : base(context, source, reference, revision) + { + } + + /// + /// Gets ListNumbering: None, Unordered, Description, Disc, Circle, Square, Ordered, Decimal, UpperRoman, LowerRoman, + /// UpperAlpha or LowerAlpha. + /// + /// ISO 32000-2 Table 382 (Unordered, Description and Ordered are PDF 2.0). + public string? ListNumbering => NameValue(ListNumberingName); + + /// Gets a value indicating whether marks an ordered list: Ordered, Decimal, UpperRoman, LowerRoman, UpperAlpha or LowerAlpha. + /// ISO 32000-2 Table 382. + public bool IsOrdered => ListNumbering is "Ordered" or "Decimal" or "UpperRoman" or "LowerRoman" or "UpperAlpha" or "LowerAlpha"; + + /// Gets ContinuedList: whether the list continues a previous one (PDF 2.0). + /// ISO 32000-2 Table 382. + public bool? ContinuedList => StructureValues.Boolean(Document, Dictionary, ContinuedListName); + + /// Gets ContinuedFrom: the ID of the list this one continues (PDF 2.0). + /// ISO 32000-2 Table 382. + public CosString? ContinuedFrom => GetValue(ContinuedFromName) as CosString; +} diff --git a/src/Broadside/Structure/PdfMarkInfo.cs b/src/Broadside/Structure/PdfMarkInfo.cs new file mode 100644 index 00000000..768cfd28 --- /dev/null +++ b/src/Broadside/Structure/PdfMarkInfo.cs @@ -0,0 +1,54 @@ +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Structure; + +/// The document's mark information dictionary: whether it is a tagged PDF and which tagged-PDF conventions it uses. +/// +/// ISO 32000-2 §14.7.1, Table 353, and §14.8.1 (a tagged PDF shall have Marked true). A live view over the catalog's +/// MarkInfo: every flag is read when asked for and is when the dictionary or the entry is missing. An +/// entry that is not a boolean reads as with a MarkInfoInvalid diagnostic. +/// +public sealed class PdfMarkInfo +{ + private readonly PdfDocument _document; + + internal PdfMarkInfo(PdfDocument document) => _document = document; + + /// Gets the mark information dictionary, or when the catalog has none. + /// ISO 32000-2 §7.7.2, Table 29 (MarkInfo), and Table 353. + public CosDictionary? Dictionary => StructureValues.Get(_document, _document.Catalog, StructureNames.MarkInfo) as CosDictionary; + + /// Gets a value indicating whether the document conforms to tagged PDF conventions (Marked). + /// ISO 32000-2 Table 353 (PDF 1.4 for tagged PDF); §14.8.1. + public bool Marked => Flag(StructureNames.Marked); + + /// Gets a value indicating whether structure elements carry user properties (UserProperties). + /// ISO 32000-2 Table 353 (PDF 1.6), §14.7.6.4. + public bool UserProperties => Flag(StructureNames.UserProperties); + + /// Gets a value indicating whether the document has tag suspects (Suspects; deprecated in PDF 2.0). + /// ISO 32000-2 Table 353 (PDF 1.6). + public bool Suspects => Flag(StructureNames.Suspects); + + private bool Flag(CosName key) + { + if (Dictionary is not { } dictionary || StructureValues.Get(_document, dictionary, key) is not { } value) + { + return false; + } + + if (value is CosBoolean flag) + { + return flag.Value; + } + + _document.DiagnosticSink.Report( + DiagnosticCodes.MarkInfoInvalid, + Diagnostics.DiagnosticSeverity.Warning, + $"MarkInfo {key.Value} is not a boolean (Table 353); read as false.", + offset: null, + _document.Catalog.TryGetValue(StructureNames.MarkInfo, out CosObject? reference) ? reference as CosReference : null); + return false; + } +} diff --git a/src/Broadside/Structure/PdfMarkedContentReference.cs b/src/Broadside/Structure/PdfMarkedContentReference.cs new file mode 100644 index 00000000..dbc34ad3 --- /dev/null +++ b/src/Broadside/Structure/PdfMarkedContentReference.cs @@ -0,0 +1,62 @@ +using Broadside.Objects; + +namespace Broadside.Structure; + +/// +/// A content item that is a marked-content sequence: an integer MCID in a structure element's K, or a marked-content reference +/// dictionary (/Type /MCR). +/// +/// +/// +/// ISO 32000-2 §14.7.5.2, Table 357. The sequence is the one in a content stream whose property list has this : +/// the stream is (Stm, a form XObject or an annotation appearance) when the MCR names one, +/// otherwise the content of . MCIDs are unique within one content stream, not within a page (§14.7.5.2). +/// +/// +/// The page is the MCR's Pg, else the element's Pg (Table 357: the MCR's overrides). When neither has one, the +/// nearest ancestor element's Pg is used as a repair, else the page whose parent-tree array lists the element at this MCID, with a +/// StructElemPageMissing diagnostic. +/// +/// +public sealed class PdfMarkedContentReference : PdfStructureItem +{ + internal PdfMarkedContentReference(PdfStructureElement parent, CosDictionary? dictionary, int mcid, PdfPage? page, CosDictionary? pageObject, CosStream? stream, CosObject? streamOwner) + { + Parent = parent; + Dictionary = dictionary; + Mcid = mcid; + Page = page; + PageObject = pageObject; + ContentStream = stream; + ContentStreamOwner = streamOwner; + } + + /// + public override PdfStructureElement Parent { get; } + + /// Gets the marked-content reference dictionary, or when the item is a bare integer in K. + /// ISO 32000-2 §14.7.5.2, Table 357. + public CosDictionary? Dictionary { get; } + + /// Gets the marked-content identifier: the MCID of the sequence's property list. + /// ISO 32000-2 §14.7.5.2. + public int Mcid { get; } + + /// Gets the page the sequence is on, or when no page could be found. + /// ISO 32000-2 Table 357 (Pg) and Table 355 (Pg). + public PdfPage? Page { get; } + + /// Gets the content stream holding the sequence when it is not the page's content (Stm), or . + /// ISO 32000-2 §14.7.5.2, Table 357: a form XObject or an annotation's appearance stream. + public CosStream? ContentStream { get; } + + /// Gets the object owning (StmOwn, for instance the annotation of an appearance stream), or . + /// ISO 32000-2 §14.7.5.2, Table 357. + public CosObject? ContentStreamOwner { get; } + + /// The page object of (or the Pg found, when it is not in the page tree). + internal CosDictionary? PageObject { get; } + + /// The object whose content stream holds the MCID: , else the page object. The MCID index key. + internal CosObject? StreamKey => (CosObject?)ContentStream ?? PageObject; +} diff --git a/src/Broadside/Structure/PdfObjectReference.cs b/src/Broadside/Structure/PdfObjectReference.cs new file mode 100644 index 00000000..f366a4ad --- /dev/null +++ b/src/Broadside/Structure/PdfObjectReference.cs @@ -0,0 +1,38 @@ +using Broadside.Objects; + +namespace Broadside.Structure; + +/// A content item that is a whole PDF object, such as an annotation or an XObject: an object reference dictionary (/Type /OBJR). +/// +/// ISO 32000-2 §14.7.5.3, Table 358. The object carries a StructParent entry whose parent-tree value leads back to +/// (§14.7.5.4). The page is the dictionary's Pg, else the element's. +/// +public sealed class PdfObjectReference : PdfStructureItem +{ + internal PdfObjectReference(PdfStructureElement parent, CosDictionary dictionary, CosObject referencedObject, CosReference? objectReference, PdfPage? page) + { + Parent = parent; + Dictionary = dictionary; + ReferencedObject = referencedObject; + ObjectReference = objectReference; + Page = page; + } + + /// + public override PdfStructureElement Parent { get; } + + /// Gets the object reference dictionary. + /// ISO 32000-2 §14.7.5.3, Table 358. + public CosDictionary Dictionary { get; } + + /// Gets the object that is the content item (Obj), resolved; when it does not exist. + /// ISO 32000-2 §14.7.5.3, Table 358 (required, an indirect reference). + public CosObject ReferencedObject { get; } + + /// Gets the indirect reference Obj holds, or when it holds the object directly. + public CosReference? ObjectReference { get; } + + /// Gets the page the object is rendered on, or when no page could be found. + /// ISO 32000-2 Table 358 (Pg) and Table 355 (Pg). + public PdfPage? Page { get; } +} diff --git a/src/Broadside/Structure/PdfPrintFieldAttributes.cs b/src/Broadside/Structure/PdfPrintFieldAttributes.cs new file mode 100644 index 00000000..ea006f33 --- /dev/null +++ b/src/Broadside/Structure/PdfPrintFieldAttributes.cs @@ -0,0 +1,30 @@ +using Broadside.Objects; + +namespace Broadside.Structure; + +/// An attribute object owned by PrintField: the role and state of a non-interactive form field, on a Form element. +/// ISO 32000-2 §14.8.5.6, Table 383 (PDF 1.7). None is inheritable; Checked defaults to off. +public sealed class PdfPrintFieldAttributes : PdfAttributeObject +{ + private static readonly CosName RoleName = new("Role"); + private static readonly CosName CheckedName = new("Checked"); + private static readonly CosName LegacyCheckedName = new("checked"); + private static readonly CosName DescName = new("Desc"); + + internal PdfPrintFieldAttributes(StructureContext context, CosObject source, CosReference? reference, int revision) + : base(context, source, reference, revision) + { + } + + /// Gets Role: rb (radio button), cb (check box), pb (push button), tv (text value) or lb (list box). + /// ISO 32000-2 Table 383. + public string? Role => NameValue(RoleName); + + /// Gets Checked: on, off or neutral. The lower-case key checked of PDF 1.7, deprecated in PDF 2.0, is read when Checked is absent. + /// ISO 32000-2 Table 383. + public string? Checked => NameValue(CheckedName) ?? NameValue(LegacyCheckedName); + + /// Gets Desc: the field's text description. + /// ISO 32000-2 Table 383. + public string? Description => TextValue(DescName); +} diff --git a/src/Broadside/Structure/PdfPropertyList.cs b/src/Broadside/Structure/PdfPropertyList.cs new file mode 100644 index 00000000..3e45504c --- /dev/null +++ b/src/Broadside/Structure/PdfPropertyList.cs @@ -0,0 +1,106 @@ +using Broadside.Objects; + +namespace Broadside.Structure; + +/// +/// A typed view of a marked-content sequence's tag and property list (the operands of BDC or DP): its MCID, whether it +/// is an artifact and of what kind, and the accessibility entries a Span may carry. +/// +/// +/// +/// ISO 32000-2 §14.6 (Table 352 and errata Table 352a), §14.6.2 (property lists), §14.7.5.2 (MCID), §14.8.2.2.2 (Table 363, +/// artifacts) and §14.9 (Lang, Alt, ActualText, E). The content interpreter resolves the property list +/// (an inline dictionary, or a name looked up in the resources' Properties) and hands the dictionary over; this view only reads +/// it. Look the MCID up with . Optional content (/OC) and associated +/// files (/AF) property lists are typed by the optional content and associated files views. +/// +/// The tag of a marked-content sequence is not role mapped (§14.6.1 NOTE 3). +/// +public sealed class PdfPropertyList +{ + private readonly PdfDocument? _document; + + /// Creates the view. + /// The sequence's tag, the name operand of BMC, BDC, MP or DP. + /// The resolved property list, or for BMC and MP. + /// The document, to resolve indirect references a named property list may hold; for an inline dictionary. + public PdfPropertyList(CosName tag, CosDictionary? properties, PdfDocument? document) + { + ArgumentNullException.ThrowIfNull(tag); + Tag = tag; + Properties = properties; + _document = document; + } + + /// Gets the tag. + /// ISO 32000-2 §14.6.1, Table 352. + public CosName Tag { get; } + + /// Gets the property list, or . + /// ISO 32000-2 §14.6.2. + public CosDictionary? Properties { get; } + + /// Gets the marked-content identifier (MCID), when the sequence is a content item of a structure element. + /// ISO 32000-2 §14.7.5.2. + public int? Mcid => Properties is { } properties && StructureValues.Integer(_document, properties, StructureNames.MCID) is >= 0 and var mcid ? mcid : null; + + /// Gets a value indicating whether the sequence is an artifact (tag Artifact): content that is not part of the document's real content. + /// ISO 32000-2 §14.8.2.2. + public bool IsArtifact => StructureNames.Artifact.Equals(Tag); + + /// Gets the artifact type (Type): Pagination, Layout, Page or Background; when absent or not an artifact. + /// ISO 32000-2 §14.8.2.2.2, Table 363. + public string? ArtifactType => ArtifactName(KnownNames.Type); + + /// Gets the artifact subtype (Subtype, PDF 1.7): Header, Footer, Watermark, PageNum, Bates, LineNum or Redaction. + /// ISO 32000-2 §14.8.2.2.2, Table 363. + public string? ArtifactSubtype => ArtifactName(StructureNames.Subtype); + + /// Gets the artifact's bounding box (BBox), or . + /// ISO 32000-2 §14.8.2.2.2, Table 363. + public PdfRectangle? ArtifactBoundingBox => IsArtifact && Properties is { } properties ? StructureValues.Rectangle(_document, properties, StructureNames.BBox) : null; + + /// Gets the page edges a pagination artifact is attached to (Attached): Top, Bottom, Left, Right. + /// ISO 32000-2 §14.8.2.2.2, Table 363. + public IReadOnlyList ArtifactAttachments + { + get + { + if (!IsArtifact || Properties is not { } properties || StructureValues.Get(_document, properties, StructureNames.Attached) is not CosArray array) + { + return []; + } + + var edges = new List(array.Count); + foreach (CosObject item in array) + { + if ((_document?.Resolve(item) ?? item) is CosName edge) + { + edges.Add(edge.Value); + } + } + + return edges; + } + } + + /// Gets the natural language of the sequence's content (Lang), or . + /// ISO 32000-2 §14.9.2.2, Table 352a (Span). + public string? Language => TextEntry(StructureNames.Lang); + + /// Gets the alternate description (Alt), or . + /// ISO 32000-2 §14.9.3, Table 352a (Span, PDF 1.5). + public string? AlternateDescription => TextEntry(StructureNames.Alt); + + /// Gets the replacement text (ActualText), or . + /// ISO 32000-2 §14.9.4, Table 352a (Span, PDF 1.4). + public string? ActualText => TextEntry(StructureNames.ActualText); + + /// Gets the expansion of an abbreviation (E), or . + /// ISO 32000-2 §14.9.5, Table 352a (Span, PDF 1.5). + public string? Expansion => TextEntry(StructureNames.E); + + private string? TextEntry(CosName key) => Properties is { } properties ? StructureValues.Text(_document, properties, key) : null; + + private string? ArtifactName(CosName key) => IsArtifact && Properties is { } properties ? StructureValues.Name(_document, properties, key)?.Value : null; +} diff --git a/src/Broadside/Structure/PdfStructureElement.cs b/src/Broadside/Structure/PdfStructureElement.cs new file mode 100644 index 00000000..2360d893 --- /dev/null +++ b/src/Broadside/Structure/PdfStructureElement.cs @@ -0,0 +1,433 @@ +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Structure; + +/// A structure element: one node of a document's structure tree, a live view over its structure element dictionary. +/// +/// +/// ISO 32000-2 §14.7.2, Table 355. Every property reads the dictionary when called (ADR 0004); enumerates +/// K on each call. Two views of the same dictionary are equal. +/// +/// +/// The tree's shape comes from K, read downward from the root: is the element whose K holds this one, +/// not what this element's P entry says. A P that disagrees is a StructElemParentMismatch diagnostic. A child +/// that is the element itself or one of its ancestors (a cycle) is left out of with a StructTreeCycle +/// diagnostic, and the hierarchy is cut below 256 levels (StructTreeDepthExceeded), so a recursive walk over +/// always ends. +/// +/// +public sealed class PdfStructureElement : PdfStructureItem, IEquatable +{ + private readonly StructureContext _context; + private readonly PdfStructureElement? _parent; + private readonly bool _parentKnown; + + internal PdfStructureElement(StructureContext context, CosDictionary dictionary, CosReference? reference, PdfStructureElement? parent, bool parentKnown, int depth) + { + _context = context; + Dictionary = dictionary; + Reference = reference; + _parent = parent; + _parentKnown = parentKnown; + Depth = depth; + } + + /// Gets the structure element dictionary. + /// ISO 32000-2 §14.7.2, Table 355. + public CosDictionary Dictionary { get; } + + /// Gets the indirect reference to the element, when it was reached through one. + public CosReference? Reference { get; } + + /// + /// + /// ISO 32000-2 §14.7.2. The element whose K holds this one, found by walking the tree from the root; + /// for a child of the root, and for an element that is not reachable from the root. + /// + public override PdfStructureElement? Parent => + _parentKnown ? _parent : _context.Walk.TryGet(Dictionary, out PdfStructureElement? walked) ? walked.Parent : null; + + /// Gets the structure type (S), or when the element has none. + /// ISO 32000-2 §14.7.3, Table 355 (required). + public CosName? StructureType => StructureValues.Name(_context.Document, Dictionary, StructureNames.S); + + /// + /// Gets the namespace the element is in: its NS namespace dictionary, or , the + /// default namespace, when it has none. + /// + /// + /// ISO 32000-2 §14.7.4, Table 355 (NS, PDF 2.0) and §14.8.6.2: a namespace an element uses shall be listed in the root's + /// Namespaces array; one that is not is still used, with a NamespaceNotDeclared diagnostic. + /// + public PdfStructureNamespace Namespace + { + get + { + if (!Dictionary.TryGetValue(StructureNames.NS, out CosObject? value) || _context.Resolve(value) is not CosDictionary ns) + { + return PdfStructureNamespace.Pdf17; + } + + if (!_context.IsDeclared(ns)) + { + _context.Report(DiagnosticCodes.NamespaceNotDeclared, "A structure element's namespace is not in the structure tree root's Namespaces array (§14.8.6.2); used anyway.", Reference); + } + + return _context.Namespace(ns, value as CosReference); + } + } + + /// Gets the standard structure type the element's type resolves to through the role maps, or when it resolves to none. + /// + /// ISO 32000-2 §14.7.3, §14.7.4.2, §14.8.6.2; ISO/TS 32005 §5.6. In a tagged PDF () every element shall + /// resolve to a standard type (§14.8.4.1); one that does not is a StructureTypeUnresolved diagnostic. See + /// for the chain followed. + /// + public PdfStructureType? StandardType + { + get + { + if (StructureType is not { } type) + { + return null; + } + + RoleResolution resolution = _context.ResolveRole(type, Namespace); + if (resolution.Standard is null && _context.IsTagged) + { + _context.Report(DiagnosticCodes.StructureTypeUnresolved, $"The structure type /{type.Value} does not resolve to a standard structure type through the role maps (§14.8.4.1).", Reference); + } + + return resolution.Standard; + } + } + + /// + /// Gets the role-mapping chain: the element's own type in its namespace, then each type the root's RoleMap (default + /// namespace) or a namespace's RoleMapNS maps it to, until no map applies or a type repeats. + /// + /// ISO 32000-2 §14.7.3 (cycles are permitted, NOTE 2), §14.7.4.2, §14.8.6.2. Empty when the element has no type. + public IReadOnlyList RoleMapping => StructureType is { } type ? _context.ResolveRole(type, Namespace).Chain : []; + + /// Gets the element identifier (ID), a byte string unique in the document, or . + /// ISO 32000-2 Table 355; looked up through . + public CosString? Id => StructureValues.Get(_context.Document, Dictionary, StructureNames.ID) as CosString; + + /// Gets the title (T), or . + /// ISO 32000-2 Table 355. + public string? Title => StructureValues.Text(_context.Document, Dictionary, StructureNames.T); + + /// Gets the element's own natural language (Lang, a BCP 47 tag), or . + /// ISO 32000-2 Table 355 (PDF 1.4), §14.9.2. + public string? Language => StructureValues.Text(_context.Document, Dictionary, StructureNames.Lang); + + /// Gets the natural language in effect: , else the nearest ancestor's, else the catalog's Lang; when none says. + /// ISO 32000-2 §14.9.2.3: a language specification applies to the element and everything nested in it. + public string? EffectiveLanguage + { + get + { + for (PdfStructureElement? element = this; element is not null; element = element.Parent) + { + if (element.Language is { } language) + { + return language; + } + } + + return StructureValues.Text(_context.Document, _context.Document.Catalog, StructureNames.Lang); + } + } + + /// Gets the alternate description (Alt), or . + /// ISO 32000-2 Table 355, §14.9.3. + public string? AlternateDescription => StructureValues.Text(_context.Document, Dictionary, StructureNames.Alt); + + /// Gets the expansion of an abbreviation or acronym (E), or . + /// ISO 32000-2 Table 355 (PDF 1.5), §14.9.5. + public string? Expansion => StructureValues.Text(_context.Document, Dictionary, StructureNames.E); + + /// Gets the replacement text (ActualText), or . + /// ISO 32000-2 Table 355 (PDF 1.4), §14.9.4. + public string? ActualText => StructureValues.Text(_context.Document, Dictionary, StructureNames.ActualText); + + /// Gets the element's revision number (R); 0 when absent. + /// ISO 32000-2 Table 355, §14.7.6.3 (deprecated in PDF 2.0). + public int Revision => StructureValues.Integer(_context.Document, Dictionary, StructureNames.R) is { } revision and >= 0 ? revision : 0; + + /// Gets the phonetic alphabet in effect for : the element's PhoneticAlphabet, else the nearest ancestor's, else ipa. + /// ISO 32000-2 Table 355 (PDF 2.0), §14.9.6. + public string PhoneticAlphabet + { + get + { + for (PdfStructureElement? element = this; element is not null; element = element.Parent) + { + if (StructureValues.Name(_context.Document, element.Dictionary, StructureNames.PhoneticAlphabet) is { } alphabet) + { + return alphabet.Value; + } + } + + return "ipa"; + } + } + + /// Gets the pronunciation hint (Phoneme), or . + /// ISO 32000-2 Table 355 (PDF 2.0), §14.9.6. + public string? Phoneme => StructureValues.Text(_context.Document, Dictionary, StructureNames.Phoneme); + + /// Gets the page named by the element's own Pg, or . + /// ISO 32000-2 Table 355. Content items carry their effective page (). + public PdfPage? Page => _context.FindPage(Dictionary.TryGetValue(StructureNames.Pg, out CosObject? page) ? page : null); + + /// Gets the elements this element refers to (Ref), such as the footnote a reference points at. + /// ISO 32000-2 Table 355 (PDF 2.0). + public IReadOnlyList References + { + get + { + if (StructureValues.Get(_context.Document, Dictionary, StructureNames.Ref) is not CosArray array) + { + return []; + } + + var references = new List(array.Count); + foreach (CosObject item in array) + { + if (_context.Resolve(item) is CosDictionary element) + { + references.Add(_context.Walk.TryGet(element, out PdfStructureElement? walked) + ? walked + : new PdfStructureElement(_context, element, item as CosReference, null, parentKnown: false, depth: 0)); + } + } + + return references; + } + } + + /// Gets the associated files (AF) as their COS array, or . + /// ISO 32000-2 Table 355 (PDF 2.0), §14.13. Typed by the file specification view (issue #76). + public CosArray? AssociatedFiles => StructureValues.Get(_context.Document, Dictionary, StructureNames.AF) as CosArray; + + /// Gets the attribute objects of the A entry, in order, each with its revision number. + /// ISO 32000-2 Table 355 (A), §14.7.6.1, §14.7.6.3. + public IReadOnlyList Attributes => + AttributeReader.ReadObjects(_context, Dictionary.TryGetValue(StructureNames.A, out CosObject? value) ? value : null, Reference); + + /// Gets the attribute class names of the C entry, in order. + /// ISO 32000-2 Table 355 (C), §14.7.6.2. + public IReadOnlyList ClassNames => [.. ReadClassNames().Select(static entry => entry.Name)]; + + /// Gets the attribute objects the classes of stand for in the root's ClassMap, in class order. + /// ISO 32000-2 §14.7.6.2. A class not in the class map contributes nothing. + public IReadOnlyList ClassAttributes + { + get + { + var attributes = new List(); + foreach ((CosName name, int revision) in ReadClassNames()) + { + attributes.AddRange(AttributeReader.ReadClass(_context, name, revision, Reference)); + } + + return attributes; + } + } + + /// + /// Gets the children (K), in logical order: structure elements, marked-content references and object references. + /// + /// + /// ISO 32000-2 Table 355 (K), §14.7.5, §14.8.2.5 (the order of K is the logical reading order). Entries that are not + /// valid children, and children that would close a cycle or exceed the depth limit, are left out with a diagnostic. + /// + public IReadOnlyList Children + { + get + { + var children = new List(); + foreach (CosObject entry in KidReader.Entries(_context, Dictionary)) + { + Kid kid = KidReader.Classify(_context, entry, Reference); + switch (kid.Kind) + { + case KidKind.Element: + if (IsSelfOrAncestor(kid.Dictionary!)) + { + _context.Report(DiagnosticCodes.StructTreeCycle, "A structure element's K holds the element itself or one of its ancestors (§14.7.2); left out.", kid.Reference ?? Reference); + } + else if (Depth + 1 >= StructureContext.MaxDepth) + { + _context.Report(DiagnosticCodes.StructTreeDepthExceeded, $"The structure hierarchy nests deeper than {StructureContext.MaxDepth} levels; the rest is not read.", Reference); + } + else + { + children.Add(new PdfStructureElement(_context, kid.Dictionary!, kid.Reference, this, parentKnown: true, Depth + 1)); + } + + break; + case KidKind.MarkedContent: + children.Add(CreateMarkedContent(kid)); + break; + case KidKind.Object: + children.Add(CreateObjectReference(kid)); + break; + } + } + + return children; + } + } + + /// The depth of the element below the root (a child of the root is 0), as far as the view knows it. + internal int Depth { get; } + + /// Returns the content items among : the marked-content and object references, in order. + /// The content items. + /// ISO 32000-2 §14.7.5.1.1. + public IReadOnlyList GetContentItems() => [.. Children.Where(static item => item is not PdfStructureElement)]; + + /// + /// Returns the value of attribute of in effect for this element: from its + /// A entry, else from its classes (C), else inherited from the parent when the attribute is inheritable, else the + /// attribute's default. + /// + /// The attribute owner, such as Layout, List, PrintField or Table. + /// The attribute name. + /// The value, or when no source gives one (or the default depends on the element, such as Placement). + /// + /// ISO 32000-2 §14.8.5.3 steps 2-5 and §14.7.6.2: within A, and within the classes, a later object wins; A wins over + /// C. Inheritable attributes and defaults follow Tables 378-385 (errata Table 377); TextDecorationType is not + /// inherited. Format owners (step 1, CSS-3 and the like) are not consulted. + /// + public CosObject? GetAttributeValue(CosName owner, CosName name) + { + ArgumentNullException.ThrowIfNull(owner); + ArgumentNullException.ThrowIfNull(name); + for (PdfStructureElement? element = this; element is not null; element = element.Parent) + { + if ((Find(element.Attributes, owner, name) ?? Find(element.ClassAttributes, owner, name)) is { } value) + { + return value; + } + + if (!StandardAttributes.IsInheritable(owner, name)) + { + break; + } + } + + return StandardAttributes.DefaultValue(owner, name); + } + + /// + public bool Equals(PdfStructureElement? other) => other is not null && ReferenceEquals(Dictionary, other.Dictionary); + + /// + public override bool Equals(object? obj) => Equals(obj as PdfStructureElement); + + /// + public override int GetHashCode() => System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(Dictionary); + + /// + public override string ToString() => Reference is { } reference ? $"{StructureType?.Value} {reference}" : StructureType?.Value ?? string.Empty; + + /// Creates the marked-content reference for a classified K entry, with its effective page. + internal PdfMarkedContentReference CreateMarkedContent(Kid kid) + { + CosDictionary? mcr = kid.Dictionary; + CosStream? stream = mcr is null ? null : StructureValues.Get(_context.Document, mcr, StructureNames.Stm) as CosStream; + CosObject? owner = mcr is null ? null : StructureValues.Get(_context.Document, mcr, StructureNames.StmOwn); + CosDictionary? pageObject = EffectivePage(mcr, kid.Mcid, reportMissing: stream is null); + PdfPage? page = pageObject is not null && _context.Document.Pages.TryGetPage(pageObject, out PdfPage? found) ? found : null; + return new PdfMarkedContentReference(this, mcr, kid.Mcid, page, pageObject, stream, owner); + } + + /// Creates the object reference for a classified K entry. + internal PdfObjectReference CreateObjectReference(Kid kid) + { + CosDictionary objr = kid.Dictionary!; + objr.TryGetValue(StructureNames.Obj, out CosObject? target); + CosObject referenced = _context.Resolve(target); + CosDictionary? pageObject = StructureValues.Get(_context.Document, objr, StructureNames.Pg) as CosDictionary + ?? StructureValues.Get(_context.Document, Dictionary, StructureNames.Pg) as CosDictionary + ?? (referenced is CosDictionary annotation ? StructureValues.Get(_context.Document, annotation, StructureNames.P) as CosDictionary : null); + PdfPage? page = pageObject is not null && _context.Document.Pages.TryGetPage(pageObject, out PdfPage? found) ? found : null; + return new PdfObjectReference(this, objr, referenced, target as CosReference, page); + } + + /// + /// The page object of a marked-content item: the MCR's Pg, else the element's (Table 357); else, as a repair, the nearest + /// ancestor's, with a StructElemPageMissing diagnostic. Failing that, the page whose parent-tree array lists the element at + /// that MCID. + /// + internal CosDictionary? EffectivePage(CosDictionary? item, int mcid, bool reportMissing) + { + if (item is not null && StructureValues.Get(_context.Document, item, StructureNames.Pg) is CosDictionary itemPage) + { + return itemPage; + } + + if (StructureValues.Get(_context.Document, Dictionary, StructureNames.Pg) is CosDictionary ownPage) + { + return ownPage; + } + + for (PdfStructureElement? ancestor = Parent; ancestor is not null; ancestor = ancestor.Parent) + { + if (StructureValues.Get(_context.Document, ancestor.Dictionary, StructureNames.Pg) is CosDictionary inherited) + { + _context.Report(DiagnosticCodes.StructElemPageMissing, "A structure element holds MCIDs but has no Pg (Table 355); the nearest ancestor's page is used.", Reference); + return inherited; + } + } + + if (!reportMissing) + { + return null; + } + + CosDictionary? fromParentTree = _context.PageFromParentTree(Dictionary, mcid); + _context.Report( + DiagnosticCodes.StructElemPageMissing, + fromParentTree is null + ? "A structure element holds MCIDs but no Pg names their page (Table 355); their page is unknown." + : "A structure element holds MCIDs but no Pg names their page (Table 355); the page whose parent-tree entry lists it is used.", + Reference); + return fromParentTree; + } + + private static CosObject? Find(IReadOnlyList attributes, CosName owner, CosName name) + { + for (int index = attributes.Count - 1; index >= 0; index--) + { + PdfAttributeObject candidate = attributes[index]; + if (owner.Equals(candidate.Owner) && candidate.GetValue(name) is { } value) + { + return value; + } + } + + return null; + } + + private List<(CosName Name, int Revision)> ReadClassNames() => + AttributeReader.ReadClassNames(_context, Dictionary.TryGetValue(StructureNames.C, out CosObject? value) ? value : null, Reference); + + private bool IsSelfOrAncestor(CosDictionary candidate) + { + int steps = 0; + for (PdfStructureElement? element = this; element is not null && steps <= StructureContext.MaxDepth; element = element.Parent, steps++) + { + if (ReferenceEquals(element.Dictionary, candidate)) + { + return true; + } + } + + return false; + } +} diff --git a/src/Broadside/Structure/PdfStructureItem.cs b/src/Broadside/Structure/PdfStructureItem.cs new file mode 100644 index 00000000..fb18067c --- /dev/null +++ b/src/Broadside/Structure/PdfStructureItem.cs @@ -0,0 +1,16 @@ +namespace Broadside.Structure; + +/// +/// One child of a structure element (an entry of its K): another , a marked-content sequence +/// () or a whole PDF object (). +/// +/// ISO 32000-2 §14.7.2, Table 355 (K), and §14.7.5.1.1: the last two are content items, the leaves of the tree. +public abstract class PdfStructureItem +{ + private protected PdfStructureItem() + { + } + + /// Gets the structure element whose K holds this item, or for a top-level element (a child of the root). + public abstract PdfStructureElement? Parent { get; } +} diff --git a/src/Broadside/Structure/PdfStructureNamespace.cs b/src/Broadside/Structure/PdfStructureNamespace.cs new file mode 100644 index 00000000..d8aa8353 --- /dev/null +++ b/src/Broadside/Structure/PdfStructureNamespace.cs @@ -0,0 +1,140 @@ +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Structure; + +/// A structure namespace: a namespace dictionary of the structure tree, or one of the namespaces the standard defines. +/// +/// +/// ISO 32000-2 §14.7.4 (Table 356) and §14.8.6. A structure element without an NS entry is in the default namespace, +/// , even in a PDF 2.0 file (§14.8.6.1). Two namespaces are equal when they have the same namespace name: a +/// namespace dictionary naming http://iso.org/pdf2/ssn equals , whatever object it is (§14.7.4.2). +/// +/// +/// A view over its dictionary (ADR 0004): , and read it on every call. +/// The Schema file specification is exposed as its COS object until the file specification view (issue #76) types it. +/// +/// +public sealed class PdfStructureNamespace : IEquatable +{ + /// The namespace name of the standard structure namespace for PDF 1.7, the default namespace (§14.8.6.1). + public const string Pdf17Name = "http://iso.org/pdf/ssn"; + + /// The namespace name of the standard structure namespace for PDF 2.0 (§14.8.6.1). + public const string Pdf20Name = "http://iso.org/pdf2/ssn"; + + /// The namespace name of MathML 3.0 (§14.8.6.3). + public const string MathMLName = "http://www.w3.org/1998/Math/MathML"; + + private readonly StructureContext? _context; + private readonly PdfStructureNamespaceKind _fixedKind; + + private PdfStructureNamespace(PdfStructureNamespaceKind kind) => _fixedKind = kind; + + internal PdfStructureNamespace(StructureContext context, CosDictionary dictionary, CosReference? reference) + { + _context = context; + Dictionary = dictionary; + Reference = reference; + if (StructureValues.Get(context.Document, dictionary, StructureNames.NS) is not CosString) + { + context.Report(DiagnosticCodes.NamespaceInvalid, "A namespace dictionary has no NS text string (Table 356); its namespace name reads as empty.", reference); + } + + if (StructureValues.Get(context.Document, dictionary, Objects.KnownNames.Type) is { } type && !StructureNames.Namespace.Equals(type)) + { + context.Report(DiagnosticCodes.NamespaceInvalid, "A namespace dictionary's Type is not Namespace (Table 356); read as a namespace.", reference); + } + } + + /// Gets the standard structure namespace for PDF 1.7: the default namespace of every element without NS. + /// ISO 32000-2 §14.8.6.1; Annex M. + public static PdfStructureNamespace Pdf17 { get; } = new(PdfStructureNamespaceKind.Pdf17); + + /// Gets the standard structure namespace for PDF 2.0. + /// ISO 32000-2 §14.8.6.1, §14.8.4. + public static PdfStructureNamespace Pdf20 { get; } = new(PdfStructureNamespaceKind.Pdf20); + + /// Gets the MathML 3.0 namespace. + /// ISO 32000-2 §14.8.6.3. + public static PdfStructureNamespace MathML { get; } = new(PdfStructureNamespaceKind.MathML); + + /// Gets the namespace dictionary, or for , and . + /// ISO 32000-2 §14.7.4.2, Table 356. + public CosDictionary? Dictionary { get; } + + /// Gets the indirect reference to the namespace dictionary, when it was reached through one. + public CosReference? Reference { get; } + + /// Gets the namespace name (NS), conventionally a URI; empty when the dictionary has none. + /// ISO 32000-2 §14.7.4.2, Table 356 (required, PDF 2.0). + public string Name => Dictionary is null + ? _fixedKind switch + { + PdfStructureNamespaceKind.Pdf17 => Pdf17Name, + PdfStructureNamespaceKind.Pdf20 => Pdf20Name, + _ => MathMLName, + } + : StructureValues.Text(_context?.Document, Dictionary, StructureNames.NS) ?? string.Empty; + + /// Gets which namespace this is, from its namespace name. + /// ISO 32000-2 §14.8.6. + public PdfStructureNamespaceKind Kind => Dictionary is null + ? _fixedKind + : Name switch + { + Pdf17Name => PdfStructureNamespaceKind.Pdf17, + Pdf20Name => PdfStructureNamespaceKind.Pdf20, + MathMLName => PdfStructureNamespaceKind.MathML, + _ => PdfStructureNamespaceKind.Custom, + }; + + /// Gets a value indicating whether this is the default namespace: the one an element without an NS entry is in. + /// ISO 32000-2 §14.8.6.1. Its role mapping comes from the structure tree root's RoleMap, not from a RoleMapNS. + public bool IsDefault => Dictionary is null && _fixedKind == PdfStructureNamespaceKind.Pdf17; + + /// Gets the namespace's role map (RoleMapNS), or . + /// + /// ISO 32000-2 §14.7.4.2, Table 356: each key is a type in this namespace; each value a type name in the default namespace, or + /// [name namespace] naming a type in another namespace. + /// + public CosDictionary? RoleMap => Dictionary is null ? null : StructureValues.Get(_context?.Document, Dictionary, StructureNames.RoleMapNS) as CosDictionary; + + /// Gets the schema file specification (Schema), as its COS object, or . + /// ISO 32000-2 §14.7.4.2, Table 356. + public CosObject? Schema => Dictionary is null ? null : StructureValues.Get(_context?.Document, Dictionary, StructureNames.Schema); + + /// Returns whether is a standard structure type of this namespace. + /// The structure type name. + /// + /// For the PDF 1.7 and PDF 2.0 namespaces, whether the type is in their set (§14.8.4, Annex M: Em, Strong, + /// Title, H7 and the other PDF 2.0 additions are not standard in PDF 1.7, and Art, Note, Code and + /// the other PDF 1.7 types Annex M lists are not standard in PDF 2.0); for MathML, any non-empty name (element names are not checked + /// against the MathML 3.0 schema); for a custom namespace, . + /// + /// ISO 32000-2 §14.8.4, §14.8.6, Annex M; ISO/TS 32005 §5.3-§5.5. + public bool IsStandardType(string type) + { + ArgumentNullException.ThrowIfNull(type); + return Kind switch + { + PdfStructureNamespaceKind.Pdf17 => StandardStructureTypes.IsPdf17(type), + PdfStructureNamespaceKind.Pdf20 => StandardStructureTypes.IsPdf20(type), + PdfStructureNamespaceKind.MathML => type.Length > 0, + _ => false, + }; + } + + /// + public bool Equals(PdfStructureNamespace? other) => + other is not null && (ReferenceEquals(this, other) || (Kind == other.Kind && (Kind != PdfStructureNamespaceKind.Custom || Name == other.Name))); + + /// + public override bool Equals(object? obj) => Equals(obj as PdfStructureNamespace); + + /// + public override int GetHashCode() => Kind == PdfStructureNamespaceKind.Custom ? HashCode.Combine(Kind, Name) : Kind.GetHashCode(); + + /// + public override string ToString() => Name; +} diff --git a/src/Broadside/Structure/PdfStructureNamespaceKind.cs b/src/Broadside/Structure/PdfStructureNamespaceKind.cs new file mode 100644 index 00000000..3db13a41 --- /dev/null +++ b/src/Broadside/Structure/PdfStructureNamespaceKind.cs @@ -0,0 +1,18 @@ +namespace Broadside.Structure; + +/// Which namespace a structure namespace is, by its namespace name. +/// ISO 32000-2 §14.8.6: the two standard structure namespaces and MathML 3.0, the one other namespace §14.8.6.3 identifies. +public enum PdfStructureNamespaceKind +{ + /// Any other namespace: its types are custom and reach a standard type only through its RoleMapNS. + Custom = 0, + + /// The standard structure namespace for PDF 1.7, http://iso.org/pdf/ssn: the default namespace (§14.8.6.1). + Pdf17 = 1, + + /// The standard structure namespace for PDF 2.0, http://iso.org/pdf2/ssn (§14.8.6.1). + Pdf20 = 2, + + /// MathML 3.0, http://www.w3.org/1998/Math/MathML (§14.8.6.3). + MathML = 3, +} diff --git a/src/Broadside/Structure/PdfStructureTreeRoot.cs b/src/Broadside/Structure/PdfStructureTreeRoot.cs new file mode 100644 index 00000000..f943bf81 --- /dev/null +++ b/src/Broadside/Structure/PdfStructureTreeRoot.cs @@ -0,0 +1,196 @@ +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Structure; + +/// The root of a document's structure tree: its top-level elements, role and class maps, namespaces, and the lookups from content to elements. +/// +/// +/// ISO 32000-2 §14.7.2, Table 354. A live view over the structure tree root dictionary (ADR 0004): and the map +/// properties read it on every call. The lookups (, , +/// ) use indexes built on first use and kept: they are a snapshot of the tree as it was then, safe to use from +/// several threads while nobody changes the document. Replacing the catalog's StructTreeRoot starts a new snapshot. +/// +/// +/// Reading never changes the file's objects; every repair (a wrong P, a missing Pg, a cycle) is made in the view and +/// recorded as a diagnostic when the part concerned is first read. +/// +/// +public sealed class PdfStructureTreeRoot +{ + private readonly StructureContext _context; + + internal PdfStructureTreeRoot(StructureContext context) => _context = context; + + /// Gets the structure tree root dictionary. + /// ISO 32000-2 §14.7.2, Table 354. + public CosDictionary Dictionary => _context.Root; + + /// Gets the indirect reference to the root, when the catalog holds one. + public CosReference? Reference => _context.RootReference; + + /// Gets the top-level structure elements (K), in logical order. + /// ISO 32000-2 Table 354: the root's children are structure elements only; anything else is left out with a diagnostic. + public IReadOnlyList Children + { + get + { + var children = new List(); + foreach (CosObject entry in KidReader.Entries(_context, Dictionary)) + { + Kid kid = KidReader.Classify(_context, entry, Reference); + if (kid.Kind == KidKind.Element && !ReferenceEquals(kid.Dictionary, Dictionary)) + { + children.Add(new PdfStructureElement(_context, kid.Dictionary!, kid.Reference, null, parentKnown: true, depth: 0)); + } + else if (kid.Kind != KidKind.Invalid) + { + _context.Report(DiagnosticCodes.StructTreeRootInvalid, "The structure tree root's K holds something other than a structure element (Table 354); skipped.", Reference); + } + } + + return children; + } + } + + /// Gets the role map (RoleMap): structure types of the default namespace mapped to other types, or . + /// ISO 32000-2 Table 354, §14.7.3. Applied by . + public CosDictionary? RoleMap => StructureValues.Get(_context.Document, Dictionary, StructureNames.RoleMap) as CosDictionary; + + /// Gets the class map (ClassMap): attribute class names mapped to attribute objects, or . + /// ISO 32000-2 Table 354, §14.7.6.2. Applied by . + public CosDictionary? ClassMap => StructureValues.Get(_context.Document, Dictionary, StructureNames.ClassMap) as CosDictionary; + + /// Gets the namespaces the document declares (Namespaces), in order. + /// ISO 32000-2 Table 354 (PDF 2.0), §14.7.4. + public IReadOnlyList Namespaces + { + get + { + if (StructureValues.Get(_context.Document, Dictionary, StructureNames.Namespaces) is not CosArray array) + { + return []; + } + + var namespaces = new List(array.Count); + foreach (CosObject item in array) + { + if (_context.Resolve(item) is CosDictionary ns) + { + namespaces.Add(_context.Namespace(ns, item as CosReference)); + } + } + + return namespaces; + } + } + + /// Gets ParentTreeNextKey, the key the next parent-tree entry will use, or . + /// ISO 32000-2 Table 354, §14.7.5.4. + public int? ParentTreeNextKey => StructureValues.Integer(_context.Document, Dictionary, StructureNames.ParentTreeNextKey); + + /// Gets the pronunciation lexicons (PronunciationLexicon) as their COS array of file specifications, or . + /// ISO 32000-2 Table 354 (PDF 2.0), §14.9.6. Typed by the file specification view (issue #76). + public CosArray? PronunciationLexicon => StructureValues.Get(_context.Document, Dictionary, StructureNames.PronunciationLexicon) as CosArray; + + /// Gets the associated files of the whole tree (AF) as their COS array, or . + /// ISO 32000-2 Table 354 (PDF 2.0), §14.13. Typed by the file specification view (issue #76). + public CosArray? AssociatedFiles => StructureValues.Get(_context.Document, Dictionary, StructureNames.AF) as CosArray; + + /// Gets every element reachable from the root, in document order: depth first, each element before its children, children in K order; an element reachable twice is listed once. + /// ISO 32000-2 §14.7.2, §14.8.2.5 (logical order). A snapshot, built once. + public IReadOnlyList Elements => _context.Walk.Elements; + + /// Finds the element whose ID is . + /// The identifier's bytes (IDs are byte strings, compared byte for byte). + /// The element, or . + /// + /// ISO 32000-2 Table 354 (IDTree) and Table 355 (ID): looked up in the ID tree; when the tree is missing, does not + /// list the ID, or names an element whose ID differs, the elements reachable through K are searched instead. + /// + public PdfStructureElement? FindElementById(ReadOnlySpan id) + { + if (_context.IdTree is { } tree && tree.TryGetValue(id, out CosObject? value) && value is CosDictionary dictionary) + { + if (StructureValues.Get(_context.Document, dictionary, StructureNames.ID) is CosString own && own.Bytes.SequenceEqual(id)) + { + return new PdfStructureElement(_context, dictionary, null, null, parentKnown: false, depth: 0); + } + + _context.Report(DiagnosticCodes.IdTreeEntryInvalid, "The IDTree maps an ID to an element whose ID differs (Table 354); the element is searched through K.", Reference); + } + + return _context.Walk.TryGetById(id, out PdfStructureElement? element) ? element : null; + } + + /// Finds the structure element that owns the marked-content sequence in the content of . + /// The page whose content stream holds the sequence. + /// The sequence's MCID. + /// The element, or when the sequence is not a content item. + /// ISO 32000-2 §14.7.5.4: through the page's StructParents entry and the parent tree. + public PdfStructureElement? FindElement(PdfPage page, int mcid) + { + ArgumentNullException.ThrowIfNull(page); + return GetMarkedContentElements(page).TryGetValue(mcid, out PdfStructureElement? element) ? element : null; + } + + /// Finds the structure element that owns the marked-content sequence in , a form XObject or another stream with its own StructParents. + /// The content stream holding the sequence. + /// The sequence's MCID. + /// The element, or . + /// ISO 32000-2 §14.7.5.4, Table 359: MCIDs are scoped to their content stream, so MCID 0 of a form is not MCID 0 of the page. + public PdfStructureElement? FindElement(CosStream contentStream, int mcid) + { + ArgumentNullException.ThrowIfNull(contentStream); + return GetMarkedContentElements(contentStream).TryGetValue(mcid, out PdfStructureElement? element) ? element : null; + } + + /// Returns the MCID-to-element map of the content of . + /// The page. + /// The elements owning the page's marked-content content items, by MCID. + /// ISO 32000-2 §14.7.5.4. Built once per page on first use. + public IReadOnlyDictionary GetMarkedContentElements(PdfPage page) + { + ArgumentNullException.ThrowIfNull(page); + return _context.MarkedContent(page.Dictionary).Elements; + } + + /// Returns the MCID-to-element map of . + /// A form XObject or other content stream with its own StructParents. + /// The elements owning its marked-content content items, by MCID. + /// ISO 32000-2 §14.7.5.4. Built once per stream on first use. + public IReadOnlyDictionary GetMarkedContentElements(CosStream contentStream) + { + ArgumentNullException.ThrowIfNull(contentStream); + return _context.MarkedContent(contentStream).Elements; + } + + /// Finds the structure element that has , an annotation or XObject with a StructParent entry, as an object content item. + /// The object: a dictionary, or a stream (an XObject). + /// The element, or . + /// ISO 32000-2 §14.7.5.3, §14.7.5.4, Table 359. + public PdfStructureElement? FindElementForObject(CosObject contentItem) + { + ArgumentNullException.ThrowIfNull(contentItem); + CosObject resolved = _context.Resolve(contentItem); + CosDictionary? dictionary = resolved as CosDictionary ?? (resolved as CosStream)?.Dictionary; + if (_context.ParentTree is { } tree + && dictionary is not null + && StructureValues.Integer(_context.Document, dictionary, StructureNames.StructParent) is { } key + && tree.TryGetValue(key, out CosObject? value)) + { + if (value is CosDictionary parent) + { + var element = new PdfStructureElement(_context, parent, null, null, parentKnown: false, depth: 0); + if (element.Children.Any(item => item is PdfObjectReference reference && ReferenceEquals(reference.ReferencedObject, resolved))) + { + return element; + } + } + + _context.Report(DiagnosticCodes.ParentTreeEntryInvalid, $"The parent tree entry {key} of an object content item does not name an element whose K holds the object (§14.7.5.4); the element is searched through K.", contentItem as CosReference); + } + + return _context.Walk.TryGetObjectParent(resolved, out PdfStructureElement? found) ? found : null; + } +} diff --git a/src/Broadside/Structure/PdfStructureType.cs b/src/Broadside/Structure/PdfStructureType.cs new file mode 100644 index 00000000..bea7dfde --- /dev/null +++ b/src/Broadside/Structure/PdfStructureType.cs @@ -0,0 +1,39 @@ +namespace Broadside.Structure; + +/// A structure type in a namespace: one step of a role-mapping chain, or the standard type an element resolves to. +/// ISO 32000-2 §14.7.3 (structure types), §14.7.4 (namespaces), §14.8.6.2 (role maps and namespaces). +public sealed class PdfStructureType : IEquatable +{ + /// Creates a structure type. + /// The type name, as in a structure element's S entry. + /// The namespace the name is in. + public PdfStructureType(string name, PdfStructureNamespace @namespace) + { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(@namespace); + Name = name; + Namespace = @namespace; + } + + /// Gets the type name. + public string Name { get; } + + /// Gets the namespace the name is in. + public PdfStructureNamespace Namespace { get; } + + /// Gets a value indicating whether the type is a standard type of its namespace. + /// ISO 32000-2 §14.8.4, §14.8.6; see . + public bool IsStandard => Namespace.IsStandardType(Name); + + /// + public bool Equals(PdfStructureType? other) => other is not null && Name == other.Name && Namespace.Equals(other.Namespace); + + /// + public override bool Equals(object? obj) => Equals(obj as PdfStructureType); + + /// + public override int GetHashCode() => HashCode.Combine(Name, Namespace); + + /// + public override string ToString() => $"{Name} ({Namespace.Name})"; +} diff --git a/src/Broadside/Structure/PdfTableAttributes.cs b/src/Broadside/Structure/PdfTableAttributes.cs new file mode 100644 index 00000000..abe46213 --- /dev/null +++ b/src/Broadside/Structure/PdfTableAttributes.cs @@ -0,0 +1,68 @@ +using Broadside.Objects; + +namespace Broadside.Structure; + +/// An attribute object owned by Table, on a table or its cells. +/// +/// ISO 32000-2 §14.8.5.7, Table 384. Each property is this object's own value, when absent. None is inheritable; +/// RowSpan and ColSpan default to 1 through ; the +/// default Scope is computed from the cell's position (§14.8.5.7), which this view does not do. +/// +public sealed class PdfTableAttributes : PdfAttributeObject +{ + private static readonly CosName RowSpanName = new("RowSpan"); + private static readonly CosName ColSpanName = new("ColSpan"); + private static readonly CosName HeadersName = new("Headers"); + private static readonly CosName ScopeName = new("Scope"); + private static readonly CosName SummaryName = new("Summary"); + private static readonly CosName ShortName = new("Short"); + + internal PdfTableAttributes(StructureContext context, CosObject source, CosReference? reference, int revision) + : base(context, source, reference, revision) + { + } + + /// Gets RowSpan: the number of rows the cell spans. + /// ISO 32000-2 Table 384. + public int? RowSpan => IntegerValue(RowSpanName); + + /// Gets ColSpan: the number of columns the cell spans. + /// ISO 32000-2 Table 384. + public int? ColumnSpan => IntegerValue(ColSpanName); + + /// Gets Headers: the IDs of the header cells (TH) of this cell, as byte strings. + /// ISO 32000-2 Table 384; the IDs are those of . + public IReadOnlyList? Headers + { + get + { + if (GetValue(HeadersName) is not CosArray array) + { + return null; + } + + var headers = new List(array.Count); + foreach (CosObject item in array) + { + if (Document.Resolve(item) is CosString id) + { + headers.Add(id); + } + } + + return headers; + } + } + + /// Gets Scope of a header cell: Row, Column or Both (PDF 1.5). + /// ISO 32000-2 Table 384. + public string? Scope => NameValue(ScopeName); + + /// Gets Summary of a table (PDF 1.7). + /// ISO 32000-2 Table 384. + public string? Summary => TextValue(SummaryName); + + /// Gets Short, a short form of a header cell's content (PDF 2.0). + /// ISO 32000-2 Table 384. + public string? ShortForm => TextValue(ShortName); +} diff --git a/src/Broadside/Structure/PdfUserPropertiesAttributes.cs b/src/Broadside/Structure/PdfUserPropertiesAttributes.cs new file mode 100644 index 00000000..f5bf2df1 --- /dev/null +++ b/src/Broadside/Structure/PdfUserPropertiesAttributes.cs @@ -0,0 +1,48 @@ +using Broadside.Objects; + +namespace Broadside.Structure; + +/// An attribute object owned by UserProperties: application-specific properties of an element, such as those of a CAD object. +/// +/// ISO 32000-2 §14.7.6.4, Tables 361 and 362. The document's MarkInfo UserProperties shall be true when an element +/// carries user properties (). A P entry that is not a dictionary, or lacks +/// N or V, is left out of . +/// +public sealed class PdfUserPropertiesAttributes : PdfAttributeObject +{ + internal PdfUserPropertiesAttributes(StructureContext context, CosObject source, CosReference? reference, int revision) + : base(context, source, reference, revision) + { + } + + /// Gets the user properties (P), in order. + /// ISO 32000-2 Table 361 (P) and Table 362 (N, V, F, H). + public IReadOnlyList Properties + { + get + { + if (GetValue(StructureNames.P) is not CosArray array) + { + return []; + } + + var properties = new List(array.Count); + foreach (CosObject item in array) + { + if (Document.Resolve(item) is CosDictionary property + && StructureValues.Text(Document, property, StructureNames.N) is { } name + && StructureValues.Get(Document, property, StructureNames.V) is { } value) + { + properties.Add(new PdfUserProperty( + property, + name, + value, + StructureValues.Text(Document, property, StructureNames.F), + StructureValues.Boolean(Document, property, StructureNames.H) ?? false)); + } + } + + return properties; + } + } +} diff --git a/src/Broadside/Structure/PdfUserProperty.cs b/src/Broadside/Structure/PdfUserProperty.cs new file mode 100644 index 00000000..cc924274 --- /dev/null +++ b/src/Broadside/Structure/PdfUserProperty.cs @@ -0,0 +1,36 @@ +using Broadside.Objects; + +namespace Broadside.Structure; + +/// One user property of a structure element. +/// ISO 32000-2 §14.7.6.4, Table 362. +public sealed class PdfUserProperty +{ + internal PdfUserProperty(CosDictionary dictionary, string name, CosObject value, string? formattedValue, bool isHidden) + { + Dictionary = dictionary; + Name = name; + Value = value; + FormattedValue = formattedValue; + IsHidden = isHidden; + } + + /// Gets the user property dictionary. + public CosDictionary Dictionary { get; } + + /// Gets the property's name (N). + /// ISO 32000-2 Table 362 (required). + public string Name { get; } + + /// Gets the property's value (V), of any type. + /// ISO 32000-2 Table 362 (required). + public CosObject Value { get; } + + /// Gets the formatted value (F) to show instead of , or . + /// ISO 32000-2 Table 362. + public string? FormattedValue { get; } + + /// Gets a value indicating whether the property should be hidden (H; default false). + /// ISO 32000-2 Table 362. + public bool IsHidden { get; } +} diff --git a/src/Broadside/Structure/RoleResolver.cs b/src/Broadside/Structure/RoleResolver.cs new file mode 100644 index 00000000..6797723a --- /dev/null +++ b/src/Broadside/Structure/RoleResolver.cs @@ -0,0 +1,119 @@ +using Broadside.Objects; + +namespace Broadside.Structure; + +/// The outcome of resolving a structure type through the role maps: the chain followed and the standard type reached. +/// The types visited, starting with the element's own type. +/// The standard type the chain resolves to, or . +/// Whether the chain returned to a type it had already visited (or hit the step cap). +internal sealed record RoleResolution(IReadOnlyList Chain, PdfStructureType? Standard, bool EndsInCycle); + +/// Follows role maps from a (type, namespace) pair to a standard structure type. +/// +/// +/// ISO 32000-2 §14.7.3, §14.7.4.2 (Table 356) and §14.8.6.2; ISO/TS 32005 §5.6. A type in the default namespace is mapped through +/// the root's RoleMap, always, even when it is already a standard type (§14.7.3: "shall always be mapped"); a type in an +/// explicit namespace only through that namespace's RoleMapNS. A RoleMapNS value that is a name lands in the DEFAULT +/// namespace (PDF 1.7), not in the source namespace; [name namespace] lands in the named namespace. The chain is followed until +/// no map applies; the type it ends on is the standard type when it is standard in its namespace. +/// +/// +/// Cycles are legal (§14.7.3 NOTE 2: "follow the chain ... until it either finds a structure type it recognises or returns to one it +/// has already encountered"): on a cycle, the first standard type met after the starting type wins, else the starting type when it is +/// standard. pdf.js and PDFBox apply one RoleMap step and ignore RoleMapNS; the chain is the specification's behavior. +/// +/// +internal static class RoleResolver +{ + public static RoleResolution Resolve(StructureContext context, CosName type, PdfStructureNamespace ns) + { + var chain = new List { new(type.Value, ns) }; + CosName currentName = type; + PdfStructureNamespace current = ns; + bool cycle = false; + for (int step = 0; ; step++) + { + if (step == StructureContext.MaxRoleSteps) + { + cycle = true; + break; + } + + CosDictionary? map = current.Dictionary is null + ? current.IsDefault ? StructureValues.Get(context.Document, context.Root, StructureNames.RoleMap) as CosDictionary : null + : current.RoleMap; + if (map is null || !map.TryGetValue(currentName, out CosObject? mapped)) + { + break; + } + + CosName nextName; + PdfStructureNamespace next; + switch (context.Resolve(mapped)) + { + case CosName name: + (nextName, next) = (name, PdfStructureNamespace.Pdf17); + break; + case CosArray { Count: >= 2 } array when context.Resolve(array[0]) is CosName name && context.Resolve(array[1]) is CosDictionary target: + (nextName, next) = (name, context.Namespace(target, array[1] as CosReference)); + break; + default: + nextName = null!; + next = null!; + break; + } + + if (next is null) + { + break; + } + + if (Visited(chain, nextName, next)) + { + cycle = true; + break; + } + + chain.Add(new PdfStructureType(nextName.Value, next)); + (currentName, current) = (nextName, next); + } + + PdfStructureType? standard; + if (!cycle) + { + standard = chain[^1].IsStandard ? chain[^1] : null; + } + else + { + standard = null; + for (int index = 1; index < chain.Count && standard is null; index++) + { + if (chain[index].IsStandard) + { + standard = chain[index]; + } + } + + standard ??= chain[0].IsStandard ? chain[0] : null; + } + + return new RoleResolution(chain, standard, cycle); + } + + private static bool Visited(List chain, CosName name, PdfStructureNamespace ns) + { + foreach (PdfStructureType visited in chain) + { + if (visited.Name == name.Value && SameNamespace(visited.Namespace, ns)) + { + return true; + } + } + + return false; + } + + /// Same map source: the same dictionary, or both the default namespace (which maps through the root's RoleMap). + private static bool SameNamespace(PdfStructureNamespace left, PdfStructureNamespace right) => + left.Dictionary is null ? right.Dictionary is null && left.Kind == right.Kind : ReferenceEquals(left.Dictionary, right.Dictionary); +} diff --git a/src/Broadside/Structure/StandardAttributes.cs b/src/Broadside/Structure/StandardAttributes.cs new file mode 100644 index 00000000..53b037ff --- /dev/null +++ b/src/Broadside/Structure/StandardAttributes.cs @@ -0,0 +1,77 @@ +using Broadside.Objects; + +namespace Broadside.Structure; + +/// Which standard attributes are inheritable, and their default values. +/// +/// ISO 32000-2 §14.8.5.3 and Tables 378-385, with the corrected Table 377 of the 2020 errata. A default that depends on the element +/// (Layout Placement: Block or Inline; Color and BorderColor: the text fill colour; Table Scope: computed +/// from position) has no entry: resolution returns for it. TextDecorationType inherits only into +/// directly nested inline-level elements (Table 380); it is treated as not inheritable. +/// +internal static class StandardAttributes +{ + private static readonly Dictionary<(string Owner, string Name), (bool Inheritable, CosObject? Default)> Table = Build(); + + public static bool IsInheritable(CosName owner, CosName name) => Table.TryGetValue((owner.Value, name.Value), out var entry) && entry.Inheritable; + + public static CosObject? DefaultValue(CosName owner, CosName name) => Table.TryGetValue((owner.Value, name.Value), out var entry) ? entry.Default : null; + + private static Dictionary<(string, string), (bool, CosObject?)> Build() + { + CosInteger zero = new(0); + CosInteger one = new(1); + var table = new Dictionary<(string, string), (bool, CosObject?)>(); + void Layout(string name, bool inheritable, CosObject? value) => table[("Layout", name)] = (inheritable, value); + + Layout("Placement", false, null); + Layout("WritingMode", true, new CosName("LrTb")); + Layout("BackgroundColor", false, null); + Layout("BorderColor", true, null); + Layout("BorderStyle", false, new CosName("None")); + Layout("BorderThickness", true, zero); + Layout("Padding", false, zero); + Layout("Color", true, null); + Layout("SpaceBefore", false, zero); + Layout("SpaceAfter", false, zero); + Layout("StartIndent", true, zero); + Layout("EndIndent", true, zero); + Layout("TextIndent", true, zero); + Layout("TextAlign", true, new CosName("Start")); + Layout("BBox", false, null); + Layout("Width", false, new CosName("Auto")); + Layout("Height", false, new CosName("Auto")); + Layout("BlockAlign", true, new CosName("Before")); + Layout("InlineAlign", true, new CosName("Start")); + Layout("TBorderStyle", true, new CosName("None")); + Layout("TPadding", true, zero); + Layout("BaselineShift", false, zero); + Layout("LineHeight", true, new CosName("Normal")); + Layout("TextPosition", true, new CosName("Normal")); + Layout("TextDecorationColor", true, null); + Layout("TextDecorationThickness", true, null); + Layout("TextDecorationType", false, new CosName("None")); + Layout("RubyAlign", true, new CosName("Distribute")); + Layout("RubyPosition", true, new CosName("Before")); + Layout("GlyphOrientationVertical", true, new CosName("Auto")); + Layout("ColumnCount", false, one); + Layout("ColumnGap", false, null); + Layout("ColumnWidths", false, null); + + table[("List", "ListNumbering")] = (true, new CosName("None")); + table[("List", "ContinuedList")] = (false, CosBoolean.False); + table[("List", "ContinuedFrom")] = (false, null); + + table[("PrintField", "Role")] = (false, null); + table[("PrintField", "Checked")] = (false, new CosName("off")); + table[("PrintField", "Desc")] = (false, null); + + table[("Table", "RowSpan")] = (false, one); + table[("Table", "ColSpan")] = (false, one); + table[("Table", "Headers")] = (false, null); + table[("Table", "Scope")] = (false, null); + table[("Table", "Summary")] = (false, null); + table[("Table", "Short")] = (false, null); + return table; + } +} diff --git a/src/Broadside/Structure/StandardStructureTypes.cs b/src/Broadside/Structure/StandardStructureTypes.cs new file mode 100644 index 00000000..c80124c6 --- /dev/null +++ b/src/Broadside/Structure/StandardStructureTypes.cs @@ -0,0 +1,61 @@ +namespace Broadside.Structure; + +/// The standard structure types of the PDF 1.7 and PDF 2.0 standard structure namespaces. +/// +/// ISO 32000-2 §14.8.4 (Tables 364-375, the PDF 2.0 namespace), §14.8.6.1 and Annex M (the differences); ISO/TS 32005 §5.3-§5.5 and +/// Tables 2-3 (the unique PDF 1.7 types). Hn is any H followed by a decimal number of at least 1 in PDF 2.0; the PDF 1.7 +/// namespace has only H1 to H6. +/// +internal static class StandardStructureTypes +{ + /// Types defined in both namespaces (ISO/TS 32005 §5.3), headings H1-H6 included. + private static readonly HashSet Common = new(StringComparer.Ordinal) + { + "Document", "Part", "Sect", "Div", "NonStruct", + "P", "H", "H1", "H2", "H3", "H4", "H5", "H6", + "Lbl", "Span", "Link", "Annot", "Form", "Ruby", "RB", "RT", "RP", "Warichu", "WT", "WP", + "L", "LI", "LBody", + "Table", "TR", "TH", "TD", "THead", "TBody", "TFoot", + "Caption", "Figure", "Formula", + }; + + /// Types defined solely in the PDF 1.7 namespace (Annex M; ISO/TS 32005 Tables 2 and 3). + private static readonly HashSet Pdf17Only = new(StringComparer.Ordinal) + { + "Art", "BlockQuote", "TOC", "TOCI", "Index", "Private", "Quote", "Note", "Reference", "BibEntry", "Code", + }; + + /// Types defined solely in the PDF 2.0 namespace (Annex M), except Hn with n above 6. + private static readonly HashSet Pdf20Only = new(StringComparer.Ordinal) + { + "DocumentFragment", "Aside", "Title", "FENote", "Sub", "Em", "Strong", "Artifact", + }; + + /// Whether is a standard type of the PDF 1.7 namespace. + public static bool IsPdf17(string type) => Common.Contains(type) || Pdf17Only.Contains(type); + + /// Whether is a standard type of the PDF 2.0 namespace. + public static bool IsPdf20(string type) => Common.Contains(type) || Pdf20Only.Contains(type) || IsHn(type); + + /// Whether is defined in both namespaces (ISO/TS 32005 §5.3). + public static bool IsCommon(string type) => Common.Contains(type); + + /// Whether is a heading Hn: H followed by a decimal number of at least 1 (§14.8.4.5). + public static bool IsHn(string type) + { + if (type.Length < 2 || type[0] != 'H' || type[1] == '0') + { + return false; + } + + for (int index = 1; index < type.Length; index++) + { + if (!char.IsAsciiDigit(type[index])) + { + return false; + } + } + + return true; + } +} diff --git a/src/Broadside/Structure/StructureContext.cs b/src/Broadside/Structure/StructureContext.cs new file mode 100644 index 00000000..53de3c93 --- /dev/null +++ b/src/Broadside/Structure/StructureContext.cs @@ -0,0 +1,209 @@ +using Broadside.Caching; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Structure; + +/// +/// The state one document's structure tree views share: the document (to resolve objects and find pages), its diagnostics, and the +/// derived indexes, each built once on first use through and then read without locks. +/// +/// +/// ISO 32000-2 §14.7. The indexes are snapshots of the tree as it was when first needed: they are rebuilt when the catalog's +/// StructTreeRoot is replaced ( creates a new context), not when an element inside it +/// is edited. Reading never changes a COS object; every repair lives in the views. +/// +internal sealed class StructureContext +{ + /// How deep the structure hierarchy may nest before the walk stops descending (a cap on untrusted input). + public const int MaxDepth = 256; + + /// How many role-map steps resolving one type may take; maps may form cycles, which also end the chain. + public const int MaxRoleSteps = 32; + + /// The longest parent-tree array read for one content stream; longer arrays are truncated (MCIDs are small in practice). + public const int MaxParentTreeArray = 1_000_000; + + private readonly OnceCache _walk = new(); + private readonly OnceCache _roles = new(RoleKeyComparer.Instance); + private readonly OnceCache _namespaces = new(ReferenceEqualityComparer.Instance); + private readonly OnceCache> _declaredNamespaces = new(); + private readonly OnceCache _markedContent = new(ReferenceEqualityComparer.Instance); + private readonly OnceCache> _parentTreePages = new(); + + public StructureContext(PdfDocument document, CosDictionary root, CosReference? rootReference) + { + Document = document; + Root = root; + RootReference = rootReference; + } + + public PdfDocument Document { get; } + + public CosDictionary Root { get; } + + public CosReference? RootReference { get; } + + public DiagnosticSink Diagnostics => Document.DiagnosticSink; + + /// Gets a value indicating whether the document claims to be a tagged PDF (MarkInfo Marked true, §14.8.1). + public bool IsTagged => Document.MarkInfo.Marked; + + /// Gets the document-order walk of the hierarchy from the root's K, built once. + public StructureWalk Walk => _walk.GetOrCreate( + 0, + this, + static (_, context) => new Created(StructureWalk.Build(context)), + static (_, _) => StructureWalk.Empty); + + /// Gets the reader of the root's ParentTree number tree, or when there is none (§14.7.5.4). + public NumberTreeReader? ParentTree => Root.TryGetValue(StructureNames.ParentTree, out CosObject? value) ? Document.GetNumberTreeReader(value) : null; + + /// Gets the reader of the root's IDTree name tree, or when there is none (Table 354). + public NameTreeReader? IdTree => Root.TryGetValue(StructureNames.IDTree, out CosObject? value) ? Document.GetNameTreeReader(value) : null; + + public CosObject Resolve(CosObject? value) => Document.Resolve(value); + + /// + /// Reports ParentTreeMissing when the root has no ParentTree although an element has content items (Table 354: + /// "Required if any structure element contains content items"). Lookups then fall back to the K walk. + /// + public void CheckParentTree(StructureWalk walk) + { + if (walk.HasContentItems && !Root.ContainsKey(StructureNames.ParentTree)) + { + Report(DiagnosticCodes.ParentTreeMissing, "The structure tree root has no ParentTree although elements have content items (Table 354); content is mapped to elements through K.", RootReference); + } + } + + /// + /// Finds, as a last-resort repair, the page of MCID of : the page whose + /// StructParents parent-tree array lists the element at that MCID. + /// + public CosDictionary? PageFromParentTree(CosDictionary element, int mcid) => + _parentTreePages.GetOrCreate( + 0, + this, + static (_, context) => new Created>(context.IndexParentTreePages()), + static (_, _) => []).TryGetValue((element, mcid), out CosDictionary? page) + ? page + : null; + + /// (element, MCID) to page, from every page's StructParents parent-tree array: read once, for the missing-Pg repair. + private Dictionary<(CosDictionary, int), CosDictionary> IndexParentTreePages() + { + var pages = new Dictionary<(CosDictionary, int), CosDictionary>(ElementMcidComparer.Instance); + if (ParentTree is not { } tree) + { + return pages; + } + + var pageByKey = new Dictionary(); + foreach (PdfPage page in Document.Pages) + { + if (StructureValues.Integer(Document, page.Dictionary, StructureNames.StructParents) is { } key) + { + pageByKey.TryAdd(key, page.Dictionary); + } + } + + foreach ((int key, CosObject value) in tree.Enumerate()) + { + if (value is not CosArray array || !pageByKey.TryGetValue(key, out CosDictionary? pageObject)) + { + continue; + } + + int count = Math.Min(array.Count, MaxParentTreeArray); + for (int mcid = 0; mcid < count; mcid++) + { + if (Resolve(array[mcid]) is CosDictionary listed) + { + pages.TryAdd((listed, mcid), pageObject); + } + } + } + + return pages; + } + + public void Report(string code, string message, CosReference? reference) => + Diagnostics.Report(code, DiagnosticSeverity.Warning, message, offset: null, reference); + + /// Finds the page whose page object resolves to, or . + public PdfPage? FindPage(CosObject? value) => + Resolve(value) is CosDictionary pageObject && Document.Pages.TryGetPage(pageObject, out PdfPage? page) ? page : null; + + /// Gets the view of the namespace dictionary , one per dictionary. + public PdfStructureNamespace Namespace(CosDictionary dictionary, CosReference? reference) => _namespaces.GetOrCreate( + dictionary, + (Context: this, Reference: reference), + static (key, state) => new Created(new PdfStructureNamespace(state.Context, key, state.Reference)), + static (key, state) => new PdfStructureNamespace(state.Context, key, state.Reference)); + + /// Whether the root's Namespaces array lists (§14.8.6.2: an explicit namespace shall be listed). + public bool IsDeclared(CosDictionary dictionary) => _declaredNamespaces.GetOrCreate( + 0, + this, + static (_, context) => new Created>(context.ReadDeclaredNamespaces()), + static (_, _) => []).Contains(dictionary); + + /// Resolves the standard type of (, ) through the role maps, once per pair. + public RoleResolution ResolveRole(CosName type, PdfStructureNamespace ns) => _roles.GetOrCreate( + new RoleKey(type, ns), + this, + static (key, context) => new Created(RoleResolver.Resolve(context, key.Type, key.Namespace)), + static (key, context) => RoleResolver.Resolve(context, key.Type, key.Namespace)); + + /// Gets the MCID index of the content stream (a page object or a form XObject), built once. + public MarkedContentIndex MarkedContent(CosObject owner) => _markedContent.GetOrCreate( + owner, + this, + static (key, context) => new Created(MarkedContentIndex.Build(context, key)), + static (_, _) => MarkedContentIndex.Empty); + + private HashSet ReadDeclaredNamespaces() + { + var declared = new HashSet(ReferenceEqualityComparer.Instance); + if (Root.TryGetValue(StructureNames.Namespaces, out CosObject? value) && Resolve(value) is CosArray array) + { + foreach (CosObject item in array) + { + if (Resolve(item) is CosDictionary dictionary) + { + declared.Add(dictionary); + } + } + } + + return declared; + } + + /// A role-resolution cache key: a type name and the namespace it is in, the namespace compared by its dictionary. + internal readonly record struct RoleKey(CosName Type, PdfStructureNamespace Namespace); + + private sealed class RoleKeyComparer : IEqualityComparer + { + public static readonly RoleKeyComparer Instance = new(); + + public bool Equals(RoleKey x, RoleKey y) => + x.Type.Equals(y.Type) && (x.Namespace.Dictionary is null + ? y.Namespace.Dictionary is null && x.Namespace.Kind == y.Namespace.Kind + : ReferenceEquals(x.Namespace.Dictionary, y.Namespace.Dictionary)); + + public int GetHashCode(RoleKey obj) => HashCode.Combine( + obj.Type, + obj.Namespace.Dictionary is { } dictionary ? System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(dictionary) : (int)obj.Namespace.Kind); + } + + /// Compares (element, MCID) pairs by element identity and MCID. + private sealed class ElementMcidComparer : IEqualityComparer<(CosDictionary Element, int Mcid)> + { + public static readonly ElementMcidComparer Instance = new(); + + public bool Equals((CosDictionary Element, int Mcid) x, (CosDictionary Element, int Mcid) y) => ReferenceEquals(x.Element, y.Element) && x.Mcid == y.Mcid; + + public int GetHashCode((CosDictionary Element, int Mcid) obj) => HashCode.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj.Element), obj.Mcid); + } +} diff --git a/src/Broadside/Structure/StructureNames.cs b/src/Broadside/Structure/StructureNames.cs new file mode 100644 index 00000000..86a863f6 --- /dev/null +++ b/src/Broadside/Structure/StructureNames.cs @@ -0,0 +1,77 @@ +using Broadside.Objects; + +namespace Broadside.Structure; + +/// Names the logical-structure views look up (ISO 32000-2 §14.6 to §14.8), created once. +internal static class StructureNames +{ + // Catalog (§7.7.2, Table 29) and mark information (§14.7.1, Table 353). + public static readonly CosName StructTreeRoot = new("StructTreeRoot"); + public static readonly CosName MarkInfo = new("MarkInfo"); + public static readonly CosName Marked = new("Marked"); + public static readonly CosName UserProperties = new("UserProperties"); + public static readonly CosName Suspects = new("Suspects"); + public static readonly CosName Lang = new("Lang"); + + // Structure tree root (Table 354). + public static readonly CosName K = new("K"); + public static readonly CosName IDTree = new("IDTree"); + public static readonly CosName ParentTree = new("ParentTree"); + public static readonly CosName ParentTreeNextKey = new("ParentTreeNextKey"); + public static readonly CosName RoleMap = new("RoleMap"); + public static readonly CosName ClassMap = new("ClassMap"); + public static readonly CosName Namespaces = new("Namespaces"); + public static readonly CosName PronunciationLexicon = new("PronunciationLexicon"); + public static readonly CosName AF = new("AF"); + + // Structure element (Table 355). + public static readonly CosName StructElem = new("StructElem"); + public static readonly CosName S = new("S"); + public static readonly CosName P = new("P"); + public static readonly CosName ID = new("ID"); + public static readonly CosName Ref = new("Ref"); + public static readonly CosName Pg = new("Pg"); + public static readonly CosName A = new("A"); + public static readonly CosName C = new("C"); + public static readonly CosName R = new("R"); + public static readonly CosName T = new("T"); + public static readonly CosName Alt = new("Alt"); + public static readonly CosName E = new("E"); + public static readonly CosName ActualText = new("ActualText"); + public static readonly CosName NS = new("NS"); + public static readonly CosName PhoneticAlphabet = new("PhoneticAlphabet"); + public static readonly CosName Phoneme = new("Phoneme"); + + // Namespaces (Table 356). + public static readonly CosName Namespace = new("Namespace"); + public static readonly CosName Schema = new("Schema"); + public static readonly CosName RoleMapNS = new("RoleMapNS"); + + // Content items (Tables 357-359). + public static readonly CosName MCR = new("MCR"); + public static readonly CosName OBJR = new("OBJR"); + public static readonly CosName MCID = new("MCID"); + public static readonly CosName Stm = new("Stm"); + public static readonly CosName StmOwn = new("StmOwn"); + public static readonly CosName Obj = new("Obj"); + public static readonly CosName StructParent = new("StructParent"); + public static readonly CosName StructParents = new("StructParents"); + + // Attribute objects (Tables 360-362, 376). + public static readonly CosName O = new("O"); + public static readonly CosName NSO = new("NSO"); + public static readonly CosName Layout = new("Layout"); + public static readonly CosName List = new("List"); + public static readonly CosName PrintField = new("PrintField"); + public static readonly CosName Table = new("Table"); + public static readonly CosName Artifact = new("Artifact"); + public static readonly CosName N = new("N"); + public static readonly CosName V = new("V"); + public static readonly CosName F = new("F"); + public static readonly CosName H = new("H"); + + // Artifacts and property lists (Tables 363, 385). + public static readonly CosName Subtype = new("Subtype"); + public static readonly CosName BBox = new("BBox"); + public static readonly CosName Attached = new("Attached"); +} diff --git a/src/Broadside/Structure/StructureNamespaceSuppression.cs b/src/Broadside/Structure/StructureNamespaceSuppression.cs new file mode 100644 index 00000000..5eaef745 --- /dev/null +++ b/src/Broadside/Structure/StructureNamespaceSuppression.cs @@ -0,0 +1,8 @@ +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage( + "Naming", + "CA1716:Identifiers should not match keywords", + Scope = "namespace", + Target = "~N:Broadside.Structure", + Justification = "The namespace list of spec #33 (Implementation Decisions, Namespaces) names this area Structure; it collides only with a Visual Basic keyword, and VB callers can escape it.")] diff --git a/src/Broadside/Structure/StructureValues.cs b/src/Broadside/Structure/StructureValues.cs new file mode 100644 index 00000000..fcfc188a --- /dev/null +++ b/src/Broadside/Structure/StructureValues.cs @@ -0,0 +1,68 @@ +using Broadside.Objects; + +namespace Broadside.Structure; + +/// Reads typed values out of the dictionaries of §14.6-§14.8, resolving indirect references; a value of the wrong type reads as absent. +internal static class StructureValues +{ + public static CosObject? Get(PdfDocument? document, CosDictionary dictionary, CosName key) + { + if (!dictionary.TryGetValue(key, out CosObject? value)) + { + return null; + } + + CosObject resolved = document is null ? value : document.Resolve(value); + return resolved is CosNull ? null : resolved; + } + + public static string? Text(PdfDocument? document, CosDictionary dictionary, CosName key) => + Get(document, dictionary, key) is CosString text ? text.DecodeText() : null; + + public static CosName? Name(PdfDocument? document, CosDictionary dictionary, CosName key) => + Get(document, dictionary, key) as CosName; + + public static int? Integer(PdfDocument? document, CosDictionary dictionary, CosName key) => + Get(document, dictionary, key) is CosInteger { Value: >= int.MinValue and <= int.MaxValue } integer ? (int)integer.Value : null; + + public static double? Number(PdfDocument? document, CosDictionary dictionary, CosName key) => + Get(document, dictionary, key) is CosNumber number ? number.ToDouble() : null; + + public static bool? Boolean(PdfDocument? document, CosDictionary dictionary, CosName key) => + Get(document, dictionary, key) is CosBoolean boolean ? boolean.Value : null; + + /// Reads an array of numbers; when absent, not an array, or holding a non-number. + public static double[]? Numbers(PdfDocument? document, CosDictionary dictionary, CosName key) + { + if (Get(document, dictionary, key) is not CosArray array) + { + return null; + } + + double[] values = new double[array.Count]; + for (int index = 0; index < values.Length; index++) + { + CosObject item = document is null ? array[index] : document.Resolve(array[index]); + if (item is not CosNumber number) + { + return null; + } + + values[index] = number.ToDouble(); + } + + return values; + } + + /// Reads a rectangle (§7.9.5): four numbers, normalized. + public static PdfRectangle? Rectangle(PdfDocument? document, CosDictionary dictionary, CosName key) => + Numbers(document, dictionary, key) is [var x1, var y1, var x2, var y2] ? new PdfRectangle(x1, y1, x2, y2) : null; + + /// The dictionary of an attribute object or property list, which may be a stream (legacy form, §14.7.6.1). + public static CosDictionary? DictionaryOf(CosObject value) => value switch + { + CosDictionary dictionary => dictionary, + CosStream stream => stream.Dictionary, + _ => null, + }; +} diff --git a/src/Broadside/Structure/StructureWalk.cs b/src/Broadside/Structure/StructureWalk.cs new file mode 100644 index 00000000..8d40f7b3 --- /dev/null +++ b/src/Broadside/Structure/StructureWalk.cs @@ -0,0 +1,161 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Structure; + +/// +/// One document-order walk of the structure hierarchy from the root's K, and the reverse indexes it yields: element by +/// dictionary (with its parent), (content stream, MCID) to element, object (OBJR) to element, and ID to element. +/// +/// +/// +/// ISO 32000-2 §14.7.2 and §14.7.5. The walk is iterative with an explicit stack and one visited set across all levels, so a +/// K graph that is a DAG or has cycles is read as a tree: an element met a second time is skipped +/// (StructTreeCycle), the hierarchy is cut at (StructTreeDepthExceeded). +/// +/// +/// It is the fallback for the parent tree (§14.7.5.4) when that is missing or wrong, and the source of +/// for elements found through it. MCIDs are keyed by the content stream they are in: the MCR's Stm, else the page (MCIDs are +/// unique per content stream, §14.7.5.2); a second item with the same key keeps the first (McidDuplicate). +/// +/// +internal sealed class StructureWalk +{ + private readonly List _elements = []; + private readonly Dictionary _byDictionary = new(ReferenceEqualityComparer.Instance); + private readonly Dictionary> _markedContent = new(ReferenceEqualityComparer.Instance); + private readonly Dictionary _objects = new(ReferenceEqualityComparer.Instance); + private readonly Dictionary _ids = new(StringComparer.Ordinal); + + public static StructureWalk Empty { get; } = new(); + + /// Gets every element reachable from the root, in document (depth-first, K) order. + public IReadOnlyList Elements => _elements; + + /// Gets a value indicating whether any element has a content item. + public bool HasContentItems { get; private set; } + + public static StructureWalk Build(StructureContext context) + { + var walk = new StructureWalk(); + var visited = new HashSet(ReferenceEqualityComparer.Instance); + var stack = new Stack<(CosObject Entry, PdfStructureElement? Parent, int Depth)>(); + Push(stack, KidReader.Entries(context, context.Root), null, 0); + while (stack.TryPop(out (CosObject Entry, PdfStructureElement? Parent, int Depth) next)) + { + (CosObject entry, PdfStructureElement? parent, int depth) = next; + Kid kid = KidReader.Classify(context, entry, parent?.Reference ?? context.RootReference); + if (parent is null && kid.Kind is KidKind.MarkedContent or KidKind.Object) + { + context.Report(DiagnosticCodes.StructTreeRootInvalid, "The structure tree root's K holds a content item; only structure elements may be its children (Table 354). Skipped.", context.RootReference); + continue; + } + + switch (kid.Kind) + { + case KidKind.Element: + walk.VisitElement(context, kid, parent, depth, visited, stack); + break; + case KidKind.MarkedContent: + walk.VisitMarkedContent(context, parent!.CreateMarkedContent(kid)); + break; + case KidKind.Object: + PdfObjectReference reference = parent!.CreateObjectReference(kid); + walk.HasContentItems = true; + if (reference.ReferencedObject is not CosNull) + { + walk._objects.TryAdd(reference.ReferencedObject, parent); + } + + break; + } + } + + context.CheckParentTree(walk); + return walk; + } + + public bool TryGet(CosDictionary dictionary, [MaybeNullWhen(false)] out PdfStructureElement element) => _byDictionary.TryGetValue(dictionary, out element); + + public bool TryGetObjectParent(CosObject value, [MaybeNullWhen(false)] out PdfStructureElement element) => _objects.TryGetValue(value, out element); + + public bool TryGetById(ReadOnlySpan id, [MaybeNullWhen(false)] out PdfStructureElement element) => _ids.TryGetValue(Encoding.Latin1.GetString(id), out element); + + /// The MCID-to-element map of one content stream (a page object or a stream), from K. + public IReadOnlyDictionary? MarkedContent(CosObject streamKey) => + _markedContent.TryGetValue(streamKey, out Dictionary? map) ? map : null; + + private static void Push(Stack<(CosObject, PdfStructureElement?, int)> stack, IReadOnlyList entries, PdfStructureElement? parent, int depth) + { + for (int index = entries.Count - 1; index >= 0; index--) + { + stack.Push((entries[index], parent, depth)); + } + } + + private void VisitElement(StructureContext context, Kid kid, PdfStructureElement? parent, int depth, HashSet visited, Stack<(CosObject, PdfStructureElement?, int)> stack) + { + CosDictionary dictionary = kid.Dictionary!; + CosReference? where = kid.Reference ?? parent?.Reference; + if (ReferenceEquals(dictionary, context.Root) || !visited.Add(dictionary)) + { + context.Report(DiagnosticCodes.StructTreeCycle, "A structure element is reached a second time through K (§14.7.2: the hierarchy is a tree); the second occurrence is skipped.", where); + return; + } + + if (depth >= StructureContext.MaxDepth) + { + context.Report(DiagnosticCodes.StructTreeDepthExceeded, $"The structure hierarchy nests deeper than {StructureContext.MaxDepth} levels; the rest is not read.", where); + return; + } + + var element = new PdfStructureElement(context, dictionary, kid.Reference, parent, parentKnown: true, depth); + _elements.Add(element); + _byDictionary.Add(dictionary, element); + + CosDictionary expectedParent = parent?.Dictionary ?? context.Root; + if (!dictionary.TryGetValue(StructureNames.P, out CosObject? declaredParent) || !ReferenceEquals(context.Resolve(declaredParent), expectedParent)) + { + context.Report(DiagnosticCodes.StructElemParentMismatch, "A structure element's P is not the element (or root) whose K holds it (Table 355); the K hierarchy is used.", where); + } + + if (StructureValues.Get(context.Document, dictionary, StructureNames.ID) is CosString id) + { + if (!_ids.TryAdd(Encoding.Latin1.GetString(id.Bytes), element)) + { + context.Report(DiagnosticCodes.IdTreeDuplicate, "Two structure elements have the same ID (Table 355: unique in the document); lookups find the first.", where); + } + else if (context.IdTree is not { } idTree || !idTree.TryGetValue(id.Bytes, out CosObject? listed) || !ReferenceEquals(listed, dictionary)) + { + context.Report(DiagnosticCodes.IdTreeEntryInvalid, "A structure element's ID is not in the structure tree root's IDTree, or maps to another element (Table 354); lookups find it through K.", where); + } + } + + Push(stack, KidReader.Entries(context, dictionary), element, depth + 1); + } + + private void VisitMarkedContent(StructureContext context, PdfMarkedContentReference item) + { + HasContentItems = true; + if (item.StreamKey is not { } key) + { + return; + } + + if (!_markedContent.TryGetValue(key, out Dictionary? map)) + { + map = []; + _markedContent.Add(key, map); + } + + if (!map.TryAdd(item.Mcid, item.Parent)) + { + context.Report( + DiagnosticCodes.McidDuplicate, + $"MCID {item.Mcid} of one content stream is a content item of two structure elements (§14.7.5.2: MCIDs are unique per content stream); the first is kept.", + item.Parent.Reference); + } + } +} diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 4a3ab467..69086cdf 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -37,6 +37,7 @@ internal static class FuzzTargets ["decrypt"] = Decrypt, ["mac-token"] = MacToken, ["public-key"] = PublicKey.Target, + ["structure-tree"] = StructureTree.Target, }; private static readonly CosName ContentsKey = new("Contents"); diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index 1a3db895..ffe97276 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. `structure-tree` (ISO 32000-2 §14.7, §14.8) reads a structure tree completely (every element through `Elements` and through `Children`, role mappings, attributes, languages, and every MCID, ID and object lookup): an input starting with `%PDF-` is opened as a file (the corpus seeds, `tagged-structure.pdf` foremost), any other input is split at line feeds into a synthetic tagged file whose first line is the inside of the structure tree root and whose following lines are objects 5, 6 and so on, so mutations wire elements, K arrays, role maps, namespaces, attributes and the parent and ID trees together at random; it checks that `Elements` lists each element once and every parent chain ends. For libFuzzer and AFL seed it with line-per-object texts as well as the corpus, for instance the root line `/K [5 0 R] /ParentTree << /Nums [0 [5 0 R]] >> /RoleMap << /A /B /B /A >>` followed by `<< /S /A /P 4 0 R /Pg 3 0 R /K [0 5 0 R] /A [1 << /O /Layout >> 2] >>`. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. diff --git a/tests/Broadside.Fuzz/StructureTree.cs b/tests/Broadside.Fuzz/StructureTree.cs new file mode 100644 index 00000000..1c2187e3 --- /dev/null +++ b/tests/Broadside.Fuzz/StructureTree.cs @@ -0,0 +1,153 @@ +using System.Globalization; +using System.Text; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Security; +using Broadside.Structure; + +namespace Broadside.Fuzz; + +/// +/// The structure-tree target: a random COS graph read as a structure tree. An input that starts with %PDF- is opened as +/// a file (the corpus seeds, chiefly tagged-structure.pdf, mutated); any other input is split at line feeds into object bodies +/// of a synthetic tagged file: the first line is the inside of the structure tree root dictionary (object 4), the following lines are +/// objects 5, 6, and so on, so mutations wire elements, K arrays, role maps, namespaces, class maps, attributes and the parent and ID +/// trees to each other at random. +/// +/// +/// ISO 32000-2 §14.7, §14.8. The walk reads every element through and, iteratively, +/// through , resolves every role mapping, attribute and language, and runs every lookup. +/// Invariants: lenient reading never throws; every walk ends (the harness times out otherwise); +/// lists each element once; every element's parent chain ends within the depth limit. +/// +internal static class StructureTree +{ + private const int MaxObjects = 256; + private static readonly CosName Layout = new("Layout"); + private static readonly CosName TextAlign = new("TextAlign"); + + public static void Target(ReadOnlySpan data) + { + byte[] file = data.StartsWith("%PDF-"u8) ? data.ToArray() : Synthesize(data); + using PdfDocument? document = OpenOrNull(file); + if (document is not null) + { + Walk(document); + } + } + + private static PdfDocument? OpenOrNull(byte[] file) + { + try + { + return PdfDocument.Open(file); + } + catch (Exception exception) when (exception is DiagnosticException or PdfPasswordException or PdfEncryptionNotSupportedException or PdfCertificateException) + { + return null; + } + } + + private static void Walk(PdfDocument document) + { + _ = (document.MarkInfo.Marked, document.MarkInfo.UserProperties, document.MarkInfo.Suspects); + if (document.StructureTree is not { } root) + { + return; + } + + _ = (root.Namespaces, root.ParentTreeNextKey, root.RoleMap, root.ClassMap, root.PronunciationLexicon, root.AssociatedFiles); + var listed = new HashSet(ReferenceEqualityComparer.Instance); + foreach (PdfStructureElement element in root.Elements) + { + if (!listed.Add(element.Dictionary)) + { + throw new InvalidOperationException("Elements lists an element twice."); + } + + int steps = 0; + for (PdfStructureElement? ancestor = element.Parent; ancestor is not null; ancestor = ancestor.Parent) + { + if (++steps > 256) + { + throw new InvalidOperationException("An element's parent chain does not end within the depth limit."); + } + } + + if (element.Id is { } id) + { + _ = root.FindElementById(id.Bytes); + } + } + + var seen = new HashSet(); + var stack = new Stack(root.Children); + while (stack.TryPop(out PdfStructureElement? element)) + { + if (!seen.Add(element)) + { + continue; + } + + _ = (element.StandardType, element.RoleMapping, element.Namespace.Kind, element.EffectiveLanguage, element.PhoneticAlphabet, element.Revision); + _ = (element.Attributes, element.ClassAttributes, element.GetAttributeValue(Layout, TextAlign), element.References, element.Page); + foreach (PdfAttributeObject attributes in element.Attributes) + { + _ = (attributes.Owner, attributes.Namespace, (attributes as PdfUserPropertiesAttributes)?.Properties, (attributes as PdfTableAttributes)?.Headers); + } + + foreach (PdfStructureItem item in element.Children) + { + switch (item) + { + case PdfStructureElement child: + stack.Push(child); + break; + case PdfObjectReference reference: + _ = root.FindElementForObject(reference.ReferencedObject); + break; + case PdfMarkedContentReference content when content.ContentStream is { } stream: + _ = root.FindElement(stream, content.Mcid); + break; + } + } + } + + foreach (PdfPage page in document.Pages) + { + _ = root.GetMarkedContentElements(page); + } + } + + /// Builds a one-page tagged file whose structure tree root and objects 5 onward are the input's lines. + private static byte[] Synthesize(ReadOnlySpan data) + { + string[] lines = Encoding.Latin1.GetString(data).Split('\n', MaxObjects); + var objects = new List + { + "<< /Type /Catalog /Pages 2 0 R /MarkInfo << /Marked true >> /StructTreeRoot 4 0 R /Lang (en) >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] /StructParents 0 >>", + $"<< /Type /StructTreeRoot {lines[0]} >>", + }; + objects.AddRange(lines.Skip(1)); + + var text = new StringBuilder("%PDF-2.0\n"); + var offsets = new List(); + for (int index = 0; index < objects.Count; index++) + { + offsets.Add(text.Length); + text.Append(CultureInfo.InvariantCulture, $"{index + 1} 0 obj\n{objects[index]}\nendobj\n"); + } + + int xref = text.Length; + text.Append(CultureInfo.InvariantCulture, $"xref\n0 {objects.Count + 1}\n0000000000 65535 f \n"); + foreach (int offset in offsets) + { + text.Append(CultureInfo.InvariantCulture, $"{offset:D10} 00000 n \n"); + } + + text.Append(CultureInfo.InvariantCulture, $"trailer\n<< /Size {objects.Count + 1} /Root 1 0 R /ID [<00> <00>] >>\nstartxref\n{xref}\n%%EOF\n"); + return Encoding.Latin1.GetBytes(text.ToString()); + } +} diff --git a/tests/Broadside.TestSupport/Corpus.cs b/tests/Broadside.TestSupport/Corpus.cs index d0ce8d5f..6d448ff6 100644 --- a/tests/Broadside.TestSupport/Corpus.cs +++ b/tests/Broadside.TestSupport/Corpus.cs @@ -42,6 +42,7 @@ public static class Corpus "metadata-xmp.pdf", "name-tree-deep.pdf", "number-tree-deep.pdf", + "tagged-structure.pdf", ]; private static readonly string[] Malformed = diff --git a/tests/Broadside.Tests/LogicalStructure/AttributeTests.cs b/tests/Broadside.Tests/LogicalStructure/AttributeTests.cs new file mode 100644 index 00000000..186a5730 --- /dev/null +++ b/tests/Broadside.Tests/LogicalStructure/AttributeTests.cs @@ -0,0 +1,185 @@ +using Broadside.Objects; +using Broadside.Structure; + +namespace Broadside.Tests.LogicalStructure; + +/// Attribute objects, classes, revision numbers, typed owners and inheritance. ISO 32000-2 §14.7.6, §14.8.5. +public class AttributeTests +{ + private static readonly CosName Layout = new("Layout"); + + [Fact] + public void Layout_attributes_are_typed() + { + using PdfDocument document1 = Open( + "<< /O /Layout /Placement /Block /WritingMode /TbRl /BackgroundColor [1 0 0] /BorderStyle [/Solid null /Dashed /None] " + + "/BorderThickness 2 /Padding [1 2 3 4] /Color [0 0 1] /SpaceBefore 3 /SpaceAfter 4.5 /StartIndent 5 /EndIndent 6 /TextIndent 7 " + + "/TextAlign /Justify /BBox [10 20 0 0] /Width /Auto /Height 50 /BlockAlign /Middle /InlineAlign /Center /TBorderStyle /Double " + + "/TPadding [1 1 1 1] /BaselineShift -2 /LineHeight /Normal /TextPosition /Sup /TextDecorationColor [0 1 0] " + + "/TextDecorationThickness 0.5 /TextDecorationType /Underline /RubyAlign /Center /RubyPosition /After " + + "/GlyphOrientationVertical 90 /ColumnCount 2 /ColumnGap 12 /ColumnWidths [100 200] >>"); + PdfLayoutAttributes layout = Single(document1); + + Assert.Equal("Block", layout.Placement); + Assert.Equal("TbRl", layout.WritingMode); + Assert.Equal([1.0, 0, 0], layout.BackgroundColor); + Assert.Equal(["Solid", null, "Dashed", "None"], layout.BorderStyle); + Assert.Equal([2.0, 2, 2, 2], layout.BorderThickness); + Assert.Equal([1.0, 2, 3, 4], layout.Padding); + Assert.Equal([0.0, 0, 1], layout.Color); + Assert.Equal(3, layout.SpaceBefore); + Assert.Equal(4.5, layout.SpaceAfter); + Assert.Equal(5, layout.StartIndent); + Assert.Equal(6, layout.EndIndent); + Assert.Equal(7, layout.TextIndent); + Assert.Equal("Justify", layout.TextAlign); + Assert.Equal(new PdfRectangle(0, 0, 10, 20), layout.BoundingBox); + Assert.Null(layout.Width); + Assert.Equal(new CosName("Auto"), layout.GetValue(new CosName("Width"))); + Assert.Equal(50, layout.Height); + Assert.Equal("Middle", layout.BlockAlign); + Assert.Equal("Center", layout.InlineAlign); + Assert.Equal(["Double", "Double", "Double", "Double"], layout.TableBorderStyle); + Assert.Equal([1.0, 1, 1, 1], layout.TablePadding); + Assert.Equal(-2, layout.BaselineShift); + Assert.Null(layout.LineHeight); + Assert.Equal("Sup", layout.TextPosition); + Assert.Equal([0.0, 1, 0], layout.TextDecorationColor); + Assert.Equal(0.5, layout.TextDecorationThickness); + Assert.Equal("Underline", layout.TextDecorationType); + Assert.Equal("Center", layout.RubyAlign); + Assert.Equal("After", layout.RubyPosition); + Assert.Equal(90, layout.GlyphOrientationVertical); + Assert.Equal(2, layout.ColumnCount); + Assert.Equal([12.0], layout.ColumnGap); + Assert.Equal([100.0, 200], layout.ColumnWidths); + Assert.Equal(Layout, layout.Owner); + } + + [Fact] + public void List_table_print_field_artifact_and_user_property_attributes_are_typed() + { + using PdfDocument document2 = Open("<< /O /List /ListNumbering /Disc /ContinuedList true /ContinuedFrom (list1) >>"); + PdfListAttributes list = Single(document2); + Assert.Equal("Disc", list.ListNumbering); + Assert.False(list.IsOrdered); + Assert.True(list.ContinuedList); + Assert.Equal("list1"u8.ToArray(), list.ContinuedFrom!.Bytes.ToArray()); + + using PdfDocument document3 = Open("<< /O /Table /RowSpan 2 /ColSpan 3 /Headers [(a) (b)] /Scope /Both /Summary (S) /Short (Sh) >>"); + PdfTableAttributes table = Single(document3); + Assert.Equal(2, table.RowSpan); + Assert.Equal(3, table.ColumnSpan); + Assert.Equal(2, table.Headers!.Count); + Assert.Equal("Both", table.Scope); + Assert.Equal("S", table.Summary); + Assert.Equal("Sh", table.ShortForm); + + using PdfDocument document4 = Open("<< /O /PrintField /Role /cb /checked /on /Desc (Agree) >>"); + PdfPrintFieldAttributes field = Single(document4); + Assert.Equal("cb", field.Role); + Assert.Equal("on", field.Checked); + Assert.Equal("Agree", field.Description); + + using PdfDocument document5 = Open("<< /O /Artifact /Type /Pagination /Subtype /Footer /BBox [0 0 612 40] >>"); + PdfArtifactAttributes artifact = Single(document5); + Assert.Equal("Pagination", artifact.ArtifactType); + Assert.Equal("Footer", artifact.ArtifactSubtype); + Assert.Equal(new PdfRectangle(0, 0, 612, 40), artifact.BoundingBox); + + using PdfDocument document6 = Open("<< /O /UserProperties /P [<< /N (Part) /V 42 /F (forty-two) /H true >> << /N (Bad) >> << /N (Color) /V /Red >>] >>"); + PdfUserPropertiesAttributes user = Single(document6); + Assert.Collection( + user.Properties, + static property => + { + Assert.Equal("Part", property.Name); + Assert.Equal(new CosInteger(42), property.Value); + Assert.Equal("forty-two", property.FormattedValue); + Assert.True(property.IsHidden); + }, + static property => + { + Assert.Equal("Color", property.Name); + Assert.False(property.IsHidden); + }); + } + + [Fact] + public void An_attribute_object_owned_by_a_namespace_or_another_owner_is_read_generically() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [5 0 R] /Namespaces [6 0 R]", + "<< /S /P /P 4 0 R /A [<< /O /NSO /NS 6 0 R /color (red) >> << /O /CSS-3 /color (blue) >>] >>", + "<< /Type /Namespace /NS (urn:example:attributes) >>")); + IReadOnlyList attributes = Assert.Single(document.StructureTree!.Children).Attributes; + + Assert.Equal("urn:example:attributes", attributes[0].Namespace!.Name); + Assert.Equal(typeof(PdfAttributeObject), attributes[1].GetType()); + Assert.Equal(new CosName("CSS-3"), attributes[1].Owner); + Assert.Null(attributes[1].Namespace); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Revision_numbers_follow_the_object_or_class_they_belong_to_and_later_entries_win() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [5 0 R] /ClassMap << /Wide [<< /O /Layout /Width 500 >> << /O /Layout /Width 600 >>] /Tall << /O /Layout /Height 9 >> >>", + "<< /S /Table /P 4 0 R /R 3 /A [<< /O /Layout /TextAlign /End >> 2 << /O /Layout /TextAlign /Center >>] /C [/Wide 1 /Tall] >>")); + PdfStructureElement table = Assert.Single(document.StructureTree!.Children); + + Assert.Equal([2, 0], table.Attributes.Select(static attributes => attributes.Revision)); + Assert.Equal(new CosName("Center"), table.GetAttributeValue(Layout, new CosName("TextAlign"))); + Assert.Equal([new CosName("Wide"), new CosName("Tall")], table.ClassNames); + Assert.Equal([1, 1, 0], table.ClassAttributes.Select(static attributes => attributes.Revision)); + Assert.Equal(new CosInteger(600), table.GetAttributeValue(Layout, new CosName("Width"))); + Assert.Equal(new CosInteger(9), table.GetAttributeValue(Layout, new CosName("Height"))); + Assert.Equal(3, table.Revision); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_legacy_attribute_stream_is_read_through_its_dictionary() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [5 0 R]", + "<< /S /P /P 4 0 R /A 6 0 R >>", + "<< /O /Layout /TextAlign /End /Length 0 >>\nstream\n\nendstream")); + PdfAttributeObject attributes = Assert.Single(Assert.Single(document.StructureTree!.Children).Attributes); + + Assert.NotNull(attributes.Stream); + Assert.Equal("End", Assert.IsType(attributes).TextAlign); + Assert.Equal(new CosReference(6, 0), attributes.Reference); + } + + [Fact] + public void Inheritable_attributes_pass_through_every_ancestor_and_others_stop_at_the_element() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [5 0 R]", + "<< /S /Sect /P 4 0 R /A << /O /Layout /TextAlign /Center /SpaceBefore 20 /WritingMode /RlTb >> /K [6 0 R] >>", + "<< /S /Div /P 5 0 R /A << /O /Layout /WritingMode /LrTb >> /K [7 0 R] >>", + "<< /S /P /P 6 0 R /A << /O /PrintField /Role /tv >> >>")); + PdfStructureElement paragraph = document.StructureTree!.Elements[2]; + + Assert.Equal(new CosName("Center"), paragraph.GetAttributeValue(Layout, new CosName("TextAlign"))); + Assert.Equal(new CosName("LrTb"), paragraph.GetAttributeValue(Layout, new CosName("WritingMode"))); + Assert.Equal(new CosInteger(0), paragraph.GetAttributeValue(Layout, new CosName("SpaceBefore"))); + Assert.Null(paragraph.GetAttributeValue(Layout, new CosName("Placement"))); + Assert.Equal(new CosName("off"), paragraph.GetAttributeValue(new CosName("PrintField"), new CosName("Checked"))); + Assert.Equal(new CosName("tv"), paragraph.GetAttributeValue(new CosName("PrintField"), new CosName("Role"))); + Assert.Null(document.StructureTree!.Elements[1].GetAttributeValue(new CosName("PrintField"), new CosName("Role"))); + Assert.Empty(document.Diagnostics); + } + + private static PdfDocument Open(string attributeObject) => PdfDocument.Open(TaggedPdf.Build("/K [5 0 R]", $"<< /S /P /P 4 0 R /A {attributeObject} >>")); + + private static T Single(PdfDocument document) + where T : PdfAttributeObject + { + T attributes = Assert.IsType(Assert.Single(Assert.Single(document.StructureTree!.Children).Attributes)); + Assert.Empty(document.Diagnostics); + return attributes; + } +} diff --git a/tests/Broadside.Tests/LogicalStructure/ContentItemTests.cs b/tests/Broadside.Tests/LogicalStructure/ContentItemTests.cs new file mode 100644 index 00000000..4574d199 --- /dev/null +++ b/tests/Broadside.Tests/LogicalStructure/ContentItemTests.cs @@ -0,0 +1,141 @@ +using Broadside.Objects; +using Broadside.Structure; + +namespace Broadside.Tests.LogicalStructure; + +/// Content items, their pages and streams, and the per-stream MCID index. ISO 32000-2 §14.7.5, Tables 357-359. +public class ContentItemTests +{ + private const string Form = "<< /Type /XObject /Subtype /Form /BBox [0 0 10 10] /StructParents 1 /Length 0 >>\nstream\n\nendstream"; + + [Fact] + public void Mcids_are_scoped_to_their_content_stream_so_a_form_and_its_page_both_have_mcid_0() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [5 0 R 6 0 R] /ParentTree << /Nums [0 [5 0 R] 1 [6 0 R]] >>", + "<< /S /P /P 4 0 R /Pg 3 0 R /K 0 >>", + "<< /S /Figure /P 4 0 R /Pg 3 0 R /K << /Type /MCR /MCID 0 /Stm 7 0 R /StmOwn 8 0 R >> >>", + Form, + "<< /Type /Annot /Subtype /Square /Rect [0 0 1 1] >>")); + PdfStructureTreeRoot root = document.StructureTree!; + var form = (CosStream)document.Resolve(new CosReference(7, 0)); + + Assert.Equal("P", root.FindElement(document.Pages[0], 0)!.StructureType!.Value); + Assert.Equal("Figure", root.FindElement(form, 0)!.StructureType!.Value); + PdfMarkedContentReference reference = Assert.IsType(Assert.Single(root.Elements[1].Children)); + Assert.Same(form, reference.ContentStream); + Assert.Same(document.Resolve(new CosReference(8, 0)), reference.ContentStreamOwner); + Assert.Same(document.Pages[0], reference.Page); + Assert.NotNull(reference.Dictionary); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Without_the_k_walk_a_form_resolves_through_its_own_parent_tree_entry() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [5 0 R] /ParentTree << /Nums [1 [5 0 R]] >>", + "<< /S /Figure /P 4 0 R /K << /Type /MCR /MCID 0 /Stm 6 0 R >> >>", + Form)); + var form = (CosStream)document.Resolve(new CosReference(6, 0)); + + Assert.Equal("Figure", document.StructureTree!.GetMarkedContentElements(form)[0].StructureType!.Value); + Assert.Empty(document.StructureTree!.GetMarkedContentElements(document.Pages[0])); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void An_mcr_page_overrides_the_element_page_and_an_objr_falls_back_to_the_annotation_page() + { + using PdfDocument document = PdfDocument.Open(new Document.TestPdf { Header = "%PDF-2.0", TrailerEntries = "/ID [<00> <00>]" }.Build( + "<< /Type /Catalog /Pages 2 0 R /MarkInfo << /Marked true >> /StructTreeRoot 5 0 R >>", + "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] /StructParents 0 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] /StructParents 1 >>", + "<< /Type /StructTreeRoot /K [6 0 R] /ParentTree << /Nums [0 [6 0 R] 1 [null 6 0 R] 2 6 0 R] >> >>", + "<< /S /P /P 5 0 R /Pg 3 0 R /K [0 << /Type /MCR /MCID 1 /Pg 4 0 R >> << /Type /OBJR /Obj 7 0 R >>] >>", + "<< /Type /Annot /Subtype /Square /Rect [0 0 1 1] /P 4 0 R /StructParent 2 >>")); + PdfStructureTreeRoot root = document.StructureTree!; + IReadOnlyList items = root.Elements[0].GetContentItems(); + + Assert.Same(document.Pages[0], Assert.IsType(items[0]).Page); + Assert.Same(document.Pages[1], Assert.IsType(items[1]).Page); + Assert.Same(document.Pages[0], Assert.IsType(items[2]).Page); + Assert.Equal(new CosReference(7, 0), Assert.IsType(items[2]).ObjectReference); + Assert.Same(root.Elements[0].Dictionary, root.FindElement(document.Pages[1], 1)!.Dictionary); + Assert.Null(root.FindElement(document.Pages[1], 0)); + Assert.Same(root.Elements[0].Dictionary, root.FindElementForObject(new CosReference(7, 0))!.Dictionary); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void An_mcid_with_no_page_anywhere_takes_the_page_whose_parent_tree_entry_lists_its_element() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [5 0 R] /ParentTree << /Nums [0 [null 5 0 R]] >>", + "<< /S /P /P 4 0 R /K 1 >>")); + + PdfMarkedContentReference reference = Assert.IsType(Assert.Single(document.StructureTree!.Elements[0].Children)); + + Assert.Same(document.Pages[0], reference.Page); + Assert.Equal("StructElemPageMissing", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void Language_alternates_and_pronunciation_are_read_and_inherited_along_the_hierarchy() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [5 0 R]", + "<< /S /Sect /P 4 0 R /Lang (fr) /PhoneticAlphabet /x-sampa /K [6 0 R 7 0 R] >>", + "<< /S /Span /P 5 0 R /T (Title) /Alt (alternate) /E (expansion) /ActualText (actual) /Phoneme (f@) /Ref [7 0 R] /AF [] >>", + "<< /S /P /P 5 0 R /Lang (de) >>")); + PdfStructureElement span = document.StructureTree!.Elements[1]; + PdfStructureElement section = document.StructureTree!.Elements[0]; + + Assert.Equal("Title", span.Title); + Assert.Equal("alternate", span.AlternateDescription); + Assert.Equal("expansion", span.Expansion); + Assert.Equal("actual", span.ActualText); + Assert.Equal("f@", span.Phoneme); + Assert.Null(span.Language); + Assert.Equal("fr", span.EffectiveLanguage); + Assert.Equal("x-sampa", span.PhoneticAlphabet); + Assert.Equal("de", Assert.Single(span.References).EffectiveLanguage); + Assert.Same(section, span.Parent); + Assert.Empty(span.AssociatedFiles!); + Assert.Null(section.Page); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_property_list_is_typed_for_mcid_artifacts_and_span_entries() + { + var artifact = new PdfPropertyList( + new CosName("Artifact"), + (CosDictionary)CosObject.Parse("<< /Type /Pagination /Subtype /Header /BBox [0 700 612 792] /Attached [/Top /Left] >>"u8), + document: null); + var span = new PdfPropertyList( + new CosName("Span"), + (CosDictionary)CosObject.Parse("<< /MCID 4 /Lang (en-GB) /Alt (a) /ActualText (b) /E (c) >>"u8), + document: null); + var plain = new PdfPropertyList(new CosName("Tx"), properties: null, document: null); + + Assert.True(artifact.IsArtifact); + Assert.Equal("Pagination", artifact.ArtifactType); + Assert.Equal("Header", artifact.ArtifactSubtype); + Assert.Equal(new PdfRectangle(0, 700, 612, 792), artifact.ArtifactBoundingBox); + Assert.Equal(["Top", "Left"], artifact.ArtifactAttachments); + Assert.Null(artifact.Mcid); + + Assert.False(span.IsArtifact); + Assert.Equal(4, span.Mcid); + Assert.Null(span.ArtifactType); + Assert.Equal("en-GB", span.Language); + Assert.Equal("a", span.AlternateDescription); + Assert.Equal("b", span.ActualText); + Assert.Equal("c", span.Expansion); + + Assert.Null(plain.Mcid); + Assert.Empty(plain.ArtifactAttachments); + } +} diff --git a/tests/Broadside.Tests/LogicalStructure/RoleMappingTests.cs b/tests/Broadside.Tests/LogicalStructure/RoleMappingTests.cs new file mode 100644 index 00000000..0e9eb9e8 --- /dev/null +++ b/tests/Broadside.Tests/LogicalStructure/RoleMappingTests.cs @@ -0,0 +1,190 @@ +using Broadside.Structure; +using Broadside.Tests.Document; + +namespace Broadside.Tests.LogicalStructure; + +/// +/// Resolving structure types to standard types through role maps and namespaces. ISO 32000-2 §14.7.3, §14.7.4, §14.8.4, §14.8.6, +/// Annex M; ISO/TS 32005 §5. +/// +public class RoleMappingTests +{ + private const string Pdf20 = "<< /Type /Namespace /NS (http://iso.org/pdf2/ssn) >>"; + + public static TheoryData StandardTypeMatrix => new() + { + // type, standard in PDF 1.7 (the default namespace), standard in PDF 2.0 (Annex M). + { "P", true, true }, + { "H", true, true }, + { "H1", true, true }, + { "H6", true, true }, + { "H7", false, true }, + { "H12", false, true }, + { "H0", false, false }, + { "Hx", false, false }, + { "Document", true, true }, + { "DocumentFragment", false, true }, + { "Aside", false, true }, + { "Title", false, true }, + { "FENote", false, true }, + { "Sub", false, true }, + { "Em", false, true }, + { "Strong", false, true }, + { "Artifact", false, true }, + { "Art", true, false }, + { "BlockQuote", true, false }, + { "TOC", true, false }, + { "TOCI", true, false }, + { "Index", true, false }, + { "Private", true, false }, + { "Quote", true, false }, + { "Note", true, false }, + { "Reference", true, false }, + { "BibEntry", true, false }, + { "Code", true, false }, + { "Table", true, true }, + { "Ruby", true, true }, + { "Chapter", false, false }, + { "p", false, false }, + }; + + [Theory] + [MemberData(nameof(StandardTypeMatrix))] + public void Standard_types_differ_between_the_pdf_1_7_and_pdf_2_0_namespaces(string type, bool inPdf17, bool inPdf20) + { + Assert.Equal(inPdf17, PdfStructureNamespace.Pdf17.IsStandardType(type)); + Assert.Equal(inPdf20, PdfStructureNamespace.Pdf20.IsStandardType(type)); + } + + [Fact] + public void An_element_without_ns_is_in_the_pdf_1_7_namespace_even_in_a_pdf_2_0_file() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [5 0 R 6 0 R] /Namespaces [7 0 R]", + "<< /S /Em /P 4 0 R >>", + "<< /S /Em /P 4 0 R /NS 7 0 R >>", + Pdf20)); + PdfStructureElement[] elements = [.. document.StructureTree!.Children]; + + Assert.True(elements[0].Namespace.IsDefault); + Assert.Null(elements[0].StandardType); + Assert.Equal(new PdfStructureType("Em", PdfStructureNamespace.Pdf20), elements[1].StandardType); + Assert.Equal("StructureTypeUnresolved", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void The_role_map_is_followed_as_a_chain_and_maps_even_standard_types() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [5 0 R 6 0 R] /RoleMap << /Heading /Title /Title /H1 /P /H2 >>", + "<< /S /Heading /P 4 0 R >>", + "<< /S /P /P 4 0 R >>")); + PdfStructureElement[] elements = [.. document.StructureTree!.Children]; + + Assert.Equal(["Heading", "Title", "H1"], elements[0].RoleMapping.Select(static type => type.Name)); + Assert.Equal(new PdfStructureType("H1", PdfStructureNamespace.Pdf17), elements[0].StandardType); + Assert.Equal("H2", elements[1].StandardType!.Name); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_role_map_cycle_ends_the_chain_at_the_first_standard_type_after_the_start() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [5 0 R 6 0 R 7 0 R] /RoleMap << /A /B /B /A /P /H1 /H1 /P /Self /Self >>", + "<< /S /A /P 4 0 R >>", + "<< /S /P /P 4 0 R >>", + "<< /S /Self /P 4 0 R >>")); + PdfStructureElement[] elements = [.. document.StructureTree!.Children]; + + Assert.Equal(["A", "B"], elements[0].RoleMapping.Select(static type => type.Name)); + Assert.Null(elements[0].StandardType); + Assert.Equal(["P", "H1"], elements[1].RoleMapping.Select(static type => type.Name)); + Assert.Equal("H1", elements[1].StandardType!.Name); + Assert.Equal(["Self"], elements[2].RoleMapping.Select(static type => type.Name)); + Assert.Null(elements[2].StandardType); + Assert.Equal(["StructureTypeUnresolved"], document.Diagnostics.Select(static diagnostic => diagnostic.Code).Distinct()); + } + + [Fact] + public void A_namespace_role_map_lands_a_name_in_the_default_namespace_and_an_array_in_the_named_namespace() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [5 0 R 6 0 R 7 0 R] /Namespaces [8 0 R 9 0 R] /RoleMap << /Para /P /Box /Note >>", + "<< /S /Para /P 4 0 R /NS 9 0 R >>", + "<< /S /Box /P 4 0 R /NS 9 0 R >>", + "<< /S /Aside2 /P 4 0 R /NS 9 0 R >>", + Pdf20, + "<< /Type /Namespace /NS (urn:example:custom) /RoleMapNS << /Box /Note /Aside2 [/Aside 8 0 R] >> >>")); + PdfStructureElement[] elements = [.. document.StructureTree!.Children]; + + // The root RoleMap is for the default namespace only: Para in the custom namespace has no mapping. + Assert.Null(elements[0].StandardType); + Assert.Equal(new PdfStructureType("Note", PdfStructureNamespace.Pdf17), elements[1].StandardType); + Assert.Equal(new PdfStructureType("Aside", PdfStructureNamespace.Pdf20), elements[2].StandardType); + Assert.Equal([PdfStructureNamespaceKind.Custom, PdfStructureNamespaceKind.Pdf20], elements[2].RoleMapping.Select(static type => type.Namespace.Kind)); + Assert.Equal("StructureTypeUnresolved", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_name_landing_in_the_default_namespace_continues_through_the_root_role_map() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [5 0 R] /Namespaces [6 0 R] /RoleMap << /Block /Div >>", + "<< /S /Section /P 4 0 R /NS 6 0 R >>", + "<< /Type /Namespace /NS (urn:example:custom) /RoleMapNS << /Section /Block >> >>")); + + PdfStructureElement element = Assert.Single(document.StructureTree!.Children); + + Assert.Equal(["Section", "Block", "Div"], element.RoleMapping.Select(static type => type.Name)); + Assert.Equal(new PdfStructureType("Div", PdfStructureNamespace.Pdf17), element.StandardType); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Mathml_elements_are_standard_in_their_own_namespace_without_a_role_map() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [5 0 R] /Namespaces [6 0 R]", + "<< /S /math /P 4 0 R /NS 6 0 R >>", + "<< /Type /Namespace /NS (http://www.w3.org/1998/Math/MathML) >>")); + + PdfStructureElement element = Assert.Single(document.StructureTree!.Children); + + Assert.Equal(PdfStructureNamespaceKind.MathML, element.Namespace.Kind); + Assert.Equal(PdfStructureNamespace.MathML, element.Namespace); + Assert.Equal(new PdfStructureType("math", PdfStructureNamespace.MathML), element.StandardType); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Two_namespace_dictionaries_with_a_standard_name_are_the_same_namespace() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [5 0 R 6 0 R] /Namespaces [7 0 R 8 0 R]", + "<< /S /P /P 4 0 R /NS 7 0 R >>", + "<< /S /P /P 4 0 R /NS 8 0 R >>", + Pdf20, + Pdf20)); + PdfStructureElement[] elements = [.. document.StructureTree!.Children]; + + Assert.Equal(elements[0].Namespace, elements[1].Namespace); + Assert.NotSame(elements[0].Namespace.Dictionary, elements[1].Namespace.Dictionary); + Assert.Equal(PdfStructureNamespace.Pdf20, elements[0].Namespace); + Assert.NotEqual(PdfStructureNamespace.Pdf17, elements[0].Namespace); + } + + [Fact] + public void An_unresolved_type_in_an_untagged_document_is_not_a_diagnostic() + { + using PdfDocument document = PdfDocument.Open(new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R /StructTreeRoot 4 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>", + "<< /Type /StructTreeRoot /K [5 0 R] >>", + "<< /S /Chapter /P 4 0 R >>")); + + Assert.Null(Assert.Single(document.StructureTree!.Children).StandardType); + Assert.Empty(document.Diagnostics); + } +} diff --git a/tests/Broadside.Tests/LogicalStructure/Snapshots/StructureCorpusTests.Every_real_world_structure_tree_walks_leniently_and_the_summary_matches_the_snapshot.verified.txt b/tests/Broadside.Tests/LogicalStructure/Snapshots/StructureCorpusTests.Every_real_world_structure_tree_walks_leniently_and_the_summary_matches_the_snapshot.verified.txt new file mode 100644 index 00000000..60cf7ced --- /dev/null +++ b/tests/Broadside.Tests/LogicalStructure/Snapshots/StructureCorpusTests.Every_real_world_structure_tree_walks_leniently_and_the_summary_matches_the_snapshot.verified.txt @@ -0,0 +1,19 @@ +pdfjs: 989 files, 89 with a structure tree, 36996 elements + ParentTreeMissing: 2 + StructElemPageMissing: 2 + NamespaceNotDeclared: 1 +pdfbox: 137 files, 25 with a structure tree, 2108 elements +qpdf: 639 files, 37 with a structure tree, 1830 elements + ParentTreeEntryInvalid: 4 + MarkInfoInvalid: 1 +pdfium-tests: 840 files, 73 with a structure tree, 1525 elements + StructureTypeUnresolved: 1 +pdf20examples: 7 files, 1 with a structure tree, 6 elements +verapdf-corpus: 2906 files, 590 with a structure tree, 3547 elements + ParentTreeEntryInvalid: 21 + StructureTypeUnresolved: 16 + IdTreeEntryInvalid: 3 + McidDuplicate: 2 + NamespaceNotDeclared: 2 + IdTreeDuplicate: 1 + MarkInfoInvalid: 1 diff --git a/tests/Broadside.Tests/LogicalStructure/Snapshots/TaggedStructureCorpusTests.The_tagged_file_yields_the_expected_tree.verified.txt b/tests/Broadside.Tests/LogicalStructure/Snapshots/TaggedStructureCorpusTests.The_tagged_file_yields_the_expected_tree.verified.txt new file mode 100644 index 00000000..0e947fbc --- /dev/null +++ b/tests/Broadside.Tests/LogicalStructure/Snapshots/TaggedStructureCorpusTests.The_tagged_file_yields_the_expected_tree.verified.txt @@ -0,0 +1,36 @@ +Document (2.0) -> Document (2.0) + Chapter (https://example.com/broadside-corpus) -> Sect (2.0) T=Chapter 1 + H1 (2.0) -> H1 (2.0) + A Layout SpaceAfter=12 + C Centered + MCID 0 page 1 + Para (1.7) -> P (1.7) + A Layout TextAlign=/Justify + MCID 1 page 1 + OBJR Link page 1 + L (2.0) -> L (2.0) + A List ListNumbering=/Decimal + LI (2.0) -> LI (2.0) + Lbl (2.0) -> Lbl (2.0) + MCID 2 page 1 + LBody (2.0) -> LBody (2.0) + MCID 3 page 1 + LI (2.0) -> LI (2.0) + Lbl (2.0) -> Lbl (2.0) + MCID 4 page 1 + LBody (2.0) -> LBody (2.0) + MCID 5 page 1 + Table (2.0) -> Table (2.0) ID=tbl1 + A Table Summary=(Names and values) + TR (2.0) -> TR (2.0) + TH (2.0) -> TH (2.0) ID=h1 + A Table Scope=/Column + MCID 6 page 1 + TH (2.0) -> TH (2.0) + MCID 7 page 1 + TR (2.0) -> TR (2.0) + TD (2.0) -> TD (2.0) + A Table Headers=[(h1)] + MCID 8 page 1 + TD (2.0) -> TD (2.0) + MCR MCID 9 page 1 diff --git a/tests/Broadside.Tests/LogicalStructure/StructureCorpusTests.cs b/tests/Broadside.Tests/LogicalStructure/StructureCorpusTests.cs new file mode 100644 index 00000000..3fc8fdcc --- /dev/null +++ b/tests/Broadside.Tests/LogicalStructure/StructureCorpusTests.cs @@ -0,0 +1,114 @@ +using System.Collections.Concurrent; +using System.Globalization; +using System.Text; +using Broadside.Diagnostics; +using Broadside.Security; +using Broadside.TestSupport; + +namespace Broadside.Tests.LogicalStructure; + +/// +/// The structure tree of every corpus file: the hand-written well-formed files read with no diagnostic, and every real-world file +/// (the gate's corpora plus veraPDF's, which holds most of the tagged files) walks leniently without an exception and in time. The +/// real-world summary (how many files are tagged, how many elements, which structure diagnostics) is a snapshot reviewed by hand. +/// ISO 32000-2 §14.7, §14.8. +/// +public class StructureCorpusTests(ITestOutputHelper output) +{ + private static readonly string[] CorpusIds = ["pdfjs", "pdfbox", "qpdf", "pdfium-tests", "pdf20examples", "verapdf-corpus"]; + + /// The codes the structure views report; other codes (objects loaded on the way) belong to the document gate. + private static readonly HashSet StructureCodes = new(StringComparer.Ordinal) + { + "MarkInfoInvalid", "StructTreeRootInvalid", "StructElemInvalid", "StructElemTypeUnknown", "StructElemParentMismatch", + "StructElemPageMissing", "StructTreeCycle", "StructTreeDepthExceeded", "ParentTreeMissing", "ParentTreeEntryInvalid", + "McidDuplicate", "IdTreeDuplicate", "IdTreeEntryInvalid", "NamespaceInvalid", "NamespaceNotDeclared", "StructureTypeUnresolved", + "AttributeObjectInvalid", "AttributeOwnerInvalid", "AttributeRevisionInvalid", + "NameTreeNodeInvalid", "NameTreeLimitsInvalid", "NameTreeKeysUnsorted", "NameTreeDuplicateKey", "NameTreeKeyInvalid", "NameTreeCycle", "NameTreeTooDeep", + "NumberTreeNodeInvalid", "NumberTreeLimitsInvalid", "NumberTreeKeysUnsorted", "NumberTreeDuplicateKey", "NumberTreeKeyInvalid", "NumberTreeCycle", "NumberTreeTooDeep", + }; + + [Theory] + [MemberData(nameof(Corpus.WellFormedFiles), MemberType = typeof(Corpus))] + public void A_well_formed_file_reads_its_structure_tree_with_no_diagnostics(string fileName) + { + using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName)); + + int elements = StructureWalker.Walk(document); + + Assert.Equal(fileName == "tagged-structure.pdf" ? 18 : -1, elements); + Assert.Empty(document.Diagnostics); + } + + [Fact] + [Trait("Category", "Corpus")] + public async Task Every_real_world_structure_tree_walks_leniently_and_the_summary_matches_the_snapshot() + { + string[] fetched = [.. CorpusIds.Where(id => RealWorldCorpus.Directory(id) is not null)]; + if (fetched.Length != CorpusIds.Length) + { + Assert.Skip($"Corpora not fetched ({string.Join(", ", CorpusIds.Except(fetched))}); run tools/CorpusFetcher."); + } + + var results = new ConcurrentDictionary(StringComparer.Ordinal); + Parallel.ForEach( + CorpusIds.SelectMany(RealWorldCorpus.Files), + new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, + file => results[file] = WalkWithTimeLimit(file)); + + string[] failures = [.. results.Where(static entry => entry.Value.Failure is not null).Select(static entry => $"{entry.Key}: {entry.Value.Failure}").Order(StringComparer.Ordinal)]; + Assert.Empty(failures); + string summary = Summarize(results); + output.WriteLine(summary); + foreach ((string file, (int _, string[] codes, string? _)) in results.Where(static entry => entry.Value.Codes.Length > 0).OrderBy(static entry => entry.Key, StringComparer.Ordinal)) + { + output.WriteLine($"{file}: {string.Join(", ", codes)}"); + } + + await Verify(summary); + } + + private static (int Elements, string[] Codes, string? Failure) WalkWithTimeLimit(string file) + { + Task<(int, string[], string?)> walk = Task.Factory.StartNew(() => WalkOne(file), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + return walk.Wait(RealWorldCorpus.TimeLimit) ? walk.Result : (0, [], "timed out"); + } + + private static (int Elements, string[] Codes, string? Failure) WalkOne(string file) + { + try + { + using PdfDocument document = PdfDocument.Open(File.ReadAllBytes(RealWorldCorpus.PathOf(file))); + int before = document.Diagnostics.Count; + int elements = StructureWalker.Walk(document); + string[] codes = [.. document.Diagnostics.Skip(before).Where(static diagnostic => diagnostic.Severity > DiagnosticSeverity.Information && StructureCodes.Contains(diagnostic.Code)).Select(static diagnostic => diagnostic.Code).Distinct()]; + return (elements, codes, null); + } + catch (Exception exception) when (exception is DiagnosticException or PdfPasswordException or PdfCertificateException or PdfEncryptionNotSupportedException) + { + return (-1, [], null); + } +#pragma warning disable CA1031 // Any other exception is the finding. + catch (Exception exception) +#pragma warning restore CA1031 + { + return (0, [], exception.ToString()); + } + } + + private static string Summarize(ConcurrentDictionary results) + { + var text = new StringBuilder(); + foreach (string id in CorpusIds) + { + var corpus = results.Where(entry => entry.Key.StartsWith(id + "/", StringComparison.Ordinal)).Select(static entry => entry.Value).ToList(); + text.Append(CultureInfo.InvariantCulture, $"{id}: {corpus.Count} files, {corpus.Count(static result => result.Elements >= 0)} with a structure tree, {corpus.Where(static result => result.Elements > 0).Sum(static result => (long)result.Elements)} elements\n"); + foreach (IGrouping code in corpus.SelectMany(static result => result.Codes).GroupBy(static code => code, StringComparer.Ordinal).OrderByDescending(static group => group.Count()).ThenBy(static group => group.Key, StringComparer.Ordinal)) + { + text.Append(CultureInfo.InvariantCulture, $" {code.Key}: {code.Count()}\n"); + } + } + + return text.ToString(); + } +} diff --git a/tests/Broadside.Tests/LogicalStructure/StructureProjection.cs b/tests/Broadside.Tests/LogicalStructure/StructureProjection.cs new file mode 100644 index 00000000..32a190b4 --- /dev/null +++ b/tests/Broadside.Tests/LogicalStructure/StructureProjection.cs @@ -0,0 +1,120 @@ +using System.Globalization; +using System.Text; +using Broadside.Objects; +using Broadside.Structure; + +namespace Broadside.Tests.LogicalStructure; + +/// +/// Writes a structure tree as indented text through the public API only: one line per element (type, namespace, the standard type +/// it resolves to, title, ID), one line per content item and per attribute object. The snapshot of tagged-structure.pdf is +/// written from the generator by hand, not from this code's output. +/// +internal static class StructureProjection +{ + public static string Of(PdfDocument document, PdfStructureTreeRoot root) + { + var text = new StringBuilder(); + foreach (PdfStructureElement element in root.Children) + { + Write(document, element, 0, text); + } + + return text.ToString(); + } + + private static void Write(PdfDocument document, PdfStructureElement element, int depth, StringBuilder text) + { + string indent = new(' ', depth * 2); + text.Append(indent).Append(element.StructureType?.Value ?? "?").Append(" (").Append(Name(element.Namespace)).Append(')'); + PdfStructureType? standard = element.StandardType; + text.Append(" -> ").Append(standard is null ? "unresolved" : $"{standard.Name} ({Name(standard.Namespace)})"); + if (element.Title is { } title) + { + text.Append(" T=").Append(title); + } + + if (element.Id is { } id) + { + text.Append(" ID=").Append(Encoding.ASCII.GetString(id.Bytes)); + } + + text.Append('\n'); + foreach (PdfAttributeObject attributes in element.Attributes) + { + text.Append(indent).Append(" A ").Append(Attributes(attributes)).Append('\n'); + } + + foreach (CosName className in element.ClassNames) + { + text.Append(indent).Append(" C ").Append(className.Value).Append('\n'); + } + + foreach (PdfStructureItem item in element.Children) + { + switch (item) + { + case PdfStructureElement child: + Write(document, child, depth + 1, text); + break; + case PdfMarkedContentReference content: + text.Append(indent).Append(" ").Append(content.Dictionary is null ? "MCID " : "MCR MCID ") + .Append(content.Mcid.ToString(CultureInfo.InvariantCulture)).Append(" page ").Append(PageNumber(document, content.Page)).Append('\n'); + break; + case PdfObjectReference reference: + string subtype = reference.ReferencedObject is CosDictionary dictionary && dictionary.TryGetValue(new CosName("Subtype"), out CosObject? value) && value is CosName name + ? name.Value + : "?"; + text.Append(indent).Append(" OBJR ").Append(subtype).Append(" page ").Append(PageNumber(document, reference.Page)).Append('\n'); + break; + default: + throw new InvalidOperationException(item.GetType().Name); + } + } + } + + private static string Attributes(PdfAttributeObject attributes) + { + var text = new StringBuilder(attributes.Owner?.Value ?? "?"); + if (attributes.Revision != 0) + { + text.Append(" r").Append(attributes.Revision.ToString(CultureInfo.InvariantCulture)); + } + + foreach (KeyValuePair entry in attributes.Dictionary) + { + if (entry.Key.Value is not "O") + { + text.Append(' ').Append(entry.Key.Value).Append('=').Append(entry.Value.ToString()); + } + } + + return text.ToString(); + } + + private static string PageNumber(PdfDocument document, PdfPage? page) + { + if (page is null) + { + return "?"; + } + + for (int index = 0; index < document.Pages.Count; index++) + { + if (ReferenceEquals(document.Pages[index], page)) + { + return (index + 1).ToString(CultureInfo.InvariantCulture); + } + } + + return "?"; + } + + private static string Name(PdfStructureNamespace ns) => ns.Kind switch + { + PdfStructureNamespaceKind.Pdf17 => "1.7", + PdfStructureNamespaceKind.Pdf20 => "2.0", + PdfStructureNamespaceKind.MathML => "MathML", + _ => ns.Name, + }; +} diff --git a/tests/Broadside.Tests/LogicalStructure/StructureRepairTests.cs b/tests/Broadside.Tests/LogicalStructure/StructureRepairTests.cs new file mode 100644 index 00000000..b8143cbd --- /dev/null +++ b/tests/Broadside.Tests/LogicalStructure/StructureRepairTests.cs @@ -0,0 +1,249 @@ +using System.Text; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Structure; + +namespace Broadside.Tests.LogicalStructure; + +/// +/// Damaged structure trees: each repair is made in the view, recorded once as a diagnostic in lenient mode, and thrown in strict mode. +/// ISO 32000-2 §14.7.2-§14.7.6 and ADR 0005. +/// +public class StructureRepairTests +{ + /// Each case: the diagnostic code it must produce (and nothing else), the root entries, and the objects from 5 on. + public static TheoryData Damaged => new() + { + { + "ParentTreeMissing", + "/K [5 0 R]", + ["<< /Type /StructElem /S /P /P 4 0 R /Pg 3 0 R /K 0 >>"] + }, + { + "ParentTreeEntryInvalid", + "/K [5 0 R 6 0 R] /ParentTree << /Nums [0 [6 0 R]] >>", + ["<< /Type /StructElem /S /P /P 4 0 R /Pg 3 0 R /K 0 >>", "<< /Type /StructElem /S /H1 /P 4 0 R >>"] + }, + { + "ParentTreeEntryInvalid", + "/K [5 0 R] /ParentTree << /Nums [0 5 0 R] >>", + ["<< /Type /StructElem /S /P /P 4 0 R /Pg 3 0 R /K 0 >>"] + }, + { + "McidDuplicate", + "/K [5 0 R 6 0 R] /ParentTree << /Nums [0 [5 0 R]] >>", + ["<< /Type /StructElem /S /P /P 4 0 R /Pg 3 0 R /K 0 >>", "<< /Type /StructElem /S /H1 /P 4 0 R /Pg 3 0 R /K 0 >>"] + }, + { + "StructElemPageMissing", + "/K [5 0 R] /ParentTree << /Nums [0 [6 0 R]] >>", + ["<< /Type /StructElem /S /Div /P 4 0 R /Pg 3 0 R /K [6 0 R] >>", "<< /Type /StructElem /S /P /P 5 0 R /K 0 >>"] + }, + { + "StructElemParentMismatch", + "/K [5 0 R]", + ["<< /Type /StructElem /S /Div /P 4 0 R /K [6 0 R] >>", "<< /Type /StructElem /S /P /P 4 0 R >>"] + }, + { + "IdTreeDuplicate", + "/K [5 0 R 6 0 R] /IDTree << /Names [(id) 5 0 R] >>", + ["<< /Type /StructElem /S /P /P 4 0 R /ID (id) >>", "<< /Type /StructElem /S /P /P 4 0 R /ID (id) >>"] + }, + { + "IdTreeEntryInvalid", + "/K [5 0 R 6 0 R] /IDTree << /Names [(id) 5 0 R] >>", + ["<< /Type /StructElem /S /P /P 4 0 R /ID (id) >>", "<< /Type /StructElem /S /P /P 4 0 R /ID (other) >>"] + }, + { + "StructTreeCycle", + "/K [5 0 R]", + ["<< /Type /StructElem /S /Div /P 4 0 R /K [6 0 R] >>", "<< /Type /StructElem /S /Div /P 5 0 R /K [5 0 R] >>"] + }, + { + "StructElemTypeUnknown", + "/K [5 0 R]", + ["<< /Type /Annot /S /P /P 4 0 R >>"] + }, + { + "NamespaceNotDeclared", + "/K [5 0 R]", + ["<< /Type /StructElem /S /P /P 4 0 R /NS 6 0 R >>", "<< /Type /Namespace /NS (http://iso.org/pdf2/ssn) >>"] + }, + { + "StructureTypeUnresolved", + "/K [5 0 R]", + ["<< /Type /StructElem /S /Em /P 4 0 R >>"] + }, + { + "AttributeRevisionInvalid", + "/K [5 0 R]", + ["<< /Type /StructElem /S /P /P 4 0 R /A [1 << /O /Layout /TextAlign /End >> 2 3] >>"] + }, + { + "AttributeOwnerInvalid", + "/K [5 0 R]", + ["<< /Type /StructElem /S /P /P 4 0 R /A << /O /NSO /Foo 1 >> >>"] + }, + { + "StructTreeRootInvalid", + "/K [0 5 0 R]", + ["<< /Type /StructElem /S /P /P 4 0 R >>"] + }, + }; + + [Theory] + [MemberData(nameof(Damaged))] + public void A_damaged_tree_is_read_with_exactly_one_kind_of_diagnostic(string code, string rootEntries, string[] objects) + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build(rootEntries, objects)); + + TaggedPdf.ReadEverything(document); + + Assert.Equal([code], document.Diagnostics.Select(static diagnostic => diagnostic.Code).Distinct()); + Assert.All(document.Diagnostics, static diagnostic => Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity)); + } + + [Theory] + [MemberData(nameof(Damaged))] + public void Strict_mode_throws_the_same_diagnostic(string code, string rootEntries, string[] objects) + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build(rootEntries, objects), new PdfOptions().UseStrict()); + + DiagnosticException error = Assert.Throws(() => TaggedPdf.ReadEverything(document)); + + Assert.Equal(code, error.Diagnostic.Code); + } + + [Fact] + public void The_parent_tree_finds_an_element_the_root_does_not_reach() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [] /ParentTree << /Nums [0 [5 0 R]] >>", + "<< /Type /StructElem /S /P /P 4 0 R /Pg 3 0 R /K 0 >>")); + + PdfStructureElement element = Assert.IsType(document.StructureTree!.FindElement(document.Pages[0], 0)); + + Assert.Equal("P", element.StructureType!.Value); + Assert.Null(element.Parent); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_parent_tree_entry_naming_the_wrong_element_gives_way_to_the_element_whose_k_holds_the_mcid() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [5 0 R 6 0 R] /ParentTree << /Nums [0 [6 0 R 6 0 R]] >>", + "<< /Type /StructElem /S /P /P 4 0 R /Pg 3 0 R /K 0 >>", + "<< /Type /StructElem /S /H1 /P 4 0 R /Pg 3 0 R /K 1 >>")); + PdfStructureTreeRoot root = document.StructureTree!; + + Assert.Equal("P", root.FindElement(document.Pages[0], 0)!.StructureType!.Value); + Assert.Equal("H1", root.FindElement(document.Pages[0], 1)!.StructureType!.Value); + Assert.Equal("ParentTreeEntryInvalid", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void Without_a_parent_tree_the_k_hierarchy_answers_lookups() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [5 0 R]", + "<< /Type /StructElem /S /P /P 4 0 R /Pg 3 0 R /K [0 << /Type /OBJR /Obj 6 0 R >>] >>", + "<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /StructParent 1 >>")); + PdfStructureTreeRoot root = document.StructureTree!; + + Assert.Equal("P", root.FindElement(document.Pages[0], 0)!.StructureType!.Value); + Assert.Equal("P", root.FindElementForObject(new CosReference(6, 0))!.StructureType!.Value); + Assert.Equal("ParentTreeMissing", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void The_id_tree_finds_an_element_the_root_does_not_reach_and_the_walk_finds_one_it_does_not_list() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [6 0 R] /IDTree << /Names [(far) 5 0 R] >>", + "<< /Type /StructElem /S /Note /P 4 0 R /ID (far) >>", + "<< /Type /StructElem /S /P /P 4 0 R /ID (near) >>")); + PdfStructureTreeRoot root = document.StructureTree!; + + Assert.Equal("Note", root.FindElementById("far"u8)!.StructureType!.Value); + Assert.Equal("P", root.FindElementById(Encoding.ASCII.GetBytes("near"))!.StructureType!.Value); + Assert.Equal("IdTreeEntryInvalid", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_cycle_through_k_is_cut_so_a_recursive_walk_of_the_children_ends() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K [5 0 R]", + "<< /Type /StructElem /S /Div /P 4 0 R /K [6 0 R] >>", + "<< /Type /StructElem /S /Div /P 5 0 R /K [5 0 R 6 0 R] >>")); + PdfStructureTreeRoot root = document.StructureTree!; + + Assert.Equal(2, CountRecursively(root.Children)); + Assert.Equal(2, root.Elements.Count); + Assert.Equal("StructTreeCycle", Assert.Single(document.Diagnostics.Select(static diagnostic => diagnostic.Code).Distinct())); + } + + [Fact] + public void A_hierarchy_deeper_than_the_limit_is_cut_with_a_diagnostic() + { + var objects = new List(); + for (int index = 0; index < 300; index++) + { + int number = 5 + index; + int parent = index == 0 ? 4 : number - 1; + objects.Add($"<< /Type /StructElem /S /Div /P {parent} 0 R /K [{number + 1} 0 R] >>"); + } + + objects.Add("<< /Type /StructElem /S /P /P 304 0 R >>"); + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build("/K [5 0 R]", [.. objects])); + PdfStructureTreeRoot root = document.StructureTree!; + + Assert.Equal(256, root.Elements.Count); + Assert.Equal(256, CountRecursively(root.Children)); + Assert.Equal("StructTreeDepthExceeded", Assert.Single(document.Diagnostics.Select(static diagnostic => diagnostic.Code).Distinct())); + } + + [Fact] + public void A_k_dictionary_without_type_is_read_by_what_it_holds() + { + using PdfDocument document = PdfDocument.Open(TaggedPdf.Build( + "/K 5 0 R /ParentTree << /Nums [0 [null 5 0 R]] >>", + "<< /S /Div /P 4 0 R /K [<< /S /P /P 5 0 R /Pg 3 0 R /K 0 >> << /MCID 1 /Pg 3 0 R >> << /Obj 6 0 R >>] >>", + "<< /Type /Annot /Subtype /Square /Rect [0 0 1 1] >>")); + PdfStructureElement division = Assert.Single(document.StructureTree!.Children); + + Assert.Collection( + division.Children, + static item => Assert.Equal("P", Assert.IsType(item).StructureType!.Value), + static item => Assert.Equal(1, Assert.IsType(item).Mcid), + static item => Assert.IsType(item)); + Assert.Equal(["StructElemTypeUnknown"], document.Diagnostics.Select(static diagnostic => diagnostic.Code).Distinct()); + } + + [Fact] + public void An_untagged_document_has_no_structure_tree_and_no_diagnostic() + { + using PdfDocument document = PdfDocument.Open(TestPdfOnePage()); + + Assert.Null(document.StructureTree); + Assert.False(document.MarkInfo.Marked); + Assert.Null(document.MarkInfo.Dictionary); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Mark_information_that_is_not_boolean_reads_false_with_a_diagnostic() + { + using PdfDocument document = PdfDocument.Open(Document.TestPdf.OnePage(string.Empty, "/MarkInfo << /Marked 1 /Suspects true >>")); + + Assert.False(document.MarkInfo.Marked); + Assert.True(document.MarkInfo.Suspects); + Assert.Equal("MarkInfoInvalid", Assert.Single(document.Diagnostics).Code); + } + + private static byte[] TestPdfOnePage() => Document.TestPdf.OnePage(string.Empty); + + private static int CountRecursively(IReadOnlyList items) => + items.OfType().Sum(static element => 1 + CountRecursively(element.Children)); +} diff --git a/tests/Broadside.Tests/LogicalStructure/StructureWalker.cs b/tests/Broadside.Tests/LogicalStructure/StructureWalker.cs new file mode 100644 index 00000000..1dd61d65 --- /dev/null +++ b/tests/Broadside.Tests/LogicalStructure/StructureWalker.cs @@ -0,0 +1,68 @@ +using Broadside.Objects; +using Broadside.Structure; + +namespace Broadside.Tests.LogicalStructure; + +/// +/// Reads a document's whole structure tree through the public API: every element reached through +/// (iteratively) and through , its role mapping, namespace, attributes, language and +/// content items, and every lookup (MCID per page, ID, object content item). +/// +internal static class StructureWalker +{ + private static readonly CosName Layout = new("Layout"); + private static readonly CosName TextAlign = new("TextAlign"); + + /// Walks the tree; returns the number of elements reached through the children, or -1 when the document has no tree. + public static int Walk(PdfDocument document) + { + if (document.StructureTree is not { } root) + { + return -1; + } + + _ = (document.MarkInfo.Marked, root.Namespaces, root.ParentTreeNextKey, root.RoleMap, root.ClassMap); + int count = 0; + var stack = new Stack(root.Children.Reverse()); + var seen = new HashSet(); + while (stack.TryPop(out PdfStructureElement? element)) + { + if (!seen.Add(element)) + { + continue; + } + + count++; + _ = (element.StandardType, element.RoleMapping, element.Namespace, element.Title, element.Id, element.EffectiveLanguage, element.PhoneticAlphabet); + _ = (element.Attributes, element.ClassAttributes, element.GetAttributeValue(Layout, TextAlign), element.References, element.Page); + IReadOnlyList children = element.Children; + for (int index = children.Count - 1; index >= 0; index--) + { + switch (children[index]) + { + case PdfStructureElement child: + stack.Push(child); + break; + case PdfObjectReference reference: + _ = root.FindElementForObject(reference.ReferencedObject); + break; + } + } + } + + foreach (PdfStructureElement element in root.Elements) + { + if (element.Id is { } id) + { + _ = root.FindElementById(id.Bytes); + } + } + + foreach (PdfPage page in document.Pages) + { + _ = root.GetMarkedContentElements(page); + } + + return count; + } +} diff --git a/tests/Broadside.Tests/LogicalStructure/TaggedPdf.cs b/tests/Broadside.Tests/LogicalStructure/TaggedPdf.cs new file mode 100644 index 00000000..efb33c1e --- /dev/null +++ b/tests/Broadside.Tests/LogicalStructure/TaggedPdf.cs @@ -0,0 +1,54 @@ +using Broadside.Structure; +using Broadside.Tests.Document; + +namespace Broadside.Tests.LogicalStructure; + +/// +/// Builds a one-page tagged file in memory: object 1 the catalog (MarkInfo Marked true), 2 the page tree, 3 the page +/// (StructParents 0), 4 the structure tree root with rootEntries, then the given objects as 5, 6, and so on. +/// +internal static class TaggedPdf +{ + public static byte[] Build(string rootEntries, params string[] objects) => new TestPdf { Header = "%PDF-2.0", TrailerEntries = "/ID [<00> <00>]" }.Build( + [ + "<< /Type /Catalog /Pages 2 0 R /MarkInfo << /Marked true >> /StructTreeRoot 4 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] /StructParents 0 >>", + $"<< /Type /StructTreeRoot {rootEntries} >>", + .. objects, + ]); + + /// Reads everything the views offer, so every lazily reported diagnostic is reported. + public static void ReadEverything(PdfDocument document) + { + if (document.StructureTree is not { } root) + { + return; + } + + _ = (root.Children, root.Namespaces, document.MarkInfo.Marked, document.MarkInfo.UserProperties, document.MarkInfo.Suspects); + foreach (PdfStructureElement element in root.Elements) + { + Visit(element); + } + + foreach (PdfPage page in document.Pages) + { + _ = root.GetMarkedContentElements(page); + } + + _ = root.FindElementById("id"u8); + } + + private static void Visit(PdfStructureElement element) + { + _ = (element.StandardType, element.Namespace, element.Attributes, element.ClassAttributes, element.EffectiveLanguage, element.References); + foreach (PdfStructureItem child in element.Children) + { + if (child is PdfStructureElement nested) + { + _ = nested.StandardType; + } + } + } +} diff --git a/tests/Broadside.Tests/LogicalStructure/TaggedStructureCorpusTests.cs b/tests/Broadside.Tests/LogicalStructure/TaggedStructureCorpusTests.cs new file mode 100644 index 00000000..d83014c7 --- /dev/null +++ b/tests/Broadside.Tests/LogicalStructure/TaggedStructureCorpusTests.cs @@ -0,0 +1,220 @@ +using System.Text; +using System.Text.RegularExpressions; +using Broadside.Objects; +using Broadside.Structure; +using Broadside.TestSupport; + +namespace Broadside.Tests.LogicalStructure; + +/// The tagged corpus file read through the structure tree. ISO 32000-2 §14.6-§14.8; ISO/TS 32005 §5. +public partial class TaggedStructureCorpusTests +{ + [Fact] + public Task The_tagged_file_yields_the_expected_tree() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("tagged-structure.pdf")); + + PdfStructureTreeRoot root = Assert.IsType(document.StructureTree); + string tree = StructureProjection.Of(document, root); + + Assert.Empty(document.Diagnostics); + return Verify(tree); + } + + [Fact] + public void Every_marked_content_sequence_of_the_page_maps_to_the_element_tagged_like_it_through_the_parent_tree() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("tagged-structure.pdf")); + PdfStructureTreeRoot root = document.StructureTree!; + PdfPage page = document.Pages[0]; + + // The content stream is the independent source: each "/Tag <> BDC" names the element type that owns n. + string content = Encoding.Latin1.GetString(document.DecodeStream((CosStream)document.Resolve(page.Dictionary[new CosName("Contents")])).Span); + MatchCollection sequences = MarkedContentWithMcid().Matches(content); + Assert.Equal(10, sequences.Count); + + IReadOnlyDictionary index = root.GetMarkedContentElements(page); + Assert.Equal(10, index.Count); + foreach (Match sequence in sequences) + { + int mcid = int.Parse(sequence.Groups["mcid"].Value, System.Globalization.CultureInfo.InvariantCulture); + string tag = sequence.Groups["tag"].Value; + PdfStructureElement element = Assert.IsType(root.FindElement(page, mcid)); + Assert.Equal(tag, element.StandardType!.Name); + Assert.Same(element.Dictionary, index[mcid].Dictionary); + Assert.Contains(element.GetContentItems(), item => item is PdfMarkedContentReference reference && reference.Mcid == mcid && reference.Page == page); + } + + Assert.Null(root.FindElement(page, 10)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void The_link_annotation_finds_its_paragraph_through_its_struct_parent() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("tagged-structure.pdf")); + PdfStructureTreeRoot root = document.StructureTree!; + CosObject annotation = ((CosArray)document.Pages[0].Dictionary[new CosName("Annots")])[0]; + + PdfStructureElement paragraph = Assert.IsType(root.FindElementForObject(annotation)); + + Assert.Equal("Para", paragraph.StructureType!.Value); + PdfObjectReference link = Assert.Single(paragraph.Children.OfType()); + Assert.Same(document.Resolve(annotation), link.ReferencedObject); + Assert.Same(document.Pages[0], link.Page); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Elements_are_found_by_id_through_the_id_tree() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("tagged-structure.pdf")); + PdfStructureTreeRoot root = document.StructureTree!; + + Assert.Equal("Table", root.FindElementById("tbl1"u8)!.StructureType!.Value); + Assert.Equal("TH", root.FindElementById("h1"u8)!.StructureType!.Value); + Assert.Null(root.FindElementById("missing"u8)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Lookups_return_elements_that_know_their_parents() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("tagged-structure.pdf")); + PdfStructureTreeRoot root = document.StructureTree!; + + PdfStructureElement cell = root.FindElement(document.Pages[0], 9)!; + + Assert.Equal(["TD", "TR", "Table", "Chapter", "Document"], Ancestry(cell)); + Assert.Equal("en-US", cell.EffectiveLanguage); + Assert.Equal("ipa", cell.PhoneticAlphabet); + Assert.Equal(18, root.Elements.Count); + Assert.Equal(["Document", "Chapter", "H1", "Para", "L", "LI", "Lbl", "LBody", "LI", "Lbl", "LBody", "Table", "TR", "TH", "TH", "TR", "TD", "TD"], root.Elements.Select(static element => element.StructureType!.Value)); + } + + [Fact] + public void Mark_information_says_the_document_is_tagged() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("tagged-structure.pdf")); + + Assert.True(document.MarkInfo.Marked); + Assert.False(document.MarkInfo.UserProperties); + Assert.False(document.MarkInfo.Suspects); + } + + [Fact] + public void Attributes_resolve_with_a_over_c_inheritance_and_defaults() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("tagged-structure.pdf")); + PdfStructureTreeRoot root = document.StructureTree!; + var layout = new CosName("Layout"); + var list = new CosName("List"); + var table = new CosName("Table"); + PdfStructureElement heading = root.FindElement(document.Pages[0], 0)!; + PdfStructureElement label = root.FindElement(document.Pages[0], 2)!; + PdfStructureElement header = root.FindElementById("h1"u8)!; + PdfStructureElement cell = root.FindElement(document.Pages[0], 8)!; + + // C /Centered gives TextAlign Center and SpaceAfter 6; A gives SpaceAfter 12, which wins. + Assert.Equal(new CosName("Center"), heading.GetAttributeValue(layout, new CosName("TextAlign"))); + Assert.Equal(new CosInteger(12), heading.GetAttributeValue(layout, new CosName("SpaceAfter"))); + Assert.Equal(6, Assert.IsType(Assert.Single(heading.ClassAttributes)).SpaceAfter); + Assert.Equal(12, Assert.IsType(Assert.Single(heading.Attributes)).SpaceAfter); + + // ListNumbering is inheritable: the label inherits Decimal from L; TextAlign falls back to its default. + Assert.Equal(new CosName("Decimal"), label.GetAttributeValue(list, new CosName("ListNumbering"))); + Assert.Equal(new CosName("Start"), label.GetAttributeValue(layout, new CosName("TextAlign"))); + Assert.True(Assert.IsType(Assert.Single(label.Parent!.Parent!.Attributes)).IsOrdered); + + // Table attributes are not inheritable: RowSpan defaults to 1, Scope applies only to the header itself. + PdfTableAttributes scope = Assert.IsType(Assert.Single(header.Attributes)); + Assert.Equal("Column", scope.Scope); + Assert.Equal(0, scope.Revision); + Assert.Equal(new CosInteger(1), cell.GetAttributeValue(table, new CosName("RowSpan"))); + Assert.Null(cell.GetAttributeValue(table, new CosName("Scope"))); + Assert.Equal("h1", Encoding.ASCII.GetString(Assert.Single(Assert.IsType(Assert.Single(cell.Attributes)).Headers!).Bytes)); + Assert.Equal("Names and values", Assert.IsType(Assert.Single(root.FindElementById("tbl1"u8)!.Attributes)).Summary); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Role_mapping_follows_the_root_role_map_and_the_custom_namespace_role_map() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("tagged-structure.pdf")); + PdfStructureTreeRoot root = document.StructureTree!; + PdfStructureElement chapter = root.Children[0].Children.OfType().Single(); + PdfStructureElement paragraph = root.FindElement(document.Pages[0], 1)!; + + Assert.Equal(PdfStructureNamespaceKind.Custom, chapter.Namespace.Kind); + Assert.Equal("https://example.com/broadside-corpus", chapter.Namespace.Name); + Assert.Equal([new PdfStructureType("Chapter", chapter.Namespace), new PdfStructureType("Sect", PdfStructureNamespace.Pdf20)], chapter.RoleMapping); + Assert.True(paragraph.Namespace.IsDefault); + Assert.Equal([new PdfStructureType("Para", PdfStructureNamespace.Pdf17), new PdfStructureType("P", PdfStructureNamespace.Pdf17)], paragraph.RoleMapping); + Assert.Equal([PdfStructureNamespaceKind.Pdf20, PdfStructureNamespaceKind.Custom], root.Namespaces.Select(static ns => ns.Kind)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Reading_the_whole_tree_changes_no_object() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("tagged-structure.pdf")); + PdfStructureTreeRoot root = document.StructureTree!; + + _ = StructureProjection.Of(document, root); + foreach (PdfStructureElement element in root.Elements) + { + _ = (element.StandardType, element.EffectiveLanguage, element.PhoneticAlphabet, element.ClassAttributes, element.References, element.Page); + } + + _ = root.GetMarkedContentElements(document.Pages[0]); + Assert.False(document.Catalog.IsDirty); + Assert.False(root.Dictionary.IsDirty); + Assert.All(root.Elements, static element => Assert.False(element.Dictionary.IsDirty)); + } + + [Fact] + public void Concurrent_first_lookups_build_each_index_once_and_agree() + { + for (int round = 0; round < 20; round++) + { + using PdfDocument document = PdfDocument.Open(Corpus.Bytes("tagged-structure.pdf")); + PdfStructureTreeRoot root = document.StructureTree!; + PdfPage page = document.Pages[0]; + var answers = new System.Collections.Concurrent.ConcurrentBag(); + Parallel.For(0, Environment.ProcessorCount * 4, index => + { + var text = new StringBuilder(); + for (int mcid = 0; mcid < 10; mcid++) + { + int probe = (mcid + index) % 10; + text.Append(probe).Append('=').Append(root.FindElement(page, probe)!.Reference).Append(';'); + } + + text.Append(root.FindElementById("tbl1"u8)!.Reference).Append(';'); + foreach (PdfStructureElement element in root.Elements) + { + text.Append(element.Reference).Append('<').Append(element.Parent?.Reference).Append(';'); + } + + answers.Add(string.Join(';', text.ToString().Split(';').Order(StringComparer.Ordinal))); + }); + + Assert.Single(answers.Distinct()); + Assert.Empty(document.Diagnostics); + } + } + + private static List Ancestry(PdfStructureElement element) + { + var types = new List(); + for (PdfStructureElement? current = element; current is not null; current = current.Parent) + { + types.Add(current.StructureType!.Value); + } + + return types; + } + + [GeneratedRegex(@"/(?\w+) <\d+)>> BDC")] + private static partial Regex MarkedContentWithMcid(); +} diff --git a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt index 89eff615..9ce342c6 100644 --- a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt +++ b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt @@ -40,6 +40,7 @@ png-predictor.pdf, runlength-stream.pdf, startxref-wrong.pdf, + tagged-structure.pdf, text-standard14.pdf, text-truetype-embedded.pdf, wrong-stream-length.pdf, diff --git a/tests/Corpus/README.md b/tests/Corpus/README.md index 4093ee04..b228424a 100644 --- a/tests/Corpus/README.md +++ b/tests/Corpus/README.md @@ -66,6 +66,7 @@ Verification was run with qpdf 12.4.2 (`qpdf --check`), poppler (`pdfinfo`, `pdf | `metadata-xmp.pdf` | Catalog `/Metadata` stream (`/Type /Metadata /Subtype /XML`) with a minimal XMP packet whose `dc:title` is `Broadside`, plus a trailer `/Info` dictionary with the same `/Title`. | 14.3.2, 14.3.3 | `pdfinfo` shows `Title: Broadside` | clean | | `name-tree-deep.pdf` | `/Names << /Dests ... >>` name tree four levels deep (root `/Kids`, two levels of intermediate nodes, 20 leaves) holding 200 keys in byte order: `(a)` before `(ab)` (a key that is a prefix of another), PDFDocEncoding keys whose byte order differs from their text order (`<18>`, the breve, sorts first; `<80>` bullet before `` e-acute), and UTF-16BE keys with the byte order marker (`` also reads as "a"). Each value is `[3 0 R /XYZ 0 i null]`, `i` the key's position. | 7.9.6, Annex J.3.3, 12.3.2.4 | `qpdf --check` | qpdf 12.4.2 warns `keys are not sorted` on the root (object 31) because it compares keys as decoded text; the clause compares bytes, so for Broadside the file is clean | | `number-tree-deep.pdf` | Twelve pages and a `/PageLabels` number tree three levels deep (root `/Kids`, two intermediate nodes, three leaves with `/Limits` and `/Nums`) with keys 0, 1, 2, 4, 5, 7, 8, 10, 11, so most pages fall between two keys. | 7.9.7, 12.4.2 | `qpdf --check`; `pdfinfo` reports 12 pages | clean | +| `tagged-structure.pdf` | PDF 2.0 tagged page (`/MarkInfo << /Marked true >>`, `/StructParents 0`, `/Tabs /S`): Document > Chapter > [H1, Para, L (two LI with Lbl/LBody), Table (two TR with TH/TD)] owning MCIDs 0-9 in content order, a pagination `/Artifact` outside the tree, a Link annotation as an OBJR of Para (`/StructParent 1`), MCID 9 as an MCR dictionary. Root has ParentTree, ParentTreeNextKey 2, IDTree (`h1`, `tbl1`), RoleMap `/Para /P`, ClassMap `/Centered`, Namespaces [PDF 2.0, custom `https://example.com/broadside-corpus` with RoleMapNS `/Chapter [/Sect <2.0>]`]. H1 has both C and A (A wins for SpaceAfter); L has List, Table/TH/TD have Table attributes (TH A array with revision 0). | 14.6, 14.7.2-14.7.6, 14.8.4-14.8.6 | `qpdf --check`; `pdfinfo` (Tagged: yes); `pdftotext` | clean; `pdfinfo -struct` stops at Chapter ("StructElem object is wrong type"): poppler applies only RoleMap, not RoleMapNS (14.8.6.2) | The crypt filter `/Length` entries in the R4 and R6 files are `16` and `32` (bytes), the form Acrobat and qpdf write and that Table 25 describes for the standard security handler; the same table also says the key "shall have the value of 128/256". Readers should accept both forms. diff --git a/tests/Corpus/generate.py b/tests/Corpus/generate.py index 48e09520..a0f07af1 100644 --- a/tests/Corpus/generate.py +++ b/tests/Corpus/generate.py @@ -1291,6 +1291,67 @@ def gen_metadata_xmp() -> bytes: ], trailer_extra=b" /Info 5 0 R") +def gen_tagged_structure() -> bytes: + """14.6 marked content, 14.7 logical structure and 14.8 tagged PDF: a heading, a paragraph with a + Link annotation (OBJR, StructParent), a two-item list and a two-by-two table, all as MCIDs 0..9 on + one page (StructParents 0), plus a pagination artifact outside the tree. ParentTree (14.7.5.4), + IDTree, RoleMap (Para -> P in the default 1.7 namespace), ClassMap with C and A on the heading + (14.7.6.2: A wins), namespaces (14.7.4) PDF 2.0 and a custom one whose RoleMapNS maps Chapter to + [/Sect <2.0>] (14.8.6.2), and one marked-content reference dictionary (Table 357) for MCID 9.""" + content = b"\n".join([ + b"/Artifact <> BDC BT /F1 10 Tf 300 40 Td (1) Tj ET EMC", + b"/H1 <> BDC BT /F1 24 Tf 72 720 Td (Broadside) Tj ET EMC", + b"/P <> BDC BT /F1 12 Tf 72 690 Td (A paragraph with a link.) Tj ET EMC", + b"/Lbl <> BDC BT /F1 12 Tf 72 660 Td (1.) Tj ET EMC", + b"/LBody <> BDC BT /F1 12 Tf 96 660 Td (First item) Tj ET EMC", + b"/Lbl <> BDC BT /F1 12 Tf 72 645 Td (2.) Tj ET EMC", + b"/LBody <> BDC BT /F1 12 Tf 96 645 Td (Second item) Tj ET EMC", + b"/TH <> BDC BT /F1 12 Tf 72 610 Td (Name) Tj ET EMC", + b"/TH <> BDC BT /F1 12 Tf 200 610 Td (Value) Tj ET EMC", + b"/TD <> BDC BT /F1 12 Tf 72 595 Td (Alpha) Tj ET EMC", + b"/TD <> BDC BT /F1 12 Tf 200 595 Td (1) Tj ET EMC", + ]) + ns20 = b"/NS 7 0 R" + id0 = file_id("tagged-structure").hex().encode() + + def elem(s: bytes, parent: int, extra: bytes) -> bytes: + return b"<< /Type /StructElem /S /%s /P %d 0 R %s >>" % (s, parent, extra) + + return simple_file([ + (1, catalog(b" /MarkInfo << /Marked true >> /StructTreeRoot 10 0 R /Lang (en-US)")), + (2, pages()), + (3, page(contents=4, font=6, extra=b" /StructParents 0 /Tabs /S /Annots [5 0 R]")), + (4, stream(b"", content)), + (5, b"<< /Type /Annot /Subtype /Link /Rect [72 686 240 702] /Border [0 0 0] " + b"/A << /S /URI /URI (https://example.com/) >> /StructParent 1 >>"), + (6, HELVETICA), + (7, b"<< /Type /Namespace /NS (http://iso.org/pdf2/ssn) >>"), + (8, b"<< /Type /Namespace /NS (https://example.com/broadside-corpus) /RoleMapNS << /Chapter [/Sect 7 0 R] >> >>"), + (10, b"<< /Type /StructTreeRoot /K [11 0 R] " + b"/ParentTree << /Nums [0 [13 0 R 14 0 R 17 0 R 18 0 R 20 0 R 21 0 R 24 0 R 25 0 R 27 0 R 28 0 R] 1 14 0 R] >> " + b"/ParentTreeNextKey 2 /IDTree << /Names [(h1) 24 0 R (tbl1) 22 0 R] >> /RoleMap << /Para /P >> " + b"/ClassMap << /Centered << /O /Layout /TextAlign /Center /SpaceAfter 6 >> >> /Namespaces [7 0 R 8 0 R] >>"), + (11, elem(b"Document", 10, ns20 + b" /K [12 0 R]")), + (12, elem(b"Chapter", 11, b"/NS 8 0 R /T (Chapter 1) /K [13 0 R 14 0 R 15 0 R 22 0 R]")), + (13, elem(b"H1", 12, ns20 + b" /Pg 3 0 R /K 0 /C /Centered /A << /O /Layout /SpaceAfter 12 >>")), + (14, elem(b"Para", 12, b"/Pg 3 0 R /K [1 << /Type /OBJR /Obj 5 0 R >>] /A << /O /Layout /TextAlign /Justify >>")), + (15, elem(b"L", 12, ns20 + b" /A << /O /List /ListNumbering /Decimal >> /K [16 0 R 19 0 R]")), + (16, elem(b"LI", 15, ns20 + b" /K [17 0 R 18 0 R]")), + (17, elem(b"Lbl", 16, ns20 + b" /Pg 3 0 R /K 2")), + (18, elem(b"LBody", 16, ns20 + b" /Pg 3 0 R /K 3")), + (19, elem(b"LI", 15, ns20 + b" /K [20 0 R 21 0 R]")), + (20, elem(b"Lbl", 19, ns20 + b" /Pg 3 0 R /K 4")), + (21, elem(b"LBody", 19, ns20 + b" /Pg 3 0 R /K 5")), + (22, elem(b"Table", 12, ns20 + b" /ID (tbl1) /A << /O /Table /Summary (Names and values) >> /K [23 0 R 26 0 R]")), + (23, elem(b"TR", 22, ns20 + b" /K [24 0 R 25 0 R]")), + (24, elem(b"TH", 23, ns20 + b" /ID (h1) /Pg 3 0 R /K 6 /A [<< /O /Table /Scope /Column >> 0]")), + (25, elem(b"TH", 23, ns20 + b" /Pg 3 0 R /K 7")), + (26, elem(b"TR", 22, ns20 + b" /K [27 0 R 28 0 R]")), + (27, elem(b"TD", 26, ns20 + b" /Pg 3 0 R /K 8 /A << /O /Table /Headers [(h1)] >>")), + (28, elem(b"TD", 26, ns20 + b" /K << /Type /MCR /MCID 9 /Pg 3 0 R >>")), + ], version="2.0", trailer_extra=b" /ID [<%s> <%s>]" % (id0, id0)) + + FILES = { "empty-page.pdf": gen_empty_page, "pdf20-header.pdf": gen_pdf20_header, @@ -1337,6 +1398,7 @@ def gen_metadata_xmp() -> bytes: "name-tree-deep.pdf": gen_name_tree_deep, "number-tree-deep.pdf": gen_number_tree_deep, "name-tree-broken.pdf": gen_name_tree_broken, + "tagged-structure.pdf": gen_tagged_structure, } diff --git a/tests/Corpus/tagged-structure.pdf b/tests/Corpus/tagged-structure.pdf new file mode 100644 index 0000000000000000000000000000000000000000..416983c93a46c7354bf24291a2cc7b466fa27b8b GIT binary patch literal 4518 zcma)AOLLn@5WeeI^d(i!AqIw*w3Tv|9(LLBvutJepvqxDBbfw&3Q%J2uix&O0SzEa z>w_(Z>95~kxBTg8cJ+mw+XDw|$fKWwuV2BMzi$OtQ(o~jUxW3;*P;Z57oNeo=f$s^ zY?T9DqzAEts@Ms*xB%+~KgHF&5aKz{D{yQjbH}qaoQdqq_m|IjZy>TIsUpO-N~OuV zO_n7rToV3)cI3MZu?#_a(-$N|3xQW_OT{wbll%=9WJcgH2uDofWffj4!6OA=J&Q8m z6*0OQ#Vg1d{-29SLO7-&yAqLY02-Uz#gghv4cTKFm{$_kQ7 zY(CWQ9fH7s1fDM=$&Tsw4+)cgE&L+lJX`h+m|r(81cx9XZ<#D-Wz#+~HFQWUD4ZG0Z1Q?dcSKi_~wzs_E(YFqwgS>lavwy8Le z^NmH6gV!WAX@)S#gqpl>yx8u_&luS} z7599LS}AnXSH7(%q865H1!Sn?FN4A)g}1}gA$jW-77k4h6x9q&13)T3%0gbW@q#3C za1`Y_QWH4j)iWRm$v+YU)2*H)nF3QcnY{S}hk!yLk~Nh*h_~uiyd(2lH?zHV3NtLu zUa=}Q>{%71^dv`wLeU|S_F{QpQlBLHH05Q9u~L!3fguVUbriNoBy;|r?<$-DsCb+v zYvk&wyn=;Bi5;&ft^om&rA@-o9OaRAXkR5VgogrsnTn09@>w45HZ;mn^ z(;Act)P^&5TE`VbulwDIz7c9flCf?)H)gLMtQ`yLT-P?3nin)W>pkdk@(s6y$LJ?0 zcP}m)?lEjJD&gC%#G(G)F{n>|9fR%;M?|q4X-aUa$=}#kktihX%tV}Qcq*%m8d0q* z&WM`GTt(!Iqvdsn9EurHK2i}Fg{3~Ker=)Bi{q#`^a)nkWx$%@mK%|t5mL!p(j*rURGYn<@HN0CTjrT`EeG~K~3*ai7;xIbY zkhnc+(%ko-zW%b?YPM(w#!FKZw)rS zpJHLiFEt}0TP;Ozg;))2V55QE{6OIQt`95NpJD&d4`j`mLzUG%8)8d#&Rnl2>o_hJ zRr{X9hS+(XGdJwZdLHJZeNR5Av&Lq}4={x7d(MdU@R&_oQu`ir-2NF0`e&Zq$MapR zgAQImJ5=W^w6XrXXZRJddo~RFcq6~3*R{Q#eXcX=<-=uRFMh6P_jI`4uopkq5BoX- zQ%69@{sRDJx!7vVyTvg2AUxmycJ2{{XITf2sfg literal 0 HcmV?d00001 From f35d96a2802fdb601a7cedba1561a5a9ee331da3 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:35:05 -0500 Subject: [PATCH 028/152] refactor(fonts): font diagnostic codes in their own partial file (#49) Follows the DiagnosticCodes.Navigation.cs convention from #70. Co-Authored-By: Claude Opus 5.5 --- .../Parsing/DiagnosticCodes.Fonts.cs | 21 +++++++++++++++++++ src/Broadside/Parsing/DiagnosticCodes.cs | 16 -------------- 2 files changed, 21 insertions(+), 16 deletions(-) create mode 100644 src/Broadside/Parsing/DiagnosticCodes.Fonts.cs diff --git a/src/Broadside/Parsing/DiagnosticCodes.Fonts.cs b/src/Broadside/Parsing/DiagnosticCodes.Fonts.cs new file mode 100644 index 00000000..18abb043 --- /dev/null +++ b/src/Broadside/Parsing/DiagnosticCodes.Fonts.cs @@ -0,0 +1,21 @@ +namespace Broadside.Parsing; + +/// Diagnostic codes for font dictionaries, simple-font encodings and widths, and font descriptors (issue #49). +internal static partial class DiagnosticCodes +{ + // Font dictionaries, Standard 14 fonts, encodings, widths and font descriptors (§9.5, §9.6, §9.8). + public const string FontTypeInvalid = nameof(FontTypeInvalid); + public const string FontSubtypeInvalid = nameof(FontSubtypeInvalid); + public const string FontBaseFontMissing = nameof(FontBaseFontMissing); + public const string FontStandard14Alias = nameof(FontStandard14Alias); + public const string FontStandard14EntriesIncomplete = nameof(FontStandard14EntriesIncomplete); + public const string FontDescriptorMissing = nameof(FontDescriptorMissing); + public const string FontDescriptorInvalid = nameof(FontDescriptorInvalid); + public const string FontWidthsMissing = nameof(FontWidthsMissing); + public const string FontWidthsInvalid = nameof(FontWidthsInvalid); + public const string FontEncodingInvalid = nameof(FontEncodingInvalid); + public const string FontEncodingIgnored = nameof(FontEncodingIgnored); + public const string FontDifferencesInvalid = nameof(FontDifferencesInvalid); + public const string FontBuiltInEncodingUnavailable = nameof(FontBuiltInEncodingUnavailable); + public const string FontGlyphMissing = nameof(FontGlyphMissing); +} diff --git a/src/Broadside/Parsing/DiagnosticCodes.cs b/src/Broadside/Parsing/DiagnosticCodes.cs index 3dc46489..c93ffb76 100644 --- a/src/Broadside/Parsing/DiagnosticCodes.cs +++ b/src/Broadside/Parsing/DiagnosticCodes.cs @@ -132,20 +132,4 @@ internal static partial class DiagnosticCodes public const string PageResourcesMissing = nameof(PageResourcesMissing); public const string PageResourcesInvalid = nameof(PageResourcesInvalid); public const string PageUserUnitInvalid = nameof(PageUserUnitInvalid); - - // Fonts: font dictionaries, simple-font encodings and widths, font descriptors (§9.5, §9.6, §9.8; issue #49). - public const string FontTypeInvalid = nameof(FontTypeInvalid); - public const string FontSubtypeInvalid = nameof(FontSubtypeInvalid); - public const string FontBaseFontMissing = nameof(FontBaseFontMissing); - public const string FontStandard14Alias = nameof(FontStandard14Alias); - public const string FontStandard14EntriesIncomplete = nameof(FontStandard14EntriesIncomplete); - public const string FontDescriptorMissing = nameof(FontDescriptorMissing); - public const string FontDescriptorInvalid = nameof(FontDescriptorInvalid); - public const string FontWidthsMissing = nameof(FontWidthsMissing); - public const string FontWidthsInvalid = nameof(FontWidthsInvalid); - public const string FontEncodingInvalid = nameof(FontEncodingInvalid); - public const string FontEncodingIgnored = nameof(FontEncodingIgnored); - public const string FontDifferencesInvalid = nameof(FontDifferencesInvalid); - public const string FontBuiltInEncodingUnavailable = nameof(FontBuiltInEncodingUnavailable); - public const string FontGlyphMissing = nameof(FontGlyphMissing); } From d72f10bfe36bc53cc20b333dadf38c5bfcba260a Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:36:40 -0500 Subject: [PATCH 029/152] test(model): optional content repairs, corpus-wide reading and the optional-content fuzz target (#76) Co-Authored-By: Claude Opus 5.5 --- tests/Broadside.Fuzz/FuzzTargets.cs | 3 +- tests/Broadside.Fuzz/OptionalContentTarget.cs | 164 ++++++++++++++++++ .../Files/FilesAndLayersCorpusTests.cs | 82 +++++++++ .../OptionalContentRepairTests.cs | 143 +++++++++++++++ 4 files changed, 391 insertions(+), 1 deletion(-) create mode 100644 tests/Broadside.Fuzz/OptionalContentTarget.cs create mode 100644 tests/Broadside.Tests/Files/FilesAndLayersCorpusTests.cs create mode 100644 tests/Broadside.Tests/OptionalContent/OptionalContentRepairTests.cs diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 4a3ab467..e8e97ca8 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -37,6 +37,7 @@ internal static class FuzzTargets ["decrypt"] = Decrypt, ["mac-token"] = MacToken, ["public-key"] = PublicKey.Target, + ["optional-content"] = OptionalContentTarget.Target, }; private static readonly CosName ContentsKey = new("Contents"); @@ -426,7 +427,7 @@ private static void ObjectStreamTarget(ReadOnlySpan data) } } - private static PdfDocument? OpenOrNull(ReadOnlySpan data) + internal static PdfDocument? OpenOrNull(ReadOnlySpan data) { try { diff --git a/tests/Broadside.Fuzz/OptionalContentTarget.cs b/tests/Broadside.Fuzz/OptionalContentTarget.cs new file mode 100644 index 00000000..0c1ed78b --- /dev/null +++ b/tests/Broadside.Fuzz/OptionalContentTarget.cs @@ -0,0 +1,164 @@ +using System.Globalization; +using System.Text; +using Broadside.Objects; + +namespace Broadside.Fuzz; + +/// +/// The optional-content target (issue #76): random optional content properties, membership dictionaries and visibility +/// expression graphs (cyclic, deep, mistyped), then every optional content computation. A corpus file (input starting with +/// %PDF-) is opened as is; any other input drives a generator. Invariants: nothing throws in lenient mode, every walk +/// terminates, visibility is deterministic and the tracker's nesting returns to zero. +/// +/// ISO 32000-2 §8.11. +internal static class OptionalContentTarget +{ + private static readonly string[] Operators = ["/And", "/Or", "/Not", "/Xor", "42", "(Or)"]; + private static readonly string[] Policies = ["/AllOn", "/AnyOn", "/AnyOff", "/AllOff", "/Sometimes", "7"]; + private static readonly string[] BaseStates = ["/ON", "/OFF", "/Unchanged", "/Maybe"]; + private static readonly string[] Intents = ["/View", "/Design", "/All", "[]", "[/View /Design]", "/Other"]; + + public static void Target(ReadOnlySpan data) + { + byte[] file = data.StartsWith("%PDF-"u8) ? data.ToArray() : Generate(data); + using PdfDocument? document = FuzzTargets.OpenOrNull(file); + if (document?.OptionalContent is not { } properties) + { + return; + } + + PdfOptionalContentState state = properties.GetDefaultStates(); + _ = (properties.DefaultConfiguration.Order.Count, properties.DefaultConfiguration.RadioButtonGroups.Count, properties.DefaultConfiguration.Locked.Count); + foreach (PdfOptionalContentConfiguration configuration in properties.Configurations) + { + PdfOptionalContentState alternate = properties.GetStates(configuration, state); + _ = (configuration.Order.Count, configuration.AutoStates.Count); + properties.ApplyAutoStates(alternate, PdfOptionalContentEvent.View, new PdfOptionalContentUsageContext { Zoom = 1, Language = "en-US", UserNames = ["user"] }); + } + + state = properties.ApplyUsageStates(state, PdfOptionalContentEvent.Print); + var tracker = new PdfOptionalContentTracker(properties, state); + var oc = new CosName("OC"); + int count = Math.Min(document.Trailer.TryGetValue(new CosName("Size"), out CosObject? size) && size is CosInteger { Value: > 0 and < 4096 } integer ? (int)integer.Value : 64, 4096); + for (int number = 1; number < count; number++) + { + var reference = new CosReference(number, 0); + bool visible = properties.IsVisible(reference, state); + if (properties.IsVisible(reference, state) != visible) + { + throw new InvalidOperationException($"IsVisible gave two answers for object {number}."); + } + + _ = properties.FindMembership(reference)?.VisibilityExpression?.ToString(); + tracker.BeginMarkedContent(oc, reference); + if (document.Resolve(reference) is CosArray array) + { + state = state.Apply(array); + } + } + + for (int number = 1; number < count; number++) + { + tracker.EndMarkedContent(); + } + + if (tracker.Depth != 0 || !tracker.IsVisible) + { + throw new InvalidOperationException("The tracker did not return to the top level after balanced EMCs."); + } + } + + /// Builds a file whose optional content is drawn from . + private static byte[] Generate(ReadOnlySpan data) + { + var input = new Input(data.ToArray()); + int objects = 2 + (input.Next() % 14); + int first = 4; + string Ref() => string.Create(CultureInfo.InvariantCulture, $"{first + (input.Next() % (objects + 1))} 0 R"); + string RefList(int max) + { + var builder = new StringBuilder("["); + int length = input.Next() % (max + 1); + for (int index = 0; index < length; index++) + { + builder.Append(Ref()).Append(' '); + } + + return builder.Append(']').ToString(); + } + + string Expression(int depth) + { + var builder = new StringBuilder("[").Append(Operators[input.Next() % Operators.Length]); + int operands = input.Next() % 4; + for (int index = 0; index < operands; index++) + { + builder.Append(' ').Append(input.Next() % 3 == 0 && depth < 64 ? Expression(depth + 1) : Ref()); + } + + return builder.Append(']').ToString(); + } + + string Order(int depth) + { + var builder = new StringBuilder("["); + int items = input.Next() % 4; + for (int index = 0; index < items; index++) + { + builder.Append(' ').Append((input.Next() % 4) switch + { + 0 when depth < 40 => Order(depth + 1), + 1 => "(Label)", + _ => Ref(), + }); + } + + return builder.Append(']').ToString(); + } + + var bodies = new List + { + $"<< /Type /Catalog /Pages 2 0 R /OCProperties << /OCGs {RefList(objects)} /D << /BaseState {BaseStates[input.Next() % BaseStates.Length]} /ON {RefList(3)} /OFF {RefList(3)} /Intent {Intents[input.Next() % Intents.Length]} /Order {Order(0)} /RBGroups [{RefList(3)}] /Locked {RefList(2)} /AS [<< /Event /View /Category [/View /Zoom /Language /User] /OCGs {RefList(3)} >>] >> /Configs [<< /BaseState {BaseStates[input.Next() % BaseStates.Length]} /ON {RefList(3)} /Intent {Intents[input.Next() % Intents.Length]} >>] >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 612 792] >>", + }; + for (int index = 0; index <= objects; index++) + { + bodies.Add((input.Next() % 6) switch + { + 0 => $"<< /Type /OCG /Name (G{index}) /Intent {Intents[input.Next() % Intents.Length]} /Usage << /View << /ViewState /OFF >> /Zoom << /min 0.5 /max 2 >> /Language << /Lang (en) /Preferred /ON >> /User << /Type /Ind /Name [(user)] >> >> >>", + 1 => $"<< /Type /OCMD /VE {(input.Next() % 2 == 0 ? Expression(0) : Ref())} /OCGs {RefList(3)} /P {Policies[input.Next() % Policies.Length]} >>", + 2 => Expression(0), + 3 => $"<< /Type /OCMD /OCGs {(input.Next() % 2 == 0 ? Ref() : RefList(4))} /P {Policies[input.Next() % Policies.Length]} >>", + 4 => "[/ON " + Ref() + " /Toggle " + Ref() + " /OFF " + Ref() + "]", + _ => input.Next() % 2 == 0 ? "null" : "(text)", + }); + } + + var text = new StringBuilder("%PDF-1.7\n"); + var offsets = new List(); + for (int index = 0; index < bodies.Count; index++) + { + offsets.Add(text.Length); + text.Append(CultureInfo.InvariantCulture, $"{index + 1} 0 obj\n{bodies[index]}\nendobj\n"); + } + + int xref = text.Length; + text.Append(CultureInfo.InvariantCulture, $"xref\n0 {bodies.Count + 1}\n0000000000 65535 f \n"); + foreach (int offset in offsets) + { + text.Append(CultureInfo.InvariantCulture, $"{offset:D10} 00000 n \n"); + } + + text.Append(CultureInfo.InvariantCulture, $"trailer\n<< /Size {bodies.Count + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n"); + return Encoding.Latin1.GetBytes(text.ToString()); + } + + /// The input as a stream of choices; past its end, zeros. + private sealed class Input(byte[] data) + { + private int _position; + + public int Next() => _position < data.Length ? data[_position++] : 0; + } +} diff --git a/tests/Broadside.Tests/Files/FilesAndLayersCorpusTests.cs b/tests/Broadside.Tests/Files/FilesAndLayersCorpusTests.cs new file mode 100644 index 00000000..26217bc4 --- /dev/null +++ b/tests/Broadside.Tests/Files/FilesAndLayersCorpusTests.cs @@ -0,0 +1,82 @@ +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Files; + +/// +/// Reading optional content, embedded files, collections, associated files and object metadata of every well-formed corpus file +/// records no diagnostic and changes no object (ADR 0004, ADR 0005; ISO 32000-2 §7.11, §8.11, §12.3.5, §14.3.2, §14.13). +/// +public class FilesAndLayersCorpusTests +{ + [Theory] + [MemberData(nameof(Corpus.WellFormedFiles), MemberType = typeof(Corpus))] + public void Reading_files_and_layers_of_a_well_formed_file_records_no_diagnostic(string fileName) + { + using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName)); + + ReadEverything(document); + + Assert.Empty(document.Diagnostics); + foreach (CosReference reference in Enumerable.Range(1, 200).Select(number => new CosReference(number, 0))) + { + Assert.False(document.Resolve(reference).IsDirty); + } + } + + internal static void ReadEverything(PdfDocument document) + { + if (document.OptionalContent is { } optionalContent) + { + PdfOptionalContentState state = optionalContent.GetDefaultStates(); + foreach (PdfOptionalContentConfiguration configuration in optionalContent.Configurations) + { + optionalContent.GetStates(configuration, state); + _ = (configuration.Order, configuration.RadioButtonGroups, configuration.Locked, configuration.AutoStates); + } + + foreach (PdfPage page in document.Pages) + { + if (page.Resources is { } resources && document.Resolve(resources.GetValueOrDefault(new CosName("Properties"))) is CosDictionary properties) + { + foreach (CosObject value in properties.Values) + { + optionalContent.IsVisible(value, state); + optionalContent.FindMembership(value)?.VisibilityExpression?.ToString(); + } + } + } + } + + foreach (PdfEmbeddedFileEntry entry in document.EmbeddedFiles) + { + Touch(entry.File); + } + + if (document.Collection is { } collection) + { + _ = (collection.View, collection.Schema.Select(field => (field.Type, field.Name, field.Order)).ToList(), collection.Sort?.Ascending, + collection.Colors?.Background, collection.Split.Direction, collection.RootFolder?.Children); + } + + foreach (PdfAssociatedFile file in document.EnumerateAssociatedFiles(deep: true)) + { + Touch(file.File); + } + + foreach (PdfObjectMetadata metadata in document.EnumerateObjectMetadata(deep: true)) + { + metadata.Decode(); + } + + static void Touch(PdfFileSpecification file) + { + _ = (file.FileName, file.SafeFileName, file.Description, file.Relationship, file.RelatedFiles, file.CollectionItem?.Keys); + if (file.EmbeddedFile is { } embedded) + { + embedded.Decode(); + embedded.VerifyCheckSum(); + } + } + } +} diff --git a/tests/Broadside.Tests/OptionalContent/OptionalContentRepairTests.cs b/tests/Broadside.Tests/OptionalContent/OptionalContentRepairTests.cs new file mode 100644 index 00000000..e34a2ce7 --- /dev/null +++ b/tests/Broadside.Tests/OptionalContent/OptionalContentRepairTests.cs @@ -0,0 +1,143 @@ +using Broadside.Diagnostics; +using Broadside.Objects; + +namespace Broadside.Tests.OptionalContent; + +/// Malformed optional content is repaired with a diagnostic in lenient mode and throws in strict mode. ISO 32000-2 §8.11. +public class OptionalContentRepairTests +{ + private const string TwoGroups = "<< /Type /OCG /Name (A) >>"; + + public static TheoryData Repairs => new() + { + // D missing: an empty configuration, every group ON. + { "/OCGs [4 0 R 5 0 R]", [TwoGroups, "<< /Type /OCG /Name (B) >>"], "OptionalContentConfigMissing", [true, true] }, + // BaseState OFF in D: honoured. + { "/OCGs [4 0 R 5 0 R] /D << /BaseState /OFF /ON [5 0 R] >>", [TwoGroups, "<< /Type /OCG /Name (B) >>"], "OptionalContentBaseStateInvalid", [false, true] }, + // BaseState Unchanged in D: read as ON. + { "/OCGs [4 0 R 5 0 R] /D << /BaseState /Unchanged /OFF [5 0 R] >>", [TwoGroups, "<< /Type /OCG /Name (B) >>"], "OptionalContentBaseStateInvalid", [true, false] }, + // A group in both ON and OFF: OFF wins. + { "/OCGs [4 0 R 5 0 R] /D << /ON [4 0 R] /OFF [4 0 R] >>", [TwoGroups, "<< /Type /OCG /Name (B) >>"], "OptionalContentGroupOnAndOff", [false, true] }, + // A group in OFF that OCGs does not list: not optional content. + { "/OCGs [4 0 R] /D << /OFF [5 0 R] >>", [TwoGroups, "<< /Type /OCG /Name (B) >>"], "OptionalContentGroupNotListed", [true] }, + // Intent other than View in D: honoured. + { "/OCGs [4 0 R] /D << /Intent /Design >>", [TwoGroups], "OptionalContentIntentInvalid", [true] }, + // An OCGs entry that is an OCMD: ignored. + { "/OCGs [4 0 R 5 0 R] /D << >>", [TwoGroups, "<< /Type /OCMD /OCGs [4 0 R] >>"], "OptionalContentGroupInvalid", [true] }, + }; + + [Theory] + [MemberData(nameof(Repairs))] + public void A_malformed_configuration_is_repaired_with_a_diagnostic(string properties, string[] objects, string code, bool[] expected) + { + using PdfDocument document = PdfDocument.Open(OptionalContentPdf.Build(properties, objects)); + PdfOptionalContentProperties optionalContent = document.OptionalContent!; + + PdfOptionalContentState state = optionalContent.GetDefaultStates(); + + Assert.Equal(expected, optionalContent.Groups.Select(state.IsOn)); + Assert.Contains(code, document.Diagnostics.Select(diagnostic => diagnostic.Code)); + } + + [Theory] + [MemberData(nameof(Repairs))] + public void A_malformed_configuration_throws_in_strict_mode(string properties, string[] objects, string code, bool[] expected) + { + _ = expected; + using PdfDocument document = PdfDocument.Open(OptionalContentPdf.Build(properties, objects), new PdfOptions().UseStrict()); + + DiagnosticException exception = Assert.Throws(() => document.OptionalContent!.GetDefaultStates()); + + Assert.Equal(code, exception.Diagnostic.Code); + } + + [Fact] + public void Missing_OCGs_make_nothing_optional() + { + using PdfDocument document = PdfDocument.Open(OptionalContentPdf.Build("/D << >>", TwoGroups)); + + PdfOptionalContentProperties optionalContent = document.OptionalContent!; + + Assert.Empty(optionalContent.Groups); + Assert.True(optionalContent.IsVisible(new CosReference(4, 0), optionalContent.GetDefaultStates())); + Assert.Equal(["OptionalContentGroupsMissing", "OptionalContentGroupNotListed"], document.Diagnostics.Select(diagnostic => diagnostic.Code)); + } + + public static TheoryData InvalidExpressions => new() + { + // Unknown operator: falls back to OCGs/P (A is OFF, AnyOn -> hidden). + { "/VE [/Xor 4 0 R] /OCGs [4 0 R]", false }, + // Not with two operands: the first is used (not A = visible). + { "/VE [/Not 4 0 R 5 0 R]", true }, + // An operand that is not a group or an expression: ignored (Or(B) = B ON = visible). + { "/VE [/Or 42 5 0 R]", true }, + // Too deep: falls back to OCGs/P; without OCGs it has no effect (visible). + { "/VE " + string.Concat(Enumerable.Repeat("[/Not ", 40)) + "4 0 R" + new string(']', 40), true }, + // An unknown policy: AnyOn. + { "/OCGs [4 0 R] /P /Sometimes", false }, + }; + + [Theory] + [MemberData(nameof(InvalidExpressions))] + public void An_invalid_visibility_expression_or_policy_is_repaired(string membership, bool visible) + { + using PdfDocument document = PdfDocument.Open(OptionalContentPdf.Build( + "/OCGs [4 0 R 5 0 R] /D << /OFF [4 0 R] >>", TwoGroups, "<< /Type /OCG /Name (B) >>", $"<< /Type /OCMD {membership} >>")); + PdfOptionalContentProperties optionalContent = document.OptionalContent!; + + Assert.Equal(visible, optionalContent.IsVisible(new CosReference(6, 0), optionalContent.GetDefaultStates())); + Assert.Contains(document.Diagnostics, diagnostic => diagnostic.Code is "VisibilityExpressionInvalid" or "VisibilityPolicyInvalid"); + } + + [Fact] + public void A_self_referencing_visibility_expression_terminates() + { + using PdfDocument document = PdfDocument.Open(OptionalContentPdf.Build( + "/OCGs [4 0 R] /D << >>", TwoGroups, "<< /Type /OCMD /VE 6 0 R /OCGs [4 0 R] /P /AllOff >>", "[/And 4 0 R 6 0 R]")); + PdfOptionalContentProperties optionalContent = document.OptionalContent!; + + Assert.False(optionalContent.IsVisible(new CosReference(5, 0), optionalContent.GetDefaultStates())); + Assert.Null(optionalContent.FindMembership(new CosReference(5, 0))!.VisibilityExpression); + Assert.Contains("VisibilityExpressionInvalid", document.Diagnostics.Select(diagnostic => diagnostic.Code)); + } + + [Fact] + public void A_membership_lists_its_groups_policy_and_parsed_expression() + { + using PdfDocument document = PdfDocument.Open(OptionalContentPdf.Build( + "/OCGs [4 0 R 5 0 R] /D << >>", TwoGroups, "<< /Type /OCG /Name (B) >>", + "<< /Type /OCMD /OCGs 4 0 R /P /AllOff /VE [/Or 4 0 R [/Not 5 0 R] null] >>")); + + PdfOptionalContentMembership membership = document.OptionalContent!.FindMembership(new CosReference(6, 0))!; + + Assert.Equal(["A"], membership.Groups.Select(group => group.Name)); + Assert.Equal(PdfVisibilityPolicy.AllOff, membership.Policy); + Assert.Equal("Or(A, Not(B))", membership.VisibilityExpression!.ToString()); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void An_inline_OC_property_list_is_honoured_with_a_diagnostic() + { + using PdfDocument document = PdfDocument.Open(OptionalContentPdf.Build("/OCGs [4 0 R] /D << /OFF [4 0 R] >>", TwoGroups)); + var tracker = new PdfOptionalContentTracker(document.OptionalContent, null); + var inline = new CosDictionary { [new CosName("Type")] = new CosName("OCMD"), [new CosName("OCGs")] = new CosReference(4, 0) }; + + tracker.BeginMarkedContent(new CosName("OC"), inline, inlineProperties: true); + + Assert.False(tracker.IsVisible); + Assert.Equal(["OptionalContentInlineProperties"], document.Diagnostics.Select(diagnostic => diagnostic.Code)); + } + + [Fact] + public void A_state_from_another_document_is_refused() + { + using PdfDocument first = PdfDocument.Open(OptionalContentPdf.Build("/OCGs [4 0 R] /D << >>", TwoGroups)); + using PdfDocument second = PdfDocument.Open(OptionalContentPdf.Build("/OCGs [4 0 R] /D << >>", TwoGroups)); + + PdfOptionalContentState state = first.OptionalContent!.GetDefaultStates(); + + Assert.Throws(() => second.OptionalContent!.IsVisible(new CosReference(4, 0), state)); + Assert.Throws(() => state.IsOn(second.OptionalContent!.Groups[0])); + } +} From 2358e8b40f699235ecbfedcc8b338c37b8967cbc Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:39:47 -0500 Subject: [PATCH 030/152] feat(content): content stream interpretation of paths, transforms and clipping (#55) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One content interpreter runs a page's content through one graphics-state machine and reports to processors (ISO 32000-2 §7.8.2, §8.2 to §8.5). - Public processor surface, declared whole so later issues add emission, not shape: ContentProcessor (virtual no-op events for runs, operators, state stack, paths, clips, text objects, glyphs, images, shadings, forms, Type 3 glyphs, marked content), CompositeContentProcessor, ContentEvents capability flags, ContentVisit, ContentContext, ContentOptions, payload ref structs (ContentOperator, PathEvent, ClipEvent, ClipView, GlyphEvent, ImageEvent, ShadingEvent, FormEvent, MarkedContentEvent), ContentOperand/ContentOperands views. - Broadside.Graphics: Matrix (owned here), GraphicsState, PathView, PathVerb, PathPoint, FillRule, LineCap, LineJoin, RenderingIntent, BlendMode, TextRenderingMode. - Entry point PdfPage.ProcessContent(processor[, options]). - Allocation-free reader over CosLexer: operator lookup without strings, operands in a pooled arena, glued-token splitting, BX/EX, inline images read whole. Zero bytes per run once warm, through the public API (ContentAllocationTests); ContentLexerBenchmarks and ContentInterpreterBenchmarks. - q/Q with frame floor, cm, w J j M d ri i; m l c v y h re; all Table 59 painting operators; W/W* applied after the paint of the same path. - Lenient repairs with Content* diagnostics, once per kind per stream; strict mode throws. - Fuzz targets content-lexer and content-interpreter; document now interprets every page. - Conformance rows 7.8.1-7.8.3, 8.2, 8.3.1-8.3.4, 8.4.1-8.4.5, 8.5.1-8.5.4. Co-Authored-By: Claude Opus 5.5 --- .../Broadside.Benchmarks.csproj | 1 + .../ContentInterpreterBenchmarks.cs | 73 +++ .../ContentLexerBenchmarks.cs | 50 ++ docs/conformance/iso-32000-2.md | 22 +- src/Broadside/Content/ClipArena.cs | 92 +++ src/Broadside/Content/ClipEvent.cs | 30 + src/Broadside/Content/ClipKind.cs | 18 + src/Broadside/Content/ClipView.cs | 32 + .../Content/CompositeContentProcessor.cs | 307 +++++++++ src/Broadside/Content/ContentContext.cs | 69 ++ src/Broadside/Content/ContentEvents.cs | 55 ++ .../Content/ContentInterpreter.Color.cs | 16 + .../ContentInterpreter.MarkedContent.cs | 16 + .../Content/ContentInterpreter.Path.cs | 160 +++++ .../Content/ContentInterpreter.Shading.cs | 13 + .../Content/ContentInterpreter.State.cs | 199 ++++++ .../Content/ContentInterpreter.Text.cs | 51 ++ .../Content/ContentInterpreter.XObject.cs | 20 + src/Broadside/Content/ContentInterpreter.cs | 591 ++++++++++++++++++ src/Broadside/Content/ContentIssue.cs | 64 ++ src/Broadside/Content/ContentOperand.cs | 99 +++ src/Broadside/Content/ContentOperandKind.cs | 36 ++ src/Broadside/Content/ContentOperands.cs | 104 +++ src/Broadside/Content/ContentOperator.cs | 43 ++ src/Broadside/Content/ContentOperatorCode.cs | 231 +++++++ src/Broadside/Content/ContentOptions.cs | 112 ++++ src/Broadside/Content/ContentProcessor.cs | 171 +++++ src/Broadside/Content/ContentReader.cs | 567 +++++++++++++++++ src/Broadside/Content/ContentRunKind.cs | 27 + src/Broadside/Content/ContentVisit.cs | 15 + src/Broadside/Content/FormEvent.cs | 51 ++ src/Broadside/Content/GlyphEvent.cs | 70 +++ src/Broadside/Content/ImageEvent.cs | 46 ++ src/Broadside/Content/MarkedContentEvent.cs | 33 + src/Broadside/Content/OperandArena.cs | 249 ++++++++ src/Broadside/Content/OperatorTable.cs | 276 ++++++++ src/Broadside/Content/PathBuilder.cs | 182 ++++++ src/Broadside/Content/PathEvent.cs | 32 + src/Broadside/Content/PathPaint.cs | 18 + src/Broadside/Content/ShadingEvent.cs | 26 + src/Broadside/Graphics/BlendMode.cs | 54 ++ src/Broadside/Graphics/FillRule.cs | 12 + src/Broadside/Graphics/GraphicsState.cs | 177 ++++++ src/Broadside/Graphics/LineCap.cs | 15 + src/Broadside/Graphics/LineJoin.cs | 15 + src/Broadside/Graphics/Matrix.cs | 166 +++++ src/Broadside/Graphics/PathPoint.cs | 14 + src/Broadside/Graphics/PathVerb.cs | 25 + src/Broadside/Graphics/PathView.cs | 73 +++ src/Broadside/Graphics/RenderingIntent.cs | 18 + src/Broadside/Graphics/TextRenderingMode.cs | 30 + src/Broadside/Objects/CosParser.cs | 10 +- src/Broadside/Objects/KnownNames.cs | 3 + src/Broadside/Parsing/DiagnosticCodes.cs | 21 + src/Broadside/PdfDocument.cs | 3 + src/Broadside/PdfPage.cs | 26 + src/Broadside/PublicAPI.Unshipped.txt | 428 +++++++++++++ tests/Broadside.Fuzz/FuzzTargets.cs | 112 ++++ tests/Broadside.Fuzz/README.md | 2 +- tests/Broadside.TestSupport/ContentSamples.cs | 34 + tests/Broadside.Tests/Content/ClipTests.cs | 123 ++++ .../Content/ContentAllocationTests.cs | 127 ++++ tests/Broadside.Tests/Content/ContentPdf.cs | 44 ++ .../Content/ContentRunTests.cs | 178 ++++++ .../Content/ContentSyntaxTests.cs | 256 ++++++++ .../Content/CorpusContentTests.cs | 68 ++ .../Content/GraphicsStateTests.cs | 191 ++++++ tests/Broadside.Tests/Content/MatrixTests.cs | 62 ++ tests/Broadside.Tests/Content/PathTests.cs | 145 +++++ .../Content/RecordingProcessor.cs | 139 ++++ .../Broadside.Tests/Content/StateRecorder.cs | 29 + 71 files changed, 6856 insertions(+), 11 deletions(-) create mode 100644 bench/Broadside.Benchmarks/ContentInterpreterBenchmarks.cs create mode 100644 bench/Broadside.Benchmarks/ContentLexerBenchmarks.cs create mode 100644 src/Broadside/Content/ClipArena.cs create mode 100644 src/Broadside/Content/ClipEvent.cs create mode 100644 src/Broadside/Content/ClipKind.cs create mode 100644 src/Broadside/Content/ClipView.cs create mode 100644 src/Broadside/Content/CompositeContentProcessor.cs create mode 100644 src/Broadside/Content/ContentContext.cs create mode 100644 src/Broadside/Content/ContentEvents.cs create mode 100644 src/Broadside/Content/ContentInterpreter.Color.cs create mode 100644 src/Broadside/Content/ContentInterpreter.MarkedContent.cs create mode 100644 src/Broadside/Content/ContentInterpreter.Path.cs create mode 100644 src/Broadside/Content/ContentInterpreter.Shading.cs create mode 100644 src/Broadside/Content/ContentInterpreter.State.cs create mode 100644 src/Broadside/Content/ContentInterpreter.Text.cs create mode 100644 src/Broadside/Content/ContentInterpreter.XObject.cs create mode 100644 src/Broadside/Content/ContentInterpreter.cs create mode 100644 src/Broadside/Content/ContentIssue.cs create mode 100644 src/Broadside/Content/ContentOperand.cs create mode 100644 src/Broadside/Content/ContentOperandKind.cs create mode 100644 src/Broadside/Content/ContentOperands.cs create mode 100644 src/Broadside/Content/ContentOperator.cs create mode 100644 src/Broadside/Content/ContentOperatorCode.cs create mode 100644 src/Broadside/Content/ContentOptions.cs create mode 100644 src/Broadside/Content/ContentProcessor.cs create mode 100644 src/Broadside/Content/ContentReader.cs create mode 100644 src/Broadside/Content/ContentRunKind.cs create mode 100644 src/Broadside/Content/ContentVisit.cs create mode 100644 src/Broadside/Content/FormEvent.cs create mode 100644 src/Broadside/Content/GlyphEvent.cs create mode 100644 src/Broadside/Content/ImageEvent.cs create mode 100644 src/Broadside/Content/MarkedContentEvent.cs create mode 100644 src/Broadside/Content/OperandArena.cs create mode 100644 src/Broadside/Content/OperatorTable.cs create mode 100644 src/Broadside/Content/PathBuilder.cs create mode 100644 src/Broadside/Content/PathEvent.cs create mode 100644 src/Broadside/Content/PathPaint.cs create mode 100644 src/Broadside/Content/ShadingEvent.cs create mode 100644 src/Broadside/Graphics/BlendMode.cs create mode 100644 src/Broadside/Graphics/FillRule.cs create mode 100644 src/Broadside/Graphics/GraphicsState.cs create mode 100644 src/Broadside/Graphics/LineCap.cs create mode 100644 src/Broadside/Graphics/LineJoin.cs create mode 100644 src/Broadside/Graphics/Matrix.cs create mode 100644 src/Broadside/Graphics/PathPoint.cs create mode 100644 src/Broadside/Graphics/PathVerb.cs create mode 100644 src/Broadside/Graphics/PathView.cs create mode 100644 src/Broadside/Graphics/RenderingIntent.cs create mode 100644 src/Broadside/Graphics/TextRenderingMode.cs create mode 100644 tests/Broadside.TestSupport/ContentSamples.cs create mode 100644 tests/Broadside.Tests/Content/ClipTests.cs create mode 100644 tests/Broadside.Tests/Content/ContentAllocationTests.cs create mode 100644 tests/Broadside.Tests/Content/ContentPdf.cs create mode 100644 tests/Broadside.Tests/Content/ContentRunTests.cs create mode 100644 tests/Broadside.Tests/Content/ContentSyntaxTests.cs create mode 100644 tests/Broadside.Tests/Content/CorpusContentTests.cs create mode 100644 tests/Broadside.Tests/Content/GraphicsStateTests.cs create mode 100644 tests/Broadside.Tests/Content/MatrixTests.cs create mode 100644 tests/Broadside.Tests/Content/PathTests.cs create mode 100644 tests/Broadside.Tests/Content/RecordingProcessor.cs create mode 100644 tests/Broadside.Tests/Content/StateRecorder.cs diff --git a/bench/Broadside.Benchmarks/Broadside.Benchmarks.csproj b/bench/Broadside.Benchmarks/Broadside.Benchmarks.csproj index 72543caf..d54f08c3 100644 --- a/bench/Broadside.Benchmarks/Broadside.Benchmarks.csproj +++ b/bench/Broadside.Benchmarks/Broadside.Benchmarks.csproj @@ -13,6 +13,7 @@ + diff --git a/bench/Broadside.Benchmarks/ContentInterpreterBenchmarks.cs b/bench/Broadside.Benchmarks/ContentInterpreterBenchmarks.cs new file mode 100644 index 00000000..692bf3dd --- /dev/null +++ b/bench/Broadside.Benchmarks/ContentInterpreterBenchmarks.cs @@ -0,0 +1,73 @@ +using System.Text; +using BenchmarkDotNet.Attributes; +using Broadside.Content; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Benchmarks; + +/// +/// Runs a page's content through the content interpreter into a processor that asks for every event and does nothing (ISO 32000-2 +/// §7.8.2, §8.4, §8.5). A hot path: Allocated must read - for the synthetic page; the corpus page also decodes its +/// filtered stream, which allocates the decoded bytes once per run. +/// +[MemoryDiagnoser] +public class ContentInterpreterBenchmarks +{ + private readonly ContentProcessor _processor = new NullProcessor(); + private PdfDocument? _document; + private PdfPage? _page; + + /// The page: one whose content is a synthetic 1 MB path-heavy stream, or the page of filter-chain.pdf. + [Params("path-heavy-1mb", "filter-chain.pdf")] + public string Page { get; set; } = ""; + + [GlobalSetup] + public void Setup() + { + _document = Page == "path-heavy-1mb" + ? PdfDocument.Open(OnePage(ContentSamples.PathHeavy(1 << 20))) + : PdfDocument.Open(Path.Combine(CorpusLocator.CorpusDirectory, Page)); + _page = _document.Pages[0]; + } + + [GlobalCleanup] + public void Cleanup() => _document?.Dispose(); + + [Benchmark] + public void Interpret() => _page!.ProcessContent(_processor); + + private static byte[] OnePage(byte[] content) + { + var text = new StringBuilder(); + var offsets = new List(); + text.Append("%PDF-1.7\n"); + string[] objects = + [ + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> /Contents 4 0 R >>", + $"<< /Length {content.Length} >>\nstream\n{Encoding.ASCII.GetString(content)}\nendstream", + ]; + for (int index = 0; index < objects.Length; index++) + { + offsets.Add(text.Length); + text.Append(System.Globalization.CultureInfo.InvariantCulture, $"{index + 1} 0 obj\n{objects[index]}\nendobj\n"); + } + + int xref = text.Length; + text.Append(System.Globalization.CultureInfo.InvariantCulture, $"xref\n0 {objects.Length + 1}\n0000000000 65535 f \n"); + foreach (int offset in offsets) + { + text.Append(System.Globalization.CultureInfo.InvariantCulture, $"{offset:D10} 00000 n \n"); + } + + text.Append(System.Globalization.CultureInfo.InvariantCulture, $"trailer\n<< /Size {objects.Length + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n"); + return Encoding.ASCII.GetBytes(text.ToString()); + } + + /// Asks for every event and ignores them. + private sealed class NullProcessor : ContentProcessor + { + } +} diff --git a/bench/Broadside.Benchmarks/ContentLexerBenchmarks.cs b/bench/Broadside.Benchmarks/ContentLexerBenchmarks.cs new file mode 100644 index 00000000..c2f06233 --- /dev/null +++ b/bench/Broadside.Benchmarks/ContentLexerBenchmarks.cs @@ -0,0 +1,50 @@ +using BenchmarkDotNet.Attributes; +using Broadside.Content; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Benchmarks; + +/// +/// Reads a content stream into operators and operands with the content reader (ISO 32000-2 §7.8.2). A hot path: Allocated +/// must read -; Broadside.Tests.Content.ContentAllocationTests fails the build if it does not. +/// +[MemoryDiagnoser] +public class ContentLexerBenchmarks +{ + private readonly OperandArena _arena = new(); + private byte[] _content = []; + + /// The content: a synthetic 1 MB path-heavy stream, or the decoded content of filter-chain.pdf. + [Params("path-heavy-1mb", "filter-chain.pdf")] + public string Content { get; set; } = ""; + + [GlobalSetup] + public void Setup() + { + if (Content == "path-heavy-1mb") + { + _content = ContentSamples.PathHeavy(1 << 20); + return; + } + + using PdfDocument document = PdfDocument.Open(Path.Combine(CorpusLocator.CorpusDirectory, Content)); + var stream = (CosStream)document.Resolve(document.Pages[0].Dictionary[new CosName("Contents")]); + _content = document.DecodeStream(stream).ToArray(); + } + + [Benchmark] + public int Read() + { + var reader = new ContentReader(_content, _arena); + int count = 0; + while (reader.Next(out _)) + { + _arena.Clear(); + count++; + } + + _arena.Clear(); + return count; + } +} diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index 22181c28..145704a9 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -50,7 +50,9 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.7.2 | Document catalog dictionary | partial | `PdfDocument`, `PdfVersion` | `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_catalog_version_written_as_a_number_is_read_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.A_malformed_catalog_version_is_ignored_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_catalog_without_its_type_is_read_with_a_diagnostic` | Type, Version (effective version = later of header and catalog) and Pages; the other Table 29 entries arrive with their features (outlines, names, AcroForm, ...) | | 7.7.3 | Page tree | done | `PdfPage`, `PdfPageCollection`, `PageTreeReader` | `Broadside.Tests.Document.OpenDocumentTests.Page_tree_inherited_pdf_pages_inherit_media_box_and_resources_from_the_intermediate_node`, `Broadside.Tests.Document.PageTreeTests.Pages_come_in_kids_order_depth_first_across_intermediate_nodes`, `Broadside.Tests.Document.PageTreeTests.The_nearest_ancestor_wins_and_values_are_inherited_as_is_without_merging`, `Broadside.Tests.Document.PageTreeTests.A_change_to_an_ancestor_node_shows_through_the_pages_that_inherit_from_it`, `Broadside.Tests.Document.PageTreeTests.Page_count_comes_from_the_kids_not_the_count_entry_which_is_checked`, `Broadside.Tests.Document.PageTreeTests.A_node_referenced_twice_is_read_once_with_a_diagnostic`, `Broadside.Tests.Document.PageAttributeTests.Crop_bleed_trim_and_art_boxes_default_to_the_media_box_through_the_crop_box`, `Broadside.Tests.Document.PageAttributeTests.Rotation_is_a_multiple_of_90_normalized_into_0_to_270` | 7.7.3.1 to 7.7.3.4: Kids walk with cycle guard, Count checked not trusted, Resources/MediaBox/CropBox/Rotate inherited as-is from the nearest node; page boxes, Rotate and UserUnit from Table 31; other Table 31 entries arrive with their features | | 7.7.4 | Name dictionary | not started | | | | -| 7.8 | Content streams and resources | not started | | | | +| 7.8.1 | General | n/a | | | Introductory text: content streams and resource dictionaries are specified in 7.8.2 and 7.8.3 | +| 7.8.2 | Content streams | done | `ContentReader`, `OperandArena`, `OperatorTable`, `ContentInterpreter`, `ContentProcessor`, `ContentOperator`, `ContentOperand`, `ContentOperands`, `ContentOperatorCode`, `PdfPage` | `Broadside.Tests.Content.ContentSyntaxTests`, `Broadside.Tests.Content.CorpusContentTests`, `Broadside.Tests.Content.ContentRunTests.A_contents_array_reads_as_its_parts_joined_by_white_space`, `Broadside.Tests.Content.ContentRunTests.A_contents_array_element_that_is_not_a_stream_is_skipped`, `Broadside.Tests.Content.ContentAllocationTests` | Issue #55. Operands are read in place (no object per operand, no string per keyword; zero allocation proven by `ContentAllocationTests` and `bench/Broadside.Benchmarks/ContentLexerBenchmarks.cs`); all 73 operators of Annex A recognised; glued keywords (`q1`, `0cm`, `Qq`) split when they decompose wholly into operators and numbers (`ContentGluedTokens`, Information); Table 33 BX/EX nest and silence unknown operators; outside them an unknown operator and its operands are ignored (`ContentUnknownOperator`); too few operands or wrong types skip the operator, too many use the last ones, leftovers at the end are dropped (`ContentOperandCount`, `ContentOperandType`); an inline image is read whole (BI dictionary, data to EI by L/Length or the pdf.js heuristic) and never tokenized. A Contents array is one stream with a line feed between parts (Table 31). Fuzz targets `content-lexer`, `content-interpreter`; `document` now runs every page. | +| 7.8.3 | Resource dictionaries | partial | `ContentContext` | `Broadside.Tests.Content.ContentRunTests.The_context_describes_the_page_run` | The page's (inherited) Resources are the run's `ContentContext.Resources`; looking names up in ExtGState, Font, XObject, Properties (#56), ColorSpace (#77), Pattern and Shading (#79) arrives with those operators; forms without Resources inheriting the page's is #56. | | 7.9.1 | General | not started | | | | | 7.9.2 | String object types | partial | `CosString` | `Broadside.Tests.Objects.TextStringTests` | Text strings decode (PDFDocEncoding, UTF-16BE, UTF-8, language escapes removed); encoding text into a string pending | | 7.9.3 | Text streams | not started | | | | @@ -62,10 +64,20 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.11 | File specifications | not started | | | | | 7.12 | Extensions dictionary | not started | | | | | 8.1 | Graphics: General | not started | | | | -| 8.2 | Graphics objects | not started | | | | -| 8.3 | Coordinate systems | not started | | | | -| 8.4 | Graphics state | not started | | | | -| 8.5 | Path construction and painting | not started | | | | +| 8.2 | Graphics objects | done | `ContentInterpreter`, `OperatorTable`, `ContentProcessor` | `Broadside.Tests.Content.ContentSyntaxTests.Graphics_state_operators_inside_a_path_object_apply_with_an_information_diagnostic`, `Broadside.Tests.Content.ContentRunTests.Text_showing_outside_a_text_object_is_out_of_context`, `Broadside.Tests.Content.ContentSyntaxTests.Operators_are_reported_with_their_operands_of_every_type`, `Broadside.Tests.Content.PathTests` | Table 50 categories and the Figure 9 context rules (2020 edition: q and Q are general graphics state operators): a violation is applied anyway and recorded once at Information severity (`ContentOperatorOutOfContext`), as real files do it. Path objects are reported by issue #55; the processor surface already declares text (glyphs), image, shading and form XObject events, emitted by #56, #60 and #79. | +| 8.3.1 | General | n/a | | | Introductory text | +| 8.3.2 | Coordinate spaces | partial | `Matrix`, `GraphicsState`, `ContentContext` | `Broadside.Tests.Content.GraphicsStateTests.Cm_premultiplies_the_ctm`, `Broadside.Tests.Content.PathTests.A_stroked_polyline_is_reported_in_user_space_with_the_identity_ctm`, `Broadside.Tests.Content.ContentRunTests.The_context_describes_the_page_run` | 8.3.2.1 to 8.3.2.5. Geometry is reported in user space with the CTM to the run's default user space, which starts at the identity: device space, page rotation, crop and UserUnit are the consumer's (Phase 3). `ContentContext.StreamBaseMatrix` is the base for pattern space (#77/#79). Form space (#56), text and glyph space (#56), image space (#56/#60) arrive with their operators. | +| 8.3.3 | Common transformations | done | `Matrix` | `Broadside.Tests.Content.MatrixTests.The_product_applies_the_first_matrix_first`, `Broadside.Tests.Content.GraphicsStateTests.Cm_premultiplies_the_ctm` | Translation and scaling factories; rotation and skew are any six numbers given to `cm`. | +| 8.3.4 | Transformation matrices | done | `Matrix` | `Broadside.Tests.Content.MatrixTests`, `Broadside.Tests.Content.GraphicsStateTests.Cm_premultiplies_the_ctm`, `Broadside.Tests.Content.GraphicsStateTests.A_singular_matrix_is_concatenated_as_given` | Row-vector convention, premultiplication (M′ = Mcm × CTM), inverse when one exists; singular matrices are legal and kept as given; elements and coordinates are doubles. | +| 8.4.1 | General | partial | `GraphicsState` | `Broadside.Tests.Content.GraphicsStateTests.A_path_is_painted_with_the_initial_state_of_tables_51_and_52` | Tables 51 and 52 initial values for the CTM, clip, line parameters, rendering intent, flatness, stroke adjustment, blend mode, alpha, alpha source, text knockout, overprint and the text state numbers; the CTM starts at the identity (default user space). Still to come: colour spaces and colours (#77), font, soft mask, transfer, halftone, black generation, undercolour removal, smoothness and black point compensation (#56). Out-of-range numbers are clipped into range with `ContentGraphicsStateRange`. | +| 8.4.2 | Graphics state stack | done | `ContentInterpreter`, `GraphicsState` | `Broadside.Tests.Content.GraphicsStateTests.Q_restores_the_whole_state_saved_by_q`, `Broadside.Tests.Content.GraphicsStateTests.State_stack_events_follow_q_and_q_with_the_depth_after_each`, `Broadside.Tests.Content.GraphicsStateTests.Q_without_q_is_ignored_and_recorded`, `Broadside.Tests.Content.GraphicsStateTests.Unbalanced_q_at_the_end_is_restored_with_implicit_restore_events`, `Broadside.Tests.Content.GraphicsStateTests.A_contents_array_is_one_stream_for_q_and_q`, `Broadside.Tests.Content.GraphicsStateTests.A_q_beyond_the_depth_limit_is_ignored_with_its_q`, `Broadside.Tests.Content.PathTests.The_current_path_survives_q_and_q_does_not_save_it` | q copies the state struct into a pooled stack slot, Q pops to the running stream's floor (`ContentStackUnderflow` below it); unbalanced q at the end is closed with implicit restore events (`ContentUnbalancedSave`); a q beyond `ContentOptions.MaxSaveDepth` (default 4,096) is ignored with its Q (`ContentStackOverflow`). | +| 8.4.3 | Details of graphics state parameters | done | `GraphicsState`, `LineCap`, `LineJoin` | `Broadside.Tests.Content.GraphicsStateTests.Each_operator_of_table_56_sets_its_parameter`, `Broadside.Tests.Content.GraphicsStateTests.Dash_patterns_are_normalized_as_8_4_3_6_says`, `Broadside.Tests.Content.GraphicsStateTests.A_negative_line_width_uses_its_absolute_value`, `Broadside.Tests.Content.GraphicsStateTests.Out_of_range_caps_joins_miter_limits_and_flatness_are_clipped_into_range` | 8.4.3.1 to 8.4.3.6 as the interpreter holds them: a negative line width takes its absolute value (as viewers do), a cap or join other than 0 to 2 reads as 0, a miter limit below 1 as 1, a dash array with a negative element or only zeros as solid, a negative dash phase is incremented by twice the sum. Stroking with these parameters (caps, joins, miters, dashes) is the rasterizer's (Phase 3). | +| 8.4.4 | Graphics state operators | partial | `ContentInterpreter`, `GraphicsState` | `Broadside.Tests.Content.GraphicsStateTests` | Table 56: q, Q, cm, w, J, j, M, d, ri, i done (an unrecognised intent selects RelativeColorimetric, §8.6.5.8); gs is read and checked but applied from #56. | +| 8.4.5 | Graphics state parameter dictionaries | not started | | | Issue #56 applies ExtGState (Table 57) through gs; `GraphicsState` already holds SA, BM, CA, ca, AIS, TK, OP, op and OPM with their initial values. | +| 8.5.1 | General | done | `PathBuilder`, `ContentInterpreter`, `ContentContext` | `Broadside.Tests.Content.PathTests`, `Broadside.Tests.Content.ClipTests.Nested_clips_chain_to_their_parents_and_q_restores_the_earlier_clip` | The initial clipping path is the run's clip handle 0 (for a page, its MediaBox; the renderer additionally clips to the CropBox). | +| 8.5.2 | Path construction operators | done | `PathBuilder`, `PathView`, `PathVerb`, `PathPoint` | `Broadside.Tests.Content.PathTests.A_rectangle_is_a_moveto_three_lines_and_a_close_keeping_the_signs_of_its_size`, `Broadside.Tests.Content.PathTests.The_v_and_y_curves_replicate_the_current_point_and_the_end_point`, `Broadside.Tests.Content.PathTests.A_moveto_after_a_moveto_replaces_it`, `Broadside.Tests.Content.PathTests.A_segment_after_a_close_starts_a_new_subpath_at_the_closed_subpaths_first_point`, `Broadside.Tests.Content.PathTests.A_lineto_without_a_current_point_begins_a_subpath_at_its_end_point`, `Broadside.Tests.Content.PathTests.Coordinates_keep_double_precision` | 8.5.2.1 and 8.5.2.2. Normalized to MoveTo, LineTo, CubicTo, Close (QuadTo is reserved for glyph outlines); re keeps the signs of its size; a segment with no current point begins a subpath at its end point (`ContentNoCurrentPoint`); doubles throughout; no geometry is stored when no processor wants paths or clips. | +| 8.5.3 | Path-painting operators | done | `ContentInterpreter`, `PathEvent`, `PathPaint`, `FillRule` | `Broadside.Tests.Content.PathTests.Each_painting_operator_reports_how_it_paints`, `Broadside.Tests.Content.PathTests.Painting_without_a_path_paints_nothing_and_is_recorded`, `Broadside.Tests.Content.PathTests.A_trailing_lone_moveto_is_kept_for_the_renderer_to_ignore`, `Broadside.Tests.Content.PathTests.A_path_left_unpainted_at_the_end_is_discarded_with_an_information_diagnostic` | 8.5.3.1 to 8.5.3.3: Table 59 operators (F read as f), the closing segment of s, b and b* in the path; the path is passed exactly as built: the degenerate-subpath, lone-moveto and implicit-close rules of 8.5.3.2 and 8.5.3.3 are the renderer's (Phase 3). Painting with no path is `ContentNoCurrentPath`. | +| 8.5.4 | Clipping path operators | done | `ContentInterpreter`, `ClipArena`, `ClipEvent`, `ClipView`, `ClipKind` | `Broadside.Tests.Content.ClipTests` | W and W* take effect after the painting operator of their path object (`IntersectClip` follows `PaintPath`, so W S is not clipped by its own path); W n only clips; clips are arena nodes chained to their parents by handle, so q/Q restore them by copying an int; W without a path is ignored (`ContentNoCurrentPath`). Text clips (Tr 4-7, at ET) are #56. | | 8.6 | Colour spaces | not started | | | | | 8.7 | Patterns | not started | | | | | 8.8 | External objects | not started | | | | diff --git a/src/Broadside/Content/ClipArena.cs b/src/Broadside/Content/ClipArena.cs new file mode 100644 index 00000000..5b495b58 --- /dev/null +++ b/src/Broadside/Content/ClipArena.cs @@ -0,0 +1,92 @@ +using System.Buffers; +using Broadside.Graphics; + +namespace Broadside.Content; + +/// +/// The clip nodes of a top-level run and of every nested run inside it. A graphics state refers to its clip by a handle, so +/// q and Q save and restore clips by copying an integer; nodes are never removed during the run. +/// +/// ISO 32000-2 §8.5.4: each node intersects its parent with a region; handle 0 is the run's initial clipping path. +internal sealed class ClipArena +{ + private Node[] _nodes = ArrayPool.Shared.Rent(16); + private PathVerb[] _verbs = ArrayPool.Shared.Rent(64); + private PathPoint[] _points = ArrayPool.Shared.Rent(128); + private int _nodeCount; + private int _verbCount; + private int _pointCount; + + /// Forgets every node, at the end of a top-level run, and gives oversized buffers back to the pool. + public void Reset() + { + _nodeCount = 0; + _verbCount = 0; + _pointCount = 0; + if (_points.Length > 1 << 16) + { + ArrayPool.Shared.Return(_nodes); + ArrayPool.Shared.Return(_verbs); + ArrayPool.Shared.Return(_points); + _nodes = ArrayPool.Shared.Rent(16); + _verbs = ArrayPool.Shared.Rent(64); + _points = ArrayPool.Shared.Rent(128); + } + } + + /// Adds a node intersecting with a copy of ; returns its handle. + public int Add(int parent, ClipKind kind, FillRule rule, PathView path, Matrix ctm) + { + if (_nodeCount == _nodes.Length) + { + Grow(ref _nodes, _nodeCount, _nodeCount + 1); + } + + if (_verbCount + path.Verbs.Length > _verbs.Length) + { + Grow(ref _verbs, _verbCount, _verbCount + path.Verbs.Length); + } + + if (_pointCount + path.Points.Length > _points.Length) + { + Grow(ref _points, _pointCount, _pointCount + path.Points.Length); + } + + path.Verbs.CopyTo(_verbs.AsSpan(_verbCount)); + path.Points.CopyTo(_points.AsSpan(_pointCount)); + _nodes[_nodeCount++] = new Node(parent, kind, rule, _verbCount, path.Verbs.Length, _pointCount, path.Points.Length, ctm); + _verbCount += path.Verbs.Length; + _pointCount += path.Points.Length; + return _nodeCount; + } + + /// Returns the node a handle refers to; handle 0, and any handle not issued in this run, is the initial clip. + public ClipView Get(int handle) + { + if (handle <= 0 || handle > _nodeCount) + { + return new ClipView { Kind = ClipKind.Initial, Ctm = Matrix.Identity }; + } + + ref readonly Node node = ref _nodes[handle - 1]; + return new ClipView + { + Handle = handle, + ParentHandle = node.Parent, + Kind = node.Kind, + Rule = node.Rule, + Path = new PathView(_verbs.AsSpan(node.VerbStart, node.VerbCount), _points.AsSpan(node.PointStart, node.PointCount)), + Ctm = node.Ctm, + }; + } + + private static void Grow(ref T[] array, int used, int minimum) + { + T[] larger = ArrayPool.Shared.Rent(Math.Max(minimum, array.Length * 2)); + array.AsSpan(0, used).CopyTo(larger); + ArrayPool.Shared.Return(array); + array = larger; + } + + private readonly record struct Node(int Parent, ClipKind Kind, FillRule Rule, int VerbStart, int VerbCount, int PointStart, int PointCount, Matrix Ctm); +} diff --git a/src/Broadside/Content/ClipEvent.cs b/src/Broadside/Content/ClipEvent.cs new file mode 100644 index 00000000..ba0acf83 --- /dev/null +++ b/src/Broadside/Content/ClipEvent.cs @@ -0,0 +1,30 @@ +using Broadside.Graphics; + +namespace Broadside.Content; + +/// The clipping path narrowed. Valid only during the callback. +/// +/// ISO 32000-2 §8.5.4: reported after the painting operator that ends a path object with W or W* (also n); +/// for text, at the ET of a text object with a clipping rendering mode (§9.3.6); for a form XObject, its bounding box +/// (§8.10.1). already holds the new . +/// +public readonly ref struct ClipEvent +{ + /// Gets the handle of the new clip node, now the state's . + public int Handle { get; internal init; } + + /// Gets the handle of the clip it narrows. + public int ParentHandle { get; internal init; } + + /// Gets what the clip is intersected with. + public ClipKind Kind { get; internal init; } + + /// Gets the rule that decides what is inside . + public FillRule Rule { get; internal init; } + + /// Gets the clipping region's outline in user space: the path for , the rectangle for . + public PathView Path { get; internal init; } + + /// Gets the CTM the path is in. + public Matrix Ctm { get; internal init; } +} diff --git a/src/Broadside/Content/ClipKind.cs b/src/Broadside/Content/ClipKind.cs new file mode 100644 index 00000000..8db10547 --- /dev/null +++ b/src/Broadside/Content/ClipKind.cs @@ -0,0 +1,18 @@ +namespace Broadside.Content; + +/// What a clip node intersects the clipping path with. +/// ISO 32000-2 §8.5.4 (paths), §8.10.1 (a form's bounding box), §9.3.6 (text rendering modes 4 to 7). +public enum ClipKind +{ + /// The run's initial clipping path: for a page, its media box (§8.5.1). Only handle 0 has this kind. + Initial, + + /// A path, after W or W* and the painting operator that follows. + Path, + + /// A rectangle given as a path, such as a form XObject's bounding box. + Rectangle, + + /// The glyph outlines of a text object shown with a clipping rendering mode, applied at its ET. + Text, +} diff --git a/src/Broadside/Content/ClipView.cs b/src/Broadside/Content/ClipView.cs new file mode 100644 index 00000000..d41f8247 --- /dev/null +++ b/src/Broadside/Content/ClipView.cs @@ -0,0 +1,32 @@ +using Broadside.Graphics; + +namespace Broadside.Content; + +/// +/// One node of the clipping path: the region it intersects the clip with, and the node it narrows. Following +/// to 0 gives every region the current clip is the intersection of. Valid until the run ends. +/// +/// +/// ISO 32000-2 §8.5.4: the clipping path only shrinks, by intersection; Q restores an earlier one. The path is in the user +/// space that was current when the clip was set, mapped by . +/// +public readonly ref struct ClipView +{ + /// Gets the handle of this node; 0 for the initial clipping path. + public int Handle { get; internal init; } + + /// Gets the handle of the clip this node intersects; 0 for the initial clipping path, and for the initial node itself. + public int ParentHandle { get; internal init; } + + /// Gets what the node intersects with. + public ClipKind Kind { get; internal init; } + + /// Gets the rule that decides what is inside . + public FillRule Rule { get; internal init; } + + /// Gets the clipping region's outline, in the user space of ; empty for . + public PathView Path { get; internal init; } + + /// Gets the CTM when the clip was set. + public Matrix Ctm { get; internal init; } +} diff --git a/src/Broadside/Content/CompositeContentProcessor.cs b/src/Broadside/Content/CompositeContentProcessor.cs new file mode 100644 index 00000000..ebf44a06 --- /dev/null +++ b/src/Broadside/Content/CompositeContentProcessor.cs @@ -0,0 +1,307 @@ +namespace Broadside.Content; + +/// +/// Fans one run out to several processors, so that, for example, a text extractor and a geometry collector share one pass over the +/// content. Each processor receives only the events it asks for, in the order the processors were given. +/// +/// +/// ISO 32000-2 §7.8.2. is the union of the processors' events. A processor that answers +/// to a nested stream (a form, a Type 3 glyph) receives none of its events and not its end event, +/// while the others still do; the composite skips a nested stream only when every processor skips it. +/// +public sealed class CompositeContentProcessor : ContentProcessor +{ + private readonly ContentProcessor[] _processors; + private readonly ContentEvents[] _events; + private readonly int[] _skipDepth; + + /// Initializes a new instance of the class. + /// The processors, in the order they receive each event. + /// A processor is . + public CompositeContentProcessor(params ContentProcessor[] processors) + { + ArgumentNullException.ThrowIfNull(processors); + if (Array.IndexOf(processors, null) >= 0) + { + throw new ArgumentException("A processor is null.", nameof(processors)); + } + + _processors = [.. processors]; + _events = new ContentEvents[_processors.Length]; + _skipDepth = new int[_processors.Length]; + } + + /// Gets the processors, in the order they receive each event. + public IReadOnlyList Processors => _processors; + + /// + public override ContentEvents Events + { + get + { + ContentEvents union = ContentEvents.None; + foreach (ContentProcessor processor in _processors) + { + union |= processor.Events; + } + + return union; + } + } + + /// + public override void BeginRun(ContentContext context) + { + for (int index = 0; index < _processors.Length; index++) + { + _events[index] = _processors[index].Events; + _skipDepth[index] = 0; + _processors[index].BeginRun(context); + } + } + + /// + public override void EndRun(ContentContext context) + { + for (int index = 0; index < _processors.Length; index++) + { + _processors[index].EndRun(context); + } + } + + /// + public override void VisitOperator(in ContentOperator op, ContentContext context) + { + for (int index = 0; index < _processors.Length; index++) + { + if (Wants(index, ContentEvents.Operators)) + { + _processors[index].VisitOperator(op, context); + } + } + } + + /// + public override void SaveState(ContentContext context) + { + for (int index = 0; index < _processors.Length; index++) + { + if (Wants(index, ContentEvents.StateStack)) + { + _processors[index].SaveState(context); + } + } + } + + /// + public override void RestoreState(ContentContext context) + { + for (int index = 0; index < _processors.Length; index++) + { + if (Wants(index, ContentEvents.StateStack)) + { + _processors[index].RestoreState(context); + } + } + } + + /// + public override void PaintPath(in PathEvent path, ContentContext context) + { + for (int index = 0; index < _processors.Length; index++) + { + if (Wants(index, ContentEvents.Paths)) + { + _processors[index].PaintPath(path, context); + } + } + } + + /// + public override void IntersectClip(in ClipEvent clip, ContentContext context) + { + for (int index = 0; index < _processors.Length; index++) + { + if (Wants(index, ContentEvents.Clips)) + { + _processors[index].IntersectClip(clip, context); + } + } + } + + /// + public override void BeginText(ContentContext context) + { + for (int index = 0; index < _processors.Length; index++) + { + if (Wants(index, ContentEvents.Text)) + { + _processors[index].BeginText(context); + } + } + } + + /// + public override void ShowGlyph(in GlyphEvent glyph, ContentContext context) + { + for (int index = 0; index < _processors.Length; index++) + { + if (Wants(index, ContentEvents.Glyphs)) + { + _processors[index].ShowGlyph(glyph, context); + } + } + } + + /// + public override void EndText(ContentContext context) + { + for (int index = 0; index < _processors.Length; index++) + { + if (Wants(index, ContentEvents.Text)) + { + _processors[index].EndText(context); + } + } + } + + /// + public override void PaintImage(in ImageEvent image, ContentContext context) + { + for (int index = 0; index < _processors.Length; index++) + { + if (Wants(index, ContentEvents.Images)) + { + _processors[index].PaintImage(image, context); + } + } + } + + /// + public override void PaintShading(in ShadingEvent shading, ContentContext context) + { + for (int index = 0; index < _processors.Length; index++) + { + if (Wants(index, ContentEvents.Shadings)) + { + _processors[index].PaintShading(shading, context); + } + } + } + + /// + public override ContentVisit BeginForm(in FormEvent form, ContentContext context) + { + bool anyEnters = false; + for (int index = 0; index < _processors.Length; index++) + { + if (_skipDepth[index] > 0) + { + _skipDepth[index]++; + } + else if ((_events[index] & ContentEvents.Forms) != 0 && _processors[index].BeginForm(form, context) == ContentVisit.Skip) + { + _skipDepth[index] = 1; + } + else + { + anyEnters = true; + } + } + + return anyEnters ? ContentVisit.Enter : ContentVisit.Skip; + } + + /// + public override void EndForm(in FormEvent form, ContentContext context) + { + for (int index = 0; index < _processors.Length; index++) + { + if (_skipDepth[index] > 0) + { + _skipDepth[index]--; + } + else if ((_events[index] & ContentEvents.Forms) != 0) + { + _processors[index].EndForm(form, context); + } + } + } + + /// + public override ContentVisit BeginType3Glyph(in GlyphEvent glyph, ContentContext context) + { + bool anyEnters = false; + for (int index = 0; index < _processors.Length; index++) + { + if (_skipDepth[index] > 0) + { + _skipDepth[index]++; + } + else if ((_events[index] & ContentEvents.Type3GlyphContent) == 0 || _processors[index].BeginType3Glyph(glyph, context) == ContentVisit.Skip) + { + _skipDepth[index] = 1; + } + else + { + anyEnters = true; + } + } + + return anyEnters ? ContentVisit.Enter : ContentVisit.Skip; + } + + /// + public override void EndType3Glyph(in GlyphEvent glyph, ContentContext context) + { + for (int index = 0; index < _processors.Length; index++) + { + if (_skipDepth[index] > 0) + { + _skipDepth[index]--; + } + else + { + _processors[index].EndType3Glyph(glyph, context); + } + } + } + + /// + public override void BeginMarkedContent(in MarkedContentEvent mc, ContentContext context) + { + for (int index = 0; index < _processors.Length; index++) + { + if (Wants(index, ContentEvents.MarkedContent)) + { + _processors[index].BeginMarkedContent(mc, context); + } + } + } + + /// + public override void EndMarkedContent(in MarkedContentEvent mc, ContentContext context) + { + for (int index = 0; index < _processors.Length; index++) + { + if (Wants(index, ContentEvents.MarkedContent)) + { + _processors[index].EndMarkedContent(mc, context); + } + } + } + + /// + public override void MarkedContentPoint(in MarkedContentEvent mc, ContentContext context) + { + for (int index = 0; index < _processors.Length; index++) + { + if (Wants(index, ContentEvents.MarkedContent)) + { + _processors[index].MarkedContentPoint(mc, context); + } + } + } + + private bool Wants(int index, ContentEvents events) => _skipDepth[index] == 0 && (_events[index] & events) != 0; +} diff --git a/src/Broadside/Content/ContentContext.cs b/src/Broadside/Content/ContentContext.cs new file mode 100644 index 00000000..0f4e17d0 --- /dev/null +++ b/src/Broadside/Content/ContentContext.cs @@ -0,0 +1,69 @@ +using Broadside.Graphics; +using Broadside.Objects; + +namespace Broadside.Content; + +/// +/// The run a processor is called from: the current graphics state, what is being interpreted, and how to resolve clip handles. +/// One instance serves a whole run; it is valid only during the run's callbacks. +/// +/// ISO 32000-2 §7.8.2 (content streams), §7.8.3 (resources), §8.4 (graphics state), §8.3.2 (coordinate spaces). +public sealed class ContentContext +{ + private readonly ContentInterpreter _interpreter; + + internal ContentContext(ContentInterpreter interpreter) => _interpreter = interpreter; + + /// Gets the current graphics state, by read-only reference into the interpreter's stack: copy it to keep it. + /// ISO 32000-2 §8.4.1. + public ref readonly GraphicsState State => ref _interpreter.State; + + /// Gets the number of states saved by q (and implicit saves) above the run's initial state. + /// ISO 32000-2 §8.4.2. + public int StateDepth => _interpreter.StateDepth; + + /// Gets what kind of content stream is running. + public ContentRunKind RunKind { get; internal set; } + + /// Gets the nesting depth of the running stream: 0 for the top-level run, 1 inside a form it paints, and so on. + public int Depth { get; internal set; } + + /// Gets the document the content belongs to. + public PdfDocument Document { get; internal set; } = null!; + + /// Gets the page being interpreted, or when the run is not over a page. + public PdfPage? Page { get; internal set; } + + /// Gets the resource dictionary names in the running stream resolve against, or when there is none. + /// ISO 32000-2 §7.8.3: a page's (inherited) Resources; a form's own, else the page's. + public CosDictionary? Resources { get; internal set; } + + /// + /// Gets the CTM at the start of the running stream, the space a pattern named in it is relative to: the identity for a page, + /// the CTM at Do times the form matrix for a form. + /// + /// ISO 32000-2 §8.7.2: the pattern matrix maps pattern space to the default space of the stream that uses the pattern. + public Matrix StreamBaseMatrix { get; internal set; } = Matrix.Identity; + + /// Gets a value indicating whether optional content currently hides what is painted. + /// ISO 32000-2 §8.11.3.1. Always false until optional content is evaluated (issue #76). + public bool IsHidden { get; internal set; } + + /// + /// Gets the content stream the current operator is in, or when that stream is a direct object; for a + /// page whose Contents is an array, the part being read. + /// + public CosReference? CurrentStream => _interpreter.CurrentStream; + + /// Gets the index in the page's Contents array of the part being read; 0 for a single stream. + public int CurrentPartIndex => _interpreter.CurrentPartIndex; + + /// Gets the token that cancels the run. + public CancellationToken CancellationToken { get; internal set; } + + /// Returns the clip node a clip handle refers to, such as . + /// The handle; 0 for the run's initial clipping path. + /// The node; a node of kind for 0 and for a handle this run did not issue. + /// ISO 32000-2 §8.5.4. + public ClipView GetClip(int handle) => _interpreter.Clips.Get(handle); +} diff --git a/src/Broadside/Content/ContentEvents.cs b/src/Broadside/Content/ContentEvents.cs new file mode 100644 index 00000000..c2d7e4b8 --- /dev/null +++ b/src/Broadside/Content/ContentEvents.cs @@ -0,0 +1,55 @@ +namespace Broadside.Content; + +/// +/// The events a wants. The interpreter reads once per run and +/// skips the work no processor needs: no path is built when nobody wants paths or clips, no glyph is decoded when nobody wants glyphs. +/// +/// +/// ISO 32000-2 §8.2: the graphics objects a content stream describes. Graphics state changes are always applied, whatever is +/// requested; only the reporting is skipped. +/// +[Flags] +public enum ContentEvents +{ + /// Only and . + None = 0, + + /// : path objects as they are painted (§8.5). + Paths = 1 << 0, + + /// : changes of the clipping path (§8.5.4, §9.3.6). Without it, clip handles stay 0. + Clips = 1 << 1, + + /// and : text objects (§9.4). + Text = 1 << 2, + + /// : every glyph shown (§9.4.3). + Glyphs = 1 << 3, + + /// : image XObjects and inline images (§8.9). + Images = 1 << 4, + + /// : the sh operator (§8.7.4.2). + Shadings = 1 << 5, + + /// and : form XObjects (§8.10). + Forms = 1 << 6, + + /// The marked-content events (§14.6). + MarkedContent = 1 << 7, + + /// and : the graphics state stack (§8.4.2). + StateStack = 1 << 8, + + /// : every operator with its operands and source range, before it executes (§7.8.2). + Operators = 1 << 9, + + /// Paint, glyph, image and shading events for content hidden by optional content, flagged as hidden (§8.11.3.1). + HiddenContent = 1 << 10, + + /// The events inside Type 3 glyph procedures run through (§9.6.4). + Type3GlyphContent = 1 << 11, + + /// Every event. + All = Paths | Clips | Text | Glyphs | Images | Shadings | Forms | MarkedContent | StateStack | Operators | HiddenContent | Type3GlyphContent, +} diff --git a/src/Broadside/Content/ContentInterpreter.Color.cs b/src/Broadside/Content/ContentInterpreter.Color.cs new file mode 100644 index 00000000..db6ae25b --- /dev/null +++ b/src/Broadside/Content/ContentInterpreter.Color.cs @@ -0,0 +1,16 @@ +namespace Broadside.Content; + +/// The colour operators of Table 73: CS cs SC SCN sc scn G g RG rg K k. +/// +/// ISO 32000-2 §8.6.8. Operands are checked by the core; colour spaces and colour values are resolved into the graphics state from +/// issue #77. +/// +internal sealed partial class ContentInterpreter +{ + private static void ExecuteColor(ContentOperatorCode code, ContentOperands operands, int offset) + { + _ = code; + _ = operands; + _ = offset; + } +} diff --git a/src/Broadside/Content/ContentInterpreter.MarkedContent.cs b/src/Broadside/Content/ContentInterpreter.MarkedContent.cs new file mode 100644 index 00000000..d7e011cb --- /dev/null +++ b/src/Broadside/Content/ContentInterpreter.MarkedContent.cs @@ -0,0 +1,16 @@ +namespace Broadside.Content; + +/// The marked-content operators of Table 352: MP DP BMC BDC EMC. +/// +/// ISO 32000-2 §14.6. Operands are checked by the core; sequences, property lists and their events, and optional-content visibility +/// (§8.11.3.1), come with issues #56 and #76. +/// +internal sealed partial class ContentInterpreter +{ + private static void ExecuteMarkedContent(ContentOperatorCode code, ContentOperands operands, int offset) + { + _ = code; + _ = operands; + _ = offset; + } +} diff --git a/src/Broadside/Content/ContentInterpreter.Path.cs b/src/Broadside/Content/ContentInterpreter.Path.cs new file mode 100644 index 00000000..5492d92a --- /dev/null +++ b/src/Broadside/Content/ContentInterpreter.Path.cs @@ -0,0 +1,160 @@ +using Broadside.Graphics; + +namespace Broadside.Content; + +/// Path construction (Table 58), painting (Table 59) and clipping (Table 60). +/// +/// ISO 32000-2 §8.5. A clip set by W or W* takes effect after the painting operator that ends the path object, so +/// the paint event comes first and is not clipped by its own path (§8.5.4); W n only clips. +/// +internal sealed partial class ContentInterpreter +{ + private void ExecutePathConstruction(ContentOperatorCode code, ContentOperands operands, int offset) + { + switch (code) + { + case ContentOperatorCode.MoveTo: + _path.MoveTo(operands[0].Number, operands[1].Number); + break; + case ContentOperatorCode.Rectangle: + _path.Rectangle(operands[0].Number, operands[1].Number, operands[2].Number, operands[3].Number); + break; + case ContentOperatorCode.ClosePath: + if (!_path.IsOpen) + { + Report(ContentIssue.NoCurrentPoint, offset, "h without a current point; ignored."); + } + else + { + _path.Close(); + } + + break; + case ContentOperatorCode.LineTo: + if (StartsWithoutCurrentPoint(operands[0].Number, operands[1].Number, offset)) + { + break; + } + + _path.LineTo(operands[0].Number, operands[1].Number); + break; + case ContentOperatorCode.CurveTo: + if (StartsWithoutCurrentPoint(operands[4].Number, operands[5].Number, offset)) + { + break; + } + + _path.CurveTo( + new PathPoint(operands[0].Number, operands[1].Number), + new PathPoint(operands[2].Number, operands[3].Number), + new PathPoint(operands[4].Number, operands[5].Number)); + break; + case ContentOperatorCode.CurveToInitialPointReplicated: + if (StartsWithoutCurrentPoint(operands[2].Number, operands[3].Number, offset)) + { + break; + } + + _path.CurveTo(_path.CurrentPoint, new PathPoint(operands[0].Number, operands[1].Number), new PathPoint(operands[2].Number, operands[3].Number)); + break; + case ContentOperatorCode.CurveToFinalPointReplicated: + if (StartsWithoutCurrentPoint(operands[2].Number, operands[3].Number, offset)) + { + break; + } + + var end = new PathPoint(operands[2].Number, operands[3].Number); + _path.CurveTo(new PathPoint(operands[0].Number, operands[1].Number), end, end); + break; + } + } + + /// + /// A segment operator with no current point (§8.5.2.1: an error) begins a subpath at its end point instead, as PDFBox does; + /// returns true when it did. + /// + private bool StartsWithoutCurrentPoint(double x, double y, int offset) + { + if (_path.IsOpen) + { + return false; + } + + Report(ContentIssue.NoCurrentPoint, offset, "A line or curve without a current point; read as a moveto to its end point."); + _path.MoveTo(x, y); + return true; + } + + private void ExecuteClip(ContentOperatorCode code, int offset) + { + if (!_path.IsOpen) + { + Report(ContentIssue.NoCurrentPath, offset, "W or W* without a current path; ignored."); + return; + } + + _pendingClip = code == ContentOperatorCode.Clip ? FillRule.NonZero : FillRule.EvenOdd; + } + + private void ExecutePathPainting(ContentOperatorCode code, int offset) + { + (PathPaint paint, FillRule rule, bool close) = code switch + { + ContentOperatorCode.Stroke => (PathPaint.Stroke, FillRule.NonZero, false), + ContentOperatorCode.CloseAndStroke => (PathPaint.Stroke, FillRule.NonZero, true), + ContentOperatorCode.Fill or ContentOperatorCode.FillObsolete => (PathPaint.Fill, FillRule.NonZero, false), + ContentOperatorCode.FillEvenOdd => (PathPaint.Fill, FillRule.EvenOdd, false), + ContentOperatorCode.FillAndStroke => (PathPaint.FillAndStroke, FillRule.NonZero, false), + ContentOperatorCode.FillEvenOddAndStroke => (PathPaint.FillAndStroke, FillRule.EvenOdd, false), + ContentOperatorCode.CloseFillAndStroke => (PathPaint.FillAndStroke, FillRule.NonZero, true), + ContentOperatorCode.CloseFillEvenOddAndStroke => (PathPaint.FillAndStroke, FillRule.EvenOdd, true), + _ => (PathPaint.None, FillRule.NonZero, false), + }; + + if (!_path.IsOpen) + { + Report(ContentIssue.NoCurrentPath, offset, "A path-painting operator without a current path; nothing is painted."); + _pendingClip = null; + return; + } + + if (close) + { + _path.Close(); + } + + if ((_events & ContentEvents.Paths) != 0 && (!_context.IsHidden || (_events & ContentEvents.HiddenContent) != 0)) + { + var paintEvent = new PathEvent + { + Path = _path.View, + Paint = paint, + FillRule = rule, + ClosedBeforePaint = close, + PendingClip = _pendingClip, + IsHidden = _context.IsHidden, + }; + _processor.PaintPath(paintEvent, _context); + } + + if (_pendingClip is { } clipRule && (_events & ContentEvents.Clips) != 0) + { + int parent = State.ClipHandle; + int handle = Clips.Add(parent, ClipKind.Path, clipRule, _path.View, State.Ctm); + State.ClipHandle = handle; + var clipEvent = new ClipEvent + { + Handle = handle, + ParentHandle = parent, + Kind = ClipKind.Path, + Rule = clipRule, + Path = _path.View, + Ctm = State.Ctm, + }; + _processor.IntersectClip(clipEvent, _context); + } + + _pendingClip = null; + _path.Reset(); + } +} diff --git a/src/Broadside/Content/ContentInterpreter.Shading.cs b/src/Broadside/Content/ContentInterpreter.Shading.cs new file mode 100644 index 00000000..2c86403b --- /dev/null +++ b/src/Broadside/Content/ContentInterpreter.Shading.cs @@ -0,0 +1,13 @@ +namespace Broadside.Content; + +/// The shading operator of Table 76: sh. +/// ISO 32000-2 §8.7.4.2. Its operand is checked by the core; shadings are resolved and reported from issue #79. +internal sealed partial class ContentInterpreter +{ + private static void ExecuteShading(ContentOperatorCode code, ContentOperands operands, int offset) + { + _ = code; + _ = operands; + _ = offset; + } +} diff --git a/src/Broadside/Content/ContentInterpreter.State.cs b/src/Broadside/Content/ContentInterpreter.State.cs new file mode 100644 index 00000000..f8f404c9 --- /dev/null +++ b/src/Broadside/Content/ContentInterpreter.State.cs @@ -0,0 +1,199 @@ +using System.Buffers; +using Broadside.Graphics; + +namespace Broadside.Content; + +/// The graphics state operators of Table 56: q Q cm w J j M d ri i gs. +/// ISO 32000-2 §8.4.2 to §8.4.4. Out-of-range values are clipped into range with a diagnostic (§8.4.1). +internal sealed partial class ContentInterpreter +{ + private void ExecuteGraphicsState(ContentOperatorCode code, ContentOperands operands, int offset) + { + switch (code) + { + case ContentOperatorCode.SaveState: + SaveState(offset); + break; + case ContentOperatorCode.RestoreState: + RestoreState(offset); + break; + case ContentOperatorCode.ConcatenateMatrix: + var matrix = new Matrix(operands[0].Number, operands[1].Number, operands[2].Number, operands[3].Number, operands[4].Number, operands[5].Number); + State.Ctm = matrix * State.Ctm; + break; + case ContentOperatorCode.SetLineWidth: + double width = operands[0].Number; + if (width < 0) + { + Report(ContentIssue.GraphicsStateRange, offset, "A negative line width; its absolute value is used, as viewers do."); + width = -width; + } + + State.LineWidth = width; + break; + case ContentOperatorCode.SetLineCap: + State.LineCap = (LineCap)Style(operands[0].Number, offset, "A line cap style that is not 0, 1 or 2; butt caps (0) are used."); + break; + case ContentOperatorCode.SetLineJoin: + State.LineJoin = (LineJoin)Style(operands[0].Number, offset, "A line join style that is not 0, 1 or 2; miter joins (0) are used."); + break; + case ContentOperatorCode.SetMiterLimit: + double limit = operands[0].Number; + if (limit < 1 || double.IsNaN(limit)) + { + Report(ContentIssue.GraphicsStateRange, offset, "A miter limit below 1; 1 is used."); + limit = 1; + } + + State.MiterLimit = limit; + break; + case ContentOperatorCode.SetDash: + SetDash(operands[0].Items, operands[1].Number, offset); + break; + case ContentOperatorCode.SetRenderingIntent: + State.RenderingIntent = Intent(operands[0].Bytes); + break; + case ContentOperatorCode.SetFlatness: + double flatness = operands[0].Number; + if (flatness is < 0 or > 100 || double.IsNaN(flatness)) + { + Report(ContentIssue.GraphicsStateRange, offset, "A flatness tolerance outside 0 to 100; clipped into range."); + flatness = double.IsNaN(flatness) ? 0 : Math.Clamp(flatness, 0, 100); + } + + State.Flatness = flatness; + break; + case ContentOperatorCode.SetGraphicsStateParameters: + // gs and graphics state parameter dictionaries (§8.4.5, Table 57) are applied from issue #56. + break; + } + } + + /// q: pushes a copy of the whole state (§8.4.2). Beyond the depth limit it is ignored, and so is its Q. + private void SaveState(int offset) + { + if (_depth >= _maxSaveDepth) + { + Report(ContentIssue.StackOverflow, offset, "The graphics state stack is deeper than the limit; this q and its matching Q are ignored."); + _ignoredSaves++; + return; + } + + if (_depth + 1 == _states.Length) + { + GraphicsState[] larger = ArrayPool.Shared.Rent(_states.Length * 2); + _states.AsSpan(0, _depth + 1).CopyTo(larger); + ArrayPool.Shared.Return(_states, clearArray: true); + _states = larger; + } + + _states[_depth + 1] = _states[_depth]; + _depth++; + if ((_events & ContentEvents.StateStack) != 0) + { + _processor.SaveState(_context); + } + } + + /// Q: pops the state (§8.4.2); never below the running stream's floor. + private void RestoreState(int offset) + { + if (_ignoredSaves > 0) + { + _ignoredSaves--; + return; + } + + if (_depth <= _floor) + { + Report(ContentIssue.StackUnderflow, offset, "Q without a matching q; ignored."); + return; + } + + PopState(); + } + + private void PopState() + { + _depth--; + if ((_events & ContentEvents.StateStack) != 0) + { + _processor.RestoreState(_context); + } + } + + /// + /// d (§8.4.3.6): elements shall be non-negative and not all zero, else the line is solid; a negative phase is increased by + /// twice the sum of the elements until it is not negative. + /// + private void SetDash(ContentOperands elements, double phase, int offset) + { + int count = elements.Count; + double[]? rented = null; + Span values = count <= 32 ? stackalloc double[32] : (rented = ArrayPool.Shared.Rent(count)); + values = values[..count]; + double sum = 0; + bool valid = true; + int index = 0; + foreach (ContentOperand element in elements) + { + if (!element.IsNumber) + { + Report(ContentIssue.OperandType, offset, "A dash array element is not a number; the dash pattern is not changed."); + Return(rented); + return; + } + + values[index++] = element.Number; + sum += element.Number; + valid &= element.Number >= 0; + } + + if (!valid || (count > 0 && sum <= 0) || !double.IsFinite(sum) || !double.IsFinite(phase)) + { + Report(ContentIssue.GraphicsStateRange, offset, "A dash array with a negative element, or with only zeros; a solid line is used."); + values = []; + phase = 0; + } + else if (count == 0) + { + // §8.4.3.6: with an empty array the phase is zero. + phase = 0; + } + else if (phase < 0) + { + double period = 2 * sum; + phase += period * Math.Ceiling(-phase / period); + } + + State.SetDash(values, phase); + Return(rented); + + static void Return(double[]? array) + { + if (array is not null) + { + ArrayPool.Shared.Return(array); + } + } + } + + /// A line cap or join style: an integer 0, 1 or 2 (Tables 53, 54); anything else is 0 with a diagnostic. + private int Style(double value, int offset, string message) + { + if (value is 0 or 1 or 2) + { + return (int)value; + } + + Report(ContentIssue.GraphicsStateRange, offset, message); + return 0; + } + + /// A rendering intent name (Table 69); a name not recognised selects RelativeColorimetric (§8.6.5.8). + private static RenderingIntent Intent(ReadOnlySpan name) => + name.SequenceEqual("AbsoluteColorimetric"u8) ? RenderingIntent.AbsoluteColorimetric + : name.SequenceEqual("Saturation"u8) ? RenderingIntent.Saturation + : name.SequenceEqual("Perceptual"u8) ? RenderingIntent.Perceptual + : RenderingIntent.RelativeColorimetric; +} diff --git a/src/Broadside/Content/ContentInterpreter.Text.cs b/src/Broadside/Content/ContentInterpreter.Text.cs new file mode 100644 index 00000000..9dd78da7 --- /dev/null +++ b/src/Broadside/Content/ContentInterpreter.Text.cs @@ -0,0 +1,51 @@ +namespace Broadside.Content; + +/// Text objects (Table 105), text state (Table 103), positioning (Table 106), showing (Table 107) and Type 3 glyph operators (Table 111). +/// +/// ISO 32000-2 §9.3, §9.4, §9.6.4. Issue #55 tracks text objects (BT/ET, for the Figure 9 context rules) and reports +/// them; text state, positioning and glyph events are issue #56's, Type 3 glyph procedures issue #57's. Their operands are already +/// checked by the core. +/// +internal sealed partial class ContentInterpreter +{ + private void ExecuteText(ContentOperatorCode code, ContentOperands operands, int offset) + { + _ = operands; + switch (code) + { + case ContentOperatorCode.BeginText: + if (_inText) + { + Report(ContentIssue.TextObjectUnbalanced, offset, "BT inside a text object; ignored."); + break; + } + + _inText = true; + if ((_events & ContentEvents.Text) != 0) + { + _processor.BeginText(_context); + } + + break; + case ContentOperatorCode.EndText: + if (!_inText) + { + Report(ContentIssue.TextObjectUnbalanced, offset, "ET without a text object; ignored."); + break; + } + + EndTextObject(); + break; + } + } + + /// Ends the text object: at ET, or at the end of a stream that left one open. + private void EndTextObject() + { + _inText = false; + if ((_events & ContentEvents.Text) != 0) + { + _processor.EndText(_context); + } + } +} diff --git a/src/Broadside/Content/ContentInterpreter.XObject.cs b/src/Broadside/Content/ContentInterpreter.XObject.cs new file mode 100644 index 00000000..a2c171ab --- /dev/null +++ b/src/Broadside/Content/ContentInterpreter.XObject.cs @@ -0,0 +1,20 @@ +namespace Broadside.Content; + +/// XObjects (Table 86: Do) and inline images (Table 90: BI ID EI). +/// +/// ISO 32000-2 §8.8 to §8.10. The reader already delivers an inline image whole (dictionary operand and data range, never +/// tokenized); ID or EI reaching here stand outside any inline image. Forms, images and inline images are run and +/// reported from issue #56, with the image model of issue #60. +/// +internal sealed partial class ContentInterpreter +{ + private void ExecuteXObject(ContentOperatorCode code, ContentOperands operands, ReadOperator op, int offset) + { + _ = operands; + _ = op; + if (code is ContentOperatorCode.BeginInlineImageData or ContentOperatorCode.EndInlineImage) + { + Report(ContentIssue.InlineImageInvalid, offset, "ID or EI outside an inline image; ignored."); + } + } +} diff --git a/src/Broadside/Content/ContentInterpreter.cs b/src/Broadside/Content/ContentInterpreter.cs new file mode 100644 index 00000000..fb872fc4 --- /dev/null +++ b/src/Broadside/Content/ContentInterpreter.cs @@ -0,0 +1,591 @@ +using System.Buffers; +using System.Globalization; +using Broadside.Graphics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Content; + +/// +/// The one content interpreter: reads a content stream, runs its operators through one graphics-state machine and reports the +/// result to a . Single-threaded; instances are reused per thread, so a run allocates nothing per +/// operator once its buffers are warm. +/// +/// +/// +/// ISO 32000-2 §7.8.2 (content streams, Table 33 compatibility sections), §8.2 (graphics objects, Figure 9), §8.4 (graphics +/// state), §8.5 (paths and clipping). Dispatch is split by operator category into partial files (.State, .Path, +/// .Text, .Color, .Shading, .XObject, .MarkedContent) so that later issues each edit their own. +/// +/// +/// Lenient: malformed content is repaired as described on each operator and recorded once per kind of deviation; nothing throws +/// except in strict mode, where the document's diagnostic sink throws the first deviation of severity Warning or above. +/// +/// +internal sealed partial class ContentInterpreter +{ + /// The options a page run uses when the caller passes none. + internal static readonly ContentOptions DefaultOptions = new(); + + private const int CancellationInterval = 1024; + + [ThreadStatic] + private static ContentInterpreter? _cached; + + private readonly OperandArena _arena = new(); + private readonly PathBuilder _path = new(); + private readonly ContentContext _context; + private readonly List<(int Start, CosReference? Reference)> _parts = []; + private GraphicsState[] _states = ArrayPool.Shared.Rent(16); + private ContentProcessor _processor = null!; + private ContentEvents _events; + private DiagnosticSink? _diagnostics; + private CosReference? _fallbackReference; + private ulong _reported; + private int _depth; + private int _floor; + private int _maxSaveDepth; + private int _ignoredSaves; + private int _compatibilityDepth; + private int _operatorCount; + private int _part; + private bool _inText; + private FillRule? _pendingClip; + private bool _busy; + + private ContentInterpreter() => _context = new ContentContext(this); + + /// Gets the current graphics state. + public ref GraphicsState State => ref _states[_depth]; + + /// Gets the number of saved states above the run's initial state. + public int StateDepth => _depth; + + /// Gets the clip nodes of the run. + public ClipArena Clips { get; } = new(); + + /// Gets the content stream the current operator is in. + public CosReference? CurrentStream => _parts.Count > 0 ? _parts[_part].Reference : null; + + /// Gets the index of the part the current operator is in. + public int CurrentPartIndex => _part; + + /// Runs a page's content (§7.7.3.3, Table 31): its Contents stream, or its array of streams read as one. + /// The page. + /// The document of the page. + /// The processor. + /// Limits and cancellation. + public static void RunPage(PdfPage page, PdfDocument document, ContentProcessor processor, ContentOptions options) + { + ContentInterpreter interpreter = Rent(); + try + { + interpreter.RunPageCore(page, document, processor, options); + } + finally + { + interpreter.Release(); + } + } + + /// + /// Runs decoded content bytes as the top-level stream of a page run; for benchmarks and fuzzing, which have content without a + /// file around it. + /// + internal static void RunBytes(ReadOnlySpan content, PdfDocument document, ContentProcessor processor, ContentOptions options) + { + ContentInterpreter interpreter = Rent(); + try + { + interpreter.Begin(document, page: null, processor, options, document.Pages.Count > 0 ? document.Pages[0].Reference : null); + interpreter._parts.Add((0, null)); + interpreter.Execute(content); + interpreter.End(); + } + finally + { + interpreter.Release(); + } + } + + private static ContentInterpreter Rent() + { + ContentInterpreter? interpreter = _cached; + if (interpreter is null || interpreter._busy) + { + // A run started from inside another run's callback on this thread gets an interpreter of its own. + interpreter = new ContentInterpreter(); + } + + interpreter._busy = true; + return interpreter; + } + + private void RunPageCore(PdfPage page, PdfDocument document, ContentProcessor processor, ContentOptions options) + { + Begin(document, page, processor, options, page.Reference); + byte[]? rented = null; + try + { + ReadOnlyMemory content = ReadContents(page, document, ref rented); + Execute(content.Span); + End(); + } + finally + { + if (rented is not null) + { + ArrayPool.Shared.Return(rented); + } + } + } + + /// Decodes the page's content; parts of an array are joined with a line feed between them (Table 31). + private ReadOnlyMemory ReadContents(PdfPage page, PdfDocument document, ref byte[]? rented) + { + if (!page.Dictionary.TryGetValue(KnownNames.Contents, out CosObject? entry)) + { + return ReadOnlyMemory.Empty; + } + + switch (document.Resolve(entry)) + { + case CosNull: + return ReadOnlyMemory.Empty; + case CosStream stream: + _parts.Add((0, entry as CosReference)); + return document.DecodeStream(stream); + case CosArray { Count: > 0 } array: + return ReadParts(array, document, ref rented); + case CosArray: + Report(ContentIssue.StreamInvalid, -1, "The page's Contents array is empty; the page has no content."); + return ReadOnlyMemory.Empty; + default: + Report(ContentIssue.StreamInvalid, -1, "The page's Contents is neither a stream nor an array of streams; the page has no content."); + return ReadOnlyMemory.Empty; + } + } + + private ReadOnlyMemory ReadParts(CosArray array, PdfDocument document, ref byte[]? rented) + { + var decoded = new ReadOnlyMemory[array.Count]; + int total = 0; + for (int index = 0; index < array.Count; index++) + { + if (document.Resolve(array[index]) is CosStream stream) + { + decoded[index] = document.DecodeStream(stream); + total += decoded[index].Length + 1; + } + else + { + Report(ContentIssue.StreamInvalid, -1, $"Element {index} of the page's Contents array is not a stream; skipped."); + } + } + + rented = ArrayPool.Shared.Rent(Math.Max(1, total)); + int position = 0; + for (int index = 0; index < array.Count; index++) + { + if (document.Resolve(array[index]) is CosStream) + { + _parts.Add((position, array[index] as CosReference)); + decoded[index].Span.CopyTo(rented.AsSpan(position)); + position += decoded[index].Length; + rented[position++] = (byte)'\n'; + } + } + + if (_parts.Count == 0) + { + _parts.Add((0, null)); + } + + return rented.AsMemory(0, position); + } + + private void Begin(PdfDocument document, PdfPage? page, ContentProcessor processor, ContentOptions options, CosReference? fallbackReference) + { + _processor = processor; + _events = processor.Events; + _diagnostics = document.DiagnosticSink; + _fallbackReference = fallbackReference; + _reported = 0; + _depth = 0; + _floor = 0; + _ignoredSaves = 0; + _compatibilityDepth = 0; + _operatorCount = 0; + _part = 0; + _inText = false; + _pendingClip = null; + _maxSaveDepth = options.MaxSaveDepth; + _arena.Limit = options.MaxOperands; + _path.Accumulate = (_events & (ContentEvents.Paths | ContentEvents.Clips)) != 0; + _states[0] = GraphicsState.CreateInitial(); + _parts.Clear(); + _context.RunKind = ContentRunKind.Page; + _context.Depth = 0; + _context.Document = document; + _context.Page = page; + _context.Resources = page?.Resources; + _context.StreamBaseMatrix = Matrix.Identity; + _context.IsHidden = false; + _context.CancellationToken = options.CancellationToken; + options.CancellationToken.ThrowIfCancellationRequested(); + processor.BeginRun(_context); + } + + private void End() + { + FinishStream(); + _processor.EndRun(_context); + } + + private void Release() + { + _arena.Trim(); + _path.Trim(); + Clips.Reset(); + _parts.Clear(); + _processor = null!; + _diagnostics = null; + _context.Document = null!; + _context.Page = null; + _context.Resources = null; + _busy = false; + _cached = this; + } + + /// Reads and executes every operator of . + private void Execute(ReadOnlySpan content) + { + var reader = new ContentReader(content, _arena); + _arena.Clear(); + while (reader.Next(out ReadOperator op)) + { + if (reader.Issues != ReaderIssues.None) + { + ReportReaderIssues(reader.Issues, reader.IssueOffset); + reader.ClearIssues(); + } + + if (_arena.Overflowed) + { + _arena.Overflowed = false; + Report(ContentIssue.OperandOverflow, op.KeywordStart, "More operands than the limit were written before an operator; the oldest were dropped."); + } + + if (++_operatorCount % CancellationInterval == 0) + { + _context.CancellationToken.ThrowIfCancellationRequested(); + } + + LocatePart(op.KeywordStart); + if ((_events & ContentEvents.Operators) != 0) + { + ReportOperator(op, content); + } + + Execute(op); + _arena.Clear(); + } + + if (reader.Issues != ReaderIssues.None) + { + ReportReaderIssues(reader.Issues, reader.IssueOffset); + } + + if (_arena.Count > 0 || _arena.OpenDepth > 0) + { + Report(ContentIssue.OperandCount, content.Length, "Operands are left over at the end of the content stream; ignored."); + _arena.Clear(); + } + } + + private void ReportOperator(ReadOperator op, ReadOnlySpan content) + { + int partStart = _parts.Count > 0 ? _parts[_part].Start : 0; + var report = new ContentOperator + { + Code = op.Code, + Keyword = content.Slice(op.KeywordStart, op.KeywordLength), + Operands = _arena.Operands, + Data = content.Slice(op.DataStart, op.DataLength), + Stream = CurrentStream, + PartIndex = _part, + Offset = op.Start - partStart, + Length = op.End - op.Start, + KeywordOffset = op.KeywordStart - partStart, + }; + _processor.VisitOperator(report, _context); + } + + private void Execute(ReadOperator op) + { + ContentOperatorCode code = op.Code; + int offset = op.KeywordStart; + if (code == ContentOperatorCode.Unknown) + { + if (_compatibilityDepth == 0) + { + Report(ContentIssue.UnknownOperator, offset, "A keyword that is not an operator, outside a compatibility section (BX/EX); it and its operands are ignored."); + } + + return; + } + + OperatorCategory category = OperatorTable.Category(code); + CheckContext(category, offset); + if (!TakeOperands(code, offset, out ContentOperands operands)) + { + return; + } + + switch (category) + { + case OperatorCategory.GeneralGraphicsState or OperatorCategory.SpecialGraphicsState: + ExecuteGraphicsState(code, operands, offset); + break; + case OperatorCategory.PathConstruction: + ExecutePathConstruction(code, operands, offset); + break; + case OperatorCategory.PathPainting: + ExecutePathPainting(code, offset); + break; + case OperatorCategory.ClippingPath: + ExecuteClip(code, offset); + break; + case OperatorCategory.TextObject or OperatorCategory.TextState or OperatorCategory.TextPositioning or OperatorCategory.TextShowing + or OperatorCategory.Type3Font: + ExecuteText(code, operands, offset); + break; + case OperatorCategory.Color: + ExecuteColor(code, operands, offset); + break; + case OperatorCategory.Shading: + ExecuteShading(code, operands, offset); + break; + case OperatorCategory.InlineImage or OperatorCategory.XObject: + ExecuteXObject(code, operands, op, offset); + break; + case OperatorCategory.MarkedContent: + ExecuteMarkedContent(code, operands, offset); + break; + case OperatorCategory.Compatibility: + ExecuteCompatibility(code, offset); + break; + } + } + + /// + /// Checks the operands against the operator's signature: too few, or of the wrong kind, skips the operator; too many uses the + /// last ones (they are the ones that "immediately precede" it, §7.8.2). + /// + private bool TakeOperands(ContentOperatorCode code, int offset, out ContentOperands operands) + { + OperandSignature signature = OperatorTable.Signature(code); + int count = _arena.Count; + operands = _arena.Operands; + if (signature.IsVariable) + { + if (count == 0) + { + Report(ContentIssue.OperandCount, offset, "A colour operator has no operands; skipped."); + return false; + } + + for (int index = 0; index < count; index++) + { + ContentOperand operand = operands[index]; + bool trailingName = index == count - 1 && signature.Kinds.Length > 1 && operand.Kind == ContentOperandKind.Name; + if (!operand.IsNumber && !trailingName) + { + Report(ContentIssue.OperandType, offset, "A colour operator's operands must be numbers (and, for SCN and scn, a final name); skipped."); + return false; + } + } + + return true; + } + + int expected = signature.Kinds.Length; + if (count < expected) + { + Report(ContentIssue.OperandCount, offset, "An operator has fewer operands than it takes; skipped."); + return false; + } + + if (count > expected) + { + Report(ContentIssue.OperandCount, offset, "An operator has more operands than it takes; the last ones are used and the others ignored."); + operands = _arena.Last(expected); + } + + for (int index = 0; index < expected; index++) + { + ContentOperandKind kind = operands[index].Kind; + bool matches = signature.Kinds[index] switch + { + (byte)'n' => kind is ContentOperandKind.Integer or ContentOperandKind.Real, + (byte)'N' => kind == ContentOperandKind.Name, + (byte)'s' => kind == ContentOperandKind.String, + (byte)'a' => kind == ContentOperandKind.Array, + (byte)'d' => kind == ContentOperandKind.Dictionary, + _ => kind is ContentOperandKind.Dictionary or ContentOperandKind.Name, + }; + if (!matches) + { + Report(ContentIssue.OperandType, offset, "An operand is not of the type the operator takes; the operator is skipped."); + return false; + } + } + + return true; + } + + /// + /// Figure 9: inside a path object only path construction, clipping and painting operators may appear; inside a text object, + /// general graphics state, colour, text and marked-content operators; text positioning and showing only inside a text object. + /// A violation is applied anyway and recorded at Information severity (real files do it, e.g. m l 2 w S). + /// + private void CheckContext(OperatorCategory category, int offset) + { + bool allowed; + if (_path.IsOpen) + { + allowed = category is OperatorCategory.PathConstruction or OperatorCategory.PathPainting or OperatorCategory.ClippingPath + or OperatorCategory.Compatibility; + } + else if (_inText) + { + allowed = category is OperatorCategory.GeneralGraphicsState or OperatorCategory.Color or OperatorCategory.TextState + or OperatorCategory.TextPositioning or OperatorCategory.TextShowing or OperatorCategory.TextObject + or OperatorCategory.MarkedContent or OperatorCategory.Compatibility or OperatorCategory.PathPainting + or OperatorCategory.ClippingPath; + } + else + { + allowed = category is not (OperatorCategory.TextPositioning or OperatorCategory.TextShowing); + } + + if (!allowed) + { + Report( + ContentIssue.OperatorOutOfContext, + offset, + "An operator appears where Figure 9 does not allow it (a graphics state change inside a path object, or text outside a text object); it is applied anyway."); + } + } + + private void ExecuteCompatibility(ContentOperatorCode code, int offset) + { + if (code == ContentOperatorCode.BeginCompatibility) + { + _compatibilityDepth++; + } + else if (_compatibilityDepth > 0) + { + _compatibilityDepth--; + } + else + { + Report(ContentIssue.CompatibilityUnbalanced, offset, "EX without a matching BX; ignored."); + } + } + + /// + /// Ends the running stream: leftover state that a well-formed stream would have closed is closed, with diagnostics: an + /// unpainted path is discarded, an open text object ends, an open compatibility section closes, and unbalanced q + /// operators are restored down to the stream's floor (§8.4.2). + /// + private void FinishStream() + { + if (_path.IsOpen) + { + Report(ContentIssue.PathNotPainted, -1, "The content stream ends inside a path object that was never painted; the path is discarded."); + _path.Reset(); + _pendingClip = null; + } + + if (_inText) + { + Report(ContentIssue.TextObjectUnbalanced, -1, "The content stream ends inside a text object (BT without ET); it is ended there."); + EndTextObject(); + } + + if (_compatibilityDepth > 0) + { + Report(ContentIssue.CompatibilityUnbalanced, -1, "The content stream ends inside a compatibility section (BX without EX)."); + _compatibilityDepth = 0; + } + + if (_depth > _floor) + { + Report(ContentIssue.UnbalancedSave, -1, "The content stream ends with graphics states saved by q that no Q restored; they are restored there."); + while (_depth > _floor) + { + PopState(); + } + } + + _ignoredSaves = 0; + } + + /// Moves the current part forward to the one containing (offsets only grow). + private void LocatePart(int offset) + { + while (_part + 1 < _parts.Count && _parts[_part + 1].Start <= offset) + { + _part++; + } + } + + private void ReportReaderIssues(ReaderIssues issues, int offset) + { + if ((issues & ReaderIssues.GluedTokens) != 0) + { + Report(ContentIssue.GluedTokens, offset, "Operators and operands are written without white-space between them (such as q1 or 0cm); they are read as separate tokens."); + } + + if ((issues & ReaderIssues.SyntaxInvalid) != 0) + { + Report(ContentIssue.SyntaxInvalid, offset, "A malformed token (a stray delimiter, an unbalanced ] or >>, a malformed number, string or name) was skipped or repaired."); + } + + if ((issues & ReaderIssues.ContainerUnclosed) != 0) + { + Report(ContentIssue.SyntaxInvalid, offset, "An array or dictionary operand is not closed before its operator; it is closed there."); + } + + if ((issues & ReaderIssues.InlineImageInvalid) != 0) + { + Report(ContentIssue.InlineImageInvalid, offset, "An inline image lacks ID or EI, or its dictionary holds something that is not a value; the image ends there."); + } + } + + /// + /// Records a deviation once per kind per run, on the content stream's object (the page's when the stream is direct), with the + /// part and the offset in the decoded data in the message. Strict mode throws through the document's sink. + /// + private void Report(ContentIssue issue, int offset, string message) + { + ulong bit = 1UL << (int)issue; + if ((_reported & bit) != 0 || _diagnostics is null) + { + return; + } + + _reported |= bit; + if (offset >= 0) + { + LocatePart(offset); + } + + int partStart = _parts.Count > 0 ? _parts[_part].Start : 0; + string location = offset < 0 + ? string.Empty + : string.Create(CultureInfo.InvariantCulture, $" (content stream part {_part}, decoded offset {offset - partStart})"); + _diagnostics.ReportOnce(ContentIssues.Code(issue), ContentIssues.Severity(issue), message + location, offset: null, CurrentStream ?? _fallbackReference); + } +} diff --git a/src/Broadside/Content/ContentIssue.cs b/src/Broadside/Content/ContentIssue.cs new file mode 100644 index 00000000..cb8b8eb9 --- /dev/null +++ b/src/Broadside/Content/ContentIssue.cs @@ -0,0 +1,64 @@ +using Broadside.Diagnostics; +using Broadside.Parsing; + +namespace Broadside.Content; + +/// The deviations the content interpreter records, each mapped to one diagnostic code and severity. +/// +/// Information for deviations that do not change what is painted (Figure 9 context rules, glued tokens, a path never painted); +/// Warning for operators skipped or repaired. Each is recorded at most once per run, so malformed content costs one diagnostic per +/// kind, not one per operator. +/// +internal enum ContentIssue +{ + StreamInvalid, + UnknownOperator, + OperandCount, + OperandType, + OperandOverflow, + SyntaxInvalid, + GluedTokens, + OperatorOutOfContext, + StackUnderflow, + StackOverflow, + UnbalancedSave, + NoCurrentPoint, + NoCurrentPath, + PathNotPainted, + GraphicsStateRange, + CompatibilityUnbalanced, + TextObjectUnbalanced, + InlineImageInvalid, +} + +/// The code and severity of each . +internal static class ContentIssues +{ + public static string Code(ContentIssue issue) => issue switch + { + ContentIssue.StreamInvalid => DiagnosticCodes.ContentStreamInvalid, + ContentIssue.UnknownOperator => DiagnosticCodes.ContentUnknownOperator, + ContentIssue.OperandCount => DiagnosticCodes.ContentOperandCount, + ContentIssue.OperandType => DiagnosticCodes.ContentOperandType, + ContentIssue.OperandOverflow => DiagnosticCodes.ContentOperandOverflow, + ContentIssue.SyntaxInvalid => DiagnosticCodes.ContentSyntaxInvalid, + ContentIssue.GluedTokens => DiagnosticCodes.ContentGluedTokens, + ContentIssue.OperatorOutOfContext => DiagnosticCodes.ContentOperatorOutOfContext, + ContentIssue.StackUnderflow => DiagnosticCodes.ContentStackUnderflow, + ContentIssue.StackOverflow => DiagnosticCodes.ContentStackOverflow, + ContentIssue.UnbalancedSave => DiagnosticCodes.ContentUnbalancedSave, + ContentIssue.NoCurrentPoint => DiagnosticCodes.ContentNoCurrentPoint, + ContentIssue.NoCurrentPath => DiagnosticCodes.ContentNoCurrentPath, + ContentIssue.PathNotPainted => DiagnosticCodes.ContentPathNotPainted, + ContentIssue.GraphicsStateRange => DiagnosticCodes.ContentGraphicsStateRange, + ContentIssue.CompatibilityUnbalanced => DiagnosticCodes.ContentCompatibilityUnbalanced, + ContentIssue.TextObjectUnbalanced => DiagnosticCodes.ContentTextObjectUnbalanced, + _ => DiagnosticCodes.ContentInlineImageInvalid, + }; + + public static DiagnosticSeverity Severity(ContentIssue issue) => issue switch + { + ContentIssue.GluedTokens or ContentIssue.OperatorOutOfContext or ContentIssue.PathNotPainted => DiagnosticSeverity.Information, + _ => DiagnosticSeverity.Warning, + }; +} diff --git a/src/Broadside/Content/ContentOperand.cs b/src/Broadside/Content/ContentOperand.cs new file mode 100644 index 00000000..ab52fbc0 --- /dev/null +++ b/src/Broadside/Content/ContentOperand.cs @@ -0,0 +1,99 @@ +using Broadside.Objects; + +namespace Broadside.Content; + +/// +/// One operand of a content stream operator, read in place: numbers as values, names and strings as decoded bytes, arrays and +/// dictionaries as views of their elements. Valid only during the callback that received it; copy what you keep, or call +/// . +/// +/// ISO 32000-2 §7.8.2: operands are direct objects of any basic type except a stream. +public readonly ref struct ContentOperand +{ + /// What a default operand reads as: the null object. + private static readonly OperandEntry NullEntry = new() { Kind = ContentOperandKind.Null, End = 1 }; + + private readonly ReadOnlySpan _entries; + private readonly ReadOnlySpan _bytes; + private readonly int _index; + + internal ContentOperand(ReadOnlySpan entries, ReadOnlySpan bytes, int index) + { + _entries = entries; + _bytes = bytes; + _index = index; + } + + /// Gets the object type. + public ContentOperandKind Kind => Entry.Kind; + + /// Gets a value indicating whether this is an integer or a real. + public bool IsNumber => Entry.Kind is ContentOperandKind.Integer or ContentOperandKind.Real; + + /// Gets the value of a number; 0 for any other kind. + /// ISO 32000-2 §7.3.3. Integers beyond the range of a double's exact integers keep the nearest double. + public double Number => IsNumber ? Entry.Number : 0; + + /// Gets the value of a boolean; false for any other kind. + public bool Boolean => Entry.Kind == ContentOperandKind.Boolean && Entry.Number != 0; + + /// Gets the decoded bytes of a name (without the solidus, #xx escapes resolved) or a string (escapes resolved); empty for any other kind. + /// ISO 32000-2 §7.3.4 and §7.3.5. + public ReadOnlySpan Bytes => _bytes.Slice(Entry.BytesStart, Entry.BytesLength); + + /// Gets a value indicating whether a string was written in hexadecimal (§7.3.4.3). + public bool IsHexadecimal => Entry.IsHexadecimal; + + /// Gets the elements of an array, or the alternating keys and values of a dictionary; empty for any other kind. + public ContentOperands Items => new(_entries, _bytes, _index + 1, Entry.Count); + + private ref readonly OperandEntry Entry => ref _entries.IsEmpty ? ref NullEntry : ref _entries[_index]; + + /// Returns whether this is a name with the bytes . + /// The name's bytes, without the solidus. + /// for a name equal to . + public bool IsName(ReadOnlySpan name) => Kind == ContentOperandKind.Name && Bytes.SequenceEqual(name); + + /// Returns the operand as a new COS object, copying its bytes and elements. + /// A of the matching type. + /// Allocates; for processors that keep an operand, such as a marked-content property list, beyond the callback. + public CosObject ToCosObject() + { + switch (Kind) + { + case ContentOperandKind.Boolean: + return Boolean ? CosBoolean.True : CosBoolean.False; + case ContentOperandKind.Integer: + double value = Number; + return value is >= long.MinValue and <= long.MaxValue ? new CosInteger((long)value) : new CosReal(value); + case ContentOperandKind.Real: + return new CosReal(Number); + case ContentOperandKind.Name: + return new CosName(Bytes); + case ContentOperandKind.String: + return new CosString(Bytes, IsHexadecimal); + case ContentOperandKind.Array: + var array = new CosArray(); + foreach (ContentOperand item in Items) + { + array.Add(item.ToCosObject()); + } + + return array; + case ContentOperandKind.Dictionary: + var dictionary = new CosDictionary(); + ContentOperands items = Items; + for (int index = 0; index + 1 < items.Count; index += 2) + { + if (items[index] is { Kind: ContentOperandKind.Name } key && items[index + 1].ToCosObject() is not CosNull and var item) + { + dictionary[new CosName(key.Bytes)] = item; + } + } + + return dictionary; + default: + return CosNull.Instance; + } + } +} diff --git a/src/Broadside/Content/ContentOperandKind.cs b/src/Broadside/Content/ContentOperandKind.cs new file mode 100644 index 00000000..fcaf0b19 --- /dev/null +++ b/src/Broadside/Content/ContentOperandKind.cs @@ -0,0 +1,36 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Broadside.Content; + +/// The object type of a content stream operand. +/// +/// ISO 32000-2 §7.8.2: an operand is a direct object of any basic type except a stream; indirect references are not permitted +/// (1 0 R reads as the numbers 1 and 0 followed by the unknown operator R). +/// +[SuppressMessage("Naming", "CA1720:Identifier contains type name", Justification = "The values are the ISO 32000-2 object type names (§7.3).")] +public enum ContentOperandKind +{ + /// The null object (§7.3.9). + Null, + + /// A boolean (§7.3.2). + Boolean, + + /// An integer (§7.3.3). + Integer, + + /// A real number (§7.3.3). + Real, + + /// A name (§7.3.5); its bytes are decoded, without the solidus. + Name, + + /// A literal or hexadecimal string (§7.3.4); its bytes are decoded. + String, + + /// An array (§7.3.6), such as the operand of TJ or d. + Array, + + /// A dictionary (§7.3.7), such as the property list of BDC or an inline image's parameters; its items alternate key and value. + Dictionary, +} diff --git a/src/Broadside/Content/ContentOperands.cs b/src/Broadside/Content/ContentOperands.cs new file mode 100644 index 00000000..b947d03f --- /dev/null +++ b/src/Broadside/Content/ContentOperands.cs @@ -0,0 +1,104 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Broadside.Content; + +/// +/// A list of content stream operands, or of the elements of an array or dictionary operand, read in place. Valid only during the +/// callback that received it. +/// +/// ISO 32000-2 §7.8.2. +public readonly ref struct ContentOperands +{ + private readonly ReadOnlySpan _entries; + private readonly ReadOnlySpan _bytes; + private readonly ReadOnlySpan _indices; + private readonly int _first; + private readonly bool _indexed; + + /// Initializes a new instance of the struct over top-level operands at . + internal ContentOperands(ReadOnlySpan entries, ReadOnlySpan bytes, ReadOnlySpan indices) + { + _entries = entries; + _bytes = bytes; + _indices = indices; + _indexed = true; + Count = indices.Length; + } + + /// Initializes a new instance of the struct over the siblings from . + internal ContentOperands(ReadOnlySpan entries, ReadOnlySpan bytes, int first, int count) + { + _entries = entries; + _bytes = bytes; + _first = first; + Count = count; + } + + /// Gets the number of operands. + public int Count { get; } + + /// Gets the operand at . + /// The position, from 0. + /// is negative or not less than . + public ContentOperand this[int index] + { + get + { + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, Count); + return new ContentOperand(_entries, _bytes, EntryIndex(index)); + } + } + + /// Returns an enumerator over the operands. + /// The enumerator. + public Enumerator GetEnumerator() => new(this); + + private int EntryIndex(int index) + { + if (_indexed) + { + return _indices[index]; + } + + int entry = _first; + for (int step = 0; step < index; step++) + { + entry = _entries[entry].End; + } + + return entry; + } + + /// Enumerates operands in order without allocating. + [SuppressMessage("Design", "CA1034:Nested types should not be visible", Justification = "The enumerator pattern of Span: found by foreach, never named.")] + public ref struct Enumerator + { + private readonly ContentOperands _operands; + private int _position; + private int _entry; + + internal Enumerator(ContentOperands operands) + { + _operands = operands; + _position = -1; + _entry = -1; + } + + /// Gets the current operand. + public readonly ContentOperand Current => new(_operands._entries, _operands._bytes, _entry); + + /// Advances to the next operand. + /// at the end. + public bool MoveNext() + { + if (++_position >= _operands.Count) + { + return false; + } + + _entry = _operands._indexed ? _operands._indices[_position] : _position == 0 ? _operands._first : _operands._entries[_entry].End; + return true; + } + } +} diff --git a/src/Broadside/Content/ContentOperator.cs b/src/Broadside/Content/ContentOperator.cs new file mode 100644 index 00000000..162a2bf3 --- /dev/null +++ b/src/Broadside/Content/ContentOperator.cs @@ -0,0 +1,43 @@ +using Broadside.Objects; + +namespace Broadside.Content; + +/// +/// One operator as it appears in the content stream, with its operands and where it is, reported before it executes. Valid only +/// during the callback. +/// +/// +/// ISO 32000-2 §7.8.2. Every operator is reported, unknown ones and those inside compatibility sections included, so an editor can +/// map semantic events back to bytes. Operands are those written before the operator, all of them: an operator given too many uses +/// the last ones it takes. An inline image (§8.9.7) is one operator, , whose operand +/// is its dictionary and whose is its image data. +/// +public readonly ref struct ContentOperator +{ + /// Gets the operator, or . + public ContentOperatorCode Code { get; internal init; } + + /// Gets the keyword as written, such as cm; for a glued keyword such as q1, only the operator's part. + public ReadOnlySpan Keyword { get; internal init; } + + /// Gets the operands written before the operator. + public ContentOperands Operands { get; internal init; } + + /// Gets the data of an inline image; empty for any other operator. + public ReadOnlySpan Data { get; internal init; } + + /// Gets the content stream the operator is in, or when that stream is a direct object. + public CosReference? Stream { get; internal init; } + + /// Gets the index of that stream in the page's Contents array; 0 for a single stream. + public int PartIndex { get; internal init; } + + /// Gets the offset in the stream's decoded data where the operator's first operand, or its keyword when it has none, begins. + public int Offset { get; internal init; } + + /// Gets the number of bytes from through the end of the keyword (through EI for an inline image). + public int Length { get; internal init; } + + /// Gets the offset of the keyword in the stream's decoded data. + public int KeywordOffset { get; internal init; } +} diff --git a/src/Broadside/Content/ContentOperatorCode.cs b/src/Broadside/Content/ContentOperatorCode.cs new file mode 100644 index 00000000..478c6689 --- /dev/null +++ b/src/Broadside/Content/ContentOperatorCode.cs @@ -0,0 +1,231 @@ +namespace Broadside.Content; + +/// The content stream operators of ISO 32000-2, one value per operator keyword, and for any other keyword. +/// +/// ISO 32000-2 Annex A, Table A.1 (73 operators), described in the clause tables cited on each value. Table A.1's own cross +/// references contain errata (BMC, BT and c); the clause tables are authoritative. +/// +public enum ContentOperatorCode +{ + /// A keyword that is not a PDF operator (§7.8.2): ignored, silently inside a compatibility section. + Unknown = 0, + + /// q: save the graphics state (§8.4.4, Table 56). + SaveState, + + /// Q: restore the graphics state (§8.4.4, Table 56). + RestoreState, + + /// cm: concatenate a matrix to the CTM (§8.4.4, Table 56). + ConcatenateMatrix, + + /// w: set the line width (§8.4.4, Table 56). + SetLineWidth, + + /// J: set the line cap style (§8.4.4, Table 56). + SetLineCap, + + /// j: set the line join style (§8.4.4, Table 56). + SetLineJoin, + + /// M: set the miter limit (§8.4.4, Table 56). + SetMiterLimit, + + /// d: set the line dash pattern (§8.4.4, Table 56). + SetDash, + + /// ri: set the colour rendering intent (§8.4.4, Table 56). + SetRenderingIntent, + + /// i: set the flatness tolerance (§8.4.4, Table 56). + SetFlatness, + + /// gs: set parameters from a graphics state parameter dictionary (§8.4.4, Table 56; §8.4.5). + SetGraphicsStateParameters, + + /// m: begin a subpath (§8.5.2, Table 58). + MoveTo, + + /// l: append a line segment (§8.5.2, Table 58). + LineTo, + + /// c: append a cubic Bézier curve (§8.5.2, Table 58). + CurveTo, + + /// v: append a cubic Bézier curve whose first control point is the current point (§8.5.2, Table 58). + CurveToInitialPointReplicated, + + /// y: append a cubic Bézier curve whose second control point is its end point (§8.5.2, Table 58). + CurveToFinalPointReplicated, + + /// h: close the current subpath (§8.5.2, Table 58). + ClosePath, + + /// re: append a rectangle as a complete subpath (§8.5.2, Table 58). + Rectangle, + + /// S: stroke the path (§8.5.3, Table 59). + Stroke, + + /// s: close and stroke the path (§8.5.3, Table 59). + CloseAndStroke, + + /// f: fill the path, non-zero winding number rule (§8.5.3, Table 59). + Fill, + + /// F: as f; deprecated in PDF 2.0 but readers shall accept it (§8.5.3, Table 59). + FillObsolete, + + /// f*: fill the path, even-odd rule (§8.5.3, Table 59). + FillEvenOdd, + + /// B: fill, non-zero rule, then stroke (§8.5.3, Table 59). + FillAndStroke, + + /// B*: fill, even-odd rule, then stroke (§8.5.3, Table 59). + FillEvenOddAndStroke, + + /// b: close, fill with the non-zero rule, then stroke (§8.5.3, Table 59). + CloseFillAndStroke, + + /// b*: close, fill with the even-odd rule, then stroke (§8.5.3, Table 59). + CloseFillEvenOddAndStroke, + + /// n: end the path without painting it (§8.5.3, Table 59). + EndPath, + + /// W: clip with the path, non-zero rule, after the next painting operator (§8.5.4, Table 60). + Clip, + + /// W*: clip with the path, even-odd rule, after the next painting operator (§8.5.4, Table 60). + ClipEvenOdd, + + /// BT: begin a text object (§9.4.1, Table 105). + BeginText, + + /// ET: end a text object (§9.4.1, Table 105). + EndText, + + /// Tc: set the character spacing (§9.3.1, Table 103). + SetCharacterSpacing, + + /// Tw: set the word spacing (§9.3.1, Table 103). + SetWordSpacing, + + /// Tz: set the horizontal scaling (§9.3.1, Table 103). + SetHorizontalScaling, + + /// TL: set the leading (§9.3.1, Table 103). + SetLeading, + + /// Tf: set the font and size (§9.3.1, Table 103). + SetFont, + + /// Tr: set the text rendering mode (§9.3.1, Table 103). + SetTextRenderingMode, + + /// Ts: set the text rise (§9.3.1, Table 103). + SetTextRise, + + /// Td: move to the start of the next line (§9.4.2, Table 106). + MoveText, + + /// TD: move to the start of the next line and set the leading (§9.4.2, Table 106). + MoveTextSetLeading, + + /// Tm: set the text matrix and text line matrix (§9.4.2, Table 106). + SetTextMatrix, + + /// T*: move to the start of the next line by the leading (§9.4.2, Table 106). + NextLine, + + /// Tj: show a string (§9.4.3, Table 107). + ShowText, + + /// TJ: show strings with individual position adjustments (§9.4.3, Table 107). + ShowTextAdjusted, + + /// ': move to the next line and show a string (§9.4.3, Table 107). + NextLineShowText, + + /// ": set word and character spacing, move to the next line and show a string (§9.4.3, Table 107). + NextLineShowTextWithSpacing, + + /// d0: set the glyph width of a Type 3 glyph (§9.6.4, Table 111). + SetGlyphWidth, + + /// d1: set the glyph width and bounding box of a Type 3 glyph (§9.6.4, Table 111). + SetGlyphWidthAndBoundingBox, + + /// CS: set the stroking colour space (§8.6.8, Table 73). + SetStrokeColorSpace, + + /// cs: set the non-stroking colour space (§8.6.8, Table 73). + SetFillColorSpace, + + /// SC: set the stroking colour (§8.6.8, Table 73). + SetStrokeColor, + + /// SCN: set the stroking colour, including Pattern, Separation, DeviceN and ICCBased (§8.6.8, Table 73). + SetStrokeColorExtended, + + /// sc: set the non-stroking colour (§8.6.8, Table 73). + SetFillColor, + + /// scn: set the non-stroking colour, including Pattern, Separation, DeviceN and ICCBased (§8.6.8, Table 73). + SetFillColorExtended, + + /// G: set DeviceGray and a stroking gray level (§8.6.8, Table 73). + SetStrokeGray, + + /// g: set DeviceGray and a non-stroking gray level (§8.6.8, Table 73). + SetFillGray, + + /// RG: set DeviceRGB and a stroking colour (§8.6.8, Table 73). + SetStrokeRgb, + + /// rg: set DeviceRGB and a non-stroking colour (§8.6.8, Table 73). + SetFillRgb, + + /// K: set DeviceCMYK and a stroking colour (§8.6.8, Table 73). + SetStrokeCmyk, + + /// k: set DeviceCMYK and a non-stroking colour (§8.6.8, Table 73). + SetFillCmyk, + + /// sh: paint a shading (§8.7.4.2, Table 76). + PaintShading, + + /// BI: an inline image; its dictionary is the operand and its data travels with the operator (§8.9.7, Table 90). + BeginInlineImage, + + /// ID: begin inline image data; only reported when it appears outside an inline image (§8.9.7, Table 90). + BeginInlineImageData, + + /// EI: end an inline image; only reported when it appears outside an inline image (§8.9.7, Table 90). + EndInlineImage, + + /// Do: paint an external object (§8.8, Table 86). + PaintXObject, + + /// MP: a marked-content point (§14.6, Table 352). + MarkPoint, + + /// DP: a marked-content point with a property list (§14.6, Table 352). + MarkPointWithProperties, + + /// BMC: begin a marked-content sequence (§14.6, Table 352). + BeginMarkedContent, + + /// BDC: begin a marked-content sequence with a property list (§14.6, Table 352). + BeginMarkedContentWithProperties, + + /// EMC: end a marked-content sequence (§14.6, Table 352). + EndMarkedContent, + + /// BX: begin a compatibility section (§7.8.2, Table 33). + BeginCompatibility, + + /// EX: end a compatibility section (§7.8.2, Table 33). + EndCompatibility, +} diff --git a/src/Broadside/Content/ContentOptions.cs b/src/Broadside/Content/ContentOptions.cs new file mode 100644 index 00000000..7280a881 --- /dev/null +++ b/src/Broadside/Content/ContentOptions.cs @@ -0,0 +1,112 @@ +namespace Broadside.Content; + +/// Limits and cancellation for one content run, set fluently with With* methods. +/// +/// ISO 32000-2 §7.8.2 and §8.4.2 set no limits; these protect against malformed and hostile content. Reaching a limit is a +/// diagnostic, never an exception, in lenient mode. +/// +public sealed class ContentOptions +{ + /// The default of : 65,536. + public const int DefaultMaxOperands = 1 << 16; + + /// The default of : 4,096. + public const int DefaultMaxSaveDepth = 4096; + + /// The default of : 50. + public const int DefaultMaxNestingDepth = 50; + + private int _maxOperands = DefaultMaxOperands; + private int _maxSaveDepth = DefaultMaxSaveDepth; + private int _maxNestingDepth = DefaultMaxNestingDepth; + + /// + /// Gets or sets the most operands held for one operator, the elements of array and dictionary operands included. When more are + /// written, the oldest are dropped with a diagnostic. Default 65,536. + /// + /// ISO 32000-2 §7.8.2. + /// The value is less than 16. + public int MaxOperands + { + get => _maxOperands; + set + { + ArgumentOutOfRangeException.ThrowIfLessThan(value, 16); + _maxOperands = value; + } + } + + /// + /// Gets or sets the deepest the graphics state stack may grow; a q beyond it is ignored with a diagnostic, as is its + /// matching Q. Default 4,096. + /// + /// ISO 32000-2 §8.4.2. + /// The value is not positive. + public int MaxSaveDepth + { + get => _maxSaveDepth; + set + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); + _maxSaveDepth = value; + } + } + + /// + /// Gets or sets the deepest content streams may nest: form XObjects, tiling patterns, Type 3 glyphs, soft masks and + /// appearances share one budget. Default 50. + /// + /// ISO 32000-2 §8.10.1, §8.7.3, §9.6.4, §11.6.5. + /// The value is not positive. + public int MaxNestingDepth + { + get => _maxNestingDepth; + set + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(value); + _maxNestingDepth = value; + } + } + + /// Gets or sets the token that cancels the run; it is checked every 1,024 operators and at every nested run. + public CancellationToken CancellationToken { get; set; } + + /// Sets . + /// The limit, at least 16. + /// These options. + /// is less than 16. + public ContentOptions WithMaxOperands(int maxOperands) + { + MaxOperands = maxOperands; + return this; + } + + /// Sets . + /// The limit, positive. + /// These options. + /// is not positive. + public ContentOptions WithMaxSaveDepth(int maxSaveDepth) + { + MaxSaveDepth = maxSaveDepth; + return this; + } + + /// Sets . + /// The limit, positive. + /// These options. + /// is not positive. + public ContentOptions WithMaxNestingDepth(int maxNestingDepth) + { + MaxNestingDepth = maxNestingDepth; + return this; + } + + /// Sets . + /// The token. + /// These options. + public ContentOptions WithCancellation(CancellationToken cancellationToken) + { + CancellationToken = cancellationToken; + return this; + } +} diff --git a/src/Broadside/Content/ContentProcessor.cs b/src/Broadside/Content/ContentProcessor.cs new file mode 100644 index 00000000..96cb12ef --- /dev/null +++ b/src/Broadside/Content/ContentProcessor.cs @@ -0,0 +1,171 @@ +namespace Broadside.Content; + +/// +/// A consumer of interpreted content: the one content interpreter runs a content stream through its graphics-state machine and +/// calls these methods, so every consumer (renderer, text extractor, layout detector, editor) sees the same events computed once. +/// Override what you need; every method does nothing by default. +/// +/// +/// +/// ISO 32000-2 §7.8.2 (content streams), §8.2 (graphics objects), §8.4 (graphics state), §8.5 (paths and clipping), §9.4 (text +/// objects), §8.8 to §8.10 (XObjects and images), §8.7 (shadings), §14.6 (marked content). Geometry is device independent: paths in +/// user space with holding the CTM to the run's default user space. +/// +/// +/// Payloads are passed by reference and are views valid only during the call; the context and its state likewise. A processor +/// copies what it keeps. Calls come from one thread; a processor may run nested content through the context during a call. +/// Several processors share one run through . +/// +/// +/// Which events are reported today: runs, operators, the state stack, paths, clips and text object boundaries (issue #55). Glyphs, +/// images, forms and marked content come with issue #56, shadings with #79; their methods and payloads are declared now so that +/// processors written today keep working. +/// +/// +public abstract class ContentProcessor +{ + /// Gets the events this processor wants; read once at the start of each run. Default: . + public virtual ContentEvents Events => ContentEvents.All; + + /// Called when a run starts, before the first operator. + /// The run. + public virtual void BeginRun(ContentContext context) + { + } + + /// Called when a run ends, after the implicit restores that close unbalanced q operators. + /// The run. + public virtual void EndRun(ContentContext context) + { + } + + /// Called for every operator, before it executes (). + /// The operator, its operands and its source range. + /// The run. + /// ISO 32000-2 §7.8.2. + public virtual void VisitOperator(in ContentOperator op, ContentContext context) + { + } + + /// Called after the state is pushed: by q, and implicitly when a nested stream starts (). + /// The run; its state is the new top, equal to the one saved. + /// ISO 32000-2 §8.4.2. + public virtual void SaveState(ContentContext context) + { + } + + /// Called after the state is popped: by Q, and implicitly at the end of a stream with unbalanced q (). + /// The run; its state is the restored one. + /// ISO 32000-2 §8.4.2. + public virtual void RestoreState(ContentContext context) + { + } + + /// Called when a path object is painted, or ended with n (). + /// The path and how it is painted. + /// The run; its state is the one the path is painted with. + /// ISO 32000-2 §8.5.3, Table 59. + public virtual void PaintPath(in PathEvent path, ContentContext context) + { + } + + /// Called when the clipping path narrows: after the paint that ends a path object with W or W*, at ET for text clips (). + /// The new clip node. + /// The run; its state already holds the new clip. + /// ISO 32000-2 §8.5.4, §9.3.6. + public virtual void IntersectClip(in ClipEvent clip, ContentContext context) + { + } + + /// Called at BT (). + /// The run. + /// ISO 32000-2 §9.4.1, Table 105. + public virtual void BeginText(ContentContext context) + { + } + + /// Called for every glyph shown (). + /// The glyph and its placement. + /// The run. + /// ISO 32000-2 §9.4.3, Table 107. + public virtual void ShowGlyph(in GlyphEvent glyph, ContentContext context) + { + } + + /// Called at ET, before a text clip it sets (). + /// The run. + /// ISO 32000-2 §9.4.1, Table 105. + public virtual void EndText(ContentContext context) + { + } + + /// Called for an image XObject painted by Do and for an inline image (). + /// The image. + /// The run. + /// ISO 32000-2 §8.9. + public virtual void PaintImage(in ImageEvent image, ContentContext context) + { + } + + /// Called for sh (). + /// The shading. + /// The run. + /// ISO 32000-2 §8.7.4.2, Table 76. + public virtual void PaintShading(in ShadingEvent shading, ContentContext context) + { + } + + /// Called when a form XObject's content is about to run (). + /// The form. + /// The run, with the state in effect at Do. + /// to receive the form's events; not to. + /// ISO 32000-2 §8.10.1. + public virtual ContentVisit BeginForm(in FormEvent form, ContentContext context) => ContentVisit.Enter; + + /// Called when a form XObject's content has run, for a form whose returned . + /// The form. + /// The run. + /// ISO 32000-2 §8.10.1. + public virtual void EndForm(in FormEvent form, ContentContext context) + { + } + + /// Called before a Type 3 glyph's procedure runs (). Default: . + /// The glyph. + /// The run. + /// to receive the procedure's events. + /// ISO 32000-2 §9.6.4. + public virtual ContentVisit BeginType3Glyph(in GlyphEvent glyph, ContentContext context) => ContentVisit.Skip; + + /// Called after a Type 3 glyph's procedure ran, for a glyph whose returned . + /// The glyph. + /// The run. + /// ISO 32000-2 §9.6.4. + public virtual void EndType3Glyph(in GlyphEvent glyph, ContentContext context) + { + } + + /// Called at BMC and BDC (). + /// The sequence. + /// The run. + /// ISO 32000-2 §14.6, Table 352. + public virtual void BeginMarkedContent(in MarkedContentEvent mc, ContentContext context) + { + } + + /// Called at EMC, and implicitly for sequences still open at the end of a stream (). + /// The sequence that ends. + /// The run. + /// ISO 32000-2 §14.6, Table 352. + public virtual void EndMarkedContent(in MarkedContentEvent mc, ContentContext context) + { + } + + /// Called at MP and DP (). + /// The point. + /// The run. + /// ISO 32000-2 §14.6, Table 352. + public virtual void MarkedContentPoint(in MarkedContentEvent mc, ContentContext context) + { + } +} diff --git a/src/Broadside/Content/ContentReader.cs b/src/Broadside/Content/ContentReader.cs new file mode 100644 index 00000000..326c079e --- /dev/null +++ b/src/Broadside/Content/ContentReader.cs @@ -0,0 +1,567 @@ +using System.Buffers; +using System.Globalization; +using Broadside.Objects; + +namespace Broadside.Content; + +/// Deviations the repaired while reading the last operator; the interpreter reports them. +[Flags] +internal enum ReaderIssues +{ + None = 0, + + /// A keyword that is not an operator was split into operators and numbers written without white-space between them. + GluedTokens = 1, + + /// A token that cannot appear here (a lone ) or >, an unbalanced ] or >>, a malformed number, string or name) was skipped or repaired. + SyntaxInvalid = 2, + + /// An array or dictionary operand was still open when an operator came; it was closed there. + ContainerUnclosed = 4, + + /// An inline image had no ID or no EI, or a dictionary entry that is not a value. + InlineImageInvalid = 8, +} + +/// One operator read by , with byte ranges in the content (its operands are in the arena). +/// The operator. +/// The offset of its first operand, or of the keyword when it has none. +/// The offset of the keyword. +/// The length of the keyword. +/// The offset one past the operator: past the keyword, or past EI for an inline image. +/// For an inline image, the offset of its data. +/// For an inline image, the length of its data. +internal readonly record struct ReadOperator(ContentOperatorCode Code, int Start, int KeywordStart, int KeywordLength, int End, int DataStart = 0, int DataLength = 0); + +/// +/// Reads a decoded content stream as a sequence of operators, each preceded by its operands in an , without +/// allocating: no object per operand, no string per keyword. +/// +/// +/// +/// ISO 32000-2 §7.8.2: content is PDF object syntax (§7.2, §7.3) in postfix order. Tokens come from ; numbers +/// are read leniently as the object parser reads them (--5, 5., 1.2.3). +/// +/// +/// A keyword that is not an operator but splits completely into operators and numbers (q1, Qq, 0cm, +/// BTq) is read as those tokens, as other readers do; any other keyword is an unknown operator. An inline image +/// (§8.9.7) is read whole: BI, its dictionary as one dictionary operand, and the data between ID and EI as +/// a byte range that is never tokenized. The end of the data is found from the dictionary's L/Length when it points +/// at EI, else by looking for EI between white-space followed by text that is not binary. +/// +/// +internal ref struct ContentReader +{ + private const int MaxGluedLength = 32; + private const int InlineImageLookahead = 64; + + private static readonly SearchValues Whitespace = SearchValues.Create("\0\t\n\f\r "u8); + private static readonly SearchValues NumberCharacters = SearchValues.Create("+-.0123456789"u8); + + private readonly OperandArena _arena; + private CosLexer _lexer; + + public ContentReader(ReadOnlySpan source, OperandArena arena) + { + _lexer = new CosLexer(source); + _arena = arena; + } + + /// Gets the deviations repaired since they were last cleared. + public ReaderIssues Issues { get; private set; } + + /// Gets the offset of the first deviation since they were last cleared. + public int IssueOffset { get; private set; } + + /// Gets the content. + public readonly ReadOnlySpan Source => _lexer.Source; + + /// Forgets the recorded deviations. + public void ClearIssues() => Issues = ReaderIssues.None; + + /// + /// Reads operands into the arena up to the next operator. Returns false at the end of the content, leaving any operands read + /// since the last operator in the arena. + /// + public bool Next(out ReadOperator op) + { + int first = -1; + while (true) + { + CosToken token = _lexer.Next(); + if (token.Kind == CosTokenKind.EndOfInput) + { + op = default; + return false; + } + + if (first < 0 || _arena.Count == 0 && _arena.OpenDepth == 0) + { + first = token.Start; + } + + if (token.Kind != CosTokenKind.Keyword) + { + AddOperand(token); + continue; + } + + ReadOnlySpan keyword = Bytes(token); + if (TryAddKeywordValue(keyword)) + { + continue; + } + + int length = keyword.Length; + ContentOperatorCode code = OperatorTable.Lookup(keyword); + if (code == ContentOperatorCode.Unknown && SplitGlued(keyword) is > 0 and var piece) + { + Issue(ReaderIssues.GluedTokens, token.Start); + _lexer.Position = token.Start + piece; + if (NumberCharacters.Contains(keyword[0])) + { + AddNumber(keyword[..piece], token.Start); + continue; + } + + length = piece; + code = OperatorTable.Lookup(keyword[..piece]); + } + + if (_arena.OpenDepth > 0) + { + if (code == ContentOperatorCode.Unknown) + { + // A stray keyword inside an array or dictionary operand: not a value, so it is skipped. + Issue(ReaderIssues.SyntaxInvalid, token.Start); + continue; + } + + _arena.CloseAll(); + Issue(ReaderIssues.ContainerUnclosed, token.Start); + } + + if (code == ContentOperatorCode.BeginInlineImage) + { + op = ReadInlineImage(first, token.Start); + return true; + } + + op = new ReadOperator(code, first, token.Start, length, token.Start + length); + return true; + } + } + + /// + /// Finds where the data of an inline image ends, as the offset of its EI: the first EI after + /// with white-space before it and white-space or the end after it, followed by text that is not binary. -1 when there is none. + /// + /// ISO 32000-2 §8.9.7. The same heuristic as pdf.js (findDefaultInlineStreamEnd), for data without a usable L. + internal static int FindInlineImageEnd(ReadOnlySpan source, int start) + { + int position = start; + while (position < source.Length) + { + int found = source[position..].IndexOf("EI"u8); + if (found < 0) + { + return -1; + } + + int candidate = position + found; + position = candidate + 1; + bool before = candidate == start || CosLexer.IsWhitespace(source[candidate - 1]); + bool after = candidate + 2 == source.Length || CosLexer.IsWhitespace(source[candidate + 2]); + if (before && after && !LooksBinary(source.Slice(candidate + 2, Math.Min(InlineImageLookahead, source.Length - candidate - 2)))) + { + return candidate; + } + } + + return -1; + } + + /// + /// For a keyword that is not an operator: the length of its first piece when the whole keyword splits into known operators and + /// numbers (longest operator first), else 0. + /// + private static int SplitGlued(ReadOnlySpan keyword) + { + if (keyword.Length > MaxGluedLength) + { + return 0; + } + + int first = 0; + int position = 0; + while (position < keyword.Length) + { + int piece = 0; + if (NumberCharacters.Contains(keyword[position])) + { + ReadOnlySpan rest = keyword[position..]; + int run = rest.IndexOfAnyExcept(NumberCharacters); + run = run < 0 ? rest.Length : run; + piece = rest[..run].ContainsAnyInRange((byte)'0', (byte)'9') ? run : 0; + } + else + { + for (int length = Math.Min(OperatorTable.MaxKeywordLength, keyword.Length - position); length > 0 && piece == 0; length--) + { + piece = OperatorTable.Lookup(keyword.Slice(position, length)) != ContentOperatorCode.Unknown ? length : 0; + } + } + + if (piece == 0) + { + return 0; + } + + first = first == 0 ? piece : first; + position += piece; + } + + return first; + } + + private static bool LooksBinary(ReadOnlySpan text) + { + foreach (byte value in text) + { + if (value is < 0x09 or (> 0x0D and < 0x20) or >= 0x7F) + { + return true; + } + } + + return false; + } + + private readonly ReadOnlySpan Bytes(CosToken token) => _lexer.Source.Slice(token.Start, token.Length); + + private void Issue(ReaderIssues issue, int offset) + { + if (Issues == ReaderIssues.None) + { + IssueOffset = offset; + } + + Issues |= issue; + } + + private readonly bool TryAddKeywordValue(ReadOnlySpan keyword) + { + if (keyword.SequenceEqual("true"u8) || keyword.SequenceEqual("false"u8)) + { + _arena.AddBoolean(keyword[0] == (byte)'t'); + return true; + } + + if (keyword.SequenceEqual("null"u8)) + { + _arena.AddNull(); + return true; + } + + return false; + } + + /// Adds a token that is not a keyword as an operand, or repairs it. + private void AddOperand(CosToken token) + { + switch (token.Kind) + { + case CosTokenKind.Integer or CosTokenKind.Real: + AddNumber(Bytes(token), token.Start); + break; + case CosTokenKind.LiteralString: + AddLiteralString(token); + break; + case CosTokenKind.HexString: + AddHexString(token); + break; + case CosTokenKind.Name: + AddName(token); + break; + case CosTokenKind.ArrayStart: + _arena.BeginContainer(ContentOperandKind.Array); + break; + case CosTokenKind.DictionaryStart: + _arena.BeginContainer(ContentOperandKind.Dictionary); + break; + case CosTokenKind.ArrayEnd: + if (!_arena.EndContainer(ContentOperandKind.Array)) + { + Issue(ReaderIssues.SyntaxInvalid, token.Start); + } + + break; + case CosTokenKind.DictionaryEnd: + if (!_arena.EndContainer(ContentOperandKind.Dictionary)) + { + Issue(ReaderIssues.SyntaxInvalid, token.Start); + } + + break; + default: + Issue(ReaderIssues.SyntaxInvalid, token.Start); + break; + } + } + + private void AddNumber(ReadOnlySpan text, int offset) + { + if (CosParser.TryParseStrictInteger(text, out long integer)) + { + _arena.AddNumber(integer, isInteger: true); + return; + } + + Span scratch = stackalloc byte[256]; + scoped ReadOnlySpan number = text; + if (!CosParser.IsWellFormedNumber(text)) + { + Issue(ReaderIssues.SyntaxInvalid, offset); + number = CosParser.WellFormedPrefix(text, scratch); + if (!number.Contains((byte)'.') && CosParser.TryParseStrictInteger(number, out integer)) + { + _arena.AddNumber(integer, isInteger: true); + return; + } + } + + double value = double.Parse(number, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); + if (!double.IsFinite(value)) + { + Issue(ReaderIssues.SyntaxInvalid, offset); + value = double.IsNegative(value) ? double.MinValue : double.MaxValue; + } + + // An integer too large for 64 bits reads as a real (Annex C). + _arena.AddNumber(value, isInteger: false); + } + + private void AddLiteralString(CosToken token) + { + ReadOnlySpan text = Bytes(token); + Span output = _arena.ReserveBytes(text.Length); + int written = 0; + int depth = 1; + int index = 1; + while (index < text.Length) + { + byte current = text[index]; + switch (current) + { + case (byte)'\\': + index = CosParser.ReadEscape(text, index, output, ref written); + continue; + case (byte)'(': + depth++; + break; + case (byte)')': + if (--depth == 0) + { + index = text.Length; + continue; + } + + break; + case (byte)'\r': + // §7.3.4.2: an unescaped end-of-line marker is read as a single LINE FEED. + current = (byte)'\n'; + if (index + 1 < text.Length && text[index + 1] == (byte)'\n') + { + index++; + } + + break; + } + + output[written++] = current; + index++; + } + + if (depth != 0) + { + Issue(ReaderIssues.SyntaxInvalid, token.Start); + } + + _arena.CommitBytes(ContentOperandKind.String, written); + } + + private void AddHexString(CosToken token) + { + ReadOnlySpan text = Bytes(token); + bool terminated = text.Length >= 2 && text[^1] == (byte)'>'; + ReadOnlySpan digits = terminated ? text[1..^1] : text[1..]; + Span output = _arena.ReserveBytes((digits.Length + 1) / 2); + int written = 0; + int high = -1; + foreach (byte character in digits) + { + int nibble = CosParser.HexValue(character); + if (nibble < 0) + { + if (!CosLexer.IsWhitespace(character)) + { + Issue(ReaderIssues.SyntaxInvalid, token.Start); + } + + continue; + } + + if (high < 0) + { + high = nibble; + } + else + { + output[written++] = (byte)((high << 4) | nibble); + high = -1; + } + } + + if (high >= 0) + { + // §7.3.4.3: a missing final digit is read as 0. + output[written++] = (byte)(high << 4); + } + + if (!terminated) + { + Issue(ReaderIssues.SyntaxInvalid, token.Start); + } + + _arena.CommitBytes(ContentOperandKind.String, written, hexadecimal: true); + } + + private void AddName(CosToken token) + { + ReadOnlySpan text = Bytes(token)[1..]; + Span output = _arena.ReserveBytes(text.Length); + int written = 0; + for (int index = 0; index < text.Length; index++) + { + byte current = text[index]; + if (current == (byte)'#') + { + int high = index + 1 < text.Length ? CosParser.HexValue(text[index + 1]) : -1; + int low = index + 2 < text.Length ? CosParser.HexValue(text[index + 2]) : -1; + if (high < 0 || low < 0) + { + Issue(ReaderIssues.SyntaxInvalid, token.Start); + } + else + { + index += 2; + current = (byte)((high << 4) | low); + if (current == 0) + { + Issue(ReaderIssues.SyntaxInvalid, token.Start); + continue; + } + } + } + + output[written++] = current; + } + + _arena.CommitBytes(ContentOperandKind.Name, written); + } + + /// Reads an inline image after its BI: the dictionary into the arena, then the data range up to EI. + private ReadOperator ReadInlineImage(int first, int keywordStart) + { + _arena.BeginContainer(ContentOperandKind.Dictionary); + while (true) + { + CosToken token = _lexer.Next(); + if (token.Kind == CosTokenKind.EndOfInput) + { + _arena.CloseAll(); + Issue(ReaderIssues.InlineImageInvalid, keywordStart); + return new ReadOperator(ContentOperatorCode.BeginInlineImage, first, keywordStart, 2, Source.Length); + } + + if (token.Kind != CosTokenKind.Keyword) + { + AddOperand(token); + continue; + } + + ReadOnlySpan keyword = Bytes(token); + if (TryAddKeywordValue(keyword)) + { + continue; + } + + _arena.CloseAll(); + if (!keyword.SequenceEqual("ID"u8)) + { + // Not a value and not ID: the image is abandoned here and the keyword is read again as the next operator. + Issue(ReaderIssues.InlineImageInvalid, token.Start); + _lexer.Position = token.Start; + return new ReadOperator(ContentOperatorCode.BeginInlineImage, first, keywordStart, 2, token.Start); + } + + break; + } + + ReadOnlySpan source = Source; + int dataStart = _lexer.Position; + if (dataStart < source.Length && CosLexer.IsWhitespace(source[dataStart])) + { + // §8.9.7: one white-space character separates ID from the data. + dataStart++; + } + + int end = DeclaredInlineImageEnd(source, dataStart, out int dataEnd); + if (end < 0) + { + end = FindInlineImageEnd(source, dataStart); + dataEnd = end > dataStart && CosLexer.IsWhitespace(source[end - 1]) ? end - 1 : end; + } + + if (end < 0) + { + Issue(ReaderIssues.InlineImageInvalid, keywordStart); + _lexer.Position = source.Length; + return new ReadOperator(ContentOperatorCode.BeginInlineImage, first, keywordStart, 2, source.Length, dataStart, source.Length - dataStart); + } + + _lexer.Position = end + 2; + return new ReadOperator(ContentOperatorCode.BeginInlineImage, first, keywordStart, 2, end + 2, dataStart, Math.Max(0, dataEnd - dataStart)); + } + + /// The offset of EI when the dictionary's L or Length leads to it (optional white-space between), else -1. + private readonly int DeclaredInlineImageEnd(ReadOnlySpan source, int dataStart, out int dataEnd) + { + dataEnd = -1; + if (_arena.Count == 0 || _arena.Last(1)[0].Kind != ContentOperandKind.Dictionary) + { + return -1; + } + + ContentOperands entries = _arena.Last(1)[0].Items; + for (int index = 0; index + 1 < entries.Count; index += 2) + { + ContentOperand key = entries[index]; + ContentOperand value = entries[index + 1]; + if ((key.IsName("L"u8) || key.IsName("Length"u8)) && value.Kind == ContentOperandKind.Integer && value.Number >= 0 + && value.Number <= source.Length - dataStart) + { + int position = dataStart + (int)value.Number; + int after = source[position..].IndexOfAnyExcept(Whitespace); + position = after < 0 ? source.Length : position + after; + if (source[position..].StartsWith("EI"u8) && (position + 2 == source.Length || !CosLexer.IsRegular(source[position + 2]))) + { + dataEnd = dataStart + (int)value.Number; + return position; + } + } + } + + return -1; + } +} diff --git a/src/Broadside/Content/ContentRunKind.cs b/src/Broadside/Content/ContentRunKind.cs new file mode 100644 index 00000000..138cec9a --- /dev/null +++ b/src/Broadside/Content/ContentRunKind.cs @@ -0,0 +1,27 @@ +namespace Broadside.Content; + +/// What kind of content stream a run, or a nested run inside it, interprets. +/// ISO 32000-2 §7.8.2: pages, forms, patterns, Type 3 glyphs and annotation appearances are all content streams. +public enum ContentRunKind +{ + /// A page's Contents (§7.7.3.3, Table 31). + Page, + + /// A form XObject (§8.10). + Form, + + /// A transparency group XObject (§11.6.6). + Group, + + /// A tiling pattern's cell (§8.7.3). + Pattern, + + /// A Type 3 glyph procedure (§9.6.4). + Type3Glyph, + + /// A soft mask's group (§11.6.5.2). + SoftMask, + + /// An annotation's appearance stream (§12.5.5). + Appearance, +} diff --git a/src/Broadside/Content/ContentVisit.cs b/src/Broadside/Content/ContentVisit.cs new file mode 100644 index 00000000..2dfcbc27 --- /dev/null +++ b/src/Broadside/Content/ContentVisit.cs @@ -0,0 +1,15 @@ +namespace Broadside.Content; + +/// What a processor wants done with a nested content stream (a form XObject or a Type 3 glyph procedure) it is offered. +/// +/// ISO 32000-2 §8.10 and §9.6.4. A processor that caches a form as a unit answers and runs the form itself +/// through the run context when it needs it. +/// +public enum ContentVisit +{ + /// Interpret the nested stream and report its events. + Enter, + + /// Do not report the nested stream's events to this processor. + Skip, +} diff --git a/src/Broadside/Content/FormEvent.cs b/src/Broadside/Content/FormEvent.cs new file mode 100644 index 00000000..66d39d9b --- /dev/null +++ b/src/Broadside/Content/FormEvent.cs @@ -0,0 +1,51 @@ +using Broadside.Graphics; +using Broadside.Objects; + +namespace Broadside.Content; + +/// +/// A form XObject painted by Do, reported when its content is entered and again when it is left. Valid only during the +/// callback that received it. +/// +/// +/// ISO 32000-2 §8.10.1, Table 93: Do saves the state, concatenates to the CTM, clips to +/// , paints the form's content and restores the state. For a transparency group (§11.6.6) the compositing +/// parameters in effect at Do (blend mode, alpha, soft mask) are those of during +/// . Declared with the content interpreter's processor surface (issue #55); reported from +/// issue #56. Members are added, never changed. +/// +public readonly ref struct FormEvent +{ + /// Gets the form XObject's stream. + public CosStream? Stream { get; internal init; } + + /// Gets the reference to the form XObject, when it is an indirect object. + public CosReference? Reference { get; internal init; } + + /// Gets the resource name Do used. + public ReadOnlySpan ResourceName { get; internal init; } + + /// Gets the form matrix: form space to the user space at Do (identity when absent). + public Matrix Matrix { get; internal init; } + + /// Gets the bounding box in form space, the form's clip. + public PdfRectangle BoundingBox { get; internal init; } + + /// Gets the group attributes dictionary (§8.10.3, Table 94), or . + public CosDictionary? Group { get; internal init; } + + /// Gets the reference dictionary of a reference XObject (§8.10.4, Table 95), or . + public CosDictionary? ReferenceDictionary { get; internal init; } + + /// Gets the resources the form's content uses: its own, or those it inherits (§7.8.3). + public CosDictionary? Resources { get; internal init; } + + /// Gets the form's StructParent (§14.7.5.4), or . + public int? StructParent { get; internal init; } + + /// Gets the form's StructParents (§14.7.5.4), or : marked-content identifiers inside the form resolve through it. + public int? StructParents { get; internal init; } + + /// Gets the nesting depth of the form's run. + public int Depth { get; internal init; } +} diff --git a/src/Broadside/Content/GlyphEvent.cs b/src/Broadside/Content/GlyphEvent.cs new file mode 100644 index 00000000..2968de86 --- /dev/null +++ b/src/Broadside/Content/GlyphEvent.cs @@ -0,0 +1,70 @@ +using Broadside.Graphics; +using Broadside.Objects; + +namespace Broadside.Content; + +/// +/// One glyph shown by a text-showing operator, with everything needed to place it: the single source of glyph positions for +/// rendering, extraction and hit testing. Valid only during the callback that received it. +/// +/// +/// +/// ISO 32000-2 §9.4.3 (Table 107) and §9.4.4. The glyph is drawn in text space mapped by and then +/// : T_rm = [T_fs·T_h 0 0 T_fs 0 T_rise] × T_m × CTM. +/// +/// +/// Declared with the content interpreter's processor surface (issue #55); text showing reports it from issue #56, which adds the +/// resolved font. Members are added, never changed. +/// +/// +public readonly ref struct GlyphEvent +{ + /// Gets the font dictionary named by Tf. + /// ISO 32000-2 §9.5, Table 109. + public CosDictionary? FontDictionary { get; internal init; } + + /// Gets the character code (§9.4.3): one byte for a simple font, one to four for a composite font's CMap. + public uint CharacterCode { get; internal init; } + + /// Gets the bytes of the string the code was read from. + public ReadOnlySpan SourceBytes { get; internal init; } + + /// Gets the offset of the code's first byte in . + public int SourceIndex { get; internal init; } + + /// Gets the number of bytes the code takes. + public int CodeLength { get; internal init; } + + /// Gets the matrix from text space to user space for this glyph: [T_fs·T_h 0 0 T_fs 0 T_rise] × T_m. + public Matrix TextMatrix { get; internal init; } + + /// Gets the CTM. + public Matrix Ctm { get; internal init; } + + /// Gets the glyph's horizontal displacement w0, in text space units (§9.2.4). + public double HorizontalDisplacement { get; internal init; } + + /// Gets the glyph's vertical displacement w1, in text space units (§9.2.4). + public double VerticalDisplacement { get; internal init; } + + /// Gets the horizontal advance t_x applied to the text matrix after the glyph, spacing included (§9.4.4). + public double AdvanceX { get; internal init; } + + /// Gets the vertical advance t_y applied to the text matrix after the glyph, spacing included (§9.4.4). + public double AdvanceY { get; internal init; } + + /// Gets the TJ number that came right before the glyph, in thousandths of text space units; 0 when none (§9.4.3). + public double Adjustment { get; internal init; } + + /// Gets a value indicating whether word spacing was applied (a single-byte code 32, §9.3.3). + public bool WordSpacingApplied { get; internal init; } + + /// Gets a value indicating whether the font writes vertically (§9.7.4.3). + public bool IsVertical { get; internal init; } + + /// Gets the text rendering mode (§9.3.6). + public TextRenderingMode RenderingMode { get; internal init; } + + /// Gets a value indicating whether optional content hides the glyph (§8.11.3.1). + public bool IsHidden { get; internal init; } +} diff --git a/src/Broadside/Content/ImageEvent.cs b/src/Broadside/Content/ImageEvent.cs new file mode 100644 index 00000000..340f9adb --- /dev/null +++ b/src/Broadside/Content/ImageEvent.cs @@ -0,0 +1,46 @@ +using Broadside.Graphics; +using Broadside.Objects; + +namespace Broadside.Content; + +/// +/// An image painted into the unit square of user space: an image XObject through Do, or an inline image. Valid only during +/// the callback. +/// +/// +/// ISO 32000-2 §8.9.4 (image space maps to the unit square, then the CTM), §8.9.5 (image XObjects), §8.9.7 (inline images). +/// Declared with the content interpreter's processor surface (issue #55); reported from issue #56, with the decoded image model of +/// issue #60. Members are added, never changed. +/// +public readonly ref struct ImageEvent +{ + /// Gets the image XObject's stream, or for an inline image. + public CosStream? Stream { get; internal init; } + + /// Gets the reference to the image XObject, when it is an indirect object. + public CosReference? Reference { get; internal init; } + + /// Gets the resource name Do used; empty for an inline image. + public ReadOnlySpan ResourceName { get; internal init; } + + /// Gets a value indicating whether this is an inline image. + public bool IsInline { get; internal init; } + + /// Gets an inline image's dictionary as written (abbreviated keys included); default for an image XObject. + public ContentOperand InlineDictionary { get; internal init; } + + /// Gets an inline image's data, still encoded; empty for an image XObject. + public ReadOnlySpan InlineData { get; internal init; } + + /// Gets a value indicating whether the image is a stencil mask painted with the fill colour (§8.9.6.2). + public bool IsStencil { get; internal init; } + + /// Gets the CTM: the unit square in user space maps through it. + public Matrix Ctm { get; internal init; } + + /// Gets the image's StructParent (§14.7.5.4), or . + public int? StructParent { get; internal init; } + + /// Gets a value indicating whether optional content hides the image (§8.11.3.1). + public bool IsHidden { get; internal init; } +} diff --git a/src/Broadside/Content/MarkedContentEvent.cs b/src/Broadside/Content/MarkedContentEvent.cs new file mode 100644 index 00000000..4ce5004a --- /dev/null +++ b/src/Broadside/Content/MarkedContentEvent.cs @@ -0,0 +1,33 @@ +using Broadside.Objects; + +namespace Broadside.Content; + +/// +/// A marked-content point (MP, DP) or the beginning or end of a marked-content sequence (BMC, BDC, +/// EMC). Valid only during the callback that received it. +/// +/// +/// ISO 32000-2 §14.6, Table 352. The property list is either inline () or named in the resources' +/// Properties subdictionary (). Declared with the content interpreter's processor surface +/// (issue #55); reported from issue #56. Members are added, never changed. +/// +public readonly ref struct MarkedContentEvent +{ + /// Gets the tag, a name's bytes without the solidus. + public ReadOnlySpan Tag { get; internal init; } + + /// Gets an inline property list (§14.6.2) as written; default when there is none or it is named. + public ContentOperand InlineProperties { get; internal init; } + + /// Gets the property list named in the resources, resolved, or . + public CosDictionary? Properties { get; internal init; } + + /// Gets the marked-content identifier MCID (§14.7.5.2), or . + public int? Mcid { get; internal init; } + + /// Gets the nesting depth of the sequence, 1 for the outermost. + public int Depth { get; internal init; } + + /// Gets a value indicating whether optional content hides the sequence (§8.11.3.1). + public bool IsHidden { get; internal init; } +} diff --git a/src/Broadside/Content/OperandArena.cs b/src/Broadside/Content/OperandArena.cs new file mode 100644 index 00000000..d84578cc --- /dev/null +++ b/src/Broadside/Content/OperandArena.cs @@ -0,0 +1,249 @@ +using System.Buffers; + +namespace Broadside.Content; + +/// One operand or container element in the , in parse order. +internal struct OperandEntry +{ + /// The kind. + public ContentOperandKind Kind; + + /// Whether a string was written in hexadecimal. + public bool IsHexadecimal; + + /// The value of a number, or 1/0 for a boolean. + public double Number; + + /// The offset of a name's or string's decoded bytes in the arena's byte buffer. + public int BytesStart; + + /// The length of a name's or string's decoded bytes. + public int BytesLength; + + /// The number of direct elements of an array or dictionary. + public int Count; + + /// The index one past the entry and everything it contains: the next sibling. + public int End; +} + +/// +/// The operands read since the last operator, held flat and without objects: numbers inline, names and strings as decoded byte +/// ranges in one buffer, arrays and dictionaries as entry ranges. Pooled buffers grow when needed and are reused, so reading +/// operands allocates nothing once warmed up. +/// +/// ISO 32000-2 §7.8.2: operands precede their operator; none are left over when it has executed. +internal sealed class OperandArena +{ + private OperandEntry[] _entries = ArrayPool.Shared.Rent(64); + private int[] _topLevel = ArrayPool.Shared.Rent(16); + private byte[] _bytes = ArrayPool.Shared.Rent(256); + private int[] _open = ArrayPool.Shared.Rent(8); + private int _count; + private int _topCount; + private int _byteCount; + private int _depth; + private int _droppedDepth; + + /// Gets or sets the most entries (operands and container elements together) held before older ones are dropped. + public int Limit { get; set; } = ContentOptions.DefaultMaxOperands; + + /// Gets the number of top-level operands. + public int Count => _topCount; + + /// Gets the nesting depth of arrays and dictionaries still open. + public int OpenDepth => _depth; + + /// Gets a value indicating whether the innermost open container is a dictionary. + public bool InDictionary => _depth > 0 && _entries[_open[_depth - 1]].Kind == ContentOperandKind.Dictionary; + + /// Gets or sets a value indicating whether operands were dropped because was reached. + public bool Overflowed { get; set; } + + /// Gets all top-level operands. + public ContentOperands Operands => new(_entries.AsSpan(0, _count), _bytes.AsSpan(0, _byteCount), _topLevel.AsSpan(0, _topCount)); + + /// Gets the last top-level operands. + public ContentOperands Last(int count) => + new(_entries.AsSpan(0, _count), _bytes.AsSpan(0, _byteCount), _topLevel.AsSpan(_topCount - count, count)); + + /// Drops every operand. + public void Clear() + { + _count = 0; + _topCount = 0; + _byteCount = 0; + _depth = 0; + _droppedDepth = 0; + } + + /// Gives oversized buffers back to the pool, after a run that needed them. + public void Trim() + { + Clear(); + Shrink(ref _entries, 4096, 64); + Shrink(ref _topLevel, 4096, 16); + Shrink(ref _bytes, 1 << 16, 256); + } + + /// Adds a number. + public void AddNumber(double value, bool isInteger) => + Add(new OperandEntry { Kind = isInteger ? ContentOperandKind.Integer : ContentOperandKind.Real, Number = value }); + + /// Adds a boolean. + public void AddBoolean(bool value) => Add(new OperandEntry { Kind = ContentOperandKind.Boolean, Number = value ? 1 : 0 }); + + /// Adds the null object. + public void AddNull() => Add(new OperandEntry { Kind = ContentOperandKind.Null }); + + /// Returns room for at least decoded bytes of a name or string; commit with . + public Span ReserveBytes(int length) + { + if (_bytes.Length - _byteCount < length) + { + Grow(ref _bytes, _byteCount, _byteCount + length); + } + + return _bytes.AsSpan(_byteCount); + } + + /// Adds a name or string whose decoded bytes were written into . + public void CommitBytes(ContentOperandKind kind, int length, bool hexadecimal = false) + { + int written = _byteCount; + if (!MakeRoom()) + { + return; + } + + if (_byteCount != written) + { + // The pending operands were dropped to make room: move the new bytes to the start of the emptied buffer. + _bytes.AsSpan(written, length).CopyTo(_bytes); + } + + Add(new OperandEntry { Kind = kind, BytesStart = _byteCount, BytesLength = length, IsHexadecimal = hexadecimal }); + _byteCount += length; + } + + /// Opens an array or dictionary; later entries are its elements until . + public void BeginContainer(ContentOperandKind kind) + { + if (_droppedDepth > 0 || !Add(new OperandEntry { Kind = kind })) + { + _droppedDepth++; + return; + } + + if (_depth == _open.Length) + { + Grow(ref _open, _depth, _depth * 2); + } + + _open[_depth++] = _count - 1; + } + + /// Closes the innermost open container if it is of ; returns false, changing nothing, if it is not. + public bool EndContainer(ContentOperandKind kind) + { + if (_droppedDepth > 0) + { + _droppedDepth--; + return true; + } + + if (_depth == 0 || _entries[_open[_depth - 1]].Kind != kind) + { + return false; + } + + _entries[_open[--_depth]].End = _count; + return true; + } + + /// Closes every open container; returns false when there was none. + public bool CloseAll() + { + bool any = _depth > 0 || _droppedDepth > 0; + while (_depth > 0) + { + _entries[_open[--_depth]].End = _count; + } + + _droppedDepth = 0; + return any; + } + + private static void Grow(ref T[] array, int used, int minimum) + { + T[] larger = ArrayPool.Shared.Rent(Math.Max(minimum, array.Length * 2)); + array.AsSpan(0, used).CopyTo(larger); + ArrayPool.Shared.Return(array); + array = larger; + } + + private static void Shrink(ref T[] array, int threshold, int size) + { + if (array.Length > threshold) + { + ArrayPool.Shared.Return(array); + array = ArrayPool.Shared.Rent(size); + } + } + + /// Makes room for one entry; false when there is none because the arena is full inside a container. + private bool MakeRoom() + { + if (_droppedDepth > 0) + { + return false; + } + + if (_count >= Limit) + { + Overflowed = true; + if (_depth > 0) + { + return false; + } + + // At the top level the oldest operands go: all those pending are dropped, so the operator that follows gets the newest. + Clear(); + } + + return true; + } + + /// Adds an entry; false when it was dropped because the arena is full inside a container. + private bool Add(OperandEntry entry) + { + if (!MakeRoom()) + { + return false; + } + + if (_count == _entries.Length) + { + Grow(ref _entries, _count, _count * 2); + } + + int index = _count++; + entry.End = _count; + _entries[index] = entry; + if (_depth == 0) + { + if (_topCount == _topLevel.Length) + { + Grow(ref _topLevel, _topCount, _topCount * 2); + } + + _topLevel[_topCount++] = index; + } + else + { + _entries[_open[_depth - 1]].Count++; + } + + return true; + } +} diff --git a/src/Broadside/Content/OperatorTable.cs b/src/Broadside/Content/OperatorTable.cs new file mode 100644 index 00000000..d2131240 --- /dev/null +++ b/src/Broadside/Content/OperatorTable.cs @@ -0,0 +1,276 @@ +namespace Broadside.Content; + +/// The category of an operator, as Table 50 groups them; Figure 9 says in which context each category may appear. +/// ISO 32000-2 §8.2, Table 50 and Figure 9 (2020 edition: q and Q are general graphics state operators). +internal enum OperatorCategory : byte +{ + Unknown, + GeneralGraphicsState, + SpecialGraphicsState, + PathConstruction, + PathPainting, + ClippingPath, + TextObject, + TextState, + TextPositioning, + TextShowing, + Type3Font, + Color, + Shading, + InlineImage, + XObject, + MarkedContent, + Compatibility, +} + +/// +/// What an operator takes: a fixed list of operand kinds, or a variable count (the colour operators). Kinds: n number, +/// N name, s string, a array, d dictionary, D dictionary or name. +/// +internal readonly ref struct OperandSignature(ReadOnlySpan kinds, bool variable) +{ + /// Gets the operand kinds, in order; for a variable signature, the kinds every operand may have. + public ReadOnlySpan Kinds { get; } = kinds; + + /// Gets a value indicating whether the count varies: SC, sc (numbers), SCN, scn (numbers, then optionally a name). + public bool IsVariable { get; } = variable; +} + +/// +/// The operator keywords of Annex A, Table A.1: lookup from bytes without creating a string, the keyword of each operator, its +/// operands and its category. +/// +/// ISO 32000-2 Annex A and the clause tables 33, 56, 58-60, 73, 76, 86, 90, 103, 105-107, 111 and 352. +internal static class OperatorTable +{ + /// The longest operator keyword. + public const int MaxKeywordLength = 3; + + /// Returns the operator named by , or . + public static ContentOperatorCode Lookup(ReadOnlySpan keyword) => keyword.Length switch + { + 1 => One((char)keyword[0]), + 2 => Two((char)keyword[0], (char)keyword[1]), + 3 => Three((char)keyword[0], (char)keyword[1], (char)keyword[2]), + _ => ContentOperatorCode.Unknown, + }; + + /// Returns the keyword of ; empty for . + public static ReadOnlySpan Keyword(ContentOperatorCode code) => code switch + { + ContentOperatorCode.SaveState => "q"u8, + ContentOperatorCode.RestoreState => "Q"u8, + ContentOperatorCode.ConcatenateMatrix => "cm"u8, + ContentOperatorCode.SetLineWidth => "w"u8, + ContentOperatorCode.SetLineCap => "J"u8, + ContentOperatorCode.SetLineJoin => "j"u8, + ContentOperatorCode.SetMiterLimit => "M"u8, + ContentOperatorCode.SetDash => "d"u8, + ContentOperatorCode.SetRenderingIntent => "ri"u8, + ContentOperatorCode.SetFlatness => "i"u8, + ContentOperatorCode.SetGraphicsStateParameters => "gs"u8, + ContentOperatorCode.MoveTo => "m"u8, + ContentOperatorCode.LineTo => "l"u8, + ContentOperatorCode.CurveTo => "c"u8, + ContentOperatorCode.CurveToInitialPointReplicated => "v"u8, + ContentOperatorCode.CurveToFinalPointReplicated => "y"u8, + ContentOperatorCode.ClosePath => "h"u8, + ContentOperatorCode.Rectangle => "re"u8, + ContentOperatorCode.Stroke => "S"u8, + ContentOperatorCode.CloseAndStroke => "s"u8, + ContentOperatorCode.Fill => "f"u8, + ContentOperatorCode.FillObsolete => "F"u8, + ContentOperatorCode.FillEvenOdd => "f*"u8, + ContentOperatorCode.FillAndStroke => "B"u8, + ContentOperatorCode.FillEvenOddAndStroke => "B*"u8, + ContentOperatorCode.CloseFillAndStroke => "b"u8, + ContentOperatorCode.CloseFillEvenOddAndStroke => "b*"u8, + ContentOperatorCode.EndPath => "n"u8, + ContentOperatorCode.Clip => "W"u8, + ContentOperatorCode.ClipEvenOdd => "W*"u8, + ContentOperatorCode.BeginText => "BT"u8, + ContentOperatorCode.EndText => "ET"u8, + ContentOperatorCode.SetCharacterSpacing => "Tc"u8, + ContentOperatorCode.SetWordSpacing => "Tw"u8, + ContentOperatorCode.SetHorizontalScaling => "Tz"u8, + ContentOperatorCode.SetLeading => "TL"u8, + ContentOperatorCode.SetFont => "Tf"u8, + ContentOperatorCode.SetTextRenderingMode => "Tr"u8, + ContentOperatorCode.SetTextRise => "Ts"u8, + ContentOperatorCode.MoveText => "Td"u8, + ContentOperatorCode.MoveTextSetLeading => "TD"u8, + ContentOperatorCode.SetTextMatrix => "Tm"u8, + ContentOperatorCode.NextLine => "T*"u8, + ContentOperatorCode.ShowText => "Tj"u8, + ContentOperatorCode.ShowTextAdjusted => "TJ"u8, + ContentOperatorCode.NextLineShowText => "'"u8, + ContentOperatorCode.NextLineShowTextWithSpacing => "\""u8, + ContentOperatorCode.SetGlyphWidth => "d0"u8, + ContentOperatorCode.SetGlyphWidthAndBoundingBox => "d1"u8, + ContentOperatorCode.SetStrokeColorSpace => "CS"u8, + ContentOperatorCode.SetFillColorSpace => "cs"u8, + ContentOperatorCode.SetStrokeColor => "SC"u8, + ContentOperatorCode.SetStrokeColorExtended => "SCN"u8, + ContentOperatorCode.SetFillColor => "sc"u8, + ContentOperatorCode.SetFillColorExtended => "scn"u8, + ContentOperatorCode.SetStrokeGray => "G"u8, + ContentOperatorCode.SetFillGray => "g"u8, + ContentOperatorCode.SetStrokeRgb => "RG"u8, + ContentOperatorCode.SetFillRgb => "rg"u8, + ContentOperatorCode.SetStrokeCmyk => "K"u8, + ContentOperatorCode.SetFillCmyk => "k"u8, + ContentOperatorCode.PaintShading => "sh"u8, + ContentOperatorCode.BeginInlineImage => "BI"u8, + ContentOperatorCode.BeginInlineImageData => "ID"u8, + ContentOperatorCode.EndInlineImage => "EI"u8, + ContentOperatorCode.PaintXObject => "Do"u8, + ContentOperatorCode.MarkPoint => "MP"u8, + ContentOperatorCode.MarkPointWithProperties => "DP"u8, + ContentOperatorCode.BeginMarkedContent => "BMC"u8, + ContentOperatorCode.BeginMarkedContentWithProperties => "BDC"u8, + ContentOperatorCode.EndMarkedContent => "EMC"u8, + ContentOperatorCode.BeginCompatibility => "BX"u8, + ContentOperatorCode.EndCompatibility => "EX"u8, + _ => [], + }; + + /// Returns the operands takes. + public static OperandSignature Signature(ContentOperatorCode code) => code switch + { + ContentOperatorCode.ConcatenateMatrix or ContentOperatorCode.CurveTo or ContentOperatorCode.SetTextMatrix + or ContentOperatorCode.SetGlyphWidthAndBoundingBox => new("nnnnnn"u8, false), + ContentOperatorCode.SetLineWidth or ContentOperatorCode.SetLineCap or ContentOperatorCode.SetLineJoin or ContentOperatorCode.SetMiterLimit + or ContentOperatorCode.SetFlatness or ContentOperatorCode.SetCharacterSpacing or ContentOperatorCode.SetWordSpacing + or ContentOperatorCode.SetHorizontalScaling or ContentOperatorCode.SetLeading or ContentOperatorCode.SetTextRenderingMode + or ContentOperatorCode.SetTextRise or ContentOperatorCode.SetStrokeGray or ContentOperatorCode.SetFillGray => new("n"u8, false), + ContentOperatorCode.SetDash => new("an"u8, false), + ContentOperatorCode.SetRenderingIntent or ContentOperatorCode.SetGraphicsStateParameters or ContentOperatorCode.SetStrokeColorSpace + or ContentOperatorCode.SetFillColorSpace or ContentOperatorCode.PaintShading or ContentOperatorCode.PaintXObject + or ContentOperatorCode.MarkPoint or ContentOperatorCode.BeginMarkedContent => new("N"u8, false), + ContentOperatorCode.MoveTo or ContentOperatorCode.LineTo or ContentOperatorCode.MoveText or ContentOperatorCode.MoveTextSetLeading + or ContentOperatorCode.SetGlyphWidth => new("nn"u8, false), + ContentOperatorCode.CurveToInitialPointReplicated or ContentOperatorCode.CurveToFinalPointReplicated or ContentOperatorCode.Rectangle + or ContentOperatorCode.SetStrokeCmyk or ContentOperatorCode.SetFillCmyk => new("nnnn"u8, false), + ContentOperatorCode.SetStrokeRgb or ContentOperatorCode.SetFillRgb => new("nnn"u8, false), + ContentOperatorCode.SetFont => new("Nn"u8, false), + ContentOperatorCode.ShowText or ContentOperatorCode.NextLineShowText => new("s"u8, false), + ContentOperatorCode.ShowTextAdjusted => new("a"u8, false), + ContentOperatorCode.NextLineShowTextWithSpacing => new("nns"u8, false), + ContentOperatorCode.MarkPointWithProperties or ContentOperatorCode.BeginMarkedContentWithProperties => new("ND"u8, false), + ContentOperatorCode.BeginInlineImage => new("d"u8, false), + ContentOperatorCode.SetStrokeColor or ContentOperatorCode.SetFillColor => new("n"u8, true), + ContentOperatorCode.SetStrokeColorExtended or ContentOperatorCode.SetFillColorExtended => new("nN"u8, true), + _ => new([], false), + }; + + /// Returns the Table 50 category of . + public static OperatorCategory Category(ContentOperatorCode code) => code switch + { + ContentOperatorCode.Unknown => OperatorCategory.Unknown, + <= ContentOperatorCode.RestoreState => OperatorCategory.GeneralGraphicsState, + ContentOperatorCode.ConcatenateMatrix => OperatorCategory.SpecialGraphicsState, + <= ContentOperatorCode.SetGraphicsStateParameters => OperatorCategory.GeneralGraphicsState, + <= ContentOperatorCode.Rectangle => OperatorCategory.PathConstruction, + <= ContentOperatorCode.EndPath => OperatorCategory.PathPainting, + <= ContentOperatorCode.ClipEvenOdd => OperatorCategory.ClippingPath, + <= ContentOperatorCode.EndText => OperatorCategory.TextObject, + <= ContentOperatorCode.SetTextRise => OperatorCategory.TextState, + <= ContentOperatorCode.NextLine => OperatorCategory.TextPositioning, + <= ContentOperatorCode.NextLineShowTextWithSpacing => OperatorCategory.TextShowing, + <= ContentOperatorCode.SetGlyphWidthAndBoundingBox => OperatorCategory.Type3Font, + <= ContentOperatorCode.SetFillCmyk => OperatorCategory.Color, + ContentOperatorCode.PaintShading => OperatorCategory.Shading, + <= ContentOperatorCode.EndInlineImage => OperatorCategory.InlineImage, + ContentOperatorCode.PaintXObject => OperatorCategory.XObject, + <= ContentOperatorCode.EndMarkedContent => OperatorCategory.MarkedContent, + _ => OperatorCategory.Compatibility, + }; + + private static ContentOperatorCode One(char a) => a switch + { + 'q' => ContentOperatorCode.SaveState, + 'Q' => ContentOperatorCode.RestoreState, + 'w' => ContentOperatorCode.SetLineWidth, + 'J' => ContentOperatorCode.SetLineCap, + 'j' => ContentOperatorCode.SetLineJoin, + 'M' => ContentOperatorCode.SetMiterLimit, + 'd' => ContentOperatorCode.SetDash, + 'i' => ContentOperatorCode.SetFlatness, + 'm' => ContentOperatorCode.MoveTo, + 'l' => ContentOperatorCode.LineTo, + 'c' => ContentOperatorCode.CurveTo, + 'v' => ContentOperatorCode.CurveToInitialPointReplicated, + 'y' => ContentOperatorCode.CurveToFinalPointReplicated, + 'h' => ContentOperatorCode.ClosePath, + 'S' => ContentOperatorCode.Stroke, + 's' => ContentOperatorCode.CloseAndStroke, + 'f' => ContentOperatorCode.Fill, + 'F' => ContentOperatorCode.FillObsolete, + 'B' => ContentOperatorCode.FillAndStroke, + 'b' => ContentOperatorCode.CloseFillAndStroke, + 'n' => ContentOperatorCode.EndPath, + 'W' => ContentOperatorCode.Clip, + 'G' => ContentOperatorCode.SetStrokeGray, + 'g' => ContentOperatorCode.SetFillGray, + 'K' => ContentOperatorCode.SetStrokeCmyk, + 'k' => ContentOperatorCode.SetFillCmyk, + '\'' => ContentOperatorCode.NextLineShowText, + '"' => ContentOperatorCode.NextLineShowTextWithSpacing, + _ => ContentOperatorCode.Unknown, + }; + + private static ContentOperatorCode Two(char a, char b) => (a, b) switch + { + ('c', 'm') => ContentOperatorCode.ConcatenateMatrix, + ('r', 'i') => ContentOperatorCode.SetRenderingIntent, + ('g', 's') => ContentOperatorCode.SetGraphicsStateParameters, + ('r', 'e') => ContentOperatorCode.Rectangle, + ('f', '*') => ContentOperatorCode.FillEvenOdd, + ('B', '*') => ContentOperatorCode.FillEvenOddAndStroke, + ('b', '*') => ContentOperatorCode.CloseFillEvenOddAndStroke, + ('W', '*') => ContentOperatorCode.ClipEvenOdd, + ('B', 'T') => ContentOperatorCode.BeginText, + ('E', 'T') => ContentOperatorCode.EndText, + ('T', 'c') => ContentOperatorCode.SetCharacterSpacing, + ('T', 'w') => ContentOperatorCode.SetWordSpacing, + ('T', 'z') => ContentOperatorCode.SetHorizontalScaling, + ('T', 'L') => ContentOperatorCode.SetLeading, + ('T', 'f') => ContentOperatorCode.SetFont, + ('T', 'r') => ContentOperatorCode.SetTextRenderingMode, + ('T', 's') => ContentOperatorCode.SetTextRise, + ('T', 'd') => ContentOperatorCode.MoveText, + ('T', 'D') => ContentOperatorCode.MoveTextSetLeading, + ('T', 'm') => ContentOperatorCode.SetTextMatrix, + ('T', '*') => ContentOperatorCode.NextLine, + ('T', 'j') => ContentOperatorCode.ShowText, + ('T', 'J') => ContentOperatorCode.ShowTextAdjusted, + ('d', '0') => ContentOperatorCode.SetGlyphWidth, + ('d', '1') => ContentOperatorCode.SetGlyphWidthAndBoundingBox, + ('C', 'S') => ContentOperatorCode.SetStrokeColorSpace, + ('c', 's') => ContentOperatorCode.SetFillColorSpace, + ('S', 'C') => ContentOperatorCode.SetStrokeColor, + ('s', 'c') => ContentOperatorCode.SetFillColor, + ('R', 'G') => ContentOperatorCode.SetStrokeRgb, + ('r', 'g') => ContentOperatorCode.SetFillRgb, + ('s', 'h') => ContentOperatorCode.PaintShading, + ('B', 'I') => ContentOperatorCode.BeginInlineImage, + ('I', 'D') => ContentOperatorCode.BeginInlineImageData, + ('E', 'I') => ContentOperatorCode.EndInlineImage, + ('D', 'o') => ContentOperatorCode.PaintXObject, + ('M', 'P') => ContentOperatorCode.MarkPoint, + ('D', 'P') => ContentOperatorCode.MarkPointWithProperties, + ('B', 'X') => ContentOperatorCode.BeginCompatibility, + ('E', 'X') => ContentOperatorCode.EndCompatibility, + _ => ContentOperatorCode.Unknown, + }; + + private static ContentOperatorCode Three(char a, char b, char c) => (a, b, c) switch + { + ('S', 'C', 'N') => ContentOperatorCode.SetStrokeColorExtended, + ('s', 'c', 'n') => ContentOperatorCode.SetFillColorExtended, + ('B', 'M', 'C') => ContentOperatorCode.BeginMarkedContent, + ('B', 'D', 'C') => ContentOperatorCode.BeginMarkedContentWithProperties, + ('E', 'M', 'C') => ContentOperatorCode.EndMarkedContent, + _ => ContentOperatorCode.Unknown, + }; +} diff --git a/src/Broadside/Content/PathBuilder.cs b/src/Broadside/Content/PathBuilder.cs new file mode 100644 index 00000000..6dcdfbd4 --- /dev/null +++ b/src/Broadside/Content/PathBuilder.cs @@ -0,0 +1,182 @@ +using System.Buffers; +using Broadside.Graphics; + +namespace Broadside.Content; + +/// +/// The current path of a run: segments in user space, built by the path construction operators, normalized to move, line, cubic +/// and close, in pooled buffers that are reused from one path to the next. +/// +/// +/// ISO 32000-2 §8.5.2, Table 58. The current path is not part of the graphics state: q and Q leave it alone, and a +/// painting operator ends it (§8.5.2.1). When no processor wants paths or clips the builder tracks only whether a path and a current +/// point exist, so diagnostics stay the same while no geometry is stored. +/// +internal sealed class PathBuilder +{ + private PathVerb[] _verbs = ArrayPool.Shared.Rent(32); + private PathPoint[] _points = ArrayPool.Shared.Rent(64); + private int _verbCount; + private int _pointCount; + private PathPoint _current; + private PathPoint _subpathStart; + private bool _subpathClosed; + private bool _lastWasMoveTo; + + /// Gets or sets a value indicating whether segments are stored, or only the path's existence and current point. + public bool Accumulate { get; set; } = true; + + /// Gets a value indicating whether a path object is open: m or re began one and no painting operator ended it. + public bool IsOpen { get; private set; } + + /// Gets the current point: the end of the last segment (§8.5.2.1); undefined when no path is open. + public PathPoint CurrentPoint => _current; + + /// Gets the path built so far. + public PathView View => new(_verbs.AsSpan(0, _verbCount), _points.AsSpan(0, _pointCount)); + + /// Ends the path object: the path becomes undefined. + public void Reset() + { + _verbCount = 0; + _pointCount = 0; + IsOpen = false; + _subpathClosed = false; + _lastWasMoveTo = false; + } + + /// Gives oversized buffers back to the pool. + public void Trim() + { + Reset(); + if (_points.Length > 1 << 16) + { + ArrayPool.Shared.Return(_verbs); + ArrayPool.Shared.Return(_points); + _verbs = ArrayPool.Shared.Rent(32); + _points = ArrayPool.Shared.Rent(64); + } + } + + /// m: begins a subpath; a moveto right after a moveto replaces it (Table 58). + public void MoveTo(double x, double y) + { + var point = new PathPoint(x, y); + if (_lastWasMoveTo) + { + if (Accumulate) + { + _points[_pointCount - 1] = point; + } + } + else + { + Append(PathVerb.MoveTo, point); + _lastWasMoveTo = true; + } + + IsOpen = true; + _current = point; + _subpathStart = point; + _subpathClosed = false; + } + + /// l: a line from the current point, which the caller has checked exists. + public void LineTo(double x, double y) + { + BeginSegment(); + var point = new PathPoint(x, y); + Append(PathVerb.LineTo, point); + _current = point; + } + + /// c, v, y: a cubic Bézier curve from the current point, which the caller has checked exists. + public void CurveTo(PathPoint control1, PathPoint control2, PathPoint end) + { + BeginSegment(); + if (Accumulate) + { + EnsureCapacity(1, 3); + _verbs[_verbCount++] = PathVerb.CubicTo; + _points[_pointCount++] = control1; + _points[_pointCount++] = control2; + _points[_pointCount++] = end; + } + + _current = end; + } + + /// h: closes the current subpath; nothing when it is already closed (Table 58). + public void Close() + { + if (_subpathClosed) + { + return; + } + + if (Accumulate) + { + EnsureCapacity(1, 0); + _verbs[_verbCount++] = PathVerb.Close; + } + + _current = _subpathStart; + _subpathClosed = true; + _lastWasMoveTo = false; + } + + /// re: x y m, three lines, h, keeping the signs of the width and height (Table 58). + public void Rectangle(double x, double y, double width, double height) + { + MoveTo(x, y); + LineTo(x + width, y); + LineTo(x + width, y + height); + LineTo(x, y + height); + Close(); + } + + /// Starts a segment: after h, a new subpath begins at the closed subpath's first point (Table 58). + private void BeginSegment() + { + if (_subpathClosed) + { + Append(PathVerb.MoveTo, _subpathStart); + _subpathClosed = false; + } + + _lastWasMoveTo = false; + } + + private void Append(PathVerb verb, PathPoint point) + { + if (!Accumulate) + { + return; + } + + EnsureCapacity(1, 1); + _verbs[_verbCount++] = verb; + _points[_pointCount++] = point; + } + + private void EnsureCapacity(int verbs, int points) + { + if (_verbCount + verbs > _verbs.Length) + { + Grow(ref _verbs, _verbCount); + } + + if (_pointCount + points > _points.Length) + { + Grow(ref _points, _pointCount); + } + } + + private static void Grow(ref T[] array, int used) + { + T[] larger = ArrayPool.Shared.Rent(array.Length * 2); + array.AsSpan(0, used).CopyTo(larger); + ArrayPool.Shared.Return(array); + array = larger; + } +} diff --git a/src/Broadside/Content/PathEvent.cs b/src/Broadside/Content/PathEvent.cs new file mode 100644 index 00000000..58e87370 --- /dev/null +++ b/src/Broadside/Content/PathEvent.cs @@ -0,0 +1,32 @@ +using Broadside.Graphics; + +namespace Broadside.Content; + +/// A path object being painted. Valid only during the callback. +/// +/// ISO 32000-2 §8.5.3, Table 59. The path is in user space; holds the CTM, line parameters and +/// colours in effect, and the clipping path before any W of this path object takes effect: a clip given with +/// changes the clipping path only after this paint, through +/// (§8.5.4), so a path stroked with W S is not clipped by itself. +/// +public readonly ref struct PathEvent +{ + /// Gets the path, exactly as constructed (see for the painting rules a renderer applies). + public PathView Path { get; internal init; } + + /// Gets what is painted; for n. + public PathPaint Paint { get; internal init; } + + /// Gets the rule for the fill; when nothing is filled. + public FillRule FillRule { get; internal init; } + + /// Gets a value indicating whether the operator closed the last subpath before painting: s, b, b*. + /// The closing segment is already in . + public bool ClosedBeforePaint { get; internal init; } + + /// Gets the rule of the W or W* in this path object, or when there is none. + public FillRule? PendingClip { get; internal init; } + + /// Gets a value indicating whether optional content hides the path (§8.11.3.1); reported only to processors that ask for . + public bool IsHidden { get; internal init; } +} diff --git a/src/Broadside/Content/PathPaint.cs b/src/Broadside/Content/PathPaint.cs new file mode 100644 index 00000000..56995cd3 --- /dev/null +++ b/src/Broadside/Content/PathPaint.cs @@ -0,0 +1,18 @@ +namespace Broadside.Content; + +/// How a path-painting operator paints the current path. +/// ISO 32000-2 §8.5.3, Table 59. +public enum PathPaint +{ + /// n: nothing is painted; the path object ends, usually to set a clip. + None, + + /// S, s: stroke. + Stroke, + + /// f, F, f*: fill. + Fill, + + /// B, B*, b, b*: fill, then stroke, as two path objects painted in turn. + FillAndStroke, +} diff --git a/src/Broadside/Content/ShadingEvent.cs b/src/Broadside/Content/ShadingEvent.cs new file mode 100644 index 00000000..53e62846 --- /dev/null +++ b/src/Broadside/Content/ShadingEvent.cs @@ -0,0 +1,26 @@ +using Broadside.Graphics; +using Broadside.Objects; + +namespace Broadside.Content; + +/// A shading painted by sh. Valid only during the callback. +/// +/// ISO 32000-2 §8.7.4.2, Table 76: the shading fills the current clipping path, in user space mapped by the CTM. Fills with a +/// shading pattern carry no event of their own: the paint event's state holds the pattern colour. Declared with the content +/// interpreter's processor surface (issue #55); reported from issue #79, which adds the resolved shading model. Members are added, +/// never changed. +/// +public readonly ref struct ShadingEvent +{ + /// Gets the shading dictionary or stream (§8.7.4.5, Tables 77 to 83). + public CosObject? Shading { get; internal init; } + + /// Gets the resource name sh used. + public ReadOnlySpan ResourceName { get; internal init; } + + /// Gets the CTM. + public Matrix Ctm { get; internal init; } + + /// Gets a value indicating whether optional content hides the shading (§8.11.3.1). + public bool IsHidden { get; internal init; } +} diff --git a/src/Broadside/Graphics/BlendMode.cs b/src/Broadside/Graphics/BlendMode.cs new file mode 100644 index 00000000..c1058a4d --- /dev/null +++ b/src/Broadside/Graphics/BlendMode.cs @@ -0,0 +1,54 @@ +namespace Broadside.Graphics; + +/// The blend mode of the transparent imaging model. +/// ISO 32000-2 §11.3.5, Tables 134 and 135. Compatible (deprecated) is read as . +public enum BlendMode +{ + /// Normal, the initial value (Table 52). + Normal, + + /// Multiply. + Multiply, + + /// Screen. + Screen, + + /// Overlay. + Overlay, + + /// Darken. + Darken, + + /// Lighten. + Lighten, + + /// ColorDodge. + ColorDodge, + + /// ColorBurn. + ColorBurn, + + /// HardLight. + HardLight, + + /// SoftLight. + SoftLight, + + /// Difference. + Difference, + + /// Exclusion. + Exclusion, + + /// Hue (non-separable). + Hue, + + /// Saturation (non-separable). + Saturation, + + /// Color (non-separable). + Color, + + /// Luminosity (non-separable). + Luminosity, +} diff --git a/src/Broadside/Graphics/FillRule.cs b/src/Broadside/Graphics/FillRule.cs new file mode 100644 index 00000000..0204c06c --- /dev/null +++ b/src/Broadside/Graphics/FillRule.cs @@ -0,0 +1,12 @@ +namespace Broadside.Graphics; + +/// The rule that decides which points lie inside a path, for filling and for clipping. +/// ISO 32000-2 §8.5.3.3.2 (non-zero winding number) and §8.5.3.3.3 (even-odd). +public enum FillRule +{ + /// The non-zero winding number rule: f, B, b, W. + NonZero, + + /// The even-odd rule: f*, B*, b*, W*. + EvenOdd, +} diff --git a/src/Broadside/Graphics/GraphicsState.cs b/src/Broadside/Graphics/GraphicsState.cs new file mode 100644 index 00000000..6488f412 --- /dev/null +++ b/src/Broadside/Graphics/GraphicsState.cs @@ -0,0 +1,177 @@ +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace Broadside.Graphics; + +/// +/// The graphics state: the parameters every painting operator consults, as the content interpreter holds them. A processor reads +/// it through , by reference and read-only; it may copy it. +/// +/// +/// +/// ISO 32000-2 §8.4.1, Tables 51 and 52, with the text state parameters of §9.3 (Table 102). The initial values are those of +/// Tables 51, 52 and 102, except the CTM, which starts at the identity: a run reports geometry in default user space and the +/// consumer maps it to its device (§8.3.2.3). q pushes a copy of the whole state and Q pops it (§8.4.2); the current +/// path and the text matrices are not part of it (§8.5.2.1, §9.4.1). +/// +/// +/// Parameters set by operators that later issues implement (the gs parameters of §8.4.5, colours of §8.6, text state of +/// §9.3) hold their initial values until then; members for parameters whose values are document-model objects (font, colours, +/// soft mask, transfer functions, halftone) are added with those objects. Numeric parameters are always within their valid ranges: +/// the interpreter clips out-of-range operands and records a diagnostic (§8.4.1). +/// +/// +[SuppressMessage("Performance", "CA1815:Override equals and operator equals on value types", Justification = "A snapshot of interpreter state, never compared; value equality over every parameter would mislead.")] +public struct GraphicsState +{ + private DashBuffer _dash; + private double[]? _dashOverflow; + private int _dashCount; + + /// Gets the current transformation matrix: user space to the run's default user space. + /// ISO 32000-2 §8.3.2.3, Table 51. Changed by cm (Table 56). + public Matrix Ctm { readonly get; internal set; } + + /// + /// Gets the current clipping path as a handle that resolves; 0 is the run's initial + /// clipping path (for a page, its media box). Meaningful only to a processor that asks for . + /// + /// ISO 32000-2 §8.5.4, Table 51. Restored by Q with the rest of the state. + public int ClipHandle { readonly get; internal set; } + + /// Gets the line width in user space units; 0 is the thinnest line the device can render. Initially 1.0. + /// ISO 32000-2 §8.4.3.2, Table 51. + public double LineWidth { readonly get; internal set; } + + /// Gets the line cap style. Initially . + /// ISO 32000-2 §8.4.3.3, Table 51. + public LineCap LineCap { readonly get; internal set; } + + /// Gets the line join style. Initially . + /// ISO 32000-2 §8.4.3.4, Table 51. + public LineJoin LineJoin { readonly get; internal set; } + + /// Gets the miter limit, at least 1. Initially 10.0. + /// ISO 32000-2 §8.4.3.5, Table 51. + public double MiterLimit { readonly get; internal set; } + + /// Gets the lengths of the alternating dashes and gaps, in user space units; empty for a solid line. Initially empty. + /// ISO 32000-2 §8.4.3.6, Table 51. Every element is non-negative and, when there are any, not all are zero. + [UnscopedRef] + public readonly ReadOnlySpan DashArray => _dashOverflow is { } overflow ? overflow : ((ReadOnlySpan)_dash)[.._dashCount]; + + /// Gets the distance into the dash pattern at which a stroke starts, never negative; 0 for a solid line. Initially 0. + /// ISO 32000-2 §8.4.3.6: a negative phase is incremented by twice the sum of the dash array until it is not negative. + public double DashPhase { readonly get; internal set; } + + /// Gets the colour rendering intent. Initially . + /// ISO 32000-2 §8.6.5.8, Table 52. Set by ri (Table 56). + public RenderingIntent RenderingIntent { readonly get; internal set; } + + /// Gets the flatness tolerance, 0 to 100; 0 selects the device's default. Initially 1.0. + /// ISO 32000-2 §10.7.2, Table 52. Set by i (Table 56). + public double Flatness { readonly get; internal set; } + + /// Gets a value indicating whether automatic stroke adjustment is on. Initially false. + /// ISO 32000-2 §10.7.5, Table 52. Set through gs (SA). + public bool StrokeAdjustment { readonly get; internal set; } + + /// Gets the blend mode. Initially . + /// ISO 32000-2 §11.3.5, Table 52. Set through gs (BM). + public BlendMode BlendMode { readonly get; internal set; } + + /// Gets the constant opacity for stroking, 0 to 1. Initially 1.0. + /// ISO 32000-2 §11.6.4.4, Table 52. Set through gs (CA). + public double StrokeAlpha { readonly get; internal set; } + + /// Gets the constant opacity for everything else, 0 to 1. Initially 1.0. + /// ISO 32000-2 §11.6.4.4, Table 52. Set through gs (ca). + public double FillAlpha { readonly get; internal set; } + + /// Gets a value indicating whether the soft mask and alpha are shape values rather than opacity. Initially false. + /// ISO 32000-2 §11.6.4.3, Table 52. Set through gs (AIS). + public bool AlphaIsShape { readonly get; internal set; } + + /// Gets a value indicating whether text is a knockout group. Initially true. + /// ISO 32000-2 §9.3.8, Table 102. Set through gs (TK). + public bool TextKnockout { readonly get; internal set; } + + /// Gets a value indicating whether stroking overprints. Initially false. + /// ISO 32000-2 §8.6.7, Table 52. Set through gs (OP). + public bool StrokeOverprint { readonly get; internal set; } + + /// Gets a value indicating whether other painting overprints. Initially false. + /// ISO 32000-2 §8.6.7, Table 52. Set through gs (op, else OP). + public bool FillOverprint { readonly get; internal set; } + + /// Gets the overprint mode, 0 or 1. Initially 0. + /// ISO 32000-2 §8.6.7, Table 52. Set through gs (OPM). + public int OverprintMode { readonly get; internal set; } + + /// Gets the character spacing Tc, in unscaled text space units. Initially 0. + /// ISO 32000-2 §9.3.2, Table 102. Set by Tc. + public double CharacterSpacing { readonly get; internal set; } + + /// Gets the word spacing Tw, in unscaled text space units. Initially 0. + /// ISO 32000-2 §9.3.3, Table 102. Set by Tw. + public double WordSpacing { readonly get; internal set; } + + /// Gets the horizontal scaling Th as a factor (the Tz operand divided by 100). Initially 1.0. + /// ISO 32000-2 §9.3.4, Table 102. + public double HorizontalScaling { readonly get; internal set; } + + /// Gets the leading Tl, in unscaled text space units. Initially 0. + /// ISO 32000-2 §9.3.5, Table 102. Set by TL and TD. + public double Leading { readonly get; internal set; } + + /// Gets the text font size Tfs; 0 until Tf sets a font. + /// ISO 32000-2 §9.3.1, Table 102. + public double FontSize { readonly get; internal set; } + + /// Gets the text rendering mode Tmode. Initially . + /// ISO 32000-2 §9.3.6, Table 102. Set by Tr. + public TextRenderingMode TextRenderingMode { readonly get; internal set; } + + /// Gets the text rise Trise, in unscaled text space units. Initially 0. + /// ISO 32000-2 §9.3.7, Table 102. Set by Ts. + public double TextRise { readonly get; internal set; } + + /// Returns the state a content stream starts with (Tables 51, 52 and 102), with the CTM at the identity. + internal static GraphicsState CreateInitial() => new() + { + Ctm = Matrix.Identity, + LineWidth = 1.0, + MiterLimit = 10.0, + Flatness = 1.0, + StrokeAlpha = 1.0, + FillAlpha = 1.0, + TextKnockout = true, + HorizontalScaling = 1.0, + }; + + /// Sets the dash pattern; the elements are copied. A pattern longer than the inline storage gets its own array. + internal void SetDash(ReadOnlySpan array, double phase) + { + if (array.Length <= DashBuffer.Length) + { + array.CopyTo(_dash); + _dashOverflow = null; + } + else if (_dashOverflow is null || !array.SequenceEqual(_dashOverflow)) + { + _dashOverflow = array.ToArray(); + } + + _dashCount = array.Length; + DashPhase = phase; + } + + /// Storage for dash arrays of up to eight elements, the common case, so that q copies no heap object. + [InlineArray(Length)] + private struct DashBuffer + { + public const int Length = 8; + + private double _element; + } +} diff --git a/src/Broadside/Graphics/LineCap.cs b/src/Broadside/Graphics/LineCap.cs new file mode 100644 index 00000000..0f3e80f5 --- /dev/null +++ b/src/Broadside/Graphics/LineCap.cs @@ -0,0 +1,15 @@ +namespace Broadside.Graphics; + +/// The shape at the ends of open subpaths and dashes when they are stroked. +/// ISO 32000-2 §8.4.3.3, Table 53. +public enum LineCap +{ + /// Butt cap (0): the stroke is squared off at the endpoint. + Butt = 0, + + /// Round cap (1): a semicircular arc with a diameter equal to the line width. + Round = 1, + + /// Projecting square cap (2): the stroke continues half the line width beyond the endpoint. + ProjectingSquare = 2, +} diff --git a/src/Broadside/Graphics/LineJoin.cs b/src/Broadside/Graphics/LineJoin.cs new file mode 100644 index 00000000..511d6520 --- /dev/null +++ b/src/Broadside/Graphics/LineJoin.cs @@ -0,0 +1,15 @@ +namespace Broadside.Graphics; + +/// The shape at the corners of stroked paths. +/// ISO 32000-2 §8.4.3.4, Table 54. +public enum LineJoin +{ + /// Miter join (0), converted to a bevel when the miter limit is exceeded (§8.4.3.5). + Miter = 0, + + /// Round join (1). + Round = 1, + + /// Bevel join (2). + Bevel = 2, +} diff --git a/src/Broadside/Graphics/Matrix.cs b/src/Broadside/Graphics/Matrix.cs new file mode 100644 index 00000000..ace199f2 --- /dev/null +++ b/src/Broadside/Graphics/Matrix.cs @@ -0,0 +1,166 @@ +using System.Globalization; + +namespace Broadside.Graphics; + +/// +/// A transformation matrix [a b c d e f]: the 3-by-3 matrix [a b 0; c d 0; e f 1] that maps a point of one +/// coordinate space to another, applied to row vectors. +/// +/// +/// +/// ISO 32000-2 §8.3.3 and §8.3.4. A point (x, y) maps to (a·x + c·y + e, b·x + d·y + f). A transformation applied +/// after an existing one is premultiplied: M′ = Mₜ × M, which is how cm changes the current transformation matrix +/// (Table 56). Coordinates and elements are doubles so that large offsets with small scales keep their precision. +/// +/// +/// Any six numbers make a matrix, including singular ones (scaling by zero): they are legal operands and map everything to a line +/// or a point. reports whether an inverse exists. +/// +/// +public readonly struct Matrix : IEquatable +{ + /// Initializes a new instance of the struct. + /// The element a: x scale (with ) or the cosine part of a rotation. + /// The element b. + /// The element c. + /// The element d. + /// The element e: the x translation. + /// The element f: the y translation. + public Matrix(double a, double b, double c, double d, double e, double f) + { + A = a; + B = b; + C = c; + D = d; + E = e; + F = f; + } + + /// Gets the identity matrix [1 0 0 1 0 0]. + public static Matrix Identity { get; } = new(1, 0, 0, 1, 0, 0); + + /// Gets the element a. + public double A { get; } + + /// Gets the element b. + public double B { get; } + + /// Gets the element c. + public double C { get; } + + /// Gets the element d. + public double D { get; } + + /// Gets the element e. + public double E { get; } + + /// Gets the element f. + public double F { get; } + + /// Gets a value indicating whether this is the identity matrix. + public bool IsIdentity => A == 1 && B == 0 && C == 0 && D == 1 && E == 0 && F == 0; + + /// Gets the determinant a·d − b·c; zero for a matrix that has no inverse. + public double Determinant => (A * D) - (B * C); + + /// Returns the composite transformation: first , then . + /// The transformation applied first. + /// The transformation applied second. + /// The product first × second. + /// ISO 32000-2 §8.3.4: cm computes Multiply(operand, CTM). + public static Matrix operator *(Matrix first, Matrix second) => Multiply(first, second); + + /// Returns whether two matrices have the same elements. + /// The first matrix. + /// The second matrix. + /// when they are equal. + public static bool operator ==(Matrix left, Matrix right) => left.Equals(right); + + /// Returns whether two matrices differ. + /// The first matrix. + /// The second matrix. + /// when they differ. + public static bool operator !=(Matrix left, Matrix right) => !left.Equals(right); + + /// Returns the composite transformation: first , then . + /// The transformation applied first. + /// The transformation applied second. + /// The product first × second. + /// ISO 32000-2 §8.3.4. + public static Matrix Multiply(Matrix first, Matrix second) => new( + (first.A * second.A) + (first.B * second.C), + (first.A * second.B) + (first.B * second.D), + (first.C * second.A) + (first.D * second.C), + (first.C * second.B) + (first.D * second.D), + (first.E * second.A) + (first.F * second.C) + second.E, + (first.E * second.B) + (first.F * second.D) + second.F); + + /// Returns a translation by (, ): [1 0 0 1 tx ty]. + /// The x offset. + /// The y offset. + /// The matrix. + /// ISO 32000-2 §8.3.3. + public static Matrix CreateTranslation(double tx, double ty) => new(1, 0, 0, 1, tx, ty); + + /// Returns a scaling by (, ): [sx 0 0 sy 0 0]. + /// The x scale. + /// The y scale. + /// The matrix. + /// ISO 32000-2 §8.3.3. + public static Matrix CreateScale(double sx, double sy) => new(sx, 0, 0, sy, 0, 0); + + /// Maps a point. + /// The x coordinate in the source space. + /// The y coordinate in the source space. + /// The point in the target space: (a·x + c·y + e, b·x + d·y + f). + /// ISO 32000-2 §8.3.4. + public PathPoint Transform(double x, double y) => new((A * x) + (C * y) + E, (B * x) + (D * y) + F); + + /// Maps a point. + /// The point in the source space. + /// The point in the target space. + /// ISO 32000-2 §8.3.4. + public PathPoint Transform(PathPoint point) => Transform(point.X, point.Y); + + /// Maps a distance vector: the linear part only, without the translation. + /// The x component. + /// The y component. + /// The vector in the target space: (a·dx + c·dy, b·dx + d·dy). + /// ISO 32000-2 §8.3.4. + public PathPoint TransformVector(double dx, double dy) => new((A * dx) + (C * dy), (B * dx) + (D * dy)); + + /// Computes the inverse transformation, when one exists. + /// The inverse; the identity when there is none. + /// when the matrix is singular (its determinant is zero or not finite). + /// ISO 32000-2 §8.3.4, NOTE 3: not every transformation is invertible. + public bool TryInvert(out Matrix inverse) + { + double determinant = Determinant; + if (determinant == 0 || !double.IsFinite(determinant)) + { + inverse = Identity; + return false; + } + + double a = D / determinant; + double b = -B / determinant; + double c = -C / determinant; + double d = A / determinant; + inverse = new Matrix(a, b, c, d, -((E * a) + (F * c)), -((E * b) + (F * d))); + return true; + } + + /// + public bool Equals(Matrix other) => + A.Equals(other.A) && B.Equals(other.B) && C.Equals(other.C) && D.Equals(other.D) && E.Equals(other.E) && F.Equals(other.F); + + /// + public override bool Equals(object? obj) => obj is Matrix other && Equals(other); + + /// + public override int GetHashCode() => HashCode.Combine(A, B, C, D, E, F); + + /// Returns the matrix as a PDF array would write it, such as [1 0 0 1 0 0]. + /// The matrix text. + public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"[{A} {B} {C} {D} {E} {F}]"); +} diff --git a/src/Broadside/Graphics/PathPoint.cs b/src/Broadside/Graphics/PathPoint.cs new file mode 100644 index 00000000..c329004e --- /dev/null +++ b/src/Broadside/Graphics/PathPoint.cs @@ -0,0 +1,14 @@ +using System.Globalization; + +namespace Broadside.Graphics; + +/// A point of a path, in the coordinate space the path is defined in (user space for a content stream path). +/// ISO 32000-2 §8.3.2, §8.5.2. Coordinates are doubles: real files combine large offsets with small scales. +/// The x coordinate. +/// The y coordinate. +public readonly record struct PathPoint(double X, double Y) +{ + /// Returns the point as (x, y) in the invariant culture. + /// The point text. + public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"({X}, {Y})"); +} diff --git a/src/Broadside/Graphics/PathVerb.cs b/src/Broadside/Graphics/PathVerb.cs new file mode 100644 index 00000000..b84aa541 --- /dev/null +++ b/src/Broadside/Graphics/PathVerb.cs @@ -0,0 +1,25 @@ +namespace Broadside.Graphics; + +/// One segment kind of a path, and how many points it takes from the path's point list. +/// +/// ISO 32000-2 §8.5.2, Table 58. Content stream paths are normalized to move, line, cubic and close (v, y and +/// re are expressed through them); exists for glyph outlines (TrueType quadratic curves), so text clips +/// and glyph outlines use the same path type. +/// +public enum PathVerb +{ + /// Begins a subpath at one point. + MoveTo, + + /// A straight line from the current point to one point. + LineTo, + + /// A quadratic Bézier curve: a control point and an end point (two points). Never produced by content stream operators. + QuadTo, + + /// A cubic Bézier curve: two control points and an end point (three points). + CubicTo, + + /// Closes the current subpath with a straight line back to its first point (no points). + Close, +} diff --git a/src/Broadside/Graphics/PathView.cs b/src/Broadside/Graphics/PathView.cs new file mode 100644 index 00000000..91adcfa6 --- /dev/null +++ b/src/Broadside/Graphics/PathView.cs @@ -0,0 +1,73 @@ +namespace Broadside.Graphics; + +/// +/// A path as verbs and points, without a copy: a view over storage the producer owns, valid only while the call that handed it +/// out runs. Copy what you keep. +/// +/// +/// +/// ISO 32000-2 §8.5.2. Each takes its points from in order: one for +/// and , two for , three for +/// , none for . +/// +/// +/// A content stream path is reported exactly as constructed, in the user space current when it was painted: degenerate subpaths, +/// a closed single point and a trailing lone m are kept. Applying the painting rules for them (§8.5.3.2: a degenerate subpath +/// is stroked as a dot only with round caps, a trailing moveto paints nothing; §8.5.3.3.1: open subpaths are closed for filling) is +/// the renderer's job. After an h, a later segment starts with an explicit to the closed +/// subpath's first point (Table 58), so every subpath begins with a moveto. +/// +/// +public readonly ref struct PathView +{ + /// Initializes a new instance of the struct. + /// The segments. + /// The points the segments take, in order. + public PathView(ReadOnlySpan verbs, ReadOnlySpan points) + { + Verbs = verbs; + Points = points; + } + + /// Gets the segments, in construction order. + public ReadOnlySpan Verbs { get; } + + /// Gets the points the segments take, in order. + public ReadOnlySpan Points { get; } + + /// Gets a value indicating whether the path has no segments at all. + public bool IsEmpty => Verbs.IsEmpty; + + /// Gets a value indicating whether the last segment is a moveto: a single-point open subpath that paints nothing (§8.5.3.2). + public bool HasTrailingMoveTo => !Verbs.IsEmpty && Verbs[^1] == PathVerb.MoveTo; + + /// + /// Gets the smallest rectangle containing every point, control points included, in the path's own space; for an empty path, a + /// rectangle of zero size at the origin. + /// + /// Control points bound the curve (a Bézier curve lies inside the convex hull of its points), so this may be larger than the painted area. + public PdfRectangle Bounds + { + get + { + if (Points.IsEmpty) + { + return default; + } + + double left = double.PositiveInfinity; + double bottom = double.PositiveInfinity; + double right = double.NegativeInfinity; + double top = double.NegativeInfinity; + foreach (PathPoint point in Points) + { + left = Math.Min(left, point.X); + right = Math.Max(right, point.X); + bottom = Math.Min(bottom, point.Y); + top = Math.Max(top, point.Y); + } + + return new PdfRectangle(left, bottom, right, top); + } + } +} diff --git a/src/Broadside/Graphics/RenderingIntent.cs b/src/Broadside/Graphics/RenderingIntent.cs new file mode 100644 index 00000000..0ac7e892 --- /dev/null +++ b/src/Broadside/Graphics/RenderingIntent.cs @@ -0,0 +1,18 @@ +namespace Broadside.Graphics; + +/// The colour rendering intent: how colours are reproduced on a device whose gamut differs from the source. +/// ISO 32000-2 §8.6.5.8, Table 69. A name a reader does not recognise selects . +public enum RenderingIntent +{ + /// RelativeColorimetric, the initial value (Table 52). + RelativeColorimetric, + + /// AbsoluteColorimetric. + AbsoluteColorimetric, + + /// Saturation. + Saturation, + + /// Perceptual. + Perceptual, +} diff --git a/src/Broadside/Graphics/TextRenderingMode.cs b/src/Broadside/Graphics/TextRenderingMode.cs new file mode 100644 index 00000000..84fb808f --- /dev/null +++ b/src/Broadside/Graphics/TextRenderingMode.cs @@ -0,0 +1,30 @@ +namespace Broadside.Graphics; + +/// Whether glyphs are filled, stroked, used as a clip, or invisible. +/// ISO 32000-2 §9.3.6, Table 104. +public enum TextRenderingMode +{ + /// 0: fill. + Fill = 0, + + /// 1: stroke. + Stroke = 1, + + /// 2: fill, then stroke. + FillStroke = 2, + + /// 3: neither fill nor stroke (invisible). + Invisible = 3, + + /// 4: fill and add to the clipping path. + FillClip = 4, + + /// 5: stroke and add to the clipping path. + StrokeClip = 5, + + /// 6: fill, stroke and add to the clipping path. + FillStrokeClip = 6, + + /// 7: add to the clipping path. + Clip = 7, +} diff --git a/src/Broadside/Objects/CosParser.cs b/src/Broadside/Objects/CosParser.cs index 2ff15388..a479b527 100644 --- a/src/Broadside/Objects/CosParser.cs +++ b/src/Broadside/Objects/CosParser.cs @@ -248,7 +248,7 @@ private readonly CosString ParseLiteralString(CosToken token) } /// Reads the escape sequence at [] (a backslash) and returns the index after it (§7.3.4.2, Table 3). - private static int ReadEscape(ReadOnlySpan text, int index, Span output, ref int written) + internal static int ReadEscape(ReadOnlySpan text, int index, Span output, ref int written) { if (index + 1 >= text.Length) { @@ -641,7 +641,7 @@ private readonly void ReportUnexpected(CosToken token) => private readonly ReadOnlySpan Bytes(CosToken token) => _lexer.Source.Slice(token.Start, token.Length); - private static int HexValue(byte character) => character switch + internal static int HexValue(byte character) => character switch { >= (byte)'0' and <= (byte)'9' => character - '0', >= (byte)'A' and <= (byte)'F' => character - 'A' + 10, @@ -650,11 +650,11 @@ private readonly void ReportUnexpected(CosToken token) => }; /// Parses [+-]?[0-9]+ into a ; fails on any other text or on overflow. - private static bool TryParseStrictInteger(ReadOnlySpan text, out long value) => + internal static bool TryParseStrictInteger(ReadOnlySpan text, out long value) => long.TryParse(text, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out value); /// Whether is [+-]?, then digits with at most one period, with at least one digit (§7.3.3). - private static bool IsWellFormedNumber(ReadOnlySpan text) + internal static bool IsWellFormedNumber(ReadOnlySpan text) { if (text.Length > 0 && text[0] is (byte)'+' or (byte)'-') { @@ -674,7 +674,7 @@ private static bool IsWellFormedNumber(ReadOnlySpan text) /// The lenient reading of a malformed number: leading signs collapse to one (negative if any is a minus), then digits and at most /// one period, stopping at the first byte that does not fit. Always has at least one digit. /// - private static ReadOnlySpan WellFormedPrefix(ReadOnlySpan text, Span scratch) + internal static ReadOnlySpan WellFormedPrefix(ReadOnlySpan text, Span scratch) { int index = 0; bool negative = false; diff --git a/src/Broadside/Objects/KnownNames.cs b/src/Broadside/Objects/KnownNames.cs index 9e835a0f..3b72b816 100644 --- a/src/Broadside/Objects/KnownNames.cs +++ b/src/Broadside/Objects/KnownNames.cs @@ -27,6 +27,9 @@ internal static class KnownNames /// /Pages, the catalog entry referring to the page tree root, and the type of a page tree node (§7.7.2, §7.7.3.2). public static readonly CosName Pages = new("Pages"); + /// /Contents, the page entry holding its content stream or array of streams (§7.7.3.3, Table 31). + public static readonly CosName Contents = new("Contents"); + /// /Page, the type of a page object (§7.7.3.3, Table 31). public static readonly CosName Page = new("Page"); diff --git a/src/Broadside/Parsing/DiagnosticCodes.cs b/src/Broadside/Parsing/DiagnosticCodes.cs index 38370fe5..3a55ae1e 100644 --- a/src/Broadside/Parsing/DiagnosticCodes.cs +++ b/src/Broadside/Parsing/DiagnosticCodes.cs @@ -132,4 +132,25 @@ internal static class DiagnosticCodes public const string PageResourcesMissing = nameof(PageResourcesMissing); public const string PageResourcesInvalid = nameof(PageResourcesInvalid); public const string PageUserUnitInvalid = nameof(PageUserUnitInvalid); + + // Content streams (§7.8.2, §8.2, §8.4, §8.5; issue #55). Reported once per code per content stream (DiagnosticSink.ReportOnce), + // on the stream's object (or the page's when the stream is direct), with the part and decoded offset in the message. + public const string ContentStreamInvalid = nameof(ContentStreamInvalid); + public const string ContentUnknownOperator = nameof(ContentUnknownOperator); + public const string ContentOperandCount = nameof(ContentOperandCount); + public const string ContentOperandType = nameof(ContentOperandType); + public const string ContentOperandOverflow = nameof(ContentOperandOverflow); + public const string ContentSyntaxInvalid = nameof(ContentSyntaxInvalid); + public const string ContentGluedTokens = nameof(ContentGluedTokens); + public const string ContentOperatorOutOfContext = nameof(ContentOperatorOutOfContext); + public const string ContentStackUnderflow = nameof(ContentStackUnderflow); + public const string ContentStackOverflow = nameof(ContentStackOverflow); + public const string ContentUnbalancedSave = nameof(ContentUnbalancedSave); + public const string ContentNoCurrentPoint = nameof(ContentNoCurrentPoint); + public const string ContentNoCurrentPath = nameof(ContentNoCurrentPath); + public const string ContentPathNotPainted = nameof(ContentPathNotPainted); + public const string ContentGraphicsStateRange = nameof(ContentGraphicsStateRange); + public const string ContentCompatibilityUnbalanced = nameof(ContentCompatibilityUnbalanced); + public const string ContentTextObjectUnbalanced = nameof(ContentTextObjectUnbalanced); + public const string ContentInlineImageInvalid = nameof(ContentInlineImageInvalid); } diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 5c0e9ec2..268f2956 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -161,6 +161,9 @@ public PdfVersion Version /// public IReadOnlyList Diagnostics => _diagnostics.Snapshot(); + /// Gets the sink the document's readers report deviations to (the content interpreter, issue #55). + internal DiagnosticSink DiagnosticSink => _diagnostics; + /// Opens the PDF file at with default options. /// The file path. The file is memory-mapped and shared for reading: do not change it until the document is disposed. /// The document. Dispose it when done. diff --git a/src/Broadside/PdfPage.cs b/src/Broadside/PdfPage.cs index b7d9ae5b..94b69a07 100644 --- a/src/Broadside/PdfPage.cs +++ b/src/Broadside/PdfPage.cs @@ -1,3 +1,4 @@ +using Broadside.Content; using Broadside.Objects; namespace Broadside; @@ -73,6 +74,31 @@ internal PdfPage(PdfDocument document, CosDictionary dictionary, CosReference? r /// ISO 32000-2 §7.7.3.3, Table 31 (PDF 1.6). public double UserUnit => ReadUserUnit(out double value) == PageAttributeState.Valid ? value : 1.0; + /// Runs the page's content through the content interpreter and reports what it paints to . + /// The processor; for several at once, a . + /// In strict mode, for the first deviation found in the content. + /// + /// ISO 32000-2 §7.8.2, §8.2 to §8.5. The content is the page's Contents stream, or the streams of its Contents + /// array read as one (Table 31), decoded through their filters; the names it uses resolve in . Geometry is + /// reported in user space with the CTM to default user space, starting at the identity: the media box, crop box, rotation and + /// user unit are the consumer's to apply. In lenient mode malformed content is repaired and recorded in + /// , once per kind of deviation per content stream. Reads the page live, on every call. + /// + public void ProcessContent(ContentProcessor processor) => ProcessContent(processor, ContentInterpreter.DefaultOptions); + + /// Runs the page's content through the content interpreter, with limits and cancellation. + /// The processor; for several at once, a . + /// Limits and cancellation for the run. + /// In strict mode, for the first deviation found in the content. + /// The options' cancellation token was canceled. + /// ISO 32000-2 §7.8.2, §8.2 to §8.5. As . + public void ProcessContent(ContentProcessor processor, ContentOptions options) + { + ArgumentNullException.ThrowIfNull(processor); + ArgumentNullException.ThrowIfNull(options); + ContentInterpreter.RunPage(this, _document, processor, options); + } + /// Reads a page boundary; for an inheritable one, from the nearest node that has it. internal PageAttributeState ReadBox(CosName key, bool inheritable, out PdfRectangle box) { diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index a576dc7d..82afdcc7 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -1,5 +1,377 @@ #nullable enable abstract Broadside.Objects.CosNumber.ToDouble() -> double +Broadside.Content.ClipEvent +Broadside.Content.ClipEvent.ClipEvent() -> void +Broadside.Content.ClipEvent.Ctm.get -> Broadside.Graphics.Matrix +Broadside.Content.ClipEvent.Handle.get -> int +Broadside.Content.ClipEvent.Kind.get -> Broadside.Content.ClipKind +Broadside.Content.ClipEvent.ParentHandle.get -> int +Broadside.Content.ClipEvent.Path.get -> Broadside.Graphics.PathView +Broadside.Content.ClipEvent.Rule.get -> Broadside.Graphics.FillRule +Broadside.Content.ClipKind +Broadside.Content.ClipKind.Initial = 0 -> Broadside.Content.ClipKind +Broadside.Content.ClipKind.Path = 1 -> Broadside.Content.ClipKind +Broadside.Content.ClipKind.Rectangle = 2 -> Broadside.Content.ClipKind +Broadside.Content.ClipKind.Text = 3 -> Broadside.Content.ClipKind +Broadside.Content.ClipView +Broadside.Content.ClipView.ClipView() -> void +Broadside.Content.ClipView.Ctm.get -> Broadside.Graphics.Matrix +Broadside.Content.ClipView.Handle.get -> int +Broadside.Content.ClipView.Kind.get -> Broadside.Content.ClipKind +Broadside.Content.ClipView.ParentHandle.get -> int +Broadside.Content.ClipView.Path.get -> Broadside.Graphics.PathView +Broadside.Content.ClipView.Rule.get -> Broadside.Graphics.FillRule +Broadside.Content.CompositeContentProcessor +Broadside.Content.CompositeContentProcessor.CompositeContentProcessor(params Broadside.Content.ContentProcessor![]! processors) -> void +Broadside.Content.CompositeContentProcessor.Processors.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Content.ContentContext +Broadside.Content.ContentContext.CancellationToken.get -> System.Threading.CancellationToken +Broadside.Content.ContentContext.CurrentPartIndex.get -> int +Broadside.Content.ContentContext.CurrentStream.get -> Broadside.Objects.CosReference? +Broadside.Content.ContentContext.Depth.get -> int +Broadside.Content.ContentContext.Document.get -> Broadside.PdfDocument! +Broadside.Content.ContentContext.GetClip(int handle) -> Broadside.Content.ClipView +Broadside.Content.ContentContext.IsHidden.get -> bool +Broadside.Content.ContentContext.Page.get -> Broadside.PdfPage? +Broadside.Content.ContentContext.Resources.get -> Broadside.Objects.CosDictionary? +Broadside.Content.ContentContext.RunKind.get -> Broadside.Content.ContentRunKind +Broadside.Content.ContentContext.State.get -> Broadside.Graphics.GraphicsState +Broadside.Content.ContentContext.StateDepth.get -> int +Broadside.Content.ContentContext.StreamBaseMatrix.get -> Broadside.Graphics.Matrix +Broadside.Content.ContentEvents +Broadside.Content.ContentEvents.All = Broadside.Content.ContentEvents.Paths | Broadside.Content.ContentEvents.Clips | Broadside.Content.ContentEvents.Text | Broadside.Content.ContentEvents.Glyphs | Broadside.Content.ContentEvents.Images | Broadside.Content.ContentEvents.Shadings | Broadside.Content.ContentEvents.Forms | Broadside.Content.ContentEvents.MarkedContent | Broadside.Content.ContentEvents.StateStack | Broadside.Content.ContentEvents.Operators | Broadside.Content.ContentEvents.HiddenContent | Broadside.Content.ContentEvents.Type3GlyphContent -> Broadside.Content.ContentEvents +Broadside.Content.ContentEvents.Clips = 2 -> Broadside.Content.ContentEvents +Broadside.Content.ContentEvents.Forms = 64 -> Broadside.Content.ContentEvents +Broadside.Content.ContentEvents.Glyphs = 8 -> Broadside.Content.ContentEvents +Broadside.Content.ContentEvents.HiddenContent = 1024 -> Broadside.Content.ContentEvents +Broadside.Content.ContentEvents.Images = 16 -> Broadside.Content.ContentEvents +Broadside.Content.ContentEvents.MarkedContent = 128 -> Broadside.Content.ContentEvents +Broadside.Content.ContentEvents.None = 0 -> Broadside.Content.ContentEvents +Broadside.Content.ContentEvents.Operators = 512 -> Broadside.Content.ContentEvents +Broadside.Content.ContentEvents.Paths = 1 -> Broadside.Content.ContentEvents +Broadside.Content.ContentEvents.Shadings = 32 -> Broadside.Content.ContentEvents +Broadside.Content.ContentEvents.StateStack = 256 -> Broadside.Content.ContentEvents +Broadside.Content.ContentEvents.Text = 4 -> Broadside.Content.ContentEvents +Broadside.Content.ContentEvents.Type3GlyphContent = 2048 -> Broadside.Content.ContentEvents +Broadside.Content.ContentOperand +Broadside.Content.ContentOperand.Boolean.get -> bool +Broadside.Content.ContentOperand.Bytes.get -> System.ReadOnlySpan +Broadside.Content.ContentOperand.ContentOperand() -> void +Broadside.Content.ContentOperand.IsHexadecimal.get -> bool +Broadside.Content.ContentOperand.IsName(System.ReadOnlySpan name) -> bool +Broadside.Content.ContentOperand.IsNumber.get -> bool +Broadside.Content.ContentOperand.Items.get -> Broadside.Content.ContentOperands +Broadside.Content.ContentOperand.Kind.get -> Broadside.Content.ContentOperandKind +Broadside.Content.ContentOperand.Number.get -> double +Broadside.Content.ContentOperand.ToCosObject() -> Broadside.Objects.CosObject! +Broadside.Content.ContentOperandKind +Broadside.Content.ContentOperandKind.Array = 6 -> Broadside.Content.ContentOperandKind +Broadside.Content.ContentOperandKind.Boolean = 1 -> Broadside.Content.ContentOperandKind +Broadside.Content.ContentOperandKind.Dictionary = 7 -> Broadside.Content.ContentOperandKind +Broadside.Content.ContentOperandKind.Integer = 2 -> Broadside.Content.ContentOperandKind +Broadside.Content.ContentOperandKind.Name = 4 -> Broadside.Content.ContentOperandKind +Broadside.Content.ContentOperandKind.Null = 0 -> Broadside.Content.ContentOperandKind +Broadside.Content.ContentOperandKind.Real = 3 -> Broadside.Content.ContentOperandKind +Broadside.Content.ContentOperandKind.String = 5 -> Broadside.Content.ContentOperandKind +Broadside.Content.ContentOperands +Broadside.Content.ContentOperands.ContentOperands() -> void +Broadside.Content.ContentOperands.Count.get -> int +Broadside.Content.ContentOperands.Enumerator +Broadside.Content.ContentOperands.Enumerator.Current.get -> Broadside.Content.ContentOperand +Broadside.Content.ContentOperands.Enumerator.Enumerator() -> void +Broadside.Content.ContentOperands.Enumerator.MoveNext() -> bool +Broadside.Content.ContentOperands.GetEnumerator() -> Broadside.Content.ContentOperands.Enumerator +Broadside.Content.ContentOperands.this[int index].get -> Broadside.Content.ContentOperand +Broadside.Content.ContentOperator +Broadside.Content.ContentOperator.Code.get -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperator.ContentOperator() -> void +Broadside.Content.ContentOperator.Data.get -> System.ReadOnlySpan +Broadside.Content.ContentOperator.Keyword.get -> System.ReadOnlySpan +Broadside.Content.ContentOperator.KeywordOffset.get -> int +Broadside.Content.ContentOperator.Length.get -> int +Broadside.Content.ContentOperator.Offset.get -> int +Broadside.Content.ContentOperator.Operands.get -> Broadside.Content.ContentOperands +Broadside.Content.ContentOperator.PartIndex.get -> int +Broadside.Content.ContentOperator.Stream.get -> Broadside.Objects.CosReference? +Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.BeginCompatibility = 72 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.BeginInlineImage = 63 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.BeginInlineImageData = 64 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.BeginMarkedContent = 69 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.BeginMarkedContentWithProperties = 70 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.BeginText = 31 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.Clip = 29 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.ClipEvenOdd = 30 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.CloseAndStroke = 20 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.CloseFillAndStroke = 26 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.CloseFillEvenOddAndStroke = 27 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.ClosePath = 17 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.ConcatenateMatrix = 3 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.CurveTo = 14 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.CurveToFinalPointReplicated = 16 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.CurveToInitialPointReplicated = 15 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.EndCompatibility = 73 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.EndInlineImage = 65 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.EndMarkedContent = 71 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.EndPath = 28 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.EndText = 32 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.Fill = 21 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.FillAndStroke = 24 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.FillEvenOdd = 23 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.FillEvenOddAndStroke = 25 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.FillObsolete = 22 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.LineTo = 13 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.MarkPoint = 67 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.MarkPointWithProperties = 68 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.MoveText = 40 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.MoveTextSetLeading = 41 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.MoveTo = 12 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.NextLine = 43 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.NextLineShowText = 46 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.NextLineShowTextWithSpacing = 47 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.PaintShading = 62 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.PaintXObject = 66 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.Rectangle = 18 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.RestoreState = 2 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SaveState = 1 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetCharacterSpacing = 33 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetDash = 8 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetFillCmyk = 61 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetFillColor = 54 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetFillColorExtended = 55 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetFillColorSpace = 51 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetFillGray = 57 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetFillRgb = 59 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetFlatness = 10 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetFont = 37 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetGlyphWidth = 48 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetGlyphWidthAndBoundingBox = 49 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetGraphicsStateParameters = 11 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetHorizontalScaling = 35 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetLeading = 36 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetLineCap = 5 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetLineJoin = 6 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetLineWidth = 4 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetMiterLimit = 7 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetRenderingIntent = 9 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetStrokeCmyk = 60 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetStrokeColor = 52 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetStrokeColorExtended = 53 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetStrokeColorSpace = 50 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetStrokeGray = 56 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetStrokeRgb = 58 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetTextMatrix = 42 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetTextRenderingMode = 38 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetTextRise = 39 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.SetWordSpacing = 34 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.ShowText = 44 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.ShowTextAdjusted = 45 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.Stroke = 19 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOperatorCode.Unknown = 0 -> Broadside.Content.ContentOperatorCode +Broadside.Content.ContentOptions +Broadside.Content.ContentOptions.CancellationToken.get -> System.Threading.CancellationToken +Broadside.Content.ContentOptions.CancellationToken.set -> void +Broadside.Content.ContentOptions.ContentOptions() -> void +Broadside.Content.ContentOptions.MaxNestingDepth.get -> int +Broadside.Content.ContentOptions.MaxNestingDepth.set -> void +Broadside.Content.ContentOptions.MaxOperands.get -> int +Broadside.Content.ContentOptions.MaxOperands.set -> void +Broadside.Content.ContentOptions.MaxSaveDepth.get -> int +Broadside.Content.ContentOptions.MaxSaveDepth.set -> void +Broadside.Content.ContentOptions.WithCancellation(System.Threading.CancellationToken cancellationToken) -> Broadside.Content.ContentOptions! +Broadside.Content.ContentOptions.WithMaxNestingDepth(int maxNestingDepth) -> Broadside.Content.ContentOptions! +Broadside.Content.ContentOptions.WithMaxOperands(int maxOperands) -> Broadside.Content.ContentOptions! +Broadside.Content.ContentOptions.WithMaxSaveDepth(int maxSaveDepth) -> Broadside.Content.ContentOptions! +Broadside.Content.ContentProcessor +Broadside.Content.ContentProcessor.ContentProcessor() -> void +Broadside.Content.ContentRunKind +Broadside.Content.ContentRunKind.Appearance = 6 -> Broadside.Content.ContentRunKind +Broadside.Content.ContentRunKind.Form = 1 -> Broadside.Content.ContentRunKind +Broadside.Content.ContentRunKind.Group = 2 -> Broadside.Content.ContentRunKind +Broadside.Content.ContentRunKind.Page = 0 -> Broadside.Content.ContentRunKind +Broadside.Content.ContentRunKind.Pattern = 3 -> Broadside.Content.ContentRunKind +Broadside.Content.ContentRunKind.SoftMask = 5 -> Broadside.Content.ContentRunKind +Broadside.Content.ContentRunKind.Type3Glyph = 4 -> Broadside.Content.ContentRunKind +Broadside.Content.ContentVisit +Broadside.Content.ContentVisit.Enter = 0 -> Broadside.Content.ContentVisit +Broadside.Content.ContentVisit.Skip = 1 -> Broadside.Content.ContentVisit +Broadside.Content.FormEvent +Broadside.Content.FormEvent.BoundingBox.get -> Broadside.PdfRectangle +Broadside.Content.FormEvent.Depth.get -> int +Broadside.Content.FormEvent.FormEvent() -> void +Broadside.Content.FormEvent.Group.get -> Broadside.Objects.CosDictionary? +Broadside.Content.FormEvent.Matrix.get -> Broadside.Graphics.Matrix +Broadside.Content.FormEvent.Reference.get -> Broadside.Objects.CosReference? +Broadside.Content.FormEvent.ReferenceDictionary.get -> Broadside.Objects.CosDictionary? +Broadside.Content.FormEvent.ResourceName.get -> System.ReadOnlySpan +Broadside.Content.FormEvent.Resources.get -> Broadside.Objects.CosDictionary? +Broadside.Content.FormEvent.Stream.get -> Broadside.Objects.CosStream? +Broadside.Content.FormEvent.StructParent.get -> int? +Broadside.Content.FormEvent.StructParents.get -> int? +Broadside.Content.GlyphEvent +Broadside.Content.GlyphEvent.Adjustment.get -> double +Broadside.Content.GlyphEvent.AdvanceX.get -> double +Broadside.Content.GlyphEvent.AdvanceY.get -> double +Broadside.Content.GlyphEvent.CharacterCode.get -> uint +Broadside.Content.GlyphEvent.CodeLength.get -> int +Broadside.Content.GlyphEvent.Ctm.get -> Broadside.Graphics.Matrix +Broadside.Content.GlyphEvent.FontDictionary.get -> Broadside.Objects.CosDictionary? +Broadside.Content.GlyphEvent.GlyphEvent() -> void +Broadside.Content.GlyphEvent.HorizontalDisplacement.get -> double +Broadside.Content.GlyphEvent.IsHidden.get -> bool +Broadside.Content.GlyphEvent.IsVertical.get -> bool +Broadside.Content.GlyphEvent.RenderingMode.get -> Broadside.Graphics.TextRenderingMode +Broadside.Content.GlyphEvent.SourceBytes.get -> System.ReadOnlySpan +Broadside.Content.GlyphEvent.SourceIndex.get -> int +Broadside.Content.GlyphEvent.TextMatrix.get -> Broadside.Graphics.Matrix +Broadside.Content.GlyphEvent.VerticalDisplacement.get -> double +Broadside.Content.GlyphEvent.WordSpacingApplied.get -> bool +Broadside.Content.ImageEvent +Broadside.Content.ImageEvent.Ctm.get -> Broadside.Graphics.Matrix +Broadside.Content.ImageEvent.ImageEvent() -> void +Broadside.Content.ImageEvent.InlineData.get -> System.ReadOnlySpan +Broadside.Content.ImageEvent.InlineDictionary.get -> Broadside.Content.ContentOperand +Broadside.Content.ImageEvent.IsHidden.get -> bool +Broadside.Content.ImageEvent.IsInline.get -> bool +Broadside.Content.ImageEvent.IsStencil.get -> bool +Broadside.Content.ImageEvent.Reference.get -> Broadside.Objects.CosReference? +Broadside.Content.ImageEvent.ResourceName.get -> System.ReadOnlySpan +Broadside.Content.ImageEvent.Stream.get -> Broadside.Objects.CosStream? +Broadside.Content.ImageEvent.StructParent.get -> int? +Broadside.Content.MarkedContentEvent +Broadside.Content.MarkedContentEvent.Depth.get -> int +Broadside.Content.MarkedContentEvent.InlineProperties.get -> Broadside.Content.ContentOperand +Broadside.Content.MarkedContentEvent.IsHidden.get -> bool +Broadside.Content.MarkedContentEvent.MarkedContentEvent() -> void +Broadside.Content.MarkedContentEvent.Mcid.get -> int? +Broadside.Content.MarkedContentEvent.Properties.get -> Broadside.Objects.CosDictionary? +Broadside.Content.MarkedContentEvent.Tag.get -> System.ReadOnlySpan +Broadside.Content.PathEvent +Broadside.Content.PathEvent.ClosedBeforePaint.get -> bool +Broadside.Content.PathEvent.FillRule.get -> Broadside.Graphics.FillRule +Broadside.Content.PathEvent.IsHidden.get -> bool +Broadside.Content.PathEvent.Paint.get -> Broadside.Content.PathPaint +Broadside.Content.PathEvent.Path.get -> Broadside.Graphics.PathView +Broadside.Content.PathEvent.PathEvent() -> void +Broadside.Content.PathEvent.PendingClip.get -> Broadside.Graphics.FillRule? +Broadside.Content.PathPaint +Broadside.Content.PathPaint.Fill = 2 -> Broadside.Content.PathPaint +Broadside.Content.PathPaint.FillAndStroke = 3 -> Broadside.Content.PathPaint +Broadside.Content.PathPaint.None = 0 -> Broadside.Content.PathPaint +Broadside.Content.PathPaint.Stroke = 1 -> Broadside.Content.PathPaint +Broadside.Content.ShadingEvent +Broadside.Content.ShadingEvent.Ctm.get -> Broadside.Graphics.Matrix +Broadside.Content.ShadingEvent.IsHidden.get -> bool +Broadside.Content.ShadingEvent.ResourceName.get -> System.ReadOnlySpan +Broadside.Content.ShadingEvent.Shading.get -> Broadside.Objects.CosObject? +Broadside.Content.ShadingEvent.ShadingEvent() -> void +Broadside.Graphics.BlendMode +Broadside.Graphics.BlendMode.Color = 14 -> Broadside.Graphics.BlendMode +Broadside.Graphics.BlendMode.ColorBurn = 7 -> Broadside.Graphics.BlendMode +Broadside.Graphics.BlendMode.ColorDodge = 6 -> Broadside.Graphics.BlendMode +Broadside.Graphics.BlendMode.Darken = 4 -> Broadside.Graphics.BlendMode +Broadside.Graphics.BlendMode.Difference = 10 -> Broadside.Graphics.BlendMode +Broadside.Graphics.BlendMode.Exclusion = 11 -> Broadside.Graphics.BlendMode +Broadside.Graphics.BlendMode.HardLight = 8 -> Broadside.Graphics.BlendMode +Broadside.Graphics.BlendMode.Hue = 12 -> Broadside.Graphics.BlendMode +Broadside.Graphics.BlendMode.Lighten = 5 -> Broadside.Graphics.BlendMode +Broadside.Graphics.BlendMode.Luminosity = 15 -> Broadside.Graphics.BlendMode +Broadside.Graphics.BlendMode.Multiply = 1 -> Broadside.Graphics.BlendMode +Broadside.Graphics.BlendMode.Normal = 0 -> Broadside.Graphics.BlendMode +Broadside.Graphics.BlendMode.Overlay = 3 -> Broadside.Graphics.BlendMode +Broadside.Graphics.BlendMode.Saturation = 13 -> Broadside.Graphics.BlendMode +Broadside.Graphics.BlendMode.Screen = 2 -> Broadside.Graphics.BlendMode +Broadside.Graphics.BlendMode.SoftLight = 9 -> Broadside.Graphics.BlendMode +Broadside.Graphics.FillRule +Broadside.Graphics.FillRule.EvenOdd = 1 -> Broadside.Graphics.FillRule +Broadside.Graphics.FillRule.NonZero = 0 -> Broadside.Graphics.FillRule +Broadside.Graphics.GraphicsState +Broadside.Graphics.GraphicsState.AlphaIsShape.get -> bool +Broadside.Graphics.GraphicsState.BlendMode.get -> Broadside.Graphics.BlendMode +Broadside.Graphics.GraphicsState.CharacterSpacing.get -> double +Broadside.Graphics.GraphicsState.ClipHandle.get -> int +Broadside.Graphics.GraphicsState.Ctm.get -> Broadside.Graphics.Matrix +Broadside.Graphics.GraphicsState.DashArray.get -> System.ReadOnlySpan +Broadside.Graphics.GraphicsState.DashPhase.get -> double +Broadside.Graphics.GraphicsState.FillAlpha.get -> double +Broadside.Graphics.GraphicsState.FillOverprint.get -> bool +Broadside.Graphics.GraphicsState.Flatness.get -> double +Broadside.Graphics.GraphicsState.FontSize.get -> double +Broadside.Graphics.GraphicsState.GraphicsState() -> void +Broadside.Graphics.GraphicsState.HorizontalScaling.get -> double +Broadside.Graphics.GraphicsState.Leading.get -> double +Broadside.Graphics.GraphicsState.LineCap.get -> Broadside.Graphics.LineCap +Broadside.Graphics.GraphicsState.LineJoin.get -> Broadside.Graphics.LineJoin +Broadside.Graphics.GraphicsState.LineWidth.get -> double +Broadside.Graphics.GraphicsState.MiterLimit.get -> double +Broadside.Graphics.GraphicsState.OverprintMode.get -> int +Broadside.Graphics.GraphicsState.RenderingIntent.get -> Broadside.Graphics.RenderingIntent +Broadside.Graphics.GraphicsState.StrokeAdjustment.get -> bool +Broadside.Graphics.GraphicsState.StrokeAlpha.get -> double +Broadside.Graphics.GraphicsState.StrokeOverprint.get -> bool +Broadside.Graphics.GraphicsState.TextKnockout.get -> bool +Broadside.Graphics.GraphicsState.TextRenderingMode.get -> Broadside.Graphics.TextRenderingMode +Broadside.Graphics.GraphicsState.TextRise.get -> double +Broadside.Graphics.GraphicsState.WordSpacing.get -> double +Broadside.Graphics.LineCap +Broadside.Graphics.LineCap.Butt = 0 -> Broadside.Graphics.LineCap +Broadside.Graphics.LineCap.ProjectingSquare = 2 -> Broadside.Graphics.LineCap +Broadside.Graphics.LineCap.Round = 1 -> Broadside.Graphics.LineCap +Broadside.Graphics.LineJoin +Broadside.Graphics.LineJoin.Bevel = 2 -> Broadside.Graphics.LineJoin +Broadside.Graphics.LineJoin.Miter = 0 -> Broadside.Graphics.LineJoin +Broadside.Graphics.LineJoin.Round = 1 -> Broadside.Graphics.LineJoin +Broadside.Graphics.Matrix +Broadside.Graphics.Matrix.A.get -> double +Broadside.Graphics.Matrix.B.get -> double +Broadside.Graphics.Matrix.C.get -> double +Broadside.Graphics.Matrix.D.get -> double +Broadside.Graphics.Matrix.Determinant.get -> double +Broadside.Graphics.Matrix.E.get -> double +Broadside.Graphics.Matrix.Equals(Broadside.Graphics.Matrix other) -> bool +Broadside.Graphics.Matrix.F.get -> double +Broadside.Graphics.Matrix.IsIdentity.get -> bool +Broadside.Graphics.Matrix.Matrix() -> void +Broadside.Graphics.Matrix.Matrix(double a, double b, double c, double d, double e, double f) -> void +Broadside.Graphics.Matrix.Transform(Broadside.Graphics.PathPoint point) -> Broadside.Graphics.PathPoint +Broadside.Graphics.Matrix.Transform(double x, double y) -> Broadside.Graphics.PathPoint +Broadside.Graphics.Matrix.TransformVector(double dx, double dy) -> Broadside.Graphics.PathPoint +Broadside.Graphics.Matrix.TryInvert(out Broadside.Graphics.Matrix inverse) -> bool +Broadside.Graphics.PathPoint +Broadside.Graphics.PathPoint.PathPoint() -> void +Broadside.Graphics.PathPoint.PathPoint(double X, double Y) -> void +Broadside.Graphics.PathPoint.X.get -> double +Broadside.Graphics.PathPoint.X.init -> void +Broadside.Graphics.PathPoint.Y.get -> double +Broadside.Graphics.PathPoint.Y.init -> void +Broadside.Graphics.PathVerb +Broadside.Graphics.PathVerb.Close = 4 -> Broadside.Graphics.PathVerb +Broadside.Graphics.PathVerb.CubicTo = 3 -> Broadside.Graphics.PathVerb +Broadside.Graphics.PathVerb.LineTo = 1 -> Broadside.Graphics.PathVerb +Broadside.Graphics.PathVerb.MoveTo = 0 -> Broadside.Graphics.PathVerb +Broadside.Graphics.PathVerb.QuadTo = 2 -> Broadside.Graphics.PathVerb +Broadside.Graphics.PathView +Broadside.Graphics.PathView.Bounds.get -> Broadside.PdfRectangle +Broadside.Graphics.PathView.HasTrailingMoveTo.get -> bool +Broadside.Graphics.PathView.IsEmpty.get -> bool +Broadside.Graphics.PathView.PathView() -> void +Broadside.Graphics.PathView.PathView(System.ReadOnlySpan verbs, System.ReadOnlySpan points) -> void +Broadside.Graphics.PathView.Points.get -> System.ReadOnlySpan +Broadside.Graphics.PathView.Verbs.get -> System.ReadOnlySpan +Broadside.Graphics.RenderingIntent +Broadside.Graphics.RenderingIntent.AbsoluteColorimetric = 1 -> Broadside.Graphics.RenderingIntent +Broadside.Graphics.RenderingIntent.Perceptual = 3 -> Broadside.Graphics.RenderingIntent +Broadside.Graphics.RenderingIntent.RelativeColorimetric = 0 -> Broadside.Graphics.RenderingIntent +Broadside.Graphics.RenderingIntent.Saturation = 2 -> Broadside.Graphics.RenderingIntent +Broadside.Graphics.TextRenderingMode +Broadside.Graphics.TextRenderingMode.Clip = 7 -> Broadside.Graphics.TextRenderingMode +Broadside.Graphics.TextRenderingMode.Fill = 0 -> Broadside.Graphics.TextRenderingMode +Broadside.Graphics.TextRenderingMode.FillClip = 4 -> Broadside.Graphics.TextRenderingMode +Broadside.Graphics.TextRenderingMode.FillStroke = 2 -> Broadside.Graphics.TextRenderingMode +Broadside.Graphics.TextRenderingMode.FillStrokeClip = 6 -> Broadside.Graphics.TextRenderingMode +Broadside.Graphics.TextRenderingMode.Invisible = 3 -> Broadside.Graphics.TextRenderingMode +Broadside.Graphics.TextRenderingMode.Stroke = 1 -> Broadside.Graphics.TextRenderingMode +Broadside.Graphics.TextRenderingMode.StrokeClip = 5 -> Broadside.Graphics.TextRenderingMode Broadside.Objects.CosArray Broadside.Objects.CosArray.Add(Broadside.Objects.CosObject! item) -> void Broadside.Objects.CosArray.Clear() -> void @@ -65,7 +437,36 @@ Broadside.Objects.CosString.CosString(System.ReadOnlySpan bytes, bool hexa Broadside.Objects.CosString.DecodeText() -> string! Broadside.Objects.CosString.Equals(Broadside.Objects.CosString? other) -> bool Broadside.Objects.CosString.IsHexadecimal.get -> bool +Broadside.PdfPage.ProcessContent(Broadside.Content.ContentProcessor! processor) -> void +Broadside.PdfPage.ProcessContent(Broadside.Content.ContentProcessor! processor, Broadside.Content.ContentOptions! options) -> void +const Broadside.Content.ContentOptions.DefaultMaxNestingDepth = 50 -> int +const Broadside.Content.ContentOptions.DefaultMaxOperands = 65536 -> int +const Broadside.Content.ContentOptions.DefaultMaxSaveDepth = 4096 -> int const Broadside.Objects.CosReference.MaxGeneration = 65535 -> int +override Broadside.Content.CompositeContentProcessor.BeginForm(in Broadside.Content.FormEvent form, Broadside.Content.ContentContext! context) -> Broadside.Content.ContentVisit +override Broadside.Content.CompositeContentProcessor.BeginMarkedContent(in Broadside.Content.MarkedContentEvent mc, Broadside.Content.ContentContext! context) -> void +override Broadside.Content.CompositeContentProcessor.BeginRun(Broadside.Content.ContentContext! context) -> void +override Broadside.Content.CompositeContentProcessor.BeginText(Broadside.Content.ContentContext! context) -> void +override Broadside.Content.CompositeContentProcessor.BeginType3Glyph(in Broadside.Content.GlyphEvent glyph, Broadside.Content.ContentContext! context) -> Broadside.Content.ContentVisit +override Broadside.Content.CompositeContentProcessor.EndForm(in Broadside.Content.FormEvent form, Broadside.Content.ContentContext! context) -> void +override Broadside.Content.CompositeContentProcessor.EndMarkedContent(in Broadside.Content.MarkedContentEvent mc, Broadside.Content.ContentContext! context) -> void +override Broadside.Content.CompositeContentProcessor.EndRun(Broadside.Content.ContentContext! context) -> void +override Broadside.Content.CompositeContentProcessor.EndText(Broadside.Content.ContentContext! context) -> void +override Broadside.Content.CompositeContentProcessor.EndType3Glyph(in Broadside.Content.GlyphEvent glyph, Broadside.Content.ContentContext! context) -> void +override Broadside.Content.CompositeContentProcessor.Events.get -> Broadside.Content.ContentEvents +override Broadside.Content.CompositeContentProcessor.IntersectClip(in Broadside.Content.ClipEvent clip, Broadside.Content.ContentContext! context) -> void +override Broadside.Content.CompositeContentProcessor.MarkedContentPoint(in Broadside.Content.MarkedContentEvent mc, Broadside.Content.ContentContext! context) -> void +override Broadside.Content.CompositeContentProcessor.PaintImage(in Broadside.Content.ImageEvent image, Broadside.Content.ContentContext! context) -> void +override Broadside.Content.CompositeContentProcessor.PaintPath(in Broadside.Content.PathEvent path, Broadside.Content.ContentContext! context) -> void +override Broadside.Content.CompositeContentProcessor.PaintShading(in Broadside.Content.ShadingEvent shading, Broadside.Content.ContentContext! context) -> void +override Broadside.Content.CompositeContentProcessor.RestoreState(Broadside.Content.ContentContext! context) -> void +override Broadside.Content.CompositeContentProcessor.SaveState(Broadside.Content.ContentContext! context) -> void +override Broadside.Content.CompositeContentProcessor.ShowGlyph(in Broadside.Content.GlyphEvent glyph, Broadside.Content.ContentContext! context) -> void +override Broadside.Content.CompositeContentProcessor.VisitOperator(in Broadside.Content.ContentOperator op, Broadside.Content.ContentContext! context) -> void +override Broadside.Graphics.Matrix.Equals(object? obj) -> bool +override Broadside.Graphics.Matrix.GetHashCode() -> int +override Broadside.Graphics.Matrix.ToString() -> string! +override Broadside.Graphics.PathPoint.ToString() -> string! override Broadside.Objects.CosArray.IsDirty.get -> bool override Broadside.Objects.CosBoolean.Equals(object? obj) -> bool override Broadside.Objects.CosBoolean.GetHashCode() -> int @@ -84,12 +485,39 @@ override Broadside.Objects.CosReference.GetHashCode() -> int override Broadside.Objects.CosStream.IsDirty.get -> bool override Broadside.Objects.CosString.Equals(object? obj) -> bool override Broadside.Objects.CosString.GetHashCode() -> int +static Broadside.Graphics.Matrix.CreateScale(double sx, double sy) -> Broadside.Graphics.Matrix +static Broadside.Graphics.Matrix.CreateTranslation(double tx, double ty) -> Broadside.Graphics.Matrix +static Broadside.Graphics.Matrix.Identity.get -> Broadside.Graphics.Matrix +static Broadside.Graphics.Matrix.Multiply(Broadside.Graphics.Matrix first, Broadside.Graphics.Matrix second) -> Broadside.Graphics.Matrix +static Broadside.Graphics.Matrix.operator !=(Broadside.Graphics.Matrix left, Broadside.Graphics.Matrix right) -> bool +static Broadside.Graphics.Matrix.operator *(Broadside.Graphics.Matrix first, Broadside.Graphics.Matrix second) -> Broadside.Graphics.Matrix +static Broadside.Graphics.Matrix.operator ==(Broadside.Graphics.Matrix left, Broadside.Graphics.Matrix right) -> bool static Broadside.Objects.CosBoolean.False.get -> Broadside.Objects.CosBoolean! static Broadside.Objects.CosBoolean.True.get -> Broadside.Objects.CosBoolean! static Broadside.Objects.CosNull.Instance.get -> Broadside.Objects.CosNull! static Broadside.Objects.CosObject.DeepEquals(Broadside.Objects.CosObject? left, Broadside.Objects.CosObject? right) -> bool static Broadside.Objects.CosObject.Parse(System.ReadOnlySpan bytes) -> Broadside.Objects.CosObject! static Broadside.Objects.CosObject.TryParse(System.ReadOnlySpan bytes, out Broadside.Objects.CosObject? result) -> bool +virtual Broadside.Content.ContentProcessor.BeginForm(in Broadside.Content.FormEvent form, Broadside.Content.ContentContext! context) -> Broadside.Content.ContentVisit +virtual Broadside.Content.ContentProcessor.BeginMarkedContent(in Broadside.Content.MarkedContentEvent mc, Broadside.Content.ContentContext! context) -> void +virtual Broadside.Content.ContentProcessor.BeginRun(Broadside.Content.ContentContext! context) -> void +virtual Broadside.Content.ContentProcessor.BeginText(Broadside.Content.ContentContext! context) -> void +virtual Broadside.Content.ContentProcessor.BeginType3Glyph(in Broadside.Content.GlyphEvent glyph, Broadside.Content.ContentContext! context) -> Broadside.Content.ContentVisit +virtual Broadside.Content.ContentProcessor.EndForm(in Broadside.Content.FormEvent form, Broadside.Content.ContentContext! context) -> void +virtual Broadside.Content.ContentProcessor.EndMarkedContent(in Broadside.Content.MarkedContentEvent mc, Broadside.Content.ContentContext! context) -> void +virtual Broadside.Content.ContentProcessor.EndRun(Broadside.Content.ContentContext! context) -> void +virtual Broadside.Content.ContentProcessor.EndText(Broadside.Content.ContentContext! context) -> void +virtual Broadside.Content.ContentProcessor.EndType3Glyph(in Broadside.Content.GlyphEvent glyph, Broadside.Content.ContentContext! context) -> void +virtual Broadside.Content.ContentProcessor.Events.get -> Broadside.Content.ContentEvents +virtual Broadside.Content.ContentProcessor.IntersectClip(in Broadside.Content.ClipEvent clip, Broadside.Content.ContentContext! context) -> void +virtual Broadside.Content.ContentProcessor.MarkedContentPoint(in Broadside.Content.MarkedContentEvent mc, Broadside.Content.ContentContext! context) -> void +virtual Broadside.Content.ContentProcessor.PaintImage(in Broadside.Content.ImageEvent image, Broadside.Content.ContentContext! context) -> void +virtual Broadside.Content.ContentProcessor.PaintPath(in Broadside.Content.PathEvent path, Broadside.Content.ContentContext! context) -> void +virtual Broadside.Content.ContentProcessor.PaintShading(in Broadside.Content.ShadingEvent shading, Broadside.Content.ContentContext! context) -> void +virtual Broadside.Content.ContentProcessor.RestoreState(Broadside.Content.ContentContext! context) -> void +virtual Broadside.Content.ContentProcessor.SaveState(Broadside.Content.ContentContext! context) -> void +virtual Broadside.Content.ContentProcessor.ShowGlyph(in Broadside.Content.GlyphEvent glyph, Broadside.Content.ContentContext! context) -> void +virtual Broadside.Content.ContentProcessor.VisitOperator(in Broadside.Content.ContentOperator op, Broadside.Content.ContentContext! context) -> void virtual Broadside.Objects.CosObject.IsDirty.get -> bool Broadside.Diagnostics.Diagnostic Broadside.Diagnostics.Diagnostic.Code.get -> string! diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 4a3ab467..ea80b0c9 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -1,6 +1,8 @@ using System.Buffers; +using Broadside.Content; using Broadside.Diagnostics; using Broadside.Filters; +using Broadside.Graphics; using Broadside.IO; using Broadside.Objects; using Broadside.Parsing; @@ -19,6 +21,8 @@ internal static class FuzzTargets public static IReadOnlyDictionary All { get; } = new Dictionary(StringComparer.Ordinal) { ["lexer"] = Lexer, + ["content-lexer"] = ContentLexer, + ["content-interpreter"] = ContentInterpreterTarget, ["object-parser"] = ObjectParser, ["document"] = Document, ["windowed-document"] = WindowedDocument, @@ -40,6 +44,7 @@ internal static class FuzzTargets }; private static readonly CosName ContentsKey = new("Contents"); + private static readonly Lazy EmptyDocument = new(() => PdfDocument.Create()); private static readonly CosName InfoKey = new("Info"); /// @@ -96,6 +101,8 @@ private static void Document(ReadOnlySpan data) { _ = document.DecodeStream(stream); } + + page.ProcessContent(new CheckingProcessor()); } } @@ -576,6 +583,51 @@ private static void Lexer(ReadOnlySpan data) } } + /// + /// Reads the input as decoded content: operator by operator, with operands. Every operator's ranges must lie inside the input, + /// after the previous operator, with a keyword of one byte or more (so the reader always progresses), and every operand, + /// nested ones included, must be readable. + /// + /// ISO 32000-2 §7.8.2 (issue #55). + private static void ContentLexer(ReadOnlySpan data) + { + var arena = new OperandArena(); + var reader = new ContentReader(data, arena); + int previousEnd = 0; + while (reader.Next(out ReadOperator op)) + { + if (op.Start > op.KeywordStart || op.KeywordStart < previousEnd || op.KeywordLength < 1 || op.KeywordStart + op.KeywordLength > op.End + || op.End > data.Length || op.DataStart < 0 || op.DataLength < 0 || op.DataStart + op.DataLength > data.Length) + { + throw new InvalidOperationException($"Operator {op} lies outside the input of {data.Length} bytes or before the previous end {previousEnd}."); + } + + _ = Walk(arena.Operands); + arena.Clear(); + previousEnd = op.KeywordStart + op.KeywordLength; + } + } + + private static double Walk(ContentOperands operands) + { + double sum = 0; + foreach (ContentOperand operand in operands) + { + sum += operand.Number + operand.Bytes.Length + Walk(operand.Items); + } + + return sum; + } + + /// + /// Runs the input as a page's decoded content through the interpreter with a processor that asks for every event and checks + /// what it receives: path verbs and points agree, clip handles resolve and chain back to the initial clip, the state stack is + /// balanced at the end of the run. Lenient mode: no exception may escape. + /// + /// ISO 32000-2 §7.8.2, §8.4, §8.5 (issue #55). + private static void ContentInterpreterTarget(ReadOnlySpan data) => + ContentInterpreter.RunBytes(data, EmptyDocument.Value, new CheckingProcessor(), ContentInterpreter.DefaultOptions); + /// /// Parses the input as a sequence of objects in lenient mode, the way a reader scans a file body, then checks the round-trip /// property for each object: what writes parses back, with no repair, to an equal object. Also @@ -620,3 +672,63 @@ private static void CheckRoundTrip(CosObject parsed) } } } + +/// A processor for the content targets: asks for every event and throws when what it receives is inconsistent. +internal sealed class CheckingProcessor : ContentProcessor +{ + private int _saves; + + public override void BeginRun(ContentContext context) => _saves = 0; + + public override void SaveState(ContentContext context) => _saves++; + + public override void RestoreState(ContentContext context) => _saves--; + + public override void EndRun(ContentContext context) + { + if (_saves != 0 || context.StateDepth != 0) + { + throw new InvalidOperationException($"The state stack is unbalanced at the end of the run: {_saves} saves, depth {context.StateDepth}."); + } + } + + public override void PaintPath(in PathEvent path, ContentContext context) => Check(path.Path); + + public override void IntersectClip(in ClipEvent clip, ContentContext context) + { + Check(clip.Path); + if (context.State.ClipHandle != clip.Handle || clip.ParentHandle >= clip.Handle) + { + throw new InvalidOperationException($"Clip {clip.Handle} (parent {clip.ParentHandle}) is not the state's clip {context.State.ClipHandle}."); + } + + int steps = 0; + for (int handle = clip.Handle; handle != 0; handle = context.GetClip(handle).ParentHandle) + { + if (++steps > clip.Handle) + { + throw new InvalidOperationException($"Clip {clip.Handle} does not chain back to the initial clip."); + } + } + } + + private static void Check(PathView path) + { + int points = 0; + foreach (PathVerb verb in path.Verbs) + { + points += verb switch + { + PathVerb.MoveTo or PathVerb.LineTo => 1, + PathVerb.QuadTo => 2, + PathVerb.CubicTo => 3, + _ => 0, + }; + } + + if (points != path.Points.Length || (path.Verbs.Length > 0 && path.Verbs[0] != PathVerb.MoveTo)) + { + throw new InvalidOperationException($"A path with {path.Verbs.Length} verbs has {path.Points.Length} points, expected {points}, or does not start with a moveto."); + } + } +} diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index 1a3db895..14fe5858 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. `content-lexer` reads the input as decoded content stream bytes with the content reader (ISO 32000-2 §7.8.2, #55): every operator must lie inside the input, after the previous one, with a keyword of at least one byte, and every operand, nested arrays and dictionaries included, must be readable; `content-interpreter` runs the input as a page's content through the interpreter with a processor that asks for every event and checks that path verbs and points agree, that clip handles chain back to the initial clip and that the state stack is balanced at the end; `document` now also interprets every page with that processor. Whole files are weak seeds for the two content targets; for libFuzzer and AFL seed them with decoded content streams (`qpdf --show-object=4 --filtered-stream-data tests/Corpus/filter-chain.pdf`) and with `ContentSamples.PathHeavy` output. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. diff --git a/tests/Broadside.TestSupport/ContentSamples.cs b/tests/Broadside.TestSupport/ContentSamples.cs new file mode 100644 index 00000000..c62866d7 --- /dev/null +++ b/tests/Broadside.TestSupport/ContentSamples.cs @@ -0,0 +1,34 @@ +using System.Globalization; +using System.Text; + +namespace Broadside.TestSupport; + +/// +/// Synthetic content streams for the content interpreter's allocation tests and benchmarks: deterministic, well-formed, and heavy +/// in the operators a path renderer sees most (ISO 32000-2 §8.4.4, §8.5). +/// +public static class ContentSamples +{ + /// + /// A path-heavy content stream of at least bytes: blocks of state changes, paths built with + /// every construction operator, every painting operator, and clips, each block balanced in q/Q. + /// + public static byte[] PathHeavy(int minimumLength) + { + var text = new StringBuilder(minimumLength + 512); + int block = 0; + while (text.Length < minimumLength) + { + double x = block % 500 * 1.25; + double y = block % 700 * 0.75; + text.Append(CultureInfo.InvariantCulture, $"q 1 0 0 1 {x} {y} cm {block % 7 + 0.5} w {block % 3} J {block % 3} j 4 M [3 {block % 4 + 1}] 0.5 d /Perceptual ri 1 i\n"); + text.Append(CultureInfo.InvariantCulture, $"0 0 m 100.5 0 l 100 100.25 l 50 150 25 175 0 100 c h S\n"); + text.Append(CultureInfo.InvariantCulture, $"10 10 m 20 30 40 50 v 60 70 80 90 y s\n"); + text.Append(CultureInfo.InvariantCulture, $"{x} {y} 50 -25 re f 0 0 10 10 re f* 5 5 m 6 6 l B 7 7 m 8 8 l B* 1 1 m 2 2 l b 3 3 m 4 4 l b*\n"); + text.Append("0 0 200 200 re W n 0 0 300 300 re W* n BX 1 2 3 newop EX Q\n"); + block++; + } + + return Encoding.ASCII.GetBytes(text.ToString()); + } +} diff --git a/tests/Broadside.Tests/Content/ClipTests.cs b/tests/Broadside.Tests/Content/ClipTests.cs new file mode 100644 index 00000000..f9c78cb6 --- /dev/null +++ b/tests/Broadside.Tests/Content/ClipTests.cs @@ -0,0 +1,123 @@ +using Broadside.Content; + +namespace Broadside.Tests.Content; + +/// +/// W and W* narrow the clip after the painting operator of their path object, never before it, and Q brings +/// the earlier clip back. ISO 32000-2 §8.5.4, Table 60. +/// +public class ClipTests +{ + private const ContentEvents PathsAndClips = ContentEvents.Paths | ContentEvents.Clips; + + [Fact] + public void W_s_strokes_the_path_unclipped_by_itself_and_clips_after_the_stroke() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("0 0 m 10 0 l 10 10 l h W S", PathsAndClips); + + Assert.Equal( + [ + "Paint Stroke NonZero clip=NonZero M 0,0 L 10,0 L 10,10 Z ctm=[1 0 0 1 0 0]", + "Clip Path NonZero #1<#0 M 0,0 L 10,0 L 10,10 Z ctm=[1 0 0 1 0 0]", + ], + events.Body); + Assert.Empty(diagnostics); + } + + [Fact] + public void The_state_at_the_paint_still_holds_the_old_clip_and_after_it_the_new_one() + { + var probe = new ClipProbe(); + using PdfDocument document = PdfDocument.Open(ContentPdf.Build("0 0 10 10 re W* f 0 0 m 5 5 l S")); + + document.Pages[0].ProcessContent(probe); + + Assert.Equal([0, 1], probe.ClipAtPaint); + Assert.Equal([1], probe.ClipInEvent); + } + + [Fact] + public void W_n_only_intersects_the_clip() + { + (RecordingProcessor events, _) = ContentPdf.Run("2 0 0 2 0 0 cm 0 0 5 5 re W* n", PathsAndClips); + + Assert.Equal( + [ + "Paint None NonZero clip=EvenOdd M 0,0 L 5,0 L 5,5 L 0,5 Z ctm=[2 0 0 2 0 0]", + "Clip Path EvenOdd #1<#0 M 0,0 L 5,0 L 5,5 L 0,5 Z ctm=[2 0 0 2 0 0]", + ], + events.Body); + } + + [Fact] + public void Nested_clips_chain_to_their_parents_and_q_restores_the_earlier_clip() + { + var probe = new ClipProbe(); + using PdfDocument document = PdfDocument.Open(ContentPdf.Build( + "0 0 100 100 re W n q 10 10 50 50 re W n 0 0 m 1 1 l S Q 0 0 m 1 1 l S")); + + document.Pages[0].ProcessContent(probe); + + Assert.Equal([1, 2, 1], probe.ClipAtPaint.Where((_, index) => index > 0)); + Assert.Equal([0, 1], probe.Parents); + Assert.Equal([ClipKind.Path, ClipKind.Initial], probe.Chain); + } + + [Fact] + public void W_without_a_path_is_ignored() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("W n", PathsAndClips); + + Assert.Empty(events.Body); + Assert.Equal(["ContentNoCurrentPath"], ContentPdf.Codes(diagnostics)); + } + + [Fact] + public void Without_clip_events_the_clip_handle_stays_at_the_initial_clip() + { + var probe = new ClipProbe(ContentEvents.Paths); + using PdfDocument document = PdfDocument.Open(ContentPdf.Build("0 0 10 10 re W n 0 0 m 1 1 l S")); + + document.Pages[0].ProcessContent(probe); + + Assert.Equal([0, 0], probe.ClipAtPaint); + Assert.Empty(probe.ClipInEvent); + } +} + +/// Records clip handles at each paint and clip event, and the chain of the last paint's clip. +internal sealed class ClipProbe(ContentEvents events = ContentEvents.Paths | ContentEvents.Clips) : ContentProcessor +{ + public List ClipAtPaint { get; } = []; + + public List ClipInEvent { get; } = []; + + public List Parents { get; } = []; + + public List Chain { get; } = []; + + public override ContentEvents Events => events; + + public override void PaintPath(in PathEvent path, ContentContext context) + { + ClipAtPaint.Add(context.State.ClipHandle); + Chain.Clear(); + for (int handle = context.State.ClipHandle; ; handle = context.GetClip(handle).ParentHandle) + { + ClipView clip = context.GetClip(handle); + Chain.Add(clip.Kind); + if (handle == 0) + { + break; + } + } + } + + public override void IntersectClip(in ClipEvent clip, ContentContext context) + { + Assert.Equal(clip.Handle, context.State.ClipHandle); + ClipInEvent.Add(clip.Handle); + Parents.Add(clip.ParentHandle); + Assert.Equal(clip.Rule, context.GetClip(clip.Handle).Rule); + } +} diff --git a/tests/Broadside.Tests/Content/ContentAllocationTests.cs b/tests/Broadside.Tests/Content/ContentAllocationTests.cs new file mode 100644 index 00000000..77cbf10c --- /dev/null +++ b/tests/Broadside.Tests/Content/ContentAllocationTests.cs @@ -0,0 +1,127 @@ +using Broadside.Content; +using Broadside.TestSupport; + +namespace Broadside.Tests.Content; + +/// +/// The content lexer and interpreter are hot paths and allocate nothing per operator (CLAUDE.md, "Code conventions"). This is +/// the build-breaking half of that rule; ContentLexerBenchmarks and ContentInterpreterBenchmarks in +/// bench/Broadside.Benchmarks are the measuring half. The lexer test drives the internal reader because no public seam +/// exposes it alone; the interpreter test goes through . +/// +public class ContentAllocationTests +{ + private const int WarmUp = 50; + + [Fact] + public void Reading_a_megabyte_of_path_operators_allocates_nothing() + { + byte[] content = ContentSamples.PathHeavy(1 << 20); + var arena = new OperandArena(); + for (int pass = 0; pass < WarmUp; pass++) + { + ReadAll(content, arena); + } + + long before = GC.GetAllocatedBytesForCurrentThread(); + int operators = ReadAll(content, arena); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.True(operators > 100_000, $"Only {operators} operators."); + Assert.Equal(0, allocated); + } + + [Fact] + public void Reading_the_filter_chain_content_allocates_nothing() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("filter-chain.pdf")); + byte[] content = document.DecodeStream(Filters.CorpusFilterTests.ContentStream(document)).ToArray(); + var arena = new OperandArena(); + for (int pass = 0; pass < WarmUp; pass++) + { + ReadAll(content, arena); + } + + long before = GC.GetAllocatedBytesForCurrentThread(); + int operators = ReadAll(content, arena); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.Equal(5, operators); + Assert.Equal(0, allocated); + } + + [Fact] + public void Interpreting_a_page_allocates_nothing_once_warm() + { + using PdfDocument document = PdfDocument.Open(ContentPdf.Build(System.Text.Encoding.ASCII.GetString(ContentSamples.PathHeavy(1 << 20)))); + PdfPage page = document.Pages[0]; + var processor = new CountingProcessor(); + for (int pass = 0; pass < WarmUp; pass++) + { + page.ProcessContent(processor); + } + + processor.Reset(); + long before = GC.GetAllocatedBytesForCurrentThread(); + page.ProcessContent(processor); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.True(processor.Paints > 20_000, $"Only {processor.Paints} paints."); + Assert.True(processor.Clips > 5_000, $"Only {processor.Clips} clips."); + Assert.Equal(0, allocated); + Assert.Empty(document.Diagnostics); + } + + private static int ReadAll(ReadOnlySpan content, OperandArena arena) + { + var reader = new ContentReader(content, arena); + int count = 0; + while (reader.Next(out _)) + { + arena.Clear(); + count++; + } + + arena.Clear(); + return count; + } +} + +/// Counts events of every kind and reads every operand, the work a real processor does per event, without allocating. +internal sealed class CountingProcessor : ContentProcessor +{ + public int Operators { get; private set; } + + public int Paints { get; private set; } + + public int Clips { get; private set; } + + public int Saves { get; private set; } + + public double Checksum { get; private set; } + + public void Reset() => (Operators, Paints, Clips, Saves, Checksum) = (0, 0, 0, 0, 0); + + public override void VisitOperator(in ContentOperator op, ContentContext context) + { + Operators++; + foreach (ContentOperand operand in op.Operands) + { + Checksum += operand.Number; + } + } + + public override void SaveState(ContentContext context) => Saves++; + + public override void PaintPath(in PathEvent path, ContentContext context) + { + Paints++; + Checksum += path.Path.Bounds.Width + context.State.Ctm.E + context.State.DashArray.Length; + } + + public override void IntersectClip(in ClipEvent clip, ContentContext context) + { + Clips++; + Checksum += context.GetClip(clip.ParentHandle).Path.Points.Length; + } +} diff --git a/tests/Broadside.Tests/Content/ContentPdf.cs b/tests/Broadside.Tests/Content/ContentPdf.cs new file mode 100644 index 00000000..6361a64d --- /dev/null +++ b/tests/Broadside.Tests/Content/ContentPdf.cs @@ -0,0 +1,44 @@ +using System.Text; +using Broadside.Content; +using Broadside.Diagnostics; +using Broadside.Tests.Document; + +namespace Broadside.Tests.Content; + +/// +/// Builds one-page documents whose page content is the given bytes, for content-stream vectors the corpus does not have +/// (ISO 32000-2 §7.8.2). One part is written as a single stream; several parts as a Contents array of streams, the case +/// Table 31 says is read as their concatenation. +/// +internal static class ContentPdf +{ + /// A one-page document whose content stream is , each part a separate stream when there are several. + public static byte[] Build(params string[] parts) + { + string contents = parts.Length == 1 ? "/Contents 4 0 R" : $"/Contents [{string.Join(' ', parts.Select((_, index) => $"{index + 4} 0 R"))}]"; + string[] objects = + [ + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + $"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> {contents} >>", + .. parts.Select(part => $"<< /Length {Encoding.Latin1.GetByteCount(part)} >>\nstream\n{part}\nendstream"), + ]; + return new TestPdf().Build(objects); + } + + /// Opens a one-page document with and records the events of its page. + public static (RecordingProcessor Events, IReadOnlyList Diagnostics) Run(string content, ContentEvents events = ContentEvents.All) => + Run([content], events); + + /// Opens a one-page document with the content parts and records the events of its page. + public static (RecordingProcessor Events, IReadOnlyList Diagnostics) Run(string[] parts, ContentEvents events = ContentEvents.All) + { + using PdfDocument document = PdfDocument.Open(Build(parts)); + var processor = new RecordingProcessor(events); + document.Pages[0].ProcessContent(processor); + return (processor, document.Diagnostics); + } + + /// The codes of the diagnostics, in order. + public static string[] Codes(IReadOnlyList diagnostics) => [.. diagnostics.Select(diagnostic => diagnostic.Code)]; +} diff --git a/tests/Broadside.Tests/Content/ContentRunTests.cs b/tests/Broadside.Tests/Content/ContentRunTests.cs new file mode 100644 index 00000000..d333a7a9 --- /dev/null +++ b/tests/Broadside.Tests/Content/ContentRunTests.cs @@ -0,0 +1,178 @@ +using Broadside.Content; +using Broadside.Tests.Document; + +namespace Broadside.Tests.Content; + +/// +/// What a run reads and how processors take part: the page's Contents forms (Table 31), text object boundaries (Table 105), +/// fan-out to several processors and runs started from inside a callback. ISO 32000-2 §7.7.3.3, §7.8.2, §9.4.1. +/// +public class ContentRunTests +{ + [Fact] + public void Text_objects_are_reported_at_bt_and_et() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("BT ET BT ET", ContentEvents.Text); + + Assert.Equal(["BT", "ET", "BT", "ET"], events.Body); + Assert.Empty(diagnostics); + } + + [Fact] + public void Unbalanced_text_objects_are_repaired_and_recorded() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("ET BT BT", ContentEvents.Text); + + Assert.Equal(["BT", "ET"], events.Body); + Assert.Equal(["ContentTextObjectUnbalanced"], ContentPdf.Codes(diagnostics)); + } + + [Fact] + public void Text_showing_outside_a_text_object_is_out_of_context() + { + Assert.Equal(["ContentOperatorOutOfContext"], ContentPdf.Codes(ContentPdf.Run("(x) Tj").Diagnostics)); + } + + [Fact] + public void A_contents_array_reads_as_its_parts_joined_by_white_space() + { + // Without the separator the two parts would read as the keyword "Sq". + (RecordingProcessor events, var diagnostics) = ContentPdf.Run(["0 0 m 1 1 l S", "q Q"], ContentEvents.Operators); + + Assert.Equal(["Op 0 0 m", "Op 1 1 l", "Op S", "Op q", "Op Q"], events.Body); + Assert.Empty(diagnostics); + } + + [Fact] + public void A_contents_array_element_that_is_not_a_stream_is_skipped() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> /Contents [4 0 R 5 0 R] >>", + "<< /Length 1 >>\nstream\nq\nendstream", + "(not a stream)"); + using PdfDocument document = PdfDocument.Open(file); + var processor = new RecordingProcessor(ContentEvents.Operators); + + document.Pages[0].ProcessContent(processor); + + Assert.Equal(["Op q"], processor.Body); + Assert.Equal(["ContentStreamInvalid", "ContentUnbalancedSave"], ContentPdf.Codes(document.Diagnostics)); + } + + [Fact] + public void Contents_that_is_neither_a_stream_nor_an_array_gives_an_empty_page() + { + using PdfDocument document = PdfDocument.Open(TestPdf.OnePage("/MediaBox [0 0 612 792] /Contents 42")); + var processor = new RecordingProcessor(); + + document.Pages[0].ProcessContent(processor); + + Assert.Equal(["BeginRun Page", "EndRun"], processor.Lines); + Assert.Equal(["ContentStreamInvalid"], ContentPdf.Codes(document.Diagnostics)); + } + + [Fact] + public void The_context_describes_the_page_run() + { + using PdfDocument document = PdfDocument.Open(ContentPdf.Build("q Q")); + var probe = new ContextProbe(); + + document.Pages[0].ProcessContent(probe); + + Assert.Same(document, probe.Document); + Assert.Same(document.Pages[0].Dictionary, probe.PageDictionary); + Assert.NotNull(probe.Resources); + Assert.Equal(ContentRunKind.Page, probe.RunKind); + Assert.Equal(0, probe.Depth); + Assert.Equal(Broadside.Graphics.Matrix.Identity, probe.BaseMatrix); + Assert.False(probe.Hidden); + } + + [Fact] + public void A_composite_gives_each_processor_only_the_events_it_asks_for() + { + var paths = new RecordingProcessor(ContentEvents.Paths); + var text = new RecordingProcessor(ContentEvents.Text); + var composite = new CompositeContentProcessor(paths, text); + using PdfDocument document = PdfDocument.Open(ContentPdf.Build("BT ET 0 0 m 1 1 l S")); + + document.Pages[0].ProcessContent(composite); + + Assert.Equal(ContentEvents.Paths | ContentEvents.Text, composite.Events); + Assert.Equal(["BeginRun Page", "Paint Stroke NonZero M 0,0 L 1,1 ctm=[1 0 0 1 0 0]", "EndRun"], paths.Lines); + Assert.Equal(["BeginRun Page", "BT", "ET", "EndRun"], text.Lines); + Assert.Equal([paths, text], composite.Processors); + } + + [Fact] + public void A_processor_can_run_another_page_from_inside_a_callback() + { + using PdfDocument document = PdfDocument.Open(ContentPdf.Build("0 0 m 1 1 l S 2 2 m 3 3 l S")); + var inner = new RecordingProcessor(ContentEvents.Paths); + var outer = new ReentrantProcessor(document.Pages[0], inner); + + document.Pages[0].ProcessContent(outer); + + Assert.Equal(2, outer.Paints); + Assert.Equal(4, inner.Count("PaintPath")); + } + + [Fact] + public void Interpreting_a_page_twice_reports_the_same_events() + { + using PdfDocument document = PdfDocument.Open(ContentPdf.Build("q 2 0 0 2 0 0 cm 0 0 10 10 re W n 0 0 m 1 1 l S Q")); + var first = new RecordingProcessor(); + var second = new RecordingProcessor(); + + document.Pages[0].ProcessContent(first); + document.Pages[0].ProcessContent(second); + + Assert.Equal(first.Lines, second.Lines); + } +} + +/// Records what the context says at the start of a run. +internal sealed class ContextProbe : ContentProcessor +{ + public PdfDocument? Document { get; private set; } + + public Broadside.Objects.CosDictionary? PageDictionary { get; private set; } + + public Broadside.Objects.CosDictionary? Resources { get; private set; } + + public ContentRunKind RunKind { get; private set; } + + public int Depth { get; private set; } = -1; + + public Broadside.Graphics.Matrix BaseMatrix { get; private set; } + + public bool Hidden { get; private set; } = true; + + public override void BeginRun(ContentContext context) + { + Document = context.Document; + PageDictionary = context.Page?.Dictionary; + Resources = context.Resources; + RunKind = context.RunKind; + Depth = context.Depth; + BaseMatrix = context.StreamBaseMatrix; + Hidden = context.IsHidden; + } +} + +/// Runs a page again, with another processor, from inside each paint callback. +internal sealed class ReentrantProcessor(PdfPage page, ContentProcessor inner) : ContentProcessor +{ + public int Paints { get; private set; } + + public override ContentEvents Events => ContentEvents.Paths; + + public override void PaintPath(in PathEvent path, ContentContext context) + { + Paints++; + page.ProcessContent(inner); + Assert.Equal(2, path.Path.Verbs.Length); + } +} diff --git a/tests/Broadside.Tests/Content/ContentSyntaxTests.cs b/tests/Broadside.Tests/Content/ContentSyntaxTests.cs new file mode 100644 index 00000000..ba18d277 --- /dev/null +++ b/tests/Broadside.Tests/Content/ContentSyntaxTests.cs @@ -0,0 +1,256 @@ +using Broadside.Content; +using Broadside.Diagnostics; + +namespace Broadside.Tests.Content; + +/// +/// Content stream syntax as the interpreter reads it, and the repairs it makes for malformed content: operands, glued tokens, +/// compatibility sections, unknown operators and operand-count recovery. ISO 32000-2 §7.8.2, Table 33. +/// +public class ContentSyntaxTests +{ + [Fact] + public void Operators_are_reported_with_their_operands_of_every_type() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run( + "/Span << /MCID 3 /Alt (a\\)b) /On true /Off false /N null >> BDC [(A) -250 <4142> 1.5] TJ EMC", + ContentEvents.Operators); + + Assert.Equal(["Op /Span <> BDC", "Op [(A) -250 (AB) 1.5] TJ", "Op EMC"], events.Body); + Assert.Equal(["ContentOperatorOutOfContext"], ContentPdf.Codes(diagnostics)); + } + + [Fact] + public void Operator_events_give_the_source_range_in_the_decoded_part() + { + var probe = new OperatorProbe(); + using PdfDocument document = PdfDocument.Open(ContentPdf.Build("q", " 1 0 0 1 5 5 cm Q")); + + document.Pages[0].ProcessContent(probe); + + Assert.Equal([(0, 0, 1, 0), (1, 2, 14, 14), (1, 17, 1, 17)], probe.Ranges); + Assert.Equal([4, 5, 5], probe.Streams); + } + + public static TheoryData GluedTokens => new() + { + { "q1 0 0 1 0 0cm Q", ["Op q", "Op 1 0 0 1 0 0 cm", "Op Q"] }, + { "Qq", ["Op Q", "Op q"] }, + { "BTq ETQ", ["Op BT", "Op q", "Op ET", "Op Q"] }, + { "0 0 1 rg1 0 0 RG", ["Op 0 0 1 rg", "Op 1 0 0 RG"] }, + }; + + [Theory] + [MemberData(nameof(GluedTokens))] + public void Glued_operators_and_numbers_are_split_into_their_tokens(string content, string[] expected) + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run(content, ContentEvents.Operators); + + Assert.Equal(expected, events.Body); + Assert.Contains("ContentGluedTokens", ContentPdf.Codes(diagnostics)); + Assert.DoesNotContain(diagnostics, diagnostic => diagnostic.Code == "ContentGluedTokens" && diagnostic.Severity != DiagnosticSeverity.Information); + } + + [Fact] + public void A_glued_save_keeps_its_state_change() + { + (RecordingProcessor events, _) = ContentPdf.Run("q2 0 0 2 0 0 cm 0 0 m 1 1 l S Q", ContentEvents.Paths); + + Assert.Equal(["Paint Stroke NonZero M 0,0 L 1,1 ctm=[2 0 0 2 0 0]"], events.Body); + } + + [Fact] + public void A_keyword_that_does_not_split_into_operators_is_one_unknown_operator() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("1 2 fxyz 0 0 m 1 1 l S", ContentEvents.Operators | ContentEvents.Paths); + + Assert.Equal(["Op 1 2 fxyz", "Op 0 0 m", "Op 1 1 l", "Op S", "Paint Stroke NonZero M 0,0 L 1,1 ctm=[1 0 0 1 0 0]"], events.Body); + Assert.Equal(["ContentUnknownOperator"], ContentPdf.Codes(diagnostics)); + } + + [Fact] + public void Unknown_operators_and_their_operands_are_ignored_silently_inside_a_compatibility_section() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("BX 1 2 newop /X sparkle EX 0 0 m 1 1 l S", ContentEvents.Paths); + + Assert.Equal(["Paint Stroke NonZero M 0,0 L 1,1 ctm=[1 0 0 1 0 0]"], events.Body); + Assert.Empty(diagnostics); + } + + [Fact] + public void Compatibility_sections_nest() + { + (_, var diagnostics) = ContentPdf.Run("BX BX newop EX newop EX"); + + Assert.Empty(diagnostics); + } + + [Fact] + public void An_unknown_operator_outside_a_compatibility_section_is_recorded_and_its_operands_do_not_leak() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("BX EX 7 newop 0 0 m 1 1 l S", ContentEvents.Paths); + + Assert.Equal(["Paint Stroke NonZero M 0,0 L 1,1 ctm=[1 0 0 1 0 0]"], events.Body); + Assert.Equal(["ContentUnknownOperator"], ContentPdf.Codes(diagnostics)); + } + + [Fact] + public void Ex_without_bx_and_bx_without_ex_are_recorded() + { + Assert.Equal(["ContentCompatibilityUnbalanced"], ContentPdf.Codes(ContentPdf.Run("EX").Diagnostics)); + Assert.Equal(["ContentCompatibilityUnbalanced"], ContentPdf.Codes(ContentPdf.Run("BX").Diagnostics)); + } + + [Fact] + public void An_operator_with_too_few_operands_is_skipped() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("2 0 0 2 cm 0 0 m 1 1 l S", ContentEvents.Paths); + + Assert.Equal(["Paint Stroke NonZero M 0,0 L 1,1 ctm=[1 0 0 1 0 0]"], events.Body); + Assert.Equal(["ContentOperandCount"], ContentPdf.Codes(diagnostics)); + } + + [Fact] + public void An_operator_with_too_many_operands_uses_the_last_ones() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("9 9 0 0 m 1 1 l S", ContentEvents.Paths); + + Assert.Equal(["Paint Stroke NonZero M 0,0 L 1,1 ctm=[1 0 0 1 0 0]"], events.Body); + Assert.Equal(["ContentOperandCount"], ContentPdf.Codes(diagnostics)); + } + + [Fact] + public void An_operand_of_the_wrong_type_skips_the_operator() + { + (StateRecorder recorder, var diagnostics) = StateRecorder.Run("/Thick w (3) 2 d 0 0 m 1 1 l S"); + + Assert.Equal(1, Assert.Single(recorder.States).LineWidth); + Assert.Empty(recorder.DashArrays[0]); + Assert.Equal(["ContentOperandType"], ContentPdf.Codes(diagnostics)); + } + + [Fact] + public void Operands_left_at_the_end_of_the_stream_are_recorded() + { + Assert.Equal(["ContentOperandCount"], ContentPdf.Codes(ContentPdf.Run("q Q 1 2").Diagnostics)); + } + + [Fact] + public void Stray_closing_delimiters_are_skipped() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("] >> ) 0 0 m 1 1 l S", ContentEvents.Paths); + + Assert.Single(events.Body); + Assert.Equal(["ContentSyntaxInvalid"], ContentPdf.Codes(diagnostics)); + } + + [Fact] + public void An_array_left_open_is_closed_at_its_operator() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("[3 1 2 d 0 0 m 1 1 l S", ContentEvents.Operators); + + Assert.Equal("Op [3 1 2] d", events.Body[0]); + Assert.Equal(["ContentSyntaxInvalid", "ContentOperandCount"], ContentPdf.Codes(diagnostics)); + } + + [Fact] + public void Lenient_numbers_are_read_as_the_object_parser_reads_them() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("--5 5. .5 cm", ContentEvents.Operators); + + Assert.Equal(["Op -5 5 0.5 cm"], events.Body); + Assert.Contains("ContentSyntaxInvalid", ContentPdf.Codes(diagnostics)); + } + + [Fact] + public void Graphics_state_operators_inside_a_path_object_apply_with_an_information_diagnostic() + { + (StateRecorder recorder, var diagnostics) = StateRecorder.Run("0 0 m 1 1 l 2 w S"); + + Assert.Equal(2, Assert.Single(recorder.States).LineWidth); + Diagnostic diagnostic = Assert.Single(diagnostics); + Assert.Equal("ContentOperatorOutOfContext", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Information, diagnostic.Severity); + } + + [Fact] + public void An_inline_image_is_one_operator_and_its_data_is_never_read_as_operators() + { + var probe = new OperatorProbe(); + using PdfDocument document = PdfDocument.Open(ContentPdf.Build("q BI /W 2 /H 1 /BPC 8 /CS /G ID \u0001Q EI\u0002 EI Q")); + + document.Pages[0].ProcessContent(probe); + + Assert.Equal(["q", "BI", "Q"], probe.Keywords); + Assert.Equal("\u0001Q EI\u0002", probe.InlineData); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void An_inline_image_length_entry_finds_the_end_of_its_data() + { + var probe = new OperatorProbe(); + using PdfDocument document = PdfDocument.Open(ContentPdf.Build("BI /W 4 /H 1 /BPC 8 /CS /G /L 4 ID EI x EI Q")); + + document.Pages[0].ProcessContent(probe); + + Assert.Equal(["BI", "Q"], probe.Keywords); + Assert.Equal("EI x", probe.InlineData); + } + + [Fact] + public void Strict_mode_throws_the_first_content_deviation() + { + using PdfDocument document = PdfDocument.Open(ContentPdf.Build("0 0 m 1 1 l S Q"), new PdfOptions().UseStrict()); + + DiagnosticException exception = Assert.Throws(() => document.Pages[0].ProcessContent(new RecordingProcessor())); + + Assert.Equal("ContentStackUnderflow", exception.Diagnostic.Code); + Assert.Equal(new Broadside.Objects.CosReference(4, 0), exception.Diagnostic.ObjectReference); + } + + [Fact] + public void Each_kind_of_deviation_is_recorded_once_per_stream() + { + (_, var diagnostics) = ContentPdf.Run("Q Q Q newop newop"); + + Assert.Equal(["ContentStackUnderflow", "ContentUnknownOperator"], ContentPdf.Codes(diagnostics)); + Assert.Contains("decoded offset 0", diagnostics[0].Message, StringComparison.Ordinal); + } + + [Fact] + public void A_canceled_token_stops_the_run() + { + using PdfDocument document = PdfDocument.Open(ContentPdf.Build("q Q")); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + + Assert.Throws( + () => document.Pages[0].ProcessContent(new RecordingProcessor(), new ContentOptions().WithCancellation(cancellation.Token))); + } +} + +/// Records the keyword, source range and stream of every operator. +internal sealed class OperatorProbe : ContentProcessor +{ + public List Keywords { get; } = []; + + public List<(int Part, int Offset, int Length, int KeywordOffset)> Ranges { get; } = []; + + public List Streams { get; } = []; + + public string InlineData { get; private set; } = string.Empty; + + public override ContentEvents Events => ContentEvents.Operators; + + public override void VisitOperator(in ContentOperator op, ContentContext context) + { + Keywords.Add(System.Text.Encoding.Latin1.GetString(op.Keyword)); + Ranges.Add((op.PartIndex, op.Offset, op.Length, op.KeywordOffset)); + Streams.Add(op.Stream?.ObjectNumber ?? 0); + if (op.Code == ContentOperatorCode.BeginInlineImage) + { + InlineData = System.Text.Encoding.Latin1.GetString(op.Data); + } + } +} diff --git a/tests/Broadside.Tests/Content/CorpusContentTests.cs b/tests/Broadside.Tests/Content/CorpusContentTests.cs new file mode 100644 index 00000000..3830415c --- /dev/null +++ b/tests/Broadside.Tests/Content/CorpusContentTests.cs @@ -0,0 +1,68 @@ +using Broadside.Content; +using Broadside.Diagnostics; +using Broadside.TestSupport; + +namespace Broadside.Tests.Content; + +/// +/// A counting processor run over the corpus pages through the public seam () +/// sees the events each file's content stream describes. ISO 32000-2 §7.8.2, §8.2. +/// +public class CorpusContentTests +{ + public static TheoryData FilterFiles => new() + { + "flate-stream.pdf", + "lzw-stream.pdf", + "ascii85-stream.pdf", + "asciihex-stream.pdf", + "runlength-stream.pdf", + "filter-chain.pdf", + }; + + [Fact] + public void A_page_without_content_begins_and_ends_a_run_and_nothing_else() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + var processor = new RecordingProcessor(); + + document.Pages[0].ProcessContent(processor); + + Assert.Equal(["BeginRun Page", "EndRun"], processor.Lines); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [MemberData(nameof(FilterFiles))] + public void A_filtered_content_stream_is_decoded_and_interpreted(string fileName) + { + using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName)); + var processor = new RecordingProcessor(); + + document.Pages[0].ProcessContent(processor); + + Assert.Equal(1, processor.Count("BeginRun")); + Assert.Equal(1, processor.Count("EndRun")); + Assert.Equal(1, processor.Count("BeginText")); + Assert.Equal(1, processor.Count("EndText")); + Assert.Equal(5, processor.Count("Operator")); + Assert.Equal(["Op BT", "Op /F1 24 Tf", "Op 72 700 Td"], processor.Lines.Where(line => line.StartsWith("Op", StringComparison.Ordinal)).Take(3)); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [MemberData(nameof(Corpus.WellFormedFiles), MemberType = typeof(Corpus))] + public void Every_page_of_a_well_formed_file_interprets_without_a_warning(string fileName) + { + using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName)); + foreach (PdfPage page in document.Pages) + { + var processor = new RecordingProcessor(); + page.ProcessContent(processor); + Assert.Equal(1, processor.Count("BeginRun")); + Assert.Equal(1, processor.Count("EndRun")); + } + + Assert.DoesNotContain(document.Diagnostics, diagnostic => diagnostic.Severity > DiagnosticSeverity.Information); + } +} diff --git a/tests/Broadside.Tests/Content/GraphicsStateTests.cs b/tests/Broadside.Tests/Content/GraphicsStateTests.cs new file mode 100644 index 00000000..df2c658e --- /dev/null +++ b/tests/Broadside.Tests/Content/GraphicsStateTests.cs @@ -0,0 +1,191 @@ +using Broadside.Content; +using Broadside.Diagnostics; +using Broadside.Graphics; + +namespace Broadside.Tests.Content; + +/// +/// The graphics state operators of Table 56 set the state processors read at each paint; q and Q save and restore +/// it. ISO 32000-2 §8.4.1 to §8.4.4. +/// +public class GraphicsStateTests +{ + [Fact] + public void A_path_is_painted_with_the_initial_state_of_tables_51_and_52() + { + (StateRecorder recorder, _) = StateRecorder.Run("0 0 m 1 1 l S"); + + GraphicsState state = Assert.Single(recorder.States); + Assert.Equal(Matrix.Identity, state.Ctm); + Assert.Equal(1.0, state.LineWidth); + Assert.Equal(LineCap.Butt, state.LineCap); + Assert.Equal(LineJoin.Miter, state.LineJoin); + Assert.Equal(10.0, state.MiterLimit); + Assert.Empty(recorder.DashArrays[0]); + Assert.Equal(0, state.DashPhase); + Assert.Equal(RenderingIntent.RelativeColorimetric, state.RenderingIntent); + Assert.Equal(1.0, state.Flatness); + Assert.Equal(0, state.ClipHandle); + Assert.Equal(BlendMode.Normal, state.BlendMode); + Assert.Equal(1.0, state.StrokeAlpha); + Assert.Equal(1.0, state.FillAlpha); + Assert.Equal(1.0, state.HorizontalScaling); + Assert.True(state.TextKnockout); + } + + [Fact] + public void Each_operator_of_table_56_sets_its_parameter() + { + (StateRecorder recorder, var diagnostics) = StateRecorder.Run("2.5 w 1 J 2 j 4 M [3 1] 2 d /Perceptual ri 50 i 0 0 m 1 1 l S"); + + GraphicsState state = Assert.Single(recorder.States); + Assert.Equal(2.5, state.LineWidth); + Assert.Equal(LineCap.Round, state.LineCap); + Assert.Equal(LineJoin.Bevel, state.LineJoin); + Assert.Equal(4, state.MiterLimit); + Assert.Equal([3.0, 1.0], recorder.DashArrays[0]); + Assert.Equal(2, state.DashPhase); + Assert.Equal(RenderingIntent.Perceptual, state.RenderingIntent); + Assert.Equal(50, state.Flatness); + Assert.Empty(diagnostics); + } + + [Fact] + public void Cm_premultiplies_the_ctm() + { + // §8.3.4: M′ = Mcm × CTM. A translation then a scale: the scale applies first to the coordinates. + (StateRecorder recorder, _) = StateRecorder.Run("1 0 0 1 100 200 cm 2 0 0 3 0 0 cm 0 0 m 1 1 l S"); + + Assert.Equal(new Matrix(2, 0, 0, 3, 100, 200), Assert.Single(recorder.States).Ctm); + } + + [Fact] + public void A_singular_matrix_is_concatenated_as_given() + { + (StateRecorder recorder, var diagnostics) = StateRecorder.Run("0 0 0 0 5 5 cm 0 0 m 1 1 l S"); + + Assert.Equal(new Matrix(0, 0, 0, 0, 5, 5), Assert.Single(recorder.States).Ctm); + Assert.Empty(diagnostics); + } + + [Fact] + public void Q_restores_the_whole_state_saved_by_q() + { + (StateRecorder recorder, _) = StateRecorder.Run("q 2 0 0 2 0 0 cm 5 w [2] 0 d 0 0 m 1 1 l S Q 0 0 m 1 1 l S"); + + Assert.Equal(2, recorder.States.Count); + Assert.Equal(new Matrix(2, 0, 0, 2, 0, 0), recorder.States[0].Ctm); + Assert.Equal(5, recorder.States[0].LineWidth); + Assert.Equal([2.0], recorder.DashArrays[0]); + Assert.Equal(Matrix.Identity, recorder.States[1].Ctm); + Assert.Equal(1, recorder.States[1].LineWidth); + Assert.Empty(recorder.DashArrays[1]); + } + + [Fact] + public void State_stack_events_follow_q_and_q_with_the_depth_after_each() + { + (RecordingProcessor events, _) = ContentPdf.Run("q q Q Q", ContentEvents.StateStack); + + Assert.Equal(["q 1", "q 2", "Q 1", "Q 0"], events.Body); + } + + [Fact] + public void Q_without_q_is_ignored_and_recorded() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("Q q Q", ContentEvents.StateStack); + + Assert.Equal(["q 1", "Q 0"], events.Body); + Assert.Equal(["ContentStackUnderflow"], ContentPdf.Codes(diagnostics)); + } + + [Fact] + public void Unbalanced_q_at_the_end_is_restored_with_implicit_restore_events() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("q q 0 0 m", ContentEvents.StateStack); + + Assert.Equal(["q 1", "q 2", "Q 1", "Q 0"], events.Body); + Assert.Equal(["ContentPathNotPainted", "ContentUnbalancedSave"], ContentPdf.Codes(diagnostics)); + } + + [Fact] + public void A_contents_array_is_one_stream_for_q_and_q() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run(["q 2 0 0 2 0 0 cm", "0 0 m 1 1 l S Q"], ContentEvents.StateStack | ContentEvents.Paths); + + Assert.Equal(["q 1", "Paint Stroke NonZero M 0,0 L 1,1 ctm=[2 0 0 2 0 0]", "Q 0"], events.Body); + Assert.Empty(diagnostics); + } + + [Fact] + public void A_q_beyond_the_depth_limit_is_ignored_with_its_q() + { + using PdfDocument document = PdfDocument.Open(ContentPdf.Build("q q q 2 w Q Q Q 0 0 m 1 1 l S")); + var recorder = new StateRecorder(); + + document.Pages[0].ProcessContent(recorder, new ContentOptions().WithMaxSaveDepth(2)); + + Assert.Equal(1, Assert.Single(recorder.States).LineWidth); + Assert.Equal(["ContentStackOverflow"], ContentPdf.Codes(document.Diagnostics)); + } + + public static TheoryData NegativeLineWidths => new() { { "-3 w", 3 }, { "0 w", 0 } }; + + [Theory] + [MemberData(nameof(NegativeLineWidths))] + public void A_negative_line_width_uses_its_absolute_value(string op, double expected) + { + (StateRecorder recorder, var diagnostics) = StateRecorder.Run($"{op} 0 0 m 1 1 l S"); + + Assert.Equal(expected, Assert.Single(recorder.States).LineWidth); + Assert.Equal(expected > 0 ? ["ContentGraphicsStateRange"] : [], ContentPdf.Codes(diagnostics)); + } + + [Fact] + public void Out_of_range_caps_joins_miter_limits_and_flatness_are_clipped_into_range() + { + (StateRecorder recorder, var diagnostics) = StateRecorder.Run("3 J 1.5 j 0.5 M 150 i 0 0 m 1 1 l S"); + + GraphicsState state = Assert.Single(recorder.States); + Assert.Equal(LineCap.Butt, state.LineCap); + Assert.Equal(LineJoin.Miter, state.LineJoin); + Assert.Equal(1, state.MiterLimit); + Assert.Equal(100, state.Flatness); + Assert.Equal(["ContentGraphicsStateRange"], ContentPdf.Codes(diagnostics)); + Assert.Equal(DiagnosticSeverity.Warning, diagnostics[0].Severity); + } + + public static TheoryData DashPatterns => new() + { + // Table 55 examples, then §8.4.3.6: a negative phase is incremented by twice the sum until it is not negative. + { "[] 0", [], 0, false }, + { "[3] 0", [3], 0, false }, + { "[2 1 3] -2", [2, 1, 3], 10, false }, + { "[2 1] -13", [2, 1], 5, false }, + { "[] 4", [], 0, false }, + { "[1 2 3 4 5 6 7 8 9 10] 1", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1, false }, + // Elements shall be non-negative and not all zero: otherwise a solid line, recorded. + { "[0 0] 0", [], 0, true }, + { "[2 -1] 0", [], 0, true }, + }; + + [Theory] + [MemberData(nameof(DashPatterns))] + public void Dash_patterns_are_normalized_as_8_4_3_6_says(string operands, double[] array, double phase, bool repaired) + { + (StateRecorder recorder, var diagnostics) = StateRecorder.Run($"{operands} d 0 0 m 1 1 l S"); + + Assert.Equal(array, recorder.DashArrays[0]); + Assert.Equal(phase, recorder.States[0].DashPhase); + Assert.Equal(repaired ? ["ContentGraphicsStateRange"] : [], ContentPdf.Codes(diagnostics)); + } + + [Fact] + public void An_unrecognized_rendering_intent_selects_relative_colorimetric() + { + (StateRecorder recorder, var diagnostics) = StateRecorder.Run("/Saturation ri /Vivid ri 0 0 m 1 1 l S"); + + Assert.Equal(RenderingIntent.RelativeColorimetric, Assert.Single(recorder.States).RenderingIntent); + Assert.Empty(diagnostics); + } +} diff --git a/tests/Broadside.Tests/Content/MatrixTests.cs b/tests/Broadside.Tests/Content/MatrixTests.cs new file mode 100644 index 00000000..9bae045b --- /dev/null +++ b/tests/Broadside.Tests/Content/MatrixTests.cs @@ -0,0 +1,62 @@ +using Broadside.Graphics; + +namespace Broadside.Tests.Content; + +/// Transformation matrices as §8.3.3 and §8.3.4 define them: row vectors, premultiplication, inverses. +public class MatrixTests +{ + [Fact] + public void A_point_maps_as_a_row_vector() + { + // §8.3.4: x′ = a·x + c·y + e, y′ = b·x + d·y + f. + var matrix = new Matrix(1, 2, 3, 4, 5, 6); + + Assert.Equal(new PathPoint(1 + 6 + 5, 2 + 8 + 6), matrix.Transform(1, 2)); + Assert.Equal(new PathPoint(1 + 6, 2 + 8), matrix.TransformVector(1, 2)); + } + + [Fact] + public void The_product_applies_the_first_matrix_first() + { + // §8.3.4 NOTE 2: X_D = (X_S × M_S) × M_C = X_S × (M_S × M_C). + Matrix scale = Matrix.CreateScale(2, 3); + Matrix translate = Matrix.CreateTranslation(10, 20); + + Matrix product = scale * translate; + + Assert.Equal(new Matrix(2, 0, 0, 3, 10, 20), product); + Assert.Equal(translate.Transform(scale.Transform(1, 1)), product.Transform(1, 1)); + Assert.Equal(product, Matrix.Multiply(scale, translate)); + Assert.NotEqual(product, translate * scale); + } + + [Fact] + public void An_invertible_matrix_has_an_inverse_that_undoes_it() + { + var matrix = new Matrix(0, 2, -3, 0, 7, 11); + + Assert.True(matrix.TryInvert(out Matrix inverse)); + Assert.True((matrix * inverse).IsIdentity); + PathPoint back = inverse.Transform(matrix.Transform(4, 5)); + Assert.Equal(4, back.X, 1e-12); + Assert.Equal(5, back.Y, 1e-12); + Assert.Equal(6, matrix.Determinant); + } + + [Fact] + public void A_singular_matrix_has_no_inverse() + { + Assert.False(new Matrix(0, 0, 0, 0, 5, 5).TryInvert(out Matrix inverse)); + Assert.Equal(Matrix.Identity, inverse); + } + + [Fact] + public void Matrices_compare_by_value_and_print_as_a_pdf_array() + { + Assert.True(new Matrix(1, 0, 0, 1, 0, 0) == Matrix.Identity); + Assert.False(Matrix.Identity != new Matrix(1, 0, 0, 1, 0, 0)); + Assert.Equal(Matrix.Identity.GetHashCode(), new Matrix(1, 0, 0, 1, 0, 0).GetHashCode()); + Assert.Equal("[1 0 0 1 0.5 -2]", new Matrix(1, 0, 0, 1, 0.5, -2).ToString()); + Assert.Equal("(1.5, 2)", new PathPoint(1.5, 2).ToString()); + } +} diff --git a/tests/Broadside.Tests/Content/PathTests.cs b/tests/Broadside.Tests/Content/PathTests.cs new file mode 100644 index 00000000..043aa662 --- /dev/null +++ b/tests/Broadside.Tests/Content/PathTests.cs @@ -0,0 +1,145 @@ +using Broadside.Content; + +namespace Broadside.Tests.Content; + +/// +/// Path construction and painting operators drive with the path in user space, as +/// Tables 58 and 59 define them. ISO 32000-2 §8.5.2, §8.5.3. +/// +public class PathTests +{ + [Fact] + public void A_stroked_polyline_is_reported_in_user_space_with_the_identity_ctm() + { + (RecordingProcessor events, _) = ContentPdf.Run("10 20 m 30 40 l 50 20 l S", ContentEvents.Paths); + + Assert.Equal(["Paint Stroke NonZero M 10,20 L 30,40 L 50,20 ctm=[1 0 0 1 0 0]"], events.Body); + } + + [Fact] + public void A_rectangle_is_a_moveto_three_lines_and_a_close_keeping_the_signs_of_its_size() + { + (RecordingProcessor events, _) = ContentPdf.Run("100 200 -50 30 re f", ContentEvents.Paths); + + Assert.Equal(["Paint Fill NonZero M 100,200 L 50,200 L 50,230 L 100,230 Z ctm=[1 0 0 1 0 0]"], events.Body); + } + + [Fact] + public void The_v_and_y_curves_replicate_the_current_point_and_the_end_point() + { + (RecordingProcessor events, _) = ContentPdf.Run("0 0 m 1 2 3 4 v 5 6 7 8 y 1 1 2 2 3 3 c n", ContentEvents.Paths); + + Assert.Equal(["Paint None NonZero M 0,0 C 0,0 1,2 3,4 C 5,6 7,8 7,8 C 1,1 2,2 3,3 ctm=[1 0 0 1 0 0]"], events.Body); + } + + [Fact] + public void A_moveto_after_a_moveto_replaces_it() + { + (RecordingProcessor events, _) = ContentPdf.Run("1 1 m 2 2 m 3 3 l S", ContentEvents.Paths); + + Assert.Equal(["Paint Stroke NonZero M 2,2 L 3,3 ctm=[1 0 0 1 0 0]"], events.Body); + } + + [Fact] + public void A_segment_after_a_close_starts_a_new_subpath_at_the_closed_subpaths_first_point() + { + (RecordingProcessor events, _) = ContentPdf.Run("0 0 m 10 0 l h h 10 10 l S", ContentEvents.Paths); + + Assert.Equal(["Paint Stroke NonZero M 0,0 L 10,0 Z M 0,0 L 10,10 ctm=[1 0 0 1 0 0]"], events.Body); + } + + [Fact] + public void A_trailing_lone_moveto_is_kept_for_the_renderer_to_ignore() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("0 0 m 10 0 l 5 5 m f", ContentEvents.Paths); + + Assert.Equal(["Paint Fill NonZero M 0,0 L 10,0 M 5,5 ctm=[1 0 0 1 0 0]"], events.Body); + Assert.Empty(diagnostics); + } + + public static TheoryData PaintingOperators => new() + { + { "S", "Paint Stroke NonZero M 0,0 L 1,0 L 1,1 ctm=[1 0 0 1 0 0]" }, + { "s", "Paint Stroke NonZero closed M 0,0 L 1,0 L 1,1 Z ctm=[1 0 0 1 0 0]" }, + { "f", "Paint Fill NonZero M 0,0 L 1,0 L 1,1 ctm=[1 0 0 1 0 0]" }, + { "F", "Paint Fill NonZero M 0,0 L 1,0 L 1,1 ctm=[1 0 0 1 0 0]" }, + { "f*", "Paint Fill EvenOdd M 0,0 L 1,0 L 1,1 ctm=[1 0 0 1 0 0]" }, + { "B", "Paint FillAndStroke NonZero M 0,0 L 1,0 L 1,1 ctm=[1 0 0 1 0 0]" }, + { "B*", "Paint FillAndStroke EvenOdd M 0,0 L 1,0 L 1,1 ctm=[1 0 0 1 0 0]" }, + { "b", "Paint FillAndStroke NonZero closed M 0,0 L 1,0 L 1,1 Z ctm=[1 0 0 1 0 0]" }, + { "b*", "Paint FillAndStroke EvenOdd closed M 0,0 L 1,0 L 1,1 Z ctm=[1 0 0 1 0 0]" }, + { "n", "Paint None NonZero M 0,0 L 1,0 L 1,1 ctm=[1 0 0 1 0 0]" }, + }; + + [Theory] + [MemberData(nameof(PaintingOperators))] + public void Each_painting_operator_reports_how_it_paints(string op, string expected) + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run($"0 0 m 1 0 l 1 1 l {op}", ContentEvents.Paths); + + Assert.Equal([expected], events.Body); + Assert.Empty(diagnostics); + } + + [Fact] + public void A_painting_operator_ends_the_path_so_a_second_paint_has_no_path() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("0 0 m 1 1 l S f", ContentEvents.Paths); + + Assert.Single(events.Body); + Assert.Equal(["ContentNoCurrentPath"], ContentPdf.Codes(diagnostics)); + } + + [Fact] + public void Painting_without_a_path_paints_nothing_and_is_recorded() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("S", ContentEvents.Paths); + + Assert.Empty(events.Body); + Assert.Equal(["ContentNoCurrentPath"], ContentPdf.Codes(diagnostics)); + } + + [Fact] + public void A_lineto_without_a_current_point_begins_a_subpath_at_its_end_point() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("5 5 l 10 10 l S", ContentEvents.Paths); + + Assert.Equal(["Paint Stroke NonZero M 5,5 L 10,10 ctm=[1 0 0 1 0 0]"], events.Body); + Assert.Equal(["ContentNoCurrentPoint"], ContentPdf.Codes(diagnostics)); + } + + [Fact] + public void The_current_path_survives_q_and_q_does_not_save_it() + { + (RecordingProcessor events, _) = ContentPdf.Run("0 0 m q 1 1 l Q 2 2 l S", ContentEvents.Paths); + + Assert.Equal(["Paint Stroke NonZero M 0,0 L 1,1 L 2,2 ctm=[1 0 0 1 0 0]"], events.Body); + } + + [Fact] + public void Coordinates_keep_double_precision() + { + (RecordingProcessor events, _) = ContentPdf.Run("1000000.125 2000000.0625 m 1000000.25 2000000.125 l S", ContentEvents.Paths); + + Assert.Equal(["Paint Stroke NonZero M 1000000.125,2000000.0625 L 1000000.25,2000000.125 ctm=[1 0 0 1 0 0]"], events.Body); + } + + [Fact] + public void A_path_left_unpainted_at_the_end_is_discarded_with_an_information_diagnostic() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("0 0 m 1 1 l", ContentEvents.Paths); + + Assert.Empty(events.Body); + Assert.Equal(["ContentPathNotPainted"], ContentPdf.Codes(diagnostics)); + Assert.Equal(Broadside.Diagnostics.DiagnosticSeverity.Information, diagnostics[0].Severity); + } + + [Fact] + public void Without_path_or_clip_events_no_geometry_is_reported_but_the_same_diagnostics_are() + { + (RecordingProcessor events, var diagnostics) = ContentPdf.Run("5 5 l S", ContentEvents.Text); + + Assert.DoesNotContain(events.Semantic, line => line.StartsWith("Paint", StringComparison.Ordinal)); + Assert.Equal(["ContentNoCurrentPoint"], ContentPdf.Codes(diagnostics)); + } +} diff --git a/tests/Broadside.Tests/Content/RecordingProcessor.cs b/tests/Broadside.Tests/Content/RecordingProcessor.cs new file mode 100644 index 00000000..b82311c1 --- /dev/null +++ b/tests/Broadside.Tests/Content/RecordingProcessor.cs @@ -0,0 +1,139 @@ +using System.Globalization; +using System.Text; +using Broadside.Content; +using Broadside.Graphics; + +namespace Broadside.Tests.Content; + +/// +/// A processor that writes every event it receives as one line of text, so a test can assert the event sequence a content +/// stream produces. Geometry is printed with the invariant culture and the shortest round-trip form of each double. +/// +internal sealed class RecordingProcessor(ContentEvents events = ContentEvents.All) : ContentProcessor +{ + public List Lines { get; } = []; + + public Dictionary Counts { get; } = []; + + public override ContentEvents Events => events; + + public override void BeginRun(ContentContext context) => Add("BeginRun", $"BeginRun {context.RunKind}"); + + public override void EndRun(ContentContext context) => Add("EndRun", "EndRun"); + + public override void VisitOperator(in ContentOperator op, ContentContext context) => + Add("Operator", $"Op{Operands(op.Operands)} {Encoding.Latin1.GetString(op.Keyword)}"); + + public override void SaveState(ContentContext context) => Add("SaveState", $"q {context.StateDepth}"); + + public override void RestoreState(ContentContext context) => Add("RestoreState", $"Q {context.StateDepth}"); + + public override void PaintPath(in PathEvent path, ContentContext context) + { + string closed = path.ClosedBeforePaint ? " closed" : string.Empty; + string clip = path.PendingClip is { } rule ? $" clip={rule}" : string.Empty; + Add("PaintPath", $"Paint {path.Paint} {path.FillRule}{closed}{clip} {Path(path.Path)} ctm={Matrix(context.State.Ctm)}"); + } + + public override void IntersectClip(in ClipEvent clip, ContentContext context) => + Add("IntersectClip", $"Clip {clip.Kind} {clip.Rule} #{clip.Handle}<#{clip.ParentHandle} {Path(clip.Path)} ctm={Matrix(clip.Ctm)}"); + + public override void BeginText(ContentContext context) => Add("BeginText", "BT"); + + public override void EndText(ContentContext context) => Add("EndText", "ET"); + + public override void ShowGlyph(in GlyphEvent glyph, ContentContext context) => Add("ShowGlyph", "Glyph"); + + public override void PaintImage(in ImageEvent image, ContentContext context) => Add("PaintImage", "Image"); + + public override void PaintShading(in ShadingEvent shading, ContentContext context) => Add("PaintShading", "Shading"); + + public override ContentVisit BeginForm(in FormEvent form, ContentContext context) + { + Add("BeginForm", "BeginForm"); + return ContentVisit.Enter; + } + + public override void EndForm(in FormEvent form, ContentContext context) => Add("EndForm", "EndForm"); + + public override void BeginMarkedContent(in MarkedContentEvent mc, ContentContext context) => Add("BeginMarkedContent", "BMC"); + + public override void EndMarkedContent(in MarkedContentEvent mc, ContentContext context) => Add("EndMarkedContent", "EMC"); + + public override void MarkedContentPoint(in MarkedContentEvent mc, ContentContext context) => Add("MarkedContentPoint", "MP"); + + public int Count(string name) => Counts.GetValueOrDefault(name); + + /// The lines between the run's begin and end lines. + public List Body => [.. Lines.Where(line => line is not ("EndRun" or "BeginRun Page"))]; + + /// The lines that are not operator lines, for tests that look at semantic events only. + public List Semantic => [.. Body.Where(line => !line.StartsWith("Op", StringComparison.Ordinal))]; + + internal static string Number(double value) => value.ToString("R", CultureInfo.InvariantCulture); + + internal static string Matrix(Matrix m) => $"[{Number(m.A)} {Number(m.B)} {Number(m.C)} {Number(m.D)} {Number(m.E)} {Number(m.F)}]"; + + internal static string Path(PathView path) + { + var text = new StringBuilder(); + int point = 0; + foreach (PathVerb verb in path.Verbs) + { + if (text.Length > 0) + { + text.Append(' '); + } + + int count = verb switch + { + PathVerb.MoveTo or PathVerb.LineTo => 1, + PathVerb.QuadTo => 2, + PathVerb.CubicTo => 3, + _ => 0, + }; + text.Append(verb switch + { + PathVerb.MoveTo => 'M', + PathVerb.LineTo => 'L', + PathVerb.QuadTo => 'Q', + PathVerb.CubicTo => 'C', + _ => 'Z', + }); + for (int index = 0; index < count; index++, point++) + { + text.Append(' ').Append(Number(path.Points[point].X)).Append(',').Append(Number(path.Points[point].Y)); + } + } + + return text.ToString(); + } + + private static string Operands(ContentOperands operands) + { + var text = new StringBuilder(); + for (int index = 0; index < operands.Count; index++) + { + text.Append(' ').Append(Operand(operands[index])); + } + + return text.ToString(); + } + + private static string Operand(ContentOperand operand) => operand.Kind switch + { + ContentOperandKind.Integer or ContentOperandKind.Real => Number(operand.Number), + ContentOperandKind.Boolean => operand.Boolean ? "true" : "false", + ContentOperandKind.Null => "null", + ContentOperandKind.Name => "/" + Encoding.Latin1.GetString(operand.Bytes), + ContentOperandKind.String => "(" + Encoding.Latin1.GetString(operand.Bytes) + ")", + ContentOperandKind.Array => "[" + Operands(operand.Items).TrimStart() + "]", + _ => "<<" + Operands(operand.Items).TrimStart() + ">>", + }; + + private void Add(string name, string line) + { + Lines.Add(line); + Counts[name] = Count(name) + 1; + } +} diff --git a/tests/Broadside.Tests/Content/StateRecorder.cs b/tests/Broadside.Tests/Content/StateRecorder.cs new file mode 100644 index 00000000..e0dd6e4a --- /dev/null +++ b/tests/Broadside.Tests/Content/StateRecorder.cs @@ -0,0 +1,29 @@ +using Broadside.Content; +using Broadside.Graphics; + +namespace Broadside.Tests.Content; + +/// Copies the graphics state at every path paint, so a test can assert the parameters a path was painted with. +internal sealed class StateRecorder : ContentProcessor +{ + public List States { get; } = []; + + public List DashArrays { get; } = []; + + public override ContentEvents Events => ContentEvents.Paths; + + public override void PaintPath(in PathEvent path, ContentContext context) + { + States.Add(context.State); + DashArrays.Add(context.State.DashArray.ToArray()); + } + + /// Opens a one-page document with and records the state of each paint. + public static (StateRecorder Recorder, IReadOnlyList Diagnostics) Run(string content) + { + using PdfDocument document = PdfDocument.Open(ContentPdf.Build(content)); + var recorder = new StateRecorder(); + document.Pages[0].ProcessContent(recorder); + return (recorder, document.Diagnostics); + } +} From 96e856e27be79e55728a99fad934824bd089b11b Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:40:52 -0500 Subject: [PATCH 031/152] feat(navigation): destinations, outlines and the action base (#70) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Second half of #70, on top of the tree walkers. - Destinations (§12.3.2): PdfDestination with PdfExplicitDestination (every Table 149 view as PdfDestinationView, parameters double? with null and XYZ zoom 0 = keep current, TargetKind/PdfDestinationTarget, PageIndex through a lazy page-object index on PdfPageCollection, structure element target and remote ID typed) and PdfNamedDestination (Resolve: names through the catalog Dests dictionary first, strings through the Names/Dests tree first, then the other, by bytes). PdfDocument.GetNamedDestination(string | CosString | CosName). Lenient: missing/extra/non-number parameters, unknown views, FitR without four numbers, local integer pages, pages outside the tree. - Outline (§12.3.3): PdfDocument.Outline, PdfOutline, PdfOutlineItem, PdfRgbColor. Iterative First/Next walk, one visited set, 256-level cap; Last/Prev/Parent checked (the chain wins); Title, Dest, A, SE, C (clamped), F, Count, IsOpen; Dest and A both exposed. Count magnitude is deliberately not checked (Isartor and PDFium files write the number of immediate children); a non-zero Count is required on items with children and the outline Count cannot be negative. - Action base (§12.6): PdfAction (S as ActionType), PdfGoToAction (D, SD), PdfUriAction (URI as UTF-8, IsMap), PdfUnknownAction for every other type; internal factory PdfAction.Create for #71/#73. - Tree readers: raw-value lookups for owners' diagnostics; the first deviation a walk meets switches later lookups to the index (found by the document fuzz smoke). Navigation names moved to NavigationNames so parallel tickets cannot collide in KnownNames. - Corpus: destinations-all.pdf, outline-full.pdf, outline-broken.pdf. DocumentWalker (real-world gate) and the document fuzz target now walk outlines and named destinations; RealWorldCorpusTests snapshot reviewed and accepted (new navigation diagnostics on real files). - Conformance: 12.3 split; 12.3.2.1, 12.3.2.2, 12.3.2.4, 12.3.3 done, 12.3.2.3 partial (page resolution needs #75), 12.3.1 n/a, 12.6 partial, 7.7.2 and 7.7.4 notes. Co-Authored-By: Claude Opus 5.5 --- docs/conformance/iso-32000-2.md | 16 +- src/Broadside/NameTreeReader.cs | 48 ++- src/Broadside/NumberTreeReader.cs | 2 +- .../Objects/KnownNames.Navigation.cs | 26 -- src/Broadside/Objects/NavigationNames.cs | 71 +++++ .../Parsing/DiagnosticCodes.Navigation.cs | 14 + src/Broadside/PdfAction.cs | 86 ++++++ src/Broadside/PdfDestination.cs | 68 +++++ src/Broadside/PdfDestinationTarget.cs | 21 ++ src/Broadside/PdfDestinationView.cs | 33 +++ src/Broadside/PdfDocument.cs | 140 ++++++++- src/Broadside/PdfExplicitDestination.cs | 276 ++++++++++++++++++ src/Broadside/PdfGoToAction.cs | 34 +++ src/Broadside/PdfNameDictionary.cs | 2 +- src/Broadside/PdfNameTree.cs | 29 +- src/Broadside/PdfNamedDestination.cs | 75 +++++ src/Broadside/PdfOutline.cs | 242 +++++++++++++++ src/Broadside/PdfOutlineItem.cs | 169 +++++++++++ src/Broadside/PdfPageCollection.cs | 25 +- src/Broadside/PdfRgbColor.cs | 56 ++++ src/Broadside/PdfUnknownAction.cs | 16 + src/Broadside/PdfUriAction.cs | 38 +++ src/Broadside/PublicAPI.Unshipped.txt | 89 ++++++ src/Broadside/TreeReader.cs | 75 +++-- tests/Broadside.Fuzz/FuzzTargets.cs | 61 +++- tests/Broadside.TestSupport/Corpus.cs | 3 + tests/Broadside.TestSupport/DocumentWalker.cs | 65 ++++- ...histograms_match_the_snapshot.verified.txt | 29 +- .../Navigation/DestinationTests.cs | 194 ++++++++++++ .../Navigation/OutlineTests.cs | 232 +++++++++++++++ ...pus_file_names_match_snapshot.verified.txt | 3 + tests/Broadside.Tests/Writing/SaveTests.cs | 2 +- tests/Corpus/README.md | 3 + tests/Corpus/destinations-all.pdf | Bin 0 -> 1281 bytes tests/Corpus/generate.py | 89 ++++++ tests/Corpus/outline-broken.pdf | Bin 0 -> 1031 bytes tests/Corpus/outline-full.pdf | Bin 0 -> 1700 bytes 37 files changed, 2233 insertions(+), 99 deletions(-) delete mode 100644 src/Broadside/Objects/KnownNames.Navigation.cs create mode 100644 src/Broadside/Objects/NavigationNames.cs create mode 100644 src/Broadside/PdfAction.cs create mode 100644 src/Broadside/PdfDestination.cs create mode 100644 src/Broadside/PdfDestinationTarget.cs create mode 100644 src/Broadside/PdfDestinationView.cs create mode 100644 src/Broadside/PdfExplicitDestination.cs create mode 100644 src/Broadside/PdfGoToAction.cs create mode 100644 src/Broadside/PdfNamedDestination.cs create mode 100644 src/Broadside/PdfOutline.cs create mode 100644 src/Broadside/PdfOutlineItem.cs create mode 100644 src/Broadside/PdfRgbColor.cs create mode 100644 src/Broadside/PdfUnknownAction.cs create mode 100644 src/Broadside/PdfUriAction.cs create mode 100644 tests/Broadside.Tests/Navigation/DestinationTests.cs create mode 100644 tests/Broadside.Tests/Navigation/OutlineTests.cs create mode 100644 tests/Corpus/destinations-all.pdf create mode 100644 tests/Corpus/outline-broken.pdf create mode 100644 tests/Corpus/outline-full.pdf diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index f18429c5..58c52806 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -47,9 +47,9 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.6.6 | Crypt filters | done | `DocumentDecryptor`, `CryptFilter`, `CryptMethod` | `Broadside.Tests.Security.CryptFilterTests.An_embedded_file_is_decrypted_with_eff_which_defaults_to_stmf`, `Broadside.Tests.Security.CryptFilterTests.Each_content_stream_decrypts_with_the_crypt_filter_it_names_or_the_default_one`, `Broadside.Tests.Security.CryptFilterTests.Metadata_is_left_as_it_is_when_encrypt_metadata_is_false`, `Broadside.Tests.Security.CryptFilterTests.The_owner_password_opens_a_document_whose_metadata_is_not_encrypted`, `Broadside.Tests.Security.CryptFilterTests.A_stream_that_names_a_crypt_filter_the_document_does_not_define_is_left_encrypted_with_a_diagnostic`, `Broadside.Tests.Security.CryptFilterTests.Metadata_in_plaintext_although_encrypt_metadata_is_true_is_read_as_it_is_with_a_diagnostic`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.An_unknown_crypt_filter_method_is_an_unsupported_algorithm` | CF, StmF, StrF, EFF (default StmF), Identity, CFM V2/AESV2/AESV3 (and AESV4, ISO/TS 32003); CFM None leaves data as is with CryptFilterMethodInvalid; AESV2 under V 5 read as AESV3 with a diagnostic; unknown CFM for StmF/StrF/EFF throws `PdfEncryptionNotSupportedException`; EncryptMetadata false leaves /Type /Metadata streams alone (plaintext XMP under EncryptMetadata true read with MetadataNotEncrypted); crypt filter Length not used (keys come from the handler); encrypted-crypt-filters.pdf | | 7.6.7 | Unencrypted wrapper document | not started | | | Collections of encrypted payloads (PDF 2.0); a wrapper opens as an ordinary unencrypted document | | 7.7.1 | General | n/a | | | Introductory text | -| 7.7.2 | Document catalog dictionary | partial | `PdfDocument`, `PdfVersion` | `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_catalog_version_written_as_a_number_is_read_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.A_malformed_catalog_version_is_ignored_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_catalog_without_its_type_is_read_with_a_diagnostic` | Type, Version (effective version = later of header and catalog) and Pages; the other Table 29 entries arrive with their features (outlines, names, AcroForm, ...) | +| 7.7.2 | Document catalog dictionary | partial | `PdfDocument`, `PdfVersion`, `PdfNameDictionary`, `PdfOutline` | `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_catalog_version_written_as_a_number_is_read_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.A_malformed_catalog_version_is_ignored_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_catalog_without_its_type_is_read_with_a_diagnostic`, `Broadside.Tests.Navigation.NameTreeTests.Name_tree_dests_pdf_maps_its_three_keys_to_their_destination_arrays_with_no_diagnostics`, `Broadside.Tests.Navigation.OutlineTests.Outline_pdf_yields_two_closed_leaf_items_with_their_destinations_and_default_style` | Type, Version (effective version = later of header and catalog) and Pages; the other Table 29 entries arrive with their features (outlines, names, AcroForm, ...); Names (`PdfDocument.Names`), Dests (named destinations) and Outlines (`PdfDocument.Outline`) since #70 | | 7.7.3 | Page tree | done | `PdfPage`, `PdfPageCollection`, `PageTreeReader` | `Broadside.Tests.Document.OpenDocumentTests.Page_tree_inherited_pdf_pages_inherit_media_box_and_resources_from_the_intermediate_node`, `Broadside.Tests.Document.PageTreeTests.Pages_come_in_kids_order_depth_first_across_intermediate_nodes`, `Broadside.Tests.Document.PageTreeTests.The_nearest_ancestor_wins_and_values_are_inherited_as_is_without_merging`, `Broadside.Tests.Document.PageTreeTests.A_change_to_an_ancestor_node_shows_through_the_pages_that_inherit_from_it`, `Broadside.Tests.Document.PageTreeTests.Page_count_comes_from_the_kids_not_the_count_entry_which_is_checked`, `Broadside.Tests.Document.PageTreeTests.A_node_referenced_twice_is_read_once_with_a_diagnostic`, `Broadside.Tests.Document.PageAttributeTests.Crop_bleed_trim_and_art_boxes_default_to_the_media_box_through_the_crop_box`, `Broadside.Tests.Document.PageAttributeTests.Rotation_is_a_multiple_of_90_normalized_into_0_to_270` | 7.7.3.1 to 7.7.3.4: Kids walk with cycle guard, Count checked not trusted, Resources/MediaBox/CropBox/Rotate inherited as-is from the nearest node; page boxes, Rotate and UserUnit from Table 31; other Table 31 entries arrive with their features | -| 7.7.4 | Name dictionary | partial | `PdfNameDictionary`, `PdfDocument` | `Broadside.Tests.Navigation.NameTreeTests.Name_tree_dests_pdf_maps_its_three_keys_to_their_destination_arrays_with_no_diagnostics`, `Broadside.Tests.Navigation.NameTreeTests.A_tree_root_that_is_not_a_dictionary_reads_as_absent_with_a_diagnostic` | `PdfDocument.Names`; every Table 32 entry is reachable as a name tree through `PdfNameDictionary.GetTree`, `Dests` by name; typed values arrive with their features (Dests destinations #70, EmbeddedFiles #76, JavaScript #73) | +| 7.7.4 | Name dictionary | partial | `PdfNameDictionary`, `PdfDocument` | `Broadside.Tests.Navigation.NameTreeTests.Name_tree_dests_pdf_maps_its_three_keys_to_their_destination_arrays_with_no_diagnostics`, `Broadside.Tests.Navigation.NameTreeTests.A_tree_root_that_is_not_a_dictionary_reads_as_absent_with_a_diagnostic` | `PdfDocument.Names`; every Table 32 entry is reachable as a name tree through `PdfNameDictionary.GetTree`; `Dests` values are typed as destinations through `PdfDocument.GetNamedDestination` (12.3.2.4); EmbeddedFiles (#76) and JavaScript (#73) arrive with their features | | 7.8 | Content streams and resources | not started | | | | | 7.9.1 | General | not started | | | | | 7.9.2 | String object types | partial | `CosString` | `Broadside.Tests.Objects.TextStringTests` | Text strings decode (PDFDocEncoding, UTF-16BE, UTF-8, language escapes removed); encoding text into a string pending | @@ -99,10 +99,18 @@ Clause numbers at the second level; split rows to the third level as clauses are | 11.7 | Colour space and rendering issues | not started | | | | | 12.1 | Interactive features: General | not started | | | | | 12.2 | Viewer preferences | not started | | | | -| 12.3 | Document-level navigation | not started | | | | +| 12.3.1 | General | n/a | | | Introductory text: the outline is 12.3.3, thumbnails 12.3.4 | +| 12.3.2.1 | General | done | `PdfDestination`, `PdfExplicitDestination`, `PdfNamedDestination` | `Broadside.Tests.Navigation.DestinationTests.Name_tree_dests_pdf_resolves_its_three_named_destinations_to_the_first_page`, `Broadside.Tests.Navigation.DestinationTests.Outline_items_refer_to_destinations_by_name_and_by_string` | A destination is explicit (array) or named (name or string); remote destinations (GoToR/GoToE, #73) keep their page number and never resolve locally (internal factory flag) | +| 12.3.2.2 | Explicit destinations | done | `PdfExplicitDestination`, `PdfDestinationView`, `PdfDestinationTarget`, `PdfPageCollection` | `Broadside.Tests.Navigation.DestinationTests.Name_tree_dests_pdf_resolves_its_three_named_destinations_to_the_first_page`, `Broadside.Tests.Navigation.DestinationTests.Every_explicit_form_of_table_149_is_typed_with_null_meaning_unchanged`, `Broadside.Tests.Navigation.DestinationTests.Malformed_destinations_are_read_leniently_each_with_a_diagnostic`, `Broadside.Tests.Navigation.DestinationTests.Strict_mode_throws_when_a_malformed_destination_is_read_not_at_open`, `Broadside.Tests.Navigation.DestinationTests.Reading_destinations_writes_nothing` | Every Table 149 view typed, parameters `double?` (null and XYZ zoom 0 = keep current); page resolved to its index through a lazy page-object map; lenient: missing parameters null, extra ignored, non-numbers null, unknown view `Unknown` with the page kept, FitR without four numbers invalid, a local integer page used as an index, a page outside the tree unresolved (`DestinationInvalid`, `DestinationPageNotFound`). `destinations-all.pdf`. | +| 12.3.2.3 | Structure destinations | partial | `PdfExplicitDestination`, `PdfGoToAction` | `Broadside.Tests.Navigation.OutlineTests.Outline_full_pdf_yields_three_levels_with_open_and_closed_items_styles_and_actions` | Syntax read: a structure element target (`TargetKind` StructureElement, `StructureElement`), a remote ID (`StructureElementId`), a go-to action's `SD`. Finding the page from the element's kids needs typed structure elements (#75); the `SD` of a named destination's dictionary value is not exposed yet | +| 12.3.2.4 | Named destinations | done | `PdfNamedDestination`, `PdfDocument`, `PdfNameTree` | `Broadside.Tests.Navigation.DestinationTests.Name_tree_dests_pdf_resolves_its_three_named_destinations_to_the_first_page`, `Broadside.Tests.Navigation.DestinationTests.A_pdf_1_1_name_resolves_through_the_catalog_dests_dictionary`, `Broadside.Tests.Navigation.DestinationTests.Outline_items_refer_to_destinations_by_name_and_by_string`, `Broadside.Tests.Navigation.OutlineTests.Malformed_item_entries_read_as_their_defaults_with_a_diagnostic` | `PdfDocument.GetNamedDestination` (string, CosString, CosName) and `PdfNamedDestination.Resolve`: a name looks in the catalog Dests dictionary first, a string in the Names/Dests tree first, then the other, by bytes (J.3.3, J.3.4); a dictionary value resolves through D; a name the file refers to that does not exist is `NamedDestinationNotFound`; chained names are not followed | +| 12.3.3 | Document outline | done | `PdfOutline`, `PdfOutlineItem`, `PdfRgbColor` | `Broadside.Tests.Navigation.OutlineTests.Outline_pdf_yields_two_closed_leaf_items_with_their_destinations_and_default_style`, `Broadside.Tests.Navigation.OutlineTests.A_document_without_outlines_has_none`, `Broadside.Tests.Navigation.OutlineTests.Outline_full_pdf_yields_three_levels_with_open_and_closed_items_styles_and_actions`, `Broadside.Tests.Navigation.OutlineTests.A_damaged_outline_is_read_as_a_finite_tree_with_exactly_the_documented_diagnostics`, `Broadside.Tests.Navigation.OutlineTests.Strict_mode_throws_from_the_walk_not_from_open`, `Broadside.Tests.Navigation.OutlineTests.Walking_the_outline_writes_nothing`, `Broadside.Tests.Navigation.OutlineTests.Malformed_item_entries_read_as_their_defaults_with_a_diagnostic`, `Broadside.Tests.Navigation.OutlineTests.An_outline_deeper_than_the_cap_ends_with_a_diagnostic` | `PdfDocument.Outline`; iterative First/Next walk with one visited set and a 256-level cap; Title, Dest, A, SE, C (clamped), F (Italic, Bold), Count as stored and IsOpen; Last/Prev/Parent checked, the chain wins; both Dest and A exposed (A to perform); a Dest holding an action reads as A; an item with children needs a non-zero Count and the outline Count cannot be negative. The magnitude of Count is deliberately not checked: Isartor and PDFium files write the number of immediate children, viewers ignore it. `outline.pdf`, `outline-full.pdf`, `outline-broken.pdf`; walked by the real-world corpus gate. | +| 12.3.4 | Thumbnail images | not started | | | | +| 12.3.5 | Collections | not started | | | #76 | +| 12.3.6 | Navigators | not started | | | | | 12.4 | Page-level navigation | not started | | | | | 12.5 | Annotations | not started | | | | -| 12.6 | Actions | not started | | | | +| 12.6 | Actions | partial | `PdfAction`, `PdfGoToAction`, `PdfUriAction`, `PdfUnknownAction` | `Broadside.Tests.Navigation.OutlineTests.Outline_full_pdf_yields_three_levels_with_open_and_closed_items_styles_and_actions`, `Broadside.Tests.Navigation.OutlineTests.Malformed_item_entries_read_as_their_defaults_with_a_diagnostic` | Minimal base (#70): Table 196 S, go-to (Table 202: D, SD) and URI (Table 210: URI as UTF-8, IsMap) actions; every other type is `PdfUnknownAction`, preserved; `ActionInvalid` for a missing S, D or URI. #73 adds the other types, Next chains and trigger events | | 12.7 | Forms | not started | | | | | 12.8 | Digital signatures | not started | | | | | 12.9 | Measurement properties | not started | | | | diff --git a/src/Broadside/NameTreeReader.cs b/src/Broadside/NameTreeReader.cs index 61d94e20..460f1709 100644 --- a/src/Broadside/NameTreeReader.cs +++ b/src/Broadside/NameTreeReader.cs @@ -1,4 +1,5 @@ using System.Diagnostics.CodeAnalysis; +using System.Text; using Broadside.Objects; using Broadside.Parsing; @@ -34,7 +35,7 @@ internal NameTreeReader(CosDictionary root, CosReference? rootReference, Func - private protected override CosName EntriesKey => KnownNames.Names; + private protected override CosName EntriesKey => NavigationNames.Names; /// private protected override TreeCodes Codes => NameTreeCodes; @@ -54,6 +55,51 @@ internal NameTreeReader(CosDictionary root, CosReference? rootReference, Func when the tree holds the key. internal bool TryGetValue(ReadOnlySpan key, [MaybeNullWhen(false)] out CosObject value) => TryGetValue(new CosString(key), out value); + /// Looks up the key that reads as ; see . + /// The key as text. + /// The value, resolved one level, when found. + /// when the tree holds a key that reads as . + internal bool TryGetValue(string key, [MaybeNullWhen(false)] out CosObject value) + { + if (TryGetRawValue(key, out CosObject? raw)) + { + value = Resolve(raw); + return true; + } + + value = null; + return false; + } + + /// Looks up the key that reads as : as PDFDocEncoding bytes, as UTF-16BE with the marker, then every key decoded. + /// The key as text. + /// The value as stored, when found. + /// when the tree holds a key that reads as . + internal bool TryGetRawValue(string key, [MaybeNullWhen(false)] out CosObject value) + { + if (TextStringEncoder.TryEncodePdfDoc(key, out byte[]? encoded) && TryGetRawValue(new CosString(encoded), out value)) + { + return true; + } + + if (TryGetRawValue(new CosString([0xFE, 0xFF, .. Encoding.BigEndianUnicode.GetBytes(key)]), out value)) + { + return true; + } + + foreach ((CosString candidate, CosObject found) in EnumerateRaw()) + { + if (string.Equals(candidate.DecodeText(), key, StringComparison.Ordinal)) + { + value = found; + return true; + } + } + + value = null; + return false; + } + /// private protected override KeyState ReadKey(CosObject key, [MaybeNullWhen(false)] out CosString value, out string? message) { diff --git a/src/Broadside/NumberTreeReader.cs b/src/Broadside/NumberTreeReader.cs index 168fe217..7369070d 100644 --- a/src/Broadside/NumberTreeReader.cs +++ b/src/Broadside/NumberTreeReader.cs @@ -33,7 +33,7 @@ internal NumberTreeReader(CosDictionary root, CosReference? rootReference, Func< } /// - private protected override CosName EntriesKey => KnownNames.Nums; + private protected override CosName EntriesKey => NavigationNames.Nums; /// private protected override TreeCodes Codes => NumberTreeCodes; diff --git a/src/Broadside/Objects/KnownNames.Navigation.cs b/src/Broadside/Objects/KnownNames.Navigation.cs deleted file mode 100644 index a478f83f..00000000 --- a/src/Broadside/Objects/KnownNames.Navigation.cs +++ /dev/null @@ -1,26 +0,0 @@ -namespace Broadside.Objects; - -/// Names looked up by name trees, number trees, destinations, outlines and actions (issue #70). -internal static partial class KnownNames -{ - /// /Names, the catalog's name dictionary (§7.7.2, Table 29) and the pairs of a name tree node (§7.9.6, Table 36). - public static readonly CosName Names = new("Names"); - - /// /Nums, the pairs of a number tree node (§7.9.7, Table 37). - public static readonly CosName Nums = new("Nums"); - - /// /Limits, the least and greatest keys under a tree node (§7.9.6, Table 36; §7.9.7, Table 37). - public static readonly CosName Limits = new("Limits"); - - /// /Dests, the named destinations: a catalog dictionary (PDF 1.1) or a name dictionary tree (§7.7.4, §12.3.2.4). - public static readonly CosName Dests = new("Dests"); - - /// /S, the type of an action (§12.6.2, Table 196). - public static readonly CosName S = new("S"); - - /// /URI, the URI action type and its URI entry (§12.6.4.8, Table 210). - public static readonly CosName Uri = new("URI"); - - /// /IsMap, whether a URI action tracks the mouse position (§12.6.4.8, Table 210). - public static readonly CosName IsMap = new("IsMap"); -} diff --git a/src/Broadside/Objects/NavigationNames.cs b/src/Broadside/Objects/NavigationNames.cs new file mode 100644 index 00000000..44999e30 --- /dev/null +++ b/src/Broadside/Objects/NavigationNames.cs @@ -0,0 +1,71 @@ +namespace Broadside.Objects; + +/// Names looked up by name trees, number trees, destinations, outlines and actions (issue #70); kept apart from so parallel tickets do not collide. +internal static class NavigationNames +{ + /// /Names, the catalog's name dictionary (§7.7.2, Table 29) and the pairs of a name tree node (§7.9.6, Table 36). + public static readonly CosName Names = new("Names"); + + /// /Nums, the pairs of a number tree node (§7.9.7, Table 37). + public static readonly CosName Nums = new("Nums"); + + /// /Limits, the least and greatest keys under a tree node (§7.9.6, Table 36; §7.9.7, Table 37). + public static readonly CosName Limits = new("Limits"); + + /// /Dests, the named destinations: a catalog dictionary (PDF 1.1) or a name dictionary tree (§7.7.4, §12.3.2.4). + public static readonly CosName Dests = new("Dests"); + + /// /S, the type of an action (§12.6.2, Table 196). + public static readonly CosName S = new("S"); + + /// /URI, the URI action type and its URI entry (§12.6.4.8, Table 210). + public static readonly CosName Uri = new("URI"); + + /// /IsMap, whether a URI action tracks the mouse position (§12.6.4.8, Table 210). + public static readonly CosName IsMap = new("IsMap"); + + /// /Outlines, the catalog's outline dictionary (§7.7.2, Table 29) and its type (§12.3.3, Table 150). + public static readonly CosName Outlines = new("Outlines"); + + /// /First, the first child of an outline dictionary or item (§12.3.3, Tables 150 and 151). + public static readonly CosName First = new("First"); + + /// /Last, the last child of an outline dictionary or item (§12.3.3, Tables 150 and 151). + public static readonly CosName Last = new("Last"); + + /// /Next, the next outline item at the same level (§12.3.3, Table 151) and the next action (§12.6.2, Table 196). + public static readonly CosName Next = new("Next"); + + /// /Title, the text of an outline item (§12.3.3, Table 151). + public static readonly CosName Title = new("Title"); + + /// /Dest, the destination of an outline item (§12.3.3, Table 151). + public static readonly CosName Dest = new("Dest"); + + /// /A, the action of an outline item (§12.3.3, Table 151). + public static readonly CosName A = new("A"); + + /// /SE, the structure element of an outline item (§12.3.3, Table 151). + public static readonly CosName SE = new("SE"); + + /// /C, the text colour of an outline item (§12.3.3, Table 151). + public static readonly CosName C = new("C"); + + /// /F, the style flags of an outline item (§12.3.3, Tables 151 and 152). + public static readonly CosName F = new("F"); + + /// /D, the destination of a named destination's dictionary value (§12.3.2.4) and of a go-to action (§12.6.4.2, Table 202). + public static readonly CosName D = new("D"); + + /// /SD, the structure destination of a go-to action (§12.6.4.2, Table 202). + public static readonly CosName SD = new("SD"); + + /// /P, the parent of a structure element (§14.7.2, Table 355). + public static readonly CosName P = new("P"); + + /// /StructElem, the type of a structure element (§14.7.2, Table 355). + public static readonly CosName StructElem = new("StructElem"); + + /// /GoTo, the go-to action type (§12.6.4.2, Table 202). + public static readonly CosName GoTo = new("GoTo"); +} diff --git a/src/Broadside/Parsing/DiagnosticCodes.Navigation.cs b/src/Broadside/Parsing/DiagnosticCodes.Navigation.cs index 6a7ba175..d8153cc9 100644 --- a/src/Broadside/Parsing/DiagnosticCodes.Navigation.cs +++ b/src/Broadside/Parsing/DiagnosticCodes.Navigation.cs @@ -24,6 +24,20 @@ internal static partial class DiagnosticCodes public const string NumberTreeCycle = nameof(NumberTreeCycle); public const string NumberTreeTooDeep = nameof(NumberTreeTooDeep); + // Destinations (§12.3.2). + public const string DestinationInvalid = nameof(DestinationInvalid); + public const string DestinationPageNotFound = nameof(DestinationPageNotFound); + public const string NamedDestinationNotFound = nameof(NamedDestinationNotFound); + + // Document outline (§12.3.3). + public const string OutlineInvalid = nameof(OutlineInvalid); + public const string OutlineItemInvalid = nameof(OutlineItemInvalid); + public const string OutlineCycle = nameof(OutlineCycle); + public const string OutlineTooDeep = nameof(OutlineTooDeep); + public const string OutlineLinkInconsistent = nameof(OutlineLinkInconsistent); + public const string OutlineCountInvalid = nameof(OutlineCountInvalid); + public const string OutlineDestAndAction = nameof(OutlineDestAndAction); + // Actions (§12.6.2, Table 196). public const string ActionInvalid = nameof(ActionInvalid); } diff --git a/src/Broadside/PdfAction.cs b/src/Broadside/PdfAction.cs new file mode 100644 index 00000000..563717a2 --- /dev/null +++ b/src/Broadside/PdfAction.cs @@ -0,0 +1,86 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// An action: what happens when an outline item, a link or another trigger is activated. A live view over the action dictionary. +/// +/// +/// ISO 32000-2 §12.6.2, Table 196. is the S entry. The types this version models are +/// (§12.6.4.2) and (§12.6.4.8); every other type reads as a +/// , kept as it is and never performed (parse-and-preserve), and gains its own view as it is modelled. +/// The Next chain (PDF 1.2) is reachable through . +/// +/// Actions are data: reading one never performs it. +/// +public abstract class PdfAction +{ + private protected PdfAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + { + Document = document; + Dictionary = dictionary; + Reference = reference; + ActionType = actionType; + } + + /// Gets the action dictionary. + /// ISO 32000-2 §12.6.2, Table 196. + public CosDictionary Dictionary { get; } + + /// Gets the indirect reference to the action dictionary, or when it is direct. + public CosReference? Reference { get; } + + /// Gets the type of action, the S entry, such as GoTo or URI. + /// ISO 32000-2 §12.6.2, Table 196, and §12.6.4.1, Table 201. + public CosName ActionType { get; } + + private protected PdfDocument Document { get; } + + /// Gets the reference diagnostics name: the action's own, or the object holding it. + private protected CosReference? Owner { get; private init; } + + /// Reads an action dictionary. + /// The document. + /// The action dictionary or a reference to it. + /// The indirect object holding the action, for diagnostics when the action is direct. + /// + /// The action; when the value is absent, or, with a diagnostic, when it is not a dictionary or has no + /// S name. + /// + internal static PdfAction? Create(PdfDocument document, CosObject? value, CosReference? owner) + { + var reference = value as CosReference; + CosReference? diagnosticReference = reference ?? owner; + CosObject resolved = document.Resolve(value); + if (resolved is CosNull) + { + return null; + } + + if (resolved is not CosDictionary dictionary || !dictionary.TryGetValue(NavigationNames.S, out CosObject? s) || document.Resolve(s) is not CosName type) + { + Report(document, "An action is not a dictionary with an S entry naming its type; it is ignored.", diagnosticReference); + return null; + } + + PdfAction action = type.Value switch + { + "GoTo" => new PdfGoToAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "URI" => new PdfUriAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + _ => new PdfUnknownAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + }; + action.Check(); + return action; + } + + /// Reports, once when the action is read, what its type's entries lack. + private protected virtual void Check() + { + } + + private protected void Report(string message) => Report(Document, message, Owner); + + private static void Report(PdfDocument document, string message, CosReference? reference) => + document.DiagnosticSink.Report(DiagnosticCodes.ActionInvalid, DiagnosticSeverity.Warning, message, objectReference: reference); +} diff --git a/src/Broadside/PdfDestination.cs b/src/Broadside/PdfDestination.cs new file mode 100644 index 00000000..2867b0e3 --- /dev/null +++ b/src/Broadside/PdfDestination.cs @@ -0,0 +1,68 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// A destination: a view of a document to show, given explicitly by an array or indirectly by name. A live view. +/// +/// +/// ISO 32000-2 §12.3.2. An explicit destination (, §12.3.2.2) is an array naming a page (or a +/// structure element, §12.3.2.3) and how to show it; a named destination (, §12.3.2.4) is a name +/// (PDF 1.1) or byte string (PDF 1.2) looked up in the document's named destinations. +/// +/// +/// A destination is remote when it belongs to a remote or embedded go-to action (§12.6.4.3, §12.6.4.4): its page is a page number +/// and its names are looked up in another document, never in this one. +/// +/// +public abstract class PdfDestination +{ + private protected PdfDestination(PdfDocument document, CosObject value, bool isRemote, CosReference? owner) + { + Document = document; + Value = value; + IsRemote = isRemote; + Owner = owner; + } + + /// Gets the destination as stored: an array for an explicit destination, a name or a string for a named one. + public CosObject Value { get; } + + /// Gets a value indicating whether the destination is in another document (a remote or embedded go-to action's). + /// ISO 32000-2 §12.3.2.2 and §12.6.4.3. + public bool IsRemote { get; } + + private protected PdfDocument Document { get; } + + /// Gets the indirect object the destination was read from, for diagnostics. + private protected CosReference? Owner { get; } + + /// Reads the value of a Dest or D entry as a destination. + /// The document. + /// The entry's value: an array, a name or a string, or a reference to one. + /// Whether the destination is in another document. + /// The indirect object holding the entry, for diagnostics. + /// The destination, or when the value is absent, or of no destination type (with a diagnostic). + internal static PdfDestination? Create(PdfDocument document, CosObject? value, bool isRemote, CosReference? owner) + { + CosObject resolved = document.Resolve(value); + CosReference? reference = value as CosReference ?? owner; + switch (resolved) + { + case CosArray array: + return new PdfExplicitDestination(document, array, isRemote, reference); + case CosName or CosString: + return new PdfNamedDestination(document, resolved, isRemote, owner); + case CosNull: + return null; + default: + document.DiagnosticSink.Report( + DiagnosticCodes.DestinationInvalid, + DiagnosticSeverity.Warning, + "A destination is not an array, a name or a string; it is ignored.", + objectReference: reference); + return null; + } + } +} diff --git a/src/Broadside/PdfDestinationTarget.cs b/src/Broadside/PdfDestinationTarget.cs new file mode 100644 index 00000000..09320c98 --- /dev/null +++ b/src/Broadside/PdfDestinationTarget.cs @@ -0,0 +1,21 @@ +namespace Broadside; + +/// What the first element of an explicit destination array designates. +/// ISO 32000-2 §12.3.2.2 (page object or remote page number) and §12.3.2.3 (structure element or remote structure element ID). +public enum PdfDestinationTarget +{ + /// The first element is missing or of no type a destination allows. + None = 0, + + /// A page object of this document (an indirect reference), possibly one the page tree does not hold. + Page, + + /// A 0-based page number: in another document for a remote destination (§12.6.4.3), or a producer's error in a local one. + PageNumber, + + /// A structure element dictionary of this document: a structure destination (§12.3.2.3, PDF 2.0). + StructureElement, + + /// A byte string naming a structure element by its ID in another document: a remote structure destination (§12.3.2.3). + StructureElementId, +} diff --git a/src/Broadside/PdfDestinationView.cs b/src/Broadside/PdfDestinationView.cs new file mode 100644 index 00000000..abad7d95 --- /dev/null +++ b/src/Broadside/PdfDestinationView.cs @@ -0,0 +1,33 @@ +namespace Broadside; + +/// How an explicit destination positions and magnifies its page: the view name in its array. +/// ISO 32000-2 §12.3.2.2, Table 149. +public enum PdfDestinationView +{ + /// The array names no view this library knows, or none at all; the destination is not valid. + Unknown = 0, + + /// [page /XYZ left top zoom]: (left, top) at the upper-left corner of the window, magnified by zoom; a null keeps the current value (PDF 1.0). + Xyz, + + /// [page /Fit]: the whole page fits the window (PDF 1.0). + Fit, + + /// [page /FitH top]: top at the top edge, the page width fits the window (PDF 1.0). + FitH, + + /// [page /FitV left]: left at the left edge, the page height fits the window (PDF 1.0). + FitV, + + /// [page /FitR left bottom right top]: the rectangle fits the window (PDF 1.0). + FitR, + + /// [page /FitB]: the page's bounding box fits the window (PDF 1.1). + FitB, + + /// [page /FitBH top]: top at the top edge, the bounding box width fits the window (PDF 1.1). + FitBH, + + /// [page /FitBV left]: left at the left edge, the bounding box height fits the window (PDF 1.1). + FitBV, +} diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index da14fec4..538bee2f 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -123,7 +123,7 @@ public PdfNameDictionary? Names { get { - if (!Catalog.TryGetValue(KnownNames.Names, out CosObject? entry)) + if (!Catalog.TryGetValue(NavigationNames.Names, out CosObject? entry)) { return null; } @@ -142,6 +142,37 @@ public PdfNameDictionary? Names } } + /// Gets the document outline (bookmarks), or when the catalog has none. + /// + /// ISO 32000-2 §7.7.2, Table 29 (Outlines), and §12.3.3. Read from the catalog on every call. An entry that is not a + /// dictionary reads as none, with a diagnostic. + /// + public PdfOutline? Outline + { + get + { + if (!Catalog.TryGetValue(NavigationNames.Outlines, out CosObject? entry)) + { + return null; + } + + switch (Resolve(entry)) + { + case CosDictionary outline: + return new PdfOutline(this, outline, entry as CosReference); + case CosNull: + return null; + default: + _diagnostics.Report( + DiagnosticCodes.OutlineInvalid, + DiagnosticSeverity.Warning, + "The catalog's Outlines entry is not a dictionary; the document is read as having no outline.", + objectReference: entry as CosReference); + return null; + } + } + } + /// Gets the revisions of the file, oldest first: the original file, then one per incremental update. /// /// ISO 32000-2 §7.5.6. The document itself always shows the newest revision: for every object number the most recent @@ -401,6 +432,113 @@ public async Task SaveAsync(Stream stream, PdfSaveOptions? options = null, Cance public PdfNumberTree? GetNumberTree(CosObject? root) => GetNumberTreeReader(root) is { } reader ? new PdfNumberTree(reader) : null; + /// Looks up the destination a name (PDF 1.1) or string (PDF 1.2) names, as text. + /// The destination's name. + /// + /// The explicit destination; when the document has none of that name, or, with a diagnostic, when the + /// value it has is not a destination. + /// + /// + /// ISO 32000-2 §12.3.2.4. The name dictionary's Dests tree first (the text as PDFDocEncoding, then UTF-16BE, then every key + /// decoded: ), then the catalog's Dests dictionary (the text as a + /// UTF-8 name). A value that is a dictionary resolves to its D entry. + /// + public PdfExplicitDestination? GetNamedDestination(string name) + { + ArgumentNullException.ThrowIfNull(name); + if (Names?.Dests is { } tree && tree.Reader.TryGetRawValue(name, out CosObject? value)) + { + return ReadNamedDestinationValue(value); + } + + if (!name.Contains('\0', StringComparison.Ordinal) && LegacyDestination(new CosName(name)) is { } legacy) + { + return ReadNamedDestinationValue(legacy); + } + + return null; + } + + /// Looks up the destination a byte string names (PDF 1.2). + /// The destination's name. + /// The explicit destination, or ; see . + /// ISO 32000-2 §12.3.2.4 and Annex J.3.3: the Dests tree first, then the catalog's Dests dictionary, by bytes. + public PdfExplicitDestination? GetNamedDestination(CosString name) + { + ArgumentNullException.ThrowIfNull(name); + return FindNamedDestination(name, out _); + } + + /// Looks up the destination a name object names (PDF 1.1). + /// The destination's name. + /// The explicit destination, or ; see . + /// ISO 32000-2 §12.3.2.4 and Annex J.3.4: the catalog's Dests dictionary first, then the Dests tree, by bytes. + public PdfExplicitDestination? GetNamedDestination(CosName name) + { + ArgumentNullException.ThrowIfNull(name); + return FindNamedDestination(name, out _); + } + + /// Looks a destination name up: a name in the catalog's Dests first, a string in the tree first, then the other. + /// A or . + /// Whether the document holds the name, whatever its value. + /// The explicit destination, or . + internal PdfExplicitDestination? FindNamedDestination(CosObject name, out bool found) + { + CosObject? value = null; + switch (name) + { + case CosName key: + value = LegacyDestination(key) ?? TreeDestination(key.Bytes); + break; + case CosString key: + value = TreeDestination(key.Bytes); + if (value is null && key.Bytes.Length > 0 && !key.Bytes.Contains((byte)0)) + { + value = LegacyDestination(new CosName(key.Bytes)); + } + + break; + } + + found = value is not null; + return value is null ? null : ReadNamedDestinationValue(value); + } + + /// Reads a named destination's value: a destination array, or a dictionary whose D entry is one (§12.3.2.4). + private PdfExplicitDestination? ReadNamedDestinationValue(CosObject value) + { + var reference = value as CosReference; + CosObject resolved = Resolve(value); + if (resolved is CosDictionary dictionary && dictionary.TryGetValue(NavigationNames.D, out CosObject? d)) + { + reference = d as CosReference ?? reference; + resolved = Resolve(d); + } + + if (resolved is CosArray array) + { + return new PdfExplicitDestination(this, array, isRemote: false, reference); + } + + _diagnostics.Report( + DiagnosticCodes.DestinationInvalid, + DiagnosticSeverity.Warning, + "A named destination's value is neither a destination array nor a dictionary with a D entry; the name shows no page.", + objectReference: reference); + return null; + } + + private CosObject? TreeDestination(ReadOnlySpan key) => + Names?.Dests is { } tree && tree.Reader.TryGetRawValue(new CosString(key), out CosObject? value) ? value : null; + + private CosObject? LegacyDestination(CosName key) => + Catalog.TryGetValue(NavigationNames.Dests, out CosObject? entry) + && Resolve(entry) is CosDictionary dests + && dests.TryGetValue(key, out CosObject? value) + ? value + : null; + /// Returns the document's reader for the name tree rooted at , creating it on first use. /// The root node or a reference to it. /// The reader; when the root does not resolve to a dictionary. diff --git a/src/Broadside/PdfExplicitDestination.cs b/src/Broadside/PdfExplicitDestination.cs new file mode 100644 index 00000000..92f3c649 --- /dev/null +++ b/src/Broadside/PdfExplicitDestination.cs @@ -0,0 +1,276 @@ +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// An explicit destination: [page /View parameters...]. A live view over the array. +/// +/// +/// ISO 32000-2 §12.3.2.2, Table 149, and §12.3.2.3. The first element is the target: a page object, or for a remote destination a +/// 0-based page number in the other document; a structure element (or, remote, its ID) makes it a structure destination (PDF 2.0). +/// The second element names the view (); the rest are its parameters in default user space. A parameter that is +/// null means "keep the current value", as does an XYZ zoom of 0, so , and +/// are then; a parameter the view does not have is too. +/// +/// +/// Read leniently, each with a diagnostic when the destination is read: missing trailing parameters read as null, extra ones are +/// ignored, a parameter that is not a number reads as null, an unknown view name reads as +/// (the page is still available), a FitR without four numbers is not valid, and a local destination whose page is an +/// integer (a common producer error) uses it as a 0-based page index. A page that is not in the page tree has no +/// , with a diagnostic when it is asked for. +/// +/// +public sealed class PdfExplicitDestination : PdfDestination +{ + internal PdfExplicitDestination(PdfDocument document, CosArray array, bool isRemote, CosReference? owner) + : base(document, array, isRemote, owner) + { + Array = array; + Check(); + } + + /// Gets the destination array. + /// ISO 32000-2 §12.3.2.2, Table 149. + public CosArray Array { get; } + + /// Gets the first element of the array as stored (a page reference, a page number, a structure element reference or ID), or null. + public CosObject Target => Array.Count > 0 ? Array[0] : CosNull.Instance; + + /// Gets what the first element designates. + /// ISO 32000-2 §12.3.2.2 and §12.3.2.3. + public PdfDestinationTarget TargetKind + { + get + { + CosObject target = Target; + switch (target) + { + case CosInteger: + return PdfDestinationTarget.PageNumber; + case CosString: + return IsRemote ? PdfDestinationTarget.StructureElementId : PdfDestinationTarget.None; + case CosReference or CosDictionary when !IsRemote: + return Document.Resolve(target) is CosDictionary node + ? Document.Pages.IndexOf(node) < 0 && IsStructureElement(node) ? PdfDestinationTarget.StructureElement : PdfDestinationTarget.Page + : PdfDestinationTarget.None; + default: + return PdfDestinationTarget.None; + } + } + } + + /// Gets the page number the first element gives, when it is an integer; otherwise . + /// ISO 32000-2 §12.3.2.2: for a remote destination, the 0-based number of a page in the other document. + public int? PageNumber => Target is CosInteger { Value: >= int.MinValue and <= int.MaxValue } number ? (int)number.Value : null; + + /// Gets the page of this document the destination shows, or when it is remote, a structure destination or its page is not in the page tree. + /// ISO 32000-2 §12.3.2.2. A structure destination's page is found from its structure element (§12.3.2.3), which this version does not do yet. + public PdfPage? Page => PageIndex is { } index ? Document.Pages[index] : null; + + /// Gets the 0-based index of in , or . + /// In strict mode, when the destination names a page that is not in the page tree. + /// + /// ISO 32000-2 §12.3.2.2. A remote destination's page number is never resolved in this document. A local destination whose first + /// element is an integer uses it as the index, with a diagnostic when the destination is read. + /// + public int? PageIndex + { + get + { + if (IsRemote) + { + return null; + } + + CosObject target = Target; + if (target is CosInteger number) + { + if (number.Value >= 0 && number.Value < Document.Pages.Count) + { + return (int)number.Value; + } + + ReportPageNotFound("A destination's page number is not the index of a page of the document."); + return null; + } + + if (Document.Resolve(target) is not CosDictionary node) + { + return null; + } + + int index = Document.Pages.IndexOf(node); + if (index >= 0) + { + return index; + } + + if (!IsStructureElement(node)) + { + ReportPageNotFound("A destination refers to a page object that is not in the page tree."); + } + + return null; + } + } + + /// Gets the structure element the destination designates (a structure destination), or . + /// ISO 32000-2 §12.3.2.3 (PDF 2.0). + public CosDictionary? StructureElement => + !IsRemote && Document.Resolve(Target) is CosDictionary node && Document.Pages.IndexOf(node) < 0 && IsStructureElement(node) ? node : null; + + /// Gets the ID of the structure element in another document a remote structure destination designates, or . + /// ISO 32000-2 §12.3.2.3, Table 355 (ID). + public CosString? StructureElementId => IsRemote ? Target as CosString : null; + + /// Gets the view the destination asks for. + /// ISO 32000-2 §12.3.2.2, Table 149. + public PdfDestinationView View => ViewOf(ViewName); + + /// Gets the view name as stored, or when the second element is not a name. + public CosName? ViewName => Array.Count > 1 ? Document.Resolve(Array[1]) as CosName : null; + + /// Gets the left coordinate (XYZ, FitV, FitBV, FitR), or to keep the current one. + /// ISO 32000-2 §12.3.2.2, Table 149; default user space. + public double? Left => Parameter(Slot.Left); + + /// Gets the top coordinate (XYZ, FitH, FitBH, FitR), or to keep the current one. + /// ISO 32000-2 §12.3.2.2, Table 149; default user space. + public double? Top => Parameter(Slot.Top); + + /// Gets the right coordinate of a FitR rectangle, or . + /// ISO 32000-2 §12.3.2.2, Table 149; default user space. + public double? Right => Parameter(Slot.Right); + + /// Gets the bottom coordinate of a FitR rectangle, or . + /// ISO 32000-2 §12.3.2.2, Table 149; default user space. + public double? Bottom => Parameter(Slot.Bottom); + + /// Gets the magnification of an XYZ destination, or to keep the current one (null or 0 in the file). + /// ISO 32000-2 §12.3.2.2, Table 149: "A zoom value of 0 has the same meaning as a null value". + public double? Zoom => Parameter(Slot.Zoom) is { } zoom && zoom != 0 ? zoom : null; + + /// + /// Gets a value indicating whether the destination can be shown: a known view, a target of an allowed type and, for FitR, a + /// rectangle of four numbers. + /// + /// ISO 32000-2 §12.3.2.2, Table 149. + public bool IsValid => + View != PdfDestinationView.Unknown + && TargetKind != PdfDestinationTarget.None + && (View != PdfDestinationView.FitR || (Left, Bottom, Right, Top) is ({ }, { }, { }, { })); + + /// Whether a dictionary is a structure element rather than a page (§14.7.2, Table 355). + private static bool IsStructureElement(CosDictionary node) => + node.TryGetValue(KnownNames.Type, out CosObject? type) + ? NavigationNames.StructElem.Equals(type) + : node.ContainsKey(NavigationNames.S) && node.ContainsKey(NavigationNames.P); + + private static PdfDestinationView ViewOf(CosName? name) => name?.Value switch + { + "XYZ" => PdfDestinationView.Xyz, + "Fit" => PdfDestinationView.Fit, + "FitH" => PdfDestinationView.FitH, + "FitV" => PdfDestinationView.FitV, + "FitR" => PdfDestinationView.FitR, + "FitB" => PdfDestinationView.FitB, + "FitBH" => PdfDestinationView.FitBH, + "FitBV" => PdfDestinationView.FitBV, + _ => PdfDestinationView.Unknown, + }; + + /// The parameters a view takes, in array order after the view name. + private static Slot[] SlotsOf(PdfDestinationView view) => view switch + { + PdfDestinationView.Xyz => [Slot.Left, Slot.Top, Slot.Zoom], + PdfDestinationView.FitH or PdfDestinationView.FitBH => [Slot.Top], + PdfDestinationView.FitV or PdfDestinationView.FitBV => [Slot.Left], + PdfDestinationView.FitR => [Slot.Left, Slot.Bottom, Slot.Right, Slot.Top], + _ => [], + }; + + private double? Parameter(Slot slot) + { + int position = System.Array.IndexOf(SlotsOf(View), slot); + if (position < 0 || position + 2 >= Array.Count) + { + return null; + } + + return Document.Resolve(Array[position + 2]) is CosNumber number && double.IsFinite(number.ToDouble()) ? number.ToDouble() : null; + } + + /// Reports what is wrong with the array, once, when the destination is read. + private void Check() + { + PdfDestinationView view = View; + if (Array.Count < 2 || ViewName is null) + { + Report("A destination array shall be [page /View parameters...]; it has no view name, so it cannot be shown."); + return; + } + + if (view == PdfDestinationView.Unknown) + { + Report(string.Create(CultureInfo.InvariantCulture, $"A destination's view /{ViewName.Value} is not one of Table 149; the destination cannot be shown.")); + } + + Slot[] slots = SlotsOf(view); + int given = Array.Count - 2; + if (view != PdfDestinationView.Unknown && given != slots.Length) + { + Report(given < slots.Length + ? view == PdfDestinationView.FitR + ? "A FitR destination shall have four coordinates; it has fewer, so it cannot be shown." + : "A destination has fewer parameters than its view takes; the missing ones read as null (keep the current value)." + : "A destination has more parameters than its view takes; the extra ones are ignored."); + } + + for (int index = 0; index < Math.Min(given, slots.Length); index++) + { + CosObject parameter = Document.Resolve(Array[index + 2]); + if (parameter is CosNull && view == PdfDestinationView.FitR) + { + Report("A FitR destination's coordinates shall be numbers; one is null, so it cannot be shown."); + } + else if (parameter is not (CosNumber or CosNull)) + { + Report("A destination parameter is not a number or null; it reads as null (keep the current value)."); + } + } + + switch (Target) + { + case CosInteger when !IsRemote: + Report("A destination in this document shall refer to its page by an indirect reference; it gives a page number, used as a 0-based page index."); + break; + case CosReference or CosDictionary when IsRemote: + case CosString when !IsRemote: + Report("A destination's first element is of no type its context allows; it designates no page."); + break; + case CosReference or CosDictionary or CosInteger or CosString: + break; + default: + Report("A destination's first element is not a page, a page number or a structure element; it designates no page."); + break; + } + } + + private void Report(string message) => + Document.DiagnosticSink.Report(DiagnosticCodes.DestinationInvalid, DiagnosticSeverity.Warning, message, objectReference: Owner); + + private void ReportPageNotFound(string message) => + Document.DiagnosticSink.Report(DiagnosticCodes.DestinationPageNotFound, DiagnosticSeverity.Warning, message + " It shows no page.", objectReference: Owner); + + /// A parameter of Table 149. + private enum Slot + { + Left, + Top, + Right, + Bottom, + Zoom, + } +} diff --git a/src/Broadside/PdfGoToAction.cs b/src/Broadside/PdfGoToAction.cs new file mode 100644 index 00000000..bd842b1b --- /dev/null +++ b/src/Broadside/PdfGoToAction.cs @@ -0,0 +1,34 @@ +using Broadside.Objects; + +namespace Broadside; + +/// A go-to action: changes the view to a destination in this document. +/// ISO 32000-2 §12.6.4.2, Table 202 (PDF 1.1). +public sealed class PdfGoToAction : PdfAction +{ + internal PdfGoToAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// Gets the destination to show, the D entry: explicit or named; when absent or invalid. + /// ISO 32000-2 §12.6.4.2, Table 202, and §12.3.2. + public PdfDestination? Destination => + Dictionary.TryGetValue(NavigationNames.D, out CosObject? d) ? PdfDestination.Create(Document, d, isRemote: false, Reference ?? Owner) : null; + + /// Gets the structure destination, the SD entry (PDF 2.0), or . When present it should take precedence over . + /// ISO 32000-2 §12.6.4.2, Table 202, and §12.3.2.3. + public PdfExplicitDestination? StructureDestination => + Dictionary.TryGetValue(NavigationNames.SD, out CosObject? sd) + ? PdfDestination.Create(Document, sd, isRemote: false, Reference ?? Owner) as PdfExplicitDestination + : null; + + /// + private protected override void Check() + { + if (!Dictionary.ContainsKey(NavigationNames.D)) + { + Report("A go-to action shall have a D entry; it has none, so it goes nowhere."); + } + } +} diff --git a/src/Broadside/PdfNameDictionary.cs b/src/Broadside/PdfNameDictionary.cs index 67dcce88..0fbdd5e6 100644 --- a/src/Broadside/PdfNameDictionary.cs +++ b/src/Broadside/PdfNameDictionary.cs @@ -28,7 +28,7 @@ internal PdfNameDictionary(PdfDocument document, CosDictionary dictionary) /// ISO 32000-2 §7.7.4, Table 32 (PDF 1.2), and §12.3.2.4: each value is a destination array, or a dictionary whose D entry /// is one. Named destinations of PDF 1.1 (name keys) are in the catalog's own Dests dictionary instead. /// - public PdfNameTree? Dests => GetTree(KnownNames.Dests); + public PdfNameTree? Dests => GetTree(NavigationNames.Dests); /// Gets the name tree under , or when the entry is absent. /// The entry, for example EmbeddedFiles or JavaScript. diff --git a/src/Broadside/PdfNameTree.cs b/src/Broadside/PdfNameTree.cs index 5248659a..76bc23b2 100644 --- a/src/Broadside/PdfNameTree.cs +++ b/src/Broadside/PdfNameTree.cs @@ -1,6 +1,5 @@ using System.Collections; using System.Diagnostics.CodeAnalysis; -using System.Text; using Broadside.Objects; namespace Broadside; @@ -18,7 +17,7 @@ namespace Broadside; /// a key that appears twice, a node reached twice (a cycle), a tree deeper than 64 levels, an odd-length Names array, and a key /// that is not a string are each reported once per node as a diagnostic; lookups then fall back to an index of every key, built once /// by walking the whole tree and kept until a node of the tree changes. When a key appears twice, the first occurrence in tree order -/// is the one both lookups and enumeration return. Diagnostics are reported when the damage is first read, so in strict mode the +/// is the one both lookups and enumeration return once a walk has met the damage (until then a lookup follows the Limits it finds). Diagnostics are reported when the damage is first read, so in strict mode the /// lookup or enumeration that meets it throws a , not . /// /// Safe for concurrent reads while nobody changes the document. @@ -67,30 +66,12 @@ public bool TryGetValue(CosString key, [MaybeNullWhen(false)] out CosObject valu public bool TryGetValue(string key, [MaybeNullWhen(false)] out CosObject value) { ArgumentNullException.ThrowIfNull(key); - if (TextStringEncoder.TryEncodePdfDoc(key, out byte[]? encoded) && _reader.TryGetValue(encoded, out value)) - { - return true; - } - - byte[] utf16 = [0xFE, 0xFF, .. Encoding.BigEndianUnicode.GetBytes(key)]; - if (_reader.TryGetValue(utf16, out value)) - { - return true; - } - - foreach ((CosString candidate, CosObject found) in _reader.Enumerate()) - { - if (string.Equals(candidate.DecodeText(), key, StringComparison.Ordinal)) - { - value = found; - return true; - } - } - - value = null; - return false; + return _reader.TryGetValue(key, out value); } + /// Gets the reader, for the document model's typed views that need values as stored. + internal NameTreeReader Reader => _reader; + /// Determines whether the tree holds the key with the same bytes as . /// The key. /// when the tree holds the key. diff --git a/src/Broadside/PdfNamedDestination.cs b/src/Broadside/PdfNamedDestination.cs new file mode 100644 index 00000000..da4fc066 --- /dev/null +++ b/src/Broadside/PdfNamedDestination.cs @@ -0,0 +1,75 @@ +using System.Text; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// A destination referred to by name: a name object (PDF 1.1) or a byte string (PDF 1.2). A live view. +/// +/// ISO 32000-2 §12.3.2.4. looks the name up in this document: a name in the catalog's Dests dictionary +/// first, a string in the name dictionary's Dests tree first, then each in the other (files mix the two), comparing bytes +/// (Annex J.3.3, J.3.4). A remote named destination is in another document and does not resolve here. +/// +public sealed class PdfNamedDestination : PdfDestination +{ + internal PdfNamedDestination(PdfDocument document, CosObject name, bool isRemote, CosReference? owner) + : base(document, name, isRemote, owner) + { + Name = name; + } + + /// Gets the name as stored: a or a . + /// ISO 32000-2 §12.3.2.4. + public CosObject Name { get; } + + /// Gets the name as text, for display: a name's bytes as UTF-8, a string decoded as a text string. + /// ISO 32000-2 §12.3.2.4: the keys "may be treated as text strings for display purposes"; §7.9.2.2. + public string Text => Name switch + { + CosName name => name.Value, + CosString text => text.DecodeText(), + _ => string.Empty, + }; + + /// Looks the name up among the document's named destinations. + /// + /// The explicit destination it stands for; when the destination is remote, or, with a diagnostic, when the + /// document has no destination of that name or its value is not a destination. + /// + /// In strict mode, when the name does not resolve. + /// + /// ISO 32000-2 §12.3.2.4. A value that is a dictionary resolves to its D entry. A value that is itself a name or string is + /// not followed. + /// + public PdfExplicitDestination? Resolve() + { + if (IsRemote) + { + return null; + } + + PdfExplicitDestination? destination = Document.FindNamedDestination(Name, out bool found); + if (!found) + { + Document.DiagnosticSink.Report( + DiagnosticCodes.NamedDestinationNotFound, + DiagnosticSeverity.Warning, + $"The document has no named destination \"{Escape(Text)}\"; the reference to it shows no page.", + objectReference: Owner); + } + + return destination; + } + + private static string Escape(string text) + { + var builder = new StringBuilder(text.Length); + foreach (char character in text) + { + builder.Append(char.IsControl(character) ? '?' : character); + } + + return builder.ToString(); + } +} diff --git a/src/Broadside/PdfOutline.cs b/src/Broadside/PdfOutline.cs new file mode 100644 index 00000000..e15b6c5f --- /dev/null +++ b/src/Broadside/PdfOutline.cs @@ -0,0 +1,242 @@ +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// The document outline (bookmarks): a tree of outline items. A live view over the outline dictionary. +/// +/// +/// ISO 32000-2 §12.3.3, Table 150. walks the outline each time it is read: each level's items in the order of +/// their First/Next chain, iteratively, with one visited set for the whole outline and a depth cap of 256 levels, so a +/// cycle (a Next back to an earlier sibling, a First back to an ancestor) or a very deep chain ends. +/// +/// +/// The walk checks the outline as it goes and reports, once per item: an item reached twice (OutlineCycle, Error), a level +/// deeper than the cap, a Last, Prev or Parent that disagrees with the chain (the chain wins), a missing or +/// non-string Title (read as empty), an item that is not a dictionary, a malformed C or F, both Dest and +/// A, an item with children but no non-zero Count (read as closed), a negative outline Count, and the +/// diagnostics of each item's destination and action. In strict mode the walk throws the first of these. +/// +/// +public sealed class PdfOutline +{ + /// The deepest outline level the walk descends to. + internal const int MaxDepth = 256; + + private readonly PdfDocument _document; + + internal PdfOutline(PdfDocument document, CosDictionary dictionary, CosReference? reference) + { + _document = document; + Dictionary = dictionary; + Reference = reference; + } + + /// Gets the outline dictionary. + /// ISO 32000-2 §12.3.3, Table 150. + public CosDictionary Dictionary { get; } + + /// Gets the indirect reference to the outline dictionary, or when it is direct. + public CosReference? Reference { get; } + + /// Gets the outline's Count as stored: the number of visible items at all levels; when absent. + /// ISO 32000-2 §12.3.3, Table 150. + public int? Count => PdfOutlineItem.ReadCount(_document, Dictionary); + + /// Walks the outline and returns its top-level items, each with its children. + /// In strict mode, for the first deviation the walk finds. + /// ISO 32000-2 §12.3.3. A new walk on every call; the items are live views over their dictionaries. + public IReadOnlyList Items => Walk(); + + private List Walk() + { + var top = new List(); + var visitedReferences = new HashSet(); + var visitedItems = new HashSet(ReferenceEqualityComparer.Instance); + if (Reference is not null) + { + visitedReferences.Add(Reference); + } + + visitedItems.Add(Dictionary); + var levels = new Stack(); + levels.Push(new Level(null, Dictionary, Reference, 0)); + while (levels.TryPop(out Level level)) + { + List siblings = level.Parent?.ChildList ?? top; + CosReference? previous = null; + PdfOutlineItem? last = null; + level.Node.TryGetValue(NavigationNames.First, out CosObject? entry); + while (entry is not null) + { + var reference = entry as CosReference; + CosObject resolved = _document.Resolve(entry); + if (resolved is not CosDictionary dictionary) + { + if (resolved is not CosNull) + { + Report(DiagnosticCodes.OutlineItemInvalid, DiagnosticSeverity.Warning, "An outline item is not a dictionary; its level ends there.", reference ?? level.Reference); + } + + break; + } + + if ((reference is not null && !visitedReferences.Add(reference)) || !visitedItems.Add(dictionary)) + { + Report( + DiagnosticCodes.OutlineCycle, + DiagnosticSeverity.Error, + "An outline item is reached a second time (a cycle through Next or First); its level ends there.", + reference ?? level.Reference); + break; + } + + var item = new PdfOutlineItem(_document, dictionary, reference, level.Parent, level.Depth); + CheckItem(item, level.Reference, previous); + siblings.Add(item); + previous = reference; + last = item; + dictionary.TryGetValue(NavigationNames.Next, out entry); + } + + if (last is not null && !(level.Node.TryGetValue(NavigationNames.Last, out CosObject? lastEntry) && SameObject(lastEntry, last))) + { + Report( + DiagnosticCodes.OutlineLinkInconsistent, + DiagnosticSeverity.Warning, + "The Last entry does not name the item the First/Next chain ends with; the chain is used.", + level.Reference); + } + + for (int index = siblings.Count - 1; index >= 0 && last is not null; index--) + { + PdfOutlineItem item = siblings[index]; + if (!item.Dictionary.ContainsKey(NavigationNames.First)) + { + continue; + } + + if (level.Depth + 1 >= MaxDepth) + { + Report( + DiagnosticCodes.OutlineTooDeep, + DiagnosticSeverity.Error, + string.Create(CultureInfo.InvariantCulture, $"The outline is deeper than {MaxDepth} levels; the deeper items are skipped."), + item.Reference ?? level.Reference); + continue; + } + + levels.Push(new Level(item, item.Dictionary, item.Reference ?? level.Reference, level.Depth + 1)); + } + } + + CheckCounts(top); + return top; + } + + /// Checks one item's entries (Table 151) as the walk reaches it. + private void CheckItem(PdfOutlineItem item, CosReference? parentReference, CosReference? previous) + { + CosDictionary dictionary = item.Dictionary; + CosReference? reference = item.Reference ?? parentReference; + bool parentMatches = parentReference is null || (dictionary.TryGetValue(KnownNames.Parent, out CosObject? parent) && parentReference.Equals(parent)); + bool hasPrev = dictionary.TryGetValue(KnownNames.Prev, out CosObject? prev); + bool prevMatches = previous is null ? !hasPrev : previous.Equals(prev); + if (!parentMatches || !prevMatches) + { + Report( + DiagnosticCodes.OutlineLinkInconsistent, + DiagnosticSeverity.Warning, + "An outline item's Parent or Prev does not name the item the First/Next chain reached it from; the chain is used.", + reference); + } + + if (_document.Resolve(dictionary.TryGetValue(NavigationNames.Title, out CosObject? title) ? title : null) is not CosString) + { + Report(DiagnosticCodes.OutlineItemInvalid, DiagnosticSeverity.Warning, "An outline item has no Title text string; it reads as empty.", reference); + } + + _ = item.ReadColor(out bool colorValid); + _ = item.ReadFlags(out bool flagsValid); + if (!colorValid || !flagsValid) + { + Report( + DiagnosticCodes.OutlineItemInvalid, + DiagnosticSeverity.Warning, + "An outline item's C is not three numbers from 0 to 1, or its F is not an integer; black or no flags are used where they cannot be read.", + reference); + } + + bool hasDest = dictionary.ContainsKey(NavigationNames.Dest); + if (hasDest && dictionary.ContainsKey(NavigationNames.A)) + { + Report( + DiagnosticCodes.OutlineDestAndAction, + DiagnosticSeverity.Warning, + "An outline item shall not have both Dest and A; both are read, and the action is the one to perform.", + reference); + } + else if (hasDest && PdfOutlineItem.IsActionDictionary(_document.Resolve(dictionary[NavigationNames.Dest]))) + { + Report(DiagnosticCodes.DestinationInvalid, DiagnosticSeverity.Warning, "An outline item's Dest holds an action dictionary; it is read as the item's action.", reference); + } + + // Read the destination and the action so that their own deviations are reported with the walk. + _ = item.Destination; + _ = item.Action; + } + + /// + /// Checks the Count entries that decide something (Tables 150 and 151), parents before children: an item with children + /// needs a non-zero Count to be open or closed, and the outline's Count cannot be negative. + /// + /// + /// The magnitude is not checked against the visible descendants: producers commonly write the number of immediate children + /// (the Isartor PDF/A suite, PDFium's test files), viewers ignore it, and nothing here uses it, so a mismatch would only make + /// strict mode reject files every reader shows alike. + /// + private void CheckCounts(List top) + { + if (Dictionary.ContainsKey(KnownNames.Count) && Count is not >= 0) + { + Report( + DiagnosticCodes.OutlineCountInvalid, + DiagnosticSeverity.Warning, + "The outline's Count is negative or not an integer; it cannot be.", + Reference); + } + + var pending = new Stack(top.AsEnumerable().Reverse()); + while (pending.TryPop(out PdfOutlineItem? item)) + { + if (item.Children.Count > 0 && item.Count is null or 0) + { + Report( + DiagnosticCodes.OutlineCountInvalid, + DiagnosticSeverity.Warning, + "An outline item with children has no non-zero Count to say whether it is open; it is read as closed.", + item.Reference); + } + + for (int index = item.Children.Count - 1; index >= 0; index--) + { + pending.Push(item.Children[index]); + } + } + } + + private bool SameObject(CosObject entry, PdfOutlineItem item) => + item.Reference is { } reference ? reference.Equals(entry) : ReferenceEquals(_document.Resolve(entry), item.Dictionary); + + private void Report(string code, DiagnosticSeverity severity, string message, CosReference? reference) => + _document.DiagnosticSink.Report(code, severity, message, objectReference: reference); + + /// A level waiting to be walked: the children of . + /// The item whose children these are, or for the top level. + /// The outline dictionary or the parent item's dictionary. + /// The node's reference, or its nearest indirect ancestor's. + /// The level of the children: 0 for top-level items. + private readonly record struct Level(PdfOutlineItem? Parent, CosDictionary Node, CosReference? Reference, int Depth); +} diff --git a/src/Broadside/PdfOutlineItem.cs b/src/Broadside/PdfOutlineItem.cs new file mode 100644 index 00000000..df9c9b55 --- /dev/null +++ b/src/Broadside/PdfOutlineItem.cs @@ -0,0 +1,169 @@ +using Broadside.Objects; + +namespace Broadside; + +/// One item (bookmark) of the document outline: its title, where it leads, how it looks, and its children. +/// +/// +/// ISO 32000-2 §12.3.3, Tables 151 and 152. The properties read the item dictionary on every call and return the defaults the clause +/// gives (black, no flags) without writing them. is the shape of the outline when +/// walked it; walk again to see changes to the links. +/// +/// +/// An item may have both Dest and A, which the clause forbids; both are exposed, and a reader that activates the item +/// should prefer (as viewers do). A Dest holding an action dictionary reads as . +/// +/// +public sealed class PdfOutlineItem +{ + private readonly PdfDocument _document; + private readonly List _children = []; + + internal PdfOutlineItem(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfOutlineItem? parent, int level) + { + _document = document; + Dictionary = dictionary; + Reference = reference; + Parent = parent; + Level = level; + } + + /// Gets the outline item dictionary. + /// ISO 32000-2 §12.3.3, Table 151. + public CosDictionary Dictionary { get; } + + /// Gets the indirect reference to the item, or when it is a direct dictionary (which the clause forbids). + public CosReference? Reference { get; } + + /// Gets the item this one is a child of, or for a top-level item. + public PdfOutlineItem? Parent { get; } + + /// Gets the depth of the item: 0 for a top-level item. + public int Level { get; } + + /// Gets the item's children, in the order of their First/Next chain. + /// ISO 32000-2 §12.3.3: "the items at a given level shall appear in the order in which they occur in the linked list". + public IReadOnlyList Children => _children; + + /// Gets the text displayed for the item, or the empty string when Title is missing or not a string. + /// ISO 32000-2 §12.3.3, Table 151; a text string (§7.9.2.2). + public string Title => _document.Resolve(Dictionary.TryGetValue(NavigationNames.Title, out CosObject? title) ? title : null) is CosString text + ? text.DecodeText() + : string.Empty; + + /// Gets the destination shown when the item is activated (Dest), or . + /// ISO 32000-2 §12.3.3, Table 151, and §12.3.2: an explicit destination, or a named one (a name or a string). + public PdfDestination? Destination => + Dictionary.TryGetValue(NavigationNames.Dest, out CosObject? dest) && !IsActionDictionary(_document.Resolve(dest)) + ? PdfDestination.Create(_document, dest, isRemote: false, Reference) + : null; + + /// Gets the action performed when the item is activated (A, PDF 1.1), or . + /// ISO 32000-2 §12.3.3, Table 151, and §12.6. + public PdfAction? Action + { + get + { + if (Dictionary.TryGetValue(NavigationNames.A, out CosObject? action)) + { + return PdfAction.Create(_document, action, Reference); + } + + return Dictionary.TryGetValue(NavigationNames.Dest, out CosObject? dest) && IsActionDictionary(_document.Resolve(dest)) + ? PdfAction.Create(_document, dest, Reference) + : null; + } + } + + /// Gets the structure element the item refers to (SE, PDF 1.3), or . Not meant for navigation. + /// ISO 32000-2 §12.3.3, Table 151, and §14.7.2. + public CosDictionary? StructureElement => + Dictionary.TryGetValue(NavigationNames.SE, out CosObject? element) ? _document.Resolve(element) as CosDictionary : null; + + /// Gets the colour of the item's text (C, PDF 1.4); black when absent or not three numbers, components clamped to 0 to 1. + /// ISO 32000-2 §12.3.3, Table 151: DeviceRGB, default [0.0 0.0 0.0]. + public PdfRgbColor Color => ReadColor(out _); + + /// Gets the style flags (F, PDF 1.4) as stored; 0 when absent or not an integer. + /// ISO 32000-2 §12.3.3, Tables 151 and 152. + public int Flags => ReadFlags(out _); + + /// Gets a value indicating whether the item's text is displayed in italic (flag bit 1). + /// ISO 32000-2 §12.3.3, Table 152. + public bool IsItalic => (Flags & 1) != 0; + + /// Gets a value indicating whether the item's text is displayed in bold (flag bit 2). + /// ISO 32000-2 §12.3.3, Table 152. + public bool IsBold => (Flags & 2) != 0; + + /// Gets the Count entry as stored, or when absent or not an integer. + /// + /// ISO 32000-2 §12.3.3, Table 151: positive when the item is open (the number of its visible descendants), negative when closed + /// (minus the number that would be visible if it were opened). Not corrected when wrong: the outline walk reports it. + /// + public int? Count => ReadCount(_document, Dictionary); + + /// Gets a value indicating whether the item is open: its children are shown. An item without a positive Count is closed. + /// ISO 32000-2 §12.3.3, Table 151. + public bool IsOpen => Count > 0; + + internal List ChildList => _children; + + /// Reads a Count entry: an integer in the 32-bit range, else . + internal static int? ReadCount(PdfDocument document, CosDictionary dictionary) => + dictionary.TryGetValue(KnownNames.Count, out CosObject? count) && document.Resolve(count) is CosInteger { Value: >= int.MinValue and <= int.MaxValue } integer + ? (int)integer.Value + : null; + + /// Reads C; is false when it is present but not three numbers from 0 to 1. + internal PdfRgbColor ReadColor(out bool valid) + { + valid = true; + if (!Dictionary.TryGetValue(NavigationNames.C, out CosObject? entry)) + { + return PdfRgbColor.Black; + } + + if (_document.Resolve(entry) is not CosArray { Count: 3 } components) + { + valid = false; + return PdfRgbColor.Black; + } + + Span values = stackalloc double[3]; + for (int index = 0; index < 3; index++) + { + if (_document.Resolve(components[index]) is not CosNumber number || !double.IsFinite(number.ToDouble())) + { + valid = false; + return PdfRgbColor.Black; + } + + values[index] = Math.Clamp(number.ToDouble(), 0, 1); + valid &= values[index] == number.ToDouble(); + } + + return new PdfRgbColor(values[0], values[1], values[2]); + } + + /// Reads F; is false when it is present but not an integer. + internal int ReadFlags(out bool valid) + { + valid = true; + if (!Dictionary.TryGetValue(NavigationNames.F, out CosObject? entry)) + { + return 0; + } + + if (_document.Resolve(entry) is CosInteger { Value: >= int.MinValue and <= int.MaxValue } flags) + { + return (int)flags.Value; + } + + valid = false; + return 0; + } + + /// Whether a Dest value is an action dictionary, a producer error read as A. + internal static bool IsActionDictionary(CosObject value) => value is CosDictionary dictionary && dictionary.ContainsKey(NavigationNames.S); +} diff --git a/src/Broadside/PdfPageCollection.cs b/src/Broadside/PdfPageCollection.cs index 18ea55a5..a50cd69a 100644 --- a/src/Broadside/PdfPageCollection.cs +++ b/src/Broadside/PdfPageCollection.cs @@ -1,4 +1,5 @@ using System.Collections; +using Broadside.Objects; namespace Broadside; @@ -11,9 +12,13 @@ namespace Broadside; public sealed class PdfPageCollection : IReadOnlyList { private readonly Lazy> _pages; + private readonly Lazy> _indexes; - internal PdfPageCollection(Func> walk) => + internal PdfPageCollection(Func> walk) + { _pages = new Lazy>(walk, LazyThreadSafetyMode.ExecutionAndPublication); + _indexes = new Lazy>(IndexPages, LazyThreadSafetyMode.ExecutionAndPublication); + } /// Gets the number of pages. public int Count => _pages.Value.Count; @@ -27,6 +32,24 @@ internal PdfPageCollection(Func> walk) => /// public IEnumerator GetEnumerator() => _pages.Value.GetEnumerator(); + /// Returns the index of the page whose page object is , or -1 when no page has it. + /// A page object, as resolved through the document (resolving returns the same instance every time). + /// The 0-based index, or -1. + /// For destinations (§12.3.2.2) and any other object that refers to a page. Built once, like the page list. + internal int IndexOf(CosDictionary page) => _indexes.Value.TryGetValue(page, out int index) ? index : -1; + /// IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + private Dictionary IndexPages() + { + IReadOnlyList pages = _pages.Value; + var indexes = new Dictionary(pages.Count, ReferenceEqualityComparer.Instance); + for (int index = 0; index < pages.Count; index++) + { + indexes.TryAdd(pages[index].Dictionary, index); + } + + return indexes; + } } diff --git a/src/Broadside/PdfRgbColor.cs b/src/Broadside/PdfRgbColor.cs new file mode 100644 index 00000000..0ee5fd0b --- /dev/null +++ b/src/Broadside/PdfRgbColor.cs @@ -0,0 +1,56 @@ +using System.Globalization; + +namespace Broadside; + +/// A colour in the DeviceRGB colour space, each component from 0.0 to 1.0, as interactive features such as outline items give it. +/// ISO 32000-2 §8.6.4.3 (DeviceRGB) and §12.3.3, Table 151 (C). +public readonly struct PdfRgbColor : IEquatable +{ + /// Initializes a new instance of the struct. + /// The red component, from 0.0 to 1.0. + /// The green component, from 0.0 to 1.0. + /// The blue component, from 0.0 to 1.0. + public PdfRgbColor(double red, double green, double blue) + { + Red = red; + Green = green; + Blue = blue; + } + + /// Gets black, [0 0 0]. + public static PdfRgbColor Black => default; + + /// Gets the red component. + public double Red { get; } + + /// Gets the green component. + public double Green { get; } + + /// Gets the blue component. + public double Blue { get; } + + /// Returns whether two colours have the same components. + /// The first colour. + /// The second colour. + /// when they are equal. + public static bool operator ==(PdfRgbColor left, PdfRgbColor right) => left.Equals(right); + + /// Returns whether two colours differ. + /// The first colour. + /// The second colour. + /// when they differ. + public static bool operator !=(PdfRgbColor left, PdfRgbColor right) => !left.Equals(right); + + /// + public bool Equals(PdfRgbColor other) => Red.Equals(other.Red) && Green.Equals(other.Green) && Blue.Equals(other.Blue); + + /// + public override bool Equals(object? obj) => obj is PdfRgbColor other && Equals(other); + + /// + public override int GetHashCode() => HashCode.Combine(Red, Green, Blue); + + /// Returns the colour as a PDF array would write it, such as [1 0 0]. + /// The colour text. + public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"[{Red} {Green} {Blue}]"); +} diff --git a/src/Broadside/PdfUnknownAction.cs b/src/Broadside/PdfUnknownAction.cs new file mode 100644 index 00000000..17550074 --- /dev/null +++ b/src/Broadside/PdfUnknownAction.cs @@ -0,0 +1,16 @@ +using Broadside.Objects; + +namespace Broadside; + +/// An action of a type this version does not model yet (any Table 201 type but GoTo and URI, or a type the table does not list). +/// +/// ISO 32000-2 §12.6.4.1, Table 201. Kept as it is (parse-and-preserve) and reachable through ; +/// says which type it is. +/// +public sealed class PdfUnknownAction : PdfAction +{ + internal PdfUnknownAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } +} diff --git a/src/Broadside/PdfUriAction.cs b/src/Broadside/PdfUriAction.cs new file mode 100644 index 00000000..a3ff0184 --- /dev/null +++ b/src/Broadside/PdfUriAction.cs @@ -0,0 +1,38 @@ +using System.Diagnostics.CodeAnalysis; +using System.Text; +using Broadside.Objects; + +namespace Broadside; + +/// A URI action: resolves a uniform resource identifier, typically a hypertext link. +/// +/// ISO 32000-2 §12.6.4.8, Table 210 (PDF 1.1). The URI is untrusted data from the file: the library never resolves it. A relative URI +/// is relative to the catalog's URI dictionary's Base (Table 211), which this view does not apply. +/// +public sealed class PdfUriAction : PdfAction +{ + internal PdfUriAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// Gets the URI, the URI string decoded as UTF-8, or when it is absent or not a string. + /// ISO 32000-2 §12.6.4.8, Table 210: an ASCII string "encoded in UTF-8". + [SuppressMessage("Design", "CA1056:URI-like properties should not be strings", Justification = "The file may hold a relative or malformed URI (relative to the catalog URI Base); the text is returned as stored.")] + public string? Uri => Dictionary.TryGetValue(NavigationNames.Uri, out CosObject? uri) && Document.Resolve(uri) is CosString text + ? Encoding.UTF8.GetString(text.Bytes) + : null; + + /// Gets a value indicating whether the mouse position is appended to the URI when a link is clicked. Default . + /// ISO 32000-2 §12.6.4.8, Table 210; ignored for outline items and the document's open action. + public bool IsMap => Dictionary.TryGetValue(NavigationNames.IsMap, out CosObject? isMap) && Document.Resolve(isMap) is CosBoolean { Value: true }; + + /// + private protected override void Check() + { + if (Uri is null) + { + Report("A URI action shall have a URI string; it has none, so it goes nowhere."); + } + } +} diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index feb3fcc7..2c43a0d8 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -426,3 +426,92 @@ Broadside.PdfNumberTree.Root.get -> Broadside.Objects.CosDictionary! Broadside.PdfNumberTree.RootReference.get -> Broadside.Objects.CosReference? Broadside.PdfNumberTree.TryGetFloor(int key, out int floorKey, out Broadside.Objects.CosObject! value) -> bool Broadside.PdfNumberTree.TryGetValue(int key, out Broadside.Objects.CosObject! value) -> bool +Broadside.PdfAction +Broadside.PdfAction.ActionType.get -> Broadside.Objects.CosName! +Broadside.PdfAction.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfAction.Reference.get -> Broadside.Objects.CosReference? +Broadside.PdfDestination +Broadside.PdfDestination.IsRemote.get -> bool +Broadside.PdfDestination.Value.get -> Broadside.Objects.CosObject! +Broadside.PdfDestinationTarget +Broadside.PdfDestinationTarget.None = 0 -> Broadside.PdfDestinationTarget +Broadside.PdfDestinationTarget.Page = 1 -> Broadside.PdfDestinationTarget +Broadside.PdfDestinationTarget.PageNumber = 2 -> Broadside.PdfDestinationTarget +Broadside.PdfDestinationTarget.StructureElement = 3 -> Broadside.PdfDestinationTarget +Broadside.PdfDestinationTarget.StructureElementId = 4 -> Broadside.PdfDestinationTarget +Broadside.PdfDestinationView +Broadside.PdfDestinationView.Fit = 2 -> Broadside.PdfDestinationView +Broadside.PdfDestinationView.FitB = 6 -> Broadside.PdfDestinationView +Broadside.PdfDestinationView.FitBH = 7 -> Broadside.PdfDestinationView +Broadside.PdfDestinationView.FitBV = 8 -> Broadside.PdfDestinationView +Broadside.PdfDestinationView.FitH = 3 -> Broadside.PdfDestinationView +Broadside.PdfDestinationView.FitR = 5 -> Broadside.PdfDestinationView +Broadside.PdfDestinationView.FitV = 4 -> Broadside.PdfDestinationView +Broadside.PdfDestinationView.Unknown = 0 -> Broadside.PdfDestinationView +Broadside.PdfDestinationView.Xyz = 1 -> Broadside.PdfDestinationView +Broadside.PdfDocument.GetNamedDestination(Broadside.Objects.CosName! name) -> Broadside.PdfExplicitDestination? +Broadside.PdfDocument.GetNamedDestination(Broadside.Objects.CosString! name) -> Broadside.PdfExplicitDestination? +Broadside.PdfDocument.GetNamedDestination(string! name) -> Broadside.PdfExplicitDestination? +Broadside.PdfDocument.Outline.get -> Broadside.PdfOutline? +Broadside.PdfExplicitDestination +Broadside.PdfExplicitDestination.Array.get -> Broadside.Objects.CosArray! +Broadside.PdfExplicitDestination.Bottom.get -> double? +Broadside.PdfExplicitDestination.IsValid.get -> bool +Broadside.PdfExplicitDestination.Left.get -> double? +Broadside.PdfExplicitDestination.Page.get -> Broadside.PdfPage? +Broadside.PdfExplicitDestination.PageIndex.get -> int? +Broadside.PdfExplicitDestination.PageNumber.get -> int? +Broadside.PdfExplicitDestination.Right.get -> double? +Broadside.PdfExplicitDestination.StructureElement.get -> Broadside.Objects.CosDictionary? +Broadside.PdfExplicitDestination.StructureElementId.get -> Broadside.Objects.CosString? +Broadside.PdfExplicitDestination.Target.get -> Broadside.Objects.CosObject! +Broadside.PdfExplicitDestination.TargetKind.get -> Broadside.PdfDestinationTarget +Broadside.PdfExplicitDestination.Top.get -> double? +Broadside.PdfExplicitDestination.View.get -> Broadside.PdfDestinationView +Broadside.PdfExplicitDestination.ViewName.get -> Broadside.Objects.CosName? +Broadside.PdfExplicitDestination.Zoom.get -> double? +Broadside.PdfGoToAction +Broadside.PdfGoToAction.Destination.get -> Broadside.PdfDestination? +Broadside.PdfGoToAction.StructureDestination.get -> Broadside.PdfExplicitDestination? +Broadside.PdfNamedDestination +Broadside.PdfNamedDestination.Name.get -> Broadside.Objects.CosObject! +Broadside.PdfNamedDestination.Resolve() -> Broadside.PdfExplicitDestination? +Broadside.PdfNamedDestination.Text.get -> string! +Broadside.PdfOutline +Broadside.PdfOutline.Count.get -> int? +Broadside.PdfOutline.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfOutline.Items.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfOutline.Reference.get -> Broadside.Objects.CosReference? +Broadside.PdfOutlineItem +Broadside.PdfOutlineItem.Action.get -> Broadside.PdfAction? +Broadside.PdfOutlineItem.Children.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfOutlineItem.Color.get -> Broadside.PdfRgbColor +Broadside.PdfOutlineItem.Count.get -> int? +Broadside.PdfOutlineItem.Destination.get -> Broadside.PdfDestination? +Broadside.PdfOutlineItem.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfOutlineItem.Flags.get -> int +Broadside.PdfOutlineItem.IsBold.get -> bool +Broadside.PdfOutlineItem.IsItalic.get -> bool +Broadside.PdfOutlineItem.IsOpen.get -> bool +Broadside.PdfOutlineItem.Level.get -> int +Broadside.PdfOutlineItem.Parent.get -> Broadside.PdfOutlineItem? +Broadside.PdfOutlineItem.Reference.get -> Broadside.Objects.CosReference? +Broadside.PdfOutlineItem.StructureElement.get -> Broadside.Objects.CosDictionary? +Broadside.PdfOutlineItem.Title.get -> string! +Broadside.PdfRgbColor +Broadside.PdfRgbColor.Blue.get -> double +Broadside.PdfRgbColor.Equals(Broadside.PdfRgbColor other) -> bool +Broadside.PdfRgbColor.Green.get -> double +Broadside.PdfRgbColor.PdfRgbColor() -> void +Broadside.PdfRgbColor.PdfRgbColor(double red, double green, double blue) -> void +Broadside.PdfRgbColor.Red.get -> double +Broadside.PdfUnknownAction +Broadside.PdfUriAction +Broadside.PdfUriAction.IsMap.get -> bool +Broadside.PdfUriAction.Uri.get -> string? +override Broadside.PdfRgbColor.Equals(object? obj) -> bool +override Broadside.PdfRgbColor.GetHashCode() -> int +override Broadside.PdfRgbColor.ToString() -> string! +static Broadside.PdfRgbColor.Black.get -> Broadside.PdfRgbColor +static Broadside.PdfRgbColor.operator !=(Broadside.PdfRgbColor left, Broadside.PdfRgbColor right) -> bool +static Broadside.PdfRgbColor.operator ==(Broadside.PdfRgbColor left, Broadside.PdfRgbColor right) -> bool diff --git a/src/Broadside/TreeReader.cs b/src/Broadside/TreeReader.cs index 83ef9976..b2bd492b 100644 --- a/src/Broadside/TreeReader.cs +++ b/src/Broadside/TreeReader.cs @@ -23,7 +23,8 @@ namespace Broadside; /// /// The walk visits nodes in tree order (a root's own pairs, then its kids, depth first), with one visited set for the whole walk /// and a depth cap, iteratively, so a cycle or a very deep chain ends. It reports each deviation once per node. A key seen -/// earlier in the walk is a duplicate and is skipped, so the first occurrence in tree order is the one every API returns. +/// earlier in the walk is a duplicate and is skipped, so the first occurrence in tree order is the one every API returns; the first +/// deviation a walk meets switches every later lookup to the index, so lookups agree with enumeration from then on. /// /// /// Values are returned resolved one level: a value that is an indirect reference comes back as the object it refers to. @@ -90,9 +91,24 @@ private protected TreeReader(CosDictionary root, CosReference? rootReference, Fu /// when the tree holds the key. public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out CosObject value) { - if (!_limitsUntrusted && _index is null && TryDescend(key, out CosObject? found)) + if (TryGetRawValue(key, out CosObject? raw)) + { + value = Resolve(raw); + return true; + } + + value = null; + return false; + } + + /// Looks up and returns its value as stored: an indirect reference stays a reference. + /// The key. + /// The value as stored in the Names or Nums array, when found. + /// when the tree holds the key. + public bool TryGetRawValue(TKey key, [MaybeNullWhen(false)] out CosObject value) + { + if (!_limitsUntrusted && _index is null && TryDescend(key, out value)) { - value = Resolve(found); return true; } @@ -104,7 +120,7 @@ public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out CosObject value) return false; } - value = Resolve(index.Values[position]); + value = index.Values[position]; return true; } @@ -144,6 +160,10 @@ public bool TryGetFloor(TKey key, [MaybeNullWhen(false)] out TKey floorKey, [May } } + /// As , with each value as stored: an indirect reference stays a reference. + /// The pairs, in tree order. + public IEnumerable<(TKey Key, CosObject Value)> EnumerateRaw() => Walk(stamps: null); + /// Reads a key from the Names or Nums array. /// The array element, resolved. /// The key. @@ -286,7 +306,7 @@ private bool TryReadLimits(CosDictionary node, [MaybeNullWhen(false)] out TKey l { least = default; greatest = default; - return node.TryGetValue(KnownNames.Limits, out CosObject? entry) + return node.TryGetValue(NavigationNames.Limits, out CosObject? entry) && Resolve(entry) is CosArray { Count: 2 } limits && ReadKey(Resolve(limits[0]), out least, out _) == KeyState.Valid && ReadKey(Resolve(limits[1]), out greatest, out _) == KeyState.Valid @@ -304,7 +324,6 @@ private bool TryReadLimits(CosDictionary node, [MaybeNullWhen(false)] out TKey l var seen = new HashSet(KeyEquality); bool hasPrevious = false; TKey previous = default!; - bool anomalies = false; if (RootReference is not null) { @@ -318,12 +337,12 @@ private bool TryReadLimits(CosDictionary node, [MaybeNullWhen(false)] out TKey l { CosDictionary node = frame.Node; stamps?.Add((node, node.Version)); - Bounds? bounds = CheckLimits(frame, ref anomalies); + Bounds? bounds = CheckLimits(frame); bool hasEntries = node.TryGetValue(EntriesKey, out CosObject? entriesEntry); bool hasKids = node.TryGetValue(KnownNames.Kids, out CosObject? kidsEntry); if (hasEntries == hasKids) { - anomalies = true; + _limitsUntrusted = true; Report( Codes.NodeInvalid, DiagnosticSeverity.Warning, @@ -337,7 +356,7 @@ private bool TryReadLimits(CosDictionary node, [MaybeNullWhen(false)] out TKey l { if (Resolve(entriesEntry) is not CosArray entries) { - anomalies = true; + _limitsUntrusted = true; Report(Codes.NodeInvalid, DiagnosticSeverity.Warning, $"A {Kind} node's {EntriesKey.Value} is not an array; it holds no keys.", frame.Reference); } else @@ -345,7 +364,7 @@ private bool TryReadLimits(CosDictionary node, [MaybeNullWhen(false)] out TKey l stamps?.Add((entries, entries.Version)); if (entries.Count % 2 != 0) { - anomalies = true; + _limitsUntrusted = true; Report( Codes.NodeInvalid, DiagnosticSeverity.Warning, @@ -358,7 +377,7 @@ private bool TryReadLimits(CosDictionary node, [MaybeNullWhen(false)] out TKey l KeyState state = ReadKey(Resolve(entries[index]), out TKey? key, out string? message); if (state != KeyState.Valid) { - anomalies = true; + _limitsUntrusted = true; Report(Codes.KeyInvalid, DiagnosticSeverity.Warning, message!, frame.Reference); if (state == KeyState.Invalid) { @@ -368,12 +387,12 @@ private bool TryReadLimits(CosDictionary node, [MaybeNullWhen(false)] out TKey l if (!IsWithin(key!, frame.Ancestors, bounds, frame.Reference)) { - anomalies = true; + _limitsUntrusted = true; } if (!seen.Add(key!)) { - anomalies = true; + _limitsUntrusted = true; Report( Codes.DuplicateKey, DiagnosticSeverity.Warning, @@ -384,7 +403,7 @@ private bool TryReadLimits(CosDictionary node, [MaybeNullWhen(false)] out TKey l if (hasPrevious && KeyComparer.Compare(key!, previous) < 0) { - anomalies = true; + _limitsUntrusted = true; Report( Codes.KeysUnsorted, DiagnosticSeverity.Warning, @@ -401,17 +420,12 @@ private bool TryReadLimits(CosDictionary node, [MaybeNullWhen(false)] out TKey l if (hasKids) { - foreach (Frame kid in ReadKids(frame, kidsEntry, bounds, visitedReferences, visitedNodes, stamps, ref anomalies)) + foreach (Frame kid in ReadKids(frame, kidsEntry, bounds, visitedReferences, visitedNodes, stamps)) { stack.Push(kid); } } } - - if (anomalies) - { - _limitsUntrusted = true; - } } /// Reads a node's kids for the walk; returns them in reverse order, ready to push. @@ -421,13 +435,12 @@ private List ReadKids( Bounds? bounds, HashSet visitedReferences, HashSet visitedNodes, - List<(CosObject Container, int Version)>? stamps, - ref bool anomalies) + List<(CosObject Container, int Version)>? stamps) { var kids = new List(); if (Resolve(kidsEntry) is not CosArray array) { - anomalies = true; + _limitsUntrusted = true; Report(Codes.NodeInvalid, DiagnosticSeverity.Warning, $"A {Kind} node's Kids is not an array; it has no kids.", frame.Reference); return kids; } @@ -435,7 +448,7 @@ private List ReadKids( stamps?.Add((array, array.Version)); if (frame.Depth >= MaxDepth) { - anomalies = true; + _limitsUntrusted = true; Report( Codes.TooDeep, DiagnosticSeverity.Error, @@ -450,20 +463,20 @@ private List ReadKids( var reference = kid as CosReference; if (Resolve(kid) is not CosDictionary child) { - anomalies = true; + _limitsUntrusted = true; Report(Codes.NodeInvalid, DiagnosticSeverity.Warning, $"A {Kind} Kids entry is not a node dictionary; it is skipped.", reference ?? frame.Reference); continue; } if (reference is null) { - anomalies = true; + _limitsUntrusted = true; Report(Codes.NodeInvalid, DiagnosticSeverity.Warning, $"A {Kind} Kids entry shall be an indirect reference; it is a direct dictionary, used as is.", frame.Reference); } if ((reference is not null && !visitedReferences.Add(reference)) || !visitedNodes.Add(child)) { - anomalies = true; + _limitsUntrusted = true; Report( Codes.Cycle, DiagnosticSeverity.Error, @@ -480,14 +493,14 @@ private List ReadKids( } /// Checks a node's Limits entry; returns the bounds when they are usable. - private Bounds? CheckLimits(Frame frame, ref bool anomalies) + private Bounds? CheckLimits(Frame frame) { - bool present = frame.Node.TryGetValue(KnownNames.Limits, out CosObject? entry); + bool present = frame.Node.TryGetValue(NavigationNames.Limits, out CosObject? entry); if (frame.IsRoot) { if (present) { - anomalies = true; + _limitsUntrusted = true; Report(Codes.LimitsInvalid, DiagnosticSeverity.Warning, $"The root of a {Kind} shall not have Limits; they are ignored.", frame.Reference); } @@ -503,7 +516,7 @@ private List ReadKids( return new Bounds(least, greatest); } - anomalies = true; + _limitsUntrusted = true; Report( Codes.LimitsInvalid, DiagnosticSeverity.Warning, diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 4a3ab467..7ddbb3bf 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -44,7 +44,7 @@ internal static class FuzzTargets /// /// Opens the input as a whole file in lenient mode and reads everything the document model exposes: version, trailer, every - /// page's boxes, rotation, user unit and resources, the revisions, and the linearization dictionary and hint tables. A is the one documented outcome for a file + /// page's boxes, rotation, user unit and resources, the revisions, the linearization dictionary and hint tables, the outline and the named destinations. A is the one documented outcome for a file /// whose cross-reference information cannot be read at all (until issue #41 reconstructs it); any other exception is a finding. /// Every box must be normalized and every rotation one of 0, 90, 180, 270; every revision must be a non-empty prefix of the input /// at its own index. @@ -97,6 +97,65 @@ private static void Document(ReadOnlySpan data) _ = document.DecodeStream(stream); } } + + Navigation(document); + } + + /// + /// Walks the outline and the named destinations (issue #70) and checks what the walk promises: every item below the 256-level cap, + /// each item reached once, every resolved page index inside the page list, every name-tree key enumerated once. + /// + /// ISO 32000-2 §7.9.6, §12.3.2, §12.3.3. + private static void Navigation(PdfDocument document) + { + var seen = new HashSet(ReferenceEqualityComparer.Instance); + var pending = new Stack(document.Outline?.Items ?? []); + while (pending.TryPop(out PdfOutlineItem? item)) + { + if (!seen.Add(item.Dictionary) || item.Level >= 256) + { + throw new InvalidOperationException($"Outline item at level {item.Level} is repeated or below the depth cap."); + } + + _ = (item.Title, item.Color, item.Flags, item.Count, item.StructureElement); + CheckDestination(document, item.Destination); + if (item.Action is PdfGoToAction goTo) + { + CheckDestination(document, goTo.Destination); + } + + foreach (PdfOutlineItem child in item.Children) + { + pending.Push(child); + } + } + + if (document.Names?.Dests is { } tree) + { + // After a complete walk, lookups agree with enumeration even in a damaged tree (the walk's first deviation switches + // lookups to the index); before it, a lookup follows the Limits it finds. + var keys = new HashSet(); + foreach (KeyValuePair entry in tree.ToList()) + { + if (!keys.Add(entry.Key) || !tree.TryGetValue(entry.Key, out CosObject? value) || !ReferenceEquals(value, entry.Value)) + { + throw new InvalidOperationException("A name tree key is enumerated twice or looks up to another value."); + } + + CheckDestination(document, document.GetNamedDestination(entry.Key)); + } + } + } + + private static void CheckDestination(PdfDocument document, PdfDestination? destination) + { + PdfExplicitDestination? resolved = destination is PdfNamedDestination named ? named.Resolve() : destination as PdfExplicitDestination; + if (resolved?.PageIndex is { } index && (index < 0 || index >= document.Pages.Count)) + { + throw new InvalidOperationException($"Destination page index {index} is outside the {document.Pages.Count} pages."); + } + + _ = (resolved?.View, resolved?.Left, resolved?.Top, resolved?.Right, resolved?.Bottom, resolved?.Zoom, resolved?.IsValid, resolved?.TargetKind); } /// diff --git a/tests/Broadside.TestSupport/Corpus.cs b/tests/Broadside.TestSupport/Corpus.cs index d0ce8d5f..1cb4156c 100644 --- a/tests/Broadside.TestSupport/Corpus.cs +++ b/tests/Broadside.TestSupport/Corpus.cs @@ -42,6 +42,8 @@ public static class Corpus "metadata-xmp.pdf", "name-tree-deep.pdf", "number-tree-deep.pdf", + "destinations-all.pdf", + "outline-full.pdf", ]; private static readonly string[] Malformed = @@ -55,6 +57,7 @@ public static class Corpus "encrypted-owner-key-variant.pdf", "encrypted-rc4-length-missing.pdf", "name-tree-broken.pdf", + "outline-broken.pdf", ]; private static readonly (string FileName, string UserPassword)[] PasswordProtected = diff --git a/tests/Broadside.TestSupport/DocumentWalker.cs b/tests/Broadside.TestSupport/DocumentWalker.cs index 572aabdc..c194fa0f 100644 --- a/tests/Broadside.TestSupport/DocumentWalker.cs +++ b/tests/Broadside.TestSupport/DocumentWalker.cs @@ -13,7 +13,7 @@ public sealed record DocumentWalkResult(int Pages, int Objects, int Streams, lon /// /// Reads everything the document model exposes, so that "the file opens" means more than "the trailer parsed" (objects load /// lazily, issue #45): version, trailer, revisions, linearization and hint tables, security, every page's boxes, rotation, user unit -/// and resources, every indirect object reachable from the trailer and every object number below the trailer's Size, and +/// and resources, the outline and every named destination (issue #70), every indirect object reachable from the trailer and every object number below the trailer's Size, and /// every stream decoded through the filter pipeline (image filters that are not implemented yet end in a diagnostic, not an /// exception). Used by the real-world corpus gate (issue #47) and meant to be shared with the open-and-walk fuzz target and /// benchmark (issue #48): link this file as source there, as is. Public API only. @@ -26,6 +26,8 @@ public static class DocumentWalker private static readonly CosName SizeKey = new("Size"); + private static readonly CosName DestsKey = new("Dests"); + /// Walks . Every exception the library throws propagates to the caller. /// An open document. /// What was read. @@ -56,6 +58,8 @@ public static DocumentWalkResult Walk(PdfDocument document) _ = (page.MediaBox, page.CropBox, page.BleedBox, page.TrimBox, page.ArtBox, page.Rotation, page.UserUnit, page.Resources?.Count); } + WalkNavigation(document); + var walk = new GraphWalk(document); walk.Visit(document.Trailer); long size = document.Trailer.TryGetValue(SizeKey, out CosObject? entry) && entry is CosInteger integer ? integer.Value : 0; @@ -67,6 +71,65 @@ public static DocumentWalkResult Walk(PdfDocument document) return new DocumentWalkResult(pages, walk.Objects, walk.Streams, walk.DecodedBytes); } + /// + /// Reads the outline (every item's title, style, destination and action, named destinations resolved) and every named + /// destination of the name dictionary's Dests tree and the catalog's Dests dictionary (ISO 32000-2 §12.3). + /// + private static void WalkNavigation(PdfDocument document) + { + var pending = new Stack(document.Outline?.Items ?? []); + while (pending.TryPop(out PdfOutlineItem? item)) + { + _ = (item.Title, item.Color, item.IsBold, item.IsOpen, item.StructureElement); + WalkDestination(item.Destination); + if (item.Action is PdfGoToAction goTo) + { + WalkDestination(goTo.Destination); + WalkDestination(goTo.StructureDestination); + } + else if (item.Action is PdfUriAction uri) + { + _ = (uri.Uri, uri.IsMap); + } + + foreach (PdfOutlineItem child in item.Children) + { + pending.Push(child); + } + } + + if (document.Names?.Dests is { } tree) + { + foreach (KeyValuePair entry in tree) + { + WalkDestination(document.GetNamedDestination(entry.Key)); + } + } + + if (document.Resolve(document.Catalog.TryGetValue(DestsKey, out CosObject? dests) ? dests : null) is CosDictionary legacy) + { + foreach (CosName name in legacy.Keys) + { + WalkDestination(document.GetNamedDestination(name)); + } + } + } + + private static void WalkDestination(PdfDestination? destination) + { + PdfExplicitDestination? explicitDestination = destination switch + { + PdfNamedDestination named => named.Resolve(), + PdfExplicitDestination value => value, + _ => null, + }; + if (explicitDestination is not null) + { + _ = (explicitDestination.PageIndex, explicitDestination.TargetKind, explicitDestination.View, explicitDestination.Left, + explicitDestination.Top, explicitDestination.Right, explicitDestination.Bottom, explicitDestination.Zoom, explicitDestination.IsValid); + } + } + /// An iterative depth-first walk (no recursion: real files nest deeply) over references, containers and streams. private sealed class GraphWalk(PdfDocument document) { diff --git a/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt b/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt index e91fe552..9fb35a2e 100644 --- a/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt +++ b/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt @@ -1,6 +1,6 @@ pdfjs: 989 files - Clean: 689 - Diagnostics: 286 + Clean: 678 + Diagnostics: 297 PasswordRequired: 12 CertificateRequired: 0 EncryptionUnsupported: 0 @@ -16,6 +16,7 @@ StartxrefInvalid: 21 MissingEndobj: 12 PageResourcesMissing: 11 + NameTreeLimitsInvalid: 8 TrailerPrevInvalid: 8 UnexpectedToken: 8 XrefEntryFormatInvalid: 8 @@ -28,6 +29,7 @@ CatalogTypeInvalid: 4 DictionaryDuplicateKey: 4 PageMediaBoxMissing: 4 + DestinationInvalid: 3 DictionaryUnterminated: 3 PageTreeNodeTypeInvalid: 3 PagesMissing: 3 @@ -53,6 +55,8 @@ NumberMalformed: 1 ObjectStreamIndexMismatch: 1 ObjectStreamInvalid: 1 + OutlineCountInvalid: 1 + OutlineLinkInconsistent: 1 PageResourcesInvalid: 1 PageTreeCycle: 1 PageTreeKidInvalid: 1 @@ -90,8 +94,8 @@ pdfbox: 137 files StartxrefInvalid: 1 StreamLengthInvalid: 1 qpdf: 639 files - Clean: 450 - Diagnostics: 152 + Clean: 441 + Diagnostics: 161 PasswordRequired: 23 CertificateRequired: 0 EncryptionUnsupported: 1 @@ -109,6 +113,7 @@ qpdf: 639 files DictionaryKeyNotName: 10 RootMissing: 10 StreamLengthInvalid: 10 + DestinationInvalid: 8 CatalogTypeInvalid: 7 ObjectStreamIndexMismatch: 7 XrefEntryInvalid: 7 @@ -151,6 +156,9 @@ qpdf: 639 files ObjectStreamHeaderInvalid: 1 ObjectStreamInvalid: 1 ObjectStreamTypeInvalid: 1 + OutlineCycle: 1 + OutlineInvalid: 1 + OutlineLinkInconsistent: 1 PageBoxInvalid: 1 PageTreeKidInvalid: 1 PageTreeKidNotIndirect: 1 @@ -163,8 +171,8 @@ qpdf: 639 files XrefStreamWidthsInvalid: 1 XrefSubsectionHeaderInvalid: 1 pdfium-tests: 840 files - Clean: 384 - Diagnostics: 449 + Clean: 347 + Diagnostics: 486 PasswordRequired: 2 CertificateRequired: 4 EncryptionUnsupported: 0 @@ -182,8 +190,11 @@ pdfium-tests: 840 files HeaderInvalid: 29 FilterDataInvalid: 28 DecodeParmsInvalid: 24 + OutlineLinkInconsistent: 22 XrefEntryOffsetInvalid: 21 MissingEndobj: 12 + OutlineCountInvalid: 12 + OutlineItemInvalid: 12 UnexpectedToken: 10 CatalogTypeInvalid: 5 DictionaryDuplicateKey: 5 @@ -191,17 +202,21 @@ pdfium-tests: 840 files PageResourcesMissing: 5 PageTreeNodeTypeInvalid: 5 PageTreeParentMismatch: 5 + DestinationInvalid: 4 DictionaryUnterminated: 4 StartxrefMissing: 4 XrefEntryFormatInvalid: 4 DictionaryKeyNotName: 3 MetadataNotEncrypted: 3 + NameTreeLimitsInvalid: 3 StringUnterminated: 3 ArrayUnterminated: 2 EncryptionRevisionInvalid: 2 EndOfFileMarkerNotLast: 2 + NamedDestinationNotFound: 2 TrailerMissing: 2 XrefSubsectionHeaderInvalid: 2 + ActionInvalid: 1 DictionaryValueMissing: 1 EncryptDictionaryInvalid: 1 EndOfFileMarkerMissing: 1 @@ -209,6 +224,8 @@ pdfium-tests: 840 files HeaderMissing: 1 HexStringInvalidDigit: 1 LinearizationHintsInvalid: 1 + NameTreeKeysUnsorted: 1 + OutlineDestAndAction: 1 PageTreeCountMismatch: 1 PageTreeKidInvalid: 1 PageTreeKidNotIndirect: 1 diff --git a/tests/Broadside.Tests/Navigation/DestinationTests.cs b/tests/Broadside.Tests/Navigation/DestinationTests.cs new file mode 100644 index 00000000..2e21c8e8 --- /dev/null +++ b/tests/Broadside.Tests/Navigation/DestinationTests.cs @@ -0,0 +1,194 @@ +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Tests.Document; +using Broadside.TestSupport; + +namespace Broadside.Tests.Navigation; + +/// +/// Explicit and named destinations (ISO 32000-2 §12.3.2.2, Table 149, and §12.3.2.4) read through +/// and outline items. +/// +public class DestinationTests +{ + /// Key in destinations-all.pdf, then "View left bottom right top zoom" with "-" for null. + public static TheoryData EveryForm => new() + { + { "alpha", "Xyz 0 - - 792 -" }, + { "fit", "Fit - - - - -" }, + { "fitb", "FitB - - - - -" }, + { "fitbh", "FitBH - - - 700 -" }, + { "fitbv", "FitBV 36 - - - -" }, + { "fith", "FitH - - - 650 -" }, + { "fith-null", "FitH - - - - -" }, + { "fitr", "FitR 10 20 300 400.5 -" }, + { "fitv", "FitV 50 - - - -" }, + { "indirect", "FitH - - - 500 -" }, + { "with-d", "Fit - - - - -" }, + { "xyz", "Xyz 72 - - 720 1.5" }, + { "xyz-null", "Xyz - - - - -" }, + { "xyz-zero", "Xyz 10 - - 20 -" }, + }; + + [Fact] + public void Name_tree_dests_pdf_resolves_its_three_named_destinations_to_the_first_page() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("name-tree-dests.pdf")); + + PdfExplicitDestination alpha = Assert.IsType(document.GetNamedDestination("alpha")); + PdfExplicitDestination beta = Assert.IsType(document.GetNamedDestination(new CosString("beta"u8))); + PdfExplicitDestination gamma = Assert.IsType(document.GetNamedDestination("gamma")); + + Assert.Equal("Fit - - - - -", Describe(alpha)); + Assert.Equal("Xyz 0 - - 792 -", Describe(beta)); // zoom 0 keeps the current zoom, like null + Assert.Equal("FitH - - - 792 -", Describe(gamma)); + Assert.All([alpha, beta, gamma], destination => + { + Assert.Equal(0, destination.PageIndex); + Assert.Same(document.Pages[0], destination.Page); + Assert.Equal(PdfDestinationTarget.Page, destination.TargetKind); + Assert.True(destination.IsValid); + Assert.False(destination.IsRemote); + }); + Assert.Null(document.GetNamedDestination("delta")); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [MemberData(nameof(EveryForm))] + public void Every_explicit_form_of_table_149_is_typed_with_null_meaning_unchanged(string name, string expected) + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("destinations-all.pdf")); + + PdfExplicitDestination destination = Assert.IsType(document.GetNamedDestination(name)); + + Assert.Equal(expected, Describe(destination)); + Assert.True(destination.IsValid); + Assert.Equal(0, destination.PageIndex); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_pdf_1_1_name_resolves_through_the_catalog_dests_dictionary() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("destinations-all.pdf")); + + Assert.Equal("FitV 72 - - - -", Describe(document.GetNamedDestination(new CosName("Chap6"))!)); + Assert.Equal("FitV 72 - - - -", Describe(document.GetNamedDestination("Chap6")!)); + Assert.Null(document.GetNamedDestination(new CosName("Chap7"))); + + // A string resolves through the tree first, a name through the catalog dictionary first; each falls back to the other. + Assert.Equal("Xyz 0 - - 792 -", Describe(document.GetNamedDestination(new CosName("alpha"))!)); + Assert.Equal("FitV 72 - - - -", Describe(document.GetNamedDestination(new CosString("Chap6"u8))!)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Outline_items_refer_to_destinations_by_name_and_by_string() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("destinations-all.pdf")); + + IReadOnlyList items = document.Outline!.Items; + + PdfNamedDestination byName = Assert.IsType(items[0].Destination); + Assert.Equal(new CosName("Chap6"), byName.Name); + Assert.Equal("Chap6", byName.Text); + Assert.Equal("FitV 72 - - - -", Describe(byName.Resolve()!)); + PdfNamedDestination byString = Assert.IsType(items[1].Destination); + Assert.Equal(new CosString("alpha"u8), byString.Name); + Assert.Equal("Xyz 0 - - 792 -", Describe(byString.Resolve()!)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Malformed_destinations_are_read_leniently_each_with_a_diagnostic() + { + using PdfDocument document = PdfDocument.Open(MalformedDestinations()); + + Assert.Equal("Xyz 10 - - - -", Describe(Named(document, "missing"))); + Assert.Equal("FitH - - - 1 -", Describe(Named(document, "extra"))); + PdfExplicitDestination fitR = Named(document, "fitr"); + Assert.False(fitR.IsValid); + PdfExplicitDestination number = Named(document, "int"); + Assert.Equal(PdfDestinationTarget.PageNumber, number.TargetKind); + Assert.Equal(0, number.PageIndex); + PdfExplicitDestination notInTree = Named(document, "nopage"); + Assert.Equal(PdfDestinationTarget.Page, notInTree.TargetKind); + Assert.Null(notInTree.PageIndex); + Assert.Equal("Xyz - - - 1 1", Describe(Named(document, "text"))); + PdfExplicitDestination unknown = Named(document, "unknown"); + Assert.Equal(PdfDestinationView.Unknown, unknown.View); + Assert.Equal(new CosName("FitW"), unknown.ViewName); + Assert.False(unknown.IsValid); + Assert.Equal(0, unknown.PageIndex); + Assert.Null(document.GetNamedDestination("chained")); + + Assert.Equal( + [ + "DestinationInvalid 5", // [3 0 R /XYZ 10]: top and zoom missing + "DestinationInvalid 6", // [3 0 R /FitH 1 2]: one parameter too many + "DestinationInvalid 7", // [3 0 R /FitR 1 2 3]: a FitR needs four coordinates + "DestinationInvalid 8", // [0 /Fit]: a page number in a local destination + "DestinationPageNotFound 9", // [12 0 R /Fit]: a page object outside the page tree + "DestinationInvalid 10", // [3 0 R /XYZ (a) 1 1]: a parameter that is not a number + "DestinationInvalid 11", // [3 0 R /FitW 5]: not a view of Table 149 + "DestinationInvalid -", // (chained) (fit): a value that is a string + ], + document.Diagnostics.Select(Describe)); + } + + [Fact] + public void Strict_mode_throws_when_a_malformed_destination_is_read_not_at_open() + { + using PdfDocument document = PdfDocument.Open(MalformedDestinations(), new PdfOptions().UseStrict()); + + DiagnosticException error = Assert.Throws(() => document.GetNamedDestination("missing")); + + Assert.Equal("DestinationInvalid 5", Describe(error.Diagnostic)); + } + + [Fact] + public void Reading_destinations_writes_nothing() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("destinations-all.pdf")); + + foreach (string name in (string[])["alpha", "fit", "fitb", "fitbh", "fitbv", "fith", "fith-null", "fitr", "fitv", "indirect", "with-d", "xyz", "xyz-null", "xyz-zero"]) + { + PdfExplicitDestination destination = document.GetNamedDestination(name)!; + _ = (destination.Page, destination.Zoom, destination.Left, destination.Top, destination.Right, destination.Bottom, destination.View); + } + + _ = document.Outline!.Items.Select(item => item.Destination).OfType().Select(named => named.Resolve()).ToList(); + + Assert.All(Enumerable.Range(1, 9), number => Assert.False(document.Resolve(new CosReference(number, 0)).IsDirty)); + } + + private static byte[] MalformedDestinations() => new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R /Names << /Dests 4 0 R >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>", + "<< /Names [(chained) (fit) (extra) 6 0 R (fitr) 7 0 R (int) 8 0 R (missing) 5 0 R (nopage) 9 0 R (text) 10 0 R (unknown) 11 0 R] >>", + "[3 0 R /XYZ 10]", + "[3 0 R /FitH 1 2]", + "[3 0 R /FitR 1 2 3]", + "[0 /Fit]", + "[12 0 R /Fit]", + "[3 0 R /XYZ (a) 1 1]", + "[3 0 R /FitW 5]", + "<< /Type /Page /MediaBox [0 0 100 100] /Resources << >> >>"); + + private static PdfExplicitDestination Named(PdfDocument document, string name) + { + PdfExplicitDestination destination = Assert.IsType(document.GetNamedDestination(name)); + _ = destination.PageIndex; + return destination; + } + + private static string Describe(PdfExplicitDestination destination) => + string.Join(' ', [destination.View.ToString(), .. new[] { destination.Left, destination.Bottom, destination.Right, destination.Top, destination.Zoom } + .Select(value => value?.ToString(CultureInfo.InvariantCulture) ?? "-")]); + + private static string Describe(Diagnostic diagnostic) => + $"{diagnostic.Code} {diagnostic.ObjectReference?.ObjectNumber.ToString(CultureInfo.InvariantCulture) ?? "-"}"; +} diff --git a/tests/Broadside.Tests/Navigation/OutlineTests.cs b/tests/Broadside.Tests/Navigation/OutlineTests.cs new file mode 100644 index 00000000..8456e61e --- /dev/null +++ b/tests/Broadside.Tests/Navigation/OutlineTests.cs @@ -0,0 +1,232 @@ +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Tests.Document; +using Broadside.TestSupport; + +namespace Broadside.Tests.Navigation; + +/// The document outline (ISO 32000-2 §12.3.3, Tables 150 to 152) and the actions of its items (§12.6.4.2, §12.6.4.8). +public class OutlineTests +{ + [Fact] + public void Outline_pdf_yields_two_closed_leaf_items_with_their_destinations_and_default_style() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("outline.pdf")); + + PdfOutline outline = Assert.IsType(document.Outline); + + Assert.Equal(2, outline.Count); + IReadOnlyList items = outline.Items; + Assert.Equal(["First", "Second"], items.Select(item => item.Title)); + PdfExplicitDestination first = Assert.IsType(items[0].Destination); + Assert.Equal(PdfDestinationView.Fit, first.View); + PdfExplicitDestination second = Assert.IsType(items[1].Destination); + Assert.Equal((PdfDestinationView.Xyz, (double?)0, (double?)792, (double?)null), (second.View, second.Left, second.Top, second.Zoom)); + Assert.All(items, item => + { + Assert.Equal(0, item.Destination is PdfExplicitDestination destination ? destination.PageIndex : -1); + Assert.Null(item.Count); + Assert.False(item.IsOpen); + Assert.Empty(item.Children); + Assert.Equal(PdfRgbColor.Black, item.Color); + Assert.Equal(0, item.Flags); + Assert.False(item.IsBold || item.IsItalic); + Assert.Null(item.Action); + Assert.Null(item.StructureElement); + Assert.Equal(0, item.Level); + Assert.Null(item.Parent); + }); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_document_without_outlines_has_none() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + + Assert.Null(document.Outline); + Assert.Null(document.Names); + } + + [Fact] + public void Outline_full_pdf_yields_three_levels_with_open_and_closed_items_styles_and_actions() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("outline-full.pdf")); + PdfOutline outline = document.Outline!; + + IReadOnlyList parts = outline.Items; + + Assert.Equal(4, outline.Count); + Assert.Equal( + [ + "0 Part I open 2", + "1 Chapter 1 closed -1", + "2 Section 1.1 closed -", + "1 Chapter 2 closed -", + "0 Part II closed -2", + "1 Chapter 3 – Übersicht closed -", + "1 Chapter 4 closed -", + ], + Flatten(parts).Select(item => $"{item.Level} {item.Title} {(item.IsOpen ? "open" : "closed")} {item.Count?.ToString(CultureInfo.InvariantCulture) ?? "-"}")); + + PdfOutlineItem chapter1 = parts[0].Children[0]; + Assert.Same(parts[0], chapter1.Parent); + Assert.Same(chapter1, chapter1.Children[0].Parent); + + PdfUriAction uri = Assert.IsType(parts[0].Children[1].Action); + Assert.Equal("https://example.org/chapter-2", uri.Uri); + Assert.False(uri.IsMap); + Assert.Equal(new CosName("URI"), uri.ActionType); + + PdfOutlineItem chapter3 = parts[1].Children[0]; + Assert.Equal(new PdfRgbColor(1, 0, 0), chapter3.Color); + Assert.Equal(3, chapter3.Flags); + Assert.True(chapter3.IsBold && chapter3.IsItalic); + PdfGoToAction goTo = Assert.IsType(chapter3.Action); + Assert.Null(goTo.StructureDestination); + PdfNamedDestination named = Assert.IsType(goTo.Destination); + PdfExplicitDestination alpha = Assert.IsType(named.Resolve()); + Assert.Equal((PdfDestinationView.Xyz, (double?)792, (int?)0), (alpha.View, alpha.Top, alpha.PageIndex)); + Assert.Null(chapter3.Destination); + + PdfOutlineItem chapter4 = parts[1].Children[1]; + CosDictionary element = Assert.IsType(chapter4.StructureElement); + Assert.Equal(new CosName("H1"), element[new CosName("S")]); + Assert.Equal(PdfDestinationView.FitB, Assert.IsType(chapter4.Destination).View); + + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_damaged_outline_is_read_as_a_finite_tree_with_exactly_the_documented_diagnostics() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("outline-broken.pdf")); + Assert.Empty(document.Diagnostics); + + IReadOnlyList items = document.Outline!.Items; + + Assert.Equal(["0 One", "1 One.One", "0 ", "0 Three", "1 Three.One"], Flatten(items).Select(item => $"{item.Level} {item.Title}")); + Assert.Empty(items[0].Children[0].Children); + Assert.Equal( + [ + "OutlineDestAndAction 5", // both Dest and A + "OutlineItemInvalid 6", // no Title + "OutlineCycle 6", // 7's Next leads back to 6 + "OutlineLinkInconsistent 4", // the outline's Last is 6, the chain ends at 7 + "OutlineCycle 5", // 8's First is its ancestor 5 + "OutlineCountInvalid 4", // the outline's Count is negative + "OutlineCountInvalid 7", // a child, but Count 0 + ], + document.Diagnostics.Select(Describe)); + Assert.Equal(DiagnosticSeverity.Error, document.Diagnostics.Single(diagnostic => diagnostic.Code == "OutlineCycle" && diagnostic.ObjectReference!.ObjectNumber == 6).Severity); + + // Both the destination and the action are exposed; the action is the one to perform. + Assert.IsType(items[0].Destination); + Assert.IsType(items[0].Action); + + // A second walk reports nothing new. + Assert.Equal(5, Flatten(document.Outline.Items).Count()); + Assert.Equal(7, document.Diagnostics.Count); + } + + [Fact] + public void Strict_mode_throws_from_the_walk_not_from_open() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("outline-broken.pdf"), new PdfOptions().UseStrict()); + PdfOutline outline = document.Outline!; + + DiagnosticException error = Assert.Throws(() => outline.Items); + + Assert.Equal("OutlineDestAndAction 5", Describe(error.Diagnostic)); + } + + [Fact] + public void Walking_the_outline_writes_nothing() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("outline-full.pdf")); + + foreach (PdfOutlineItem item in Flatten(document.Outline!.Items)) + { + _ = (item.Title, item.Color, item.Flags, item.Count, item.StructureElement, item.Destination, item.Action); + if (item.Action is PdfGoToAction { Destination: PdfNamedDestination named }) + { + _ = named.Resolve()?.Page; + } + } + + Assert.False(document.Catalog.IsDirty); + Assert.All(Enumerable.Range(4, 8), number => Assert.False(document.Resolve(new CosReference(number, 0)).IsDirty)); + } + + [Fact] + public void Malformed_item_entries_read_as_their_defaults_with_a_diagnostic() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R /Outlines 4 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>", + "<< /Type /Outlines /First 5 0 R /Last 8 0 R >>", + "<< /Title (Clamped) /Parent 4 0 R /Next 6 0 R /C [2 0.5 -1] /F 7 >>", + "<< /Title (Short colour) /Parent 4 0 R /Prev 5 0 R /Next 7 0 R /C [1 0] /F /Bold >>", + "<< /Title (Action in Dest) /Parent 4 0 R /Prev 6 0 R /Next 8 0 R /Dest << /S /URI /URI (https://example.org/) >> >>", + "<< /Title (Missing name) /Parent 4 0 R /Prev 7 0 R /Dest (nowhere) >>"); + using PdfDocument document = PdfDocument.Open(file); + + IReadOnlyList items = document.Outline!.Items; + + Assert.Equal(new PdfRgbColor(1, 0.5, 0), items[0].Color); + Assert.Equal(7, items[0].Flags); // bits other than 1 and 2 are kept as stored + Assert.Equal(PdfRgbColor.Black, items[1].Color); + Assert.Equal(0, items[1].Flags); + Assert.Null(items[2].Destination); + Assert.Equal("https://example.org/", Assert.IsType(items[2].Action).Uri); + PdfNamedDestination missing = Assert.IsType(items[3].Destination); + Assert.Null(missing.Resolve()); + Assert.Equal( + ["OutlineItemInvalid 5", "OutlineItemInvalid 6", "DestinationInvalid 7", "NamedDestinationNotFound 8"], + document.Diagnostics.Select(Describe)); + } + + [Fact] + public void An_outline_deeper_than_the_cap_ends_with_a_diagnostic() + { + const int levels = 300; + var objects = new List + { + "<< /Type /Catalog /Pages 2 0 R /Outlines 4 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>", + "<< /Type /Outlines /First 5 0 R /Last 5 0 R >>", + }; + for (int level = 0; level < levels; level++) + { + int number = 5 + level; + string children = level + 1 < levels ? string.Create(CultureInfo.InvariantCulture, $" /First {number + 1} 0 R /Last {number + 1} 0 R /Count -1") : string.Empty; + objects.Add(string.Create(CultureInfo.InvariantCulture, $"<< /Title (Level {level}) /Parent {(level == 0 ? 4 : number - 1)} 0 R{children} >>")); + } + + using PdfDocument document = PdfDocument.Open(new TestPdf().Build([.. objects])); + + IReadOnlyList items = document.Outline!.Items; + + Assert.Equal(256, Flatten(items).Count()); + Assert.Equal(["OutlineTooDeep 260"], document.Diagnostics.Select(Describe)); + } + + private static IEnumerable Flatten(IEnumerable items) + { + var pending = new Stack(items.Reverse()); + while (pending.TryPop(out PdfOutlineItem? item)) + { + yield return item; + for (int index = item.Children.Count - 1; index >= 0; index--) + { + pending.Push(item.Children[index]); + } + } + } + + private static string Describe(Diagnostic diagnostic) => + $"{diagnostic.Code} {diagnostic.ObjectReference?.ObjectNumber.ToString(CultureInfo.InvariantCulture) ?? "-"}"; +} diff --git a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt index 89eff615..5bb17d02 100644 --- a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt +++ b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt @@ -3,6 +3,7 @@ ascii85-stream.pdf, asciihex-stream.pdf, broken-xref-offsets.pdf, + destinations-all.pdf, empty-page.pdf, encrypted-aes-128.pdf, encrypted-aes-256.pdf, @@ -34,6 +35,8 @@ no-xref.pdf, number-tree-deep.pdf, object-stream.pdf, + outline-broken.pdf, + outline-full.pdf, outline.pdf, page-tree-inherited.pdf, pdf20-header.pdf, diff --git a/tests/Broadside.Tests/Writing/SaveTests.cs b/tests/Broadside.Tests/Writing/SaveTests.cs index beff1866..df3a3ef6 100644 --- a/tests/Broadside.Tests/Writing/SaveTests.cs +++ b/tests/Broadside.Tests/Writing/SaveTests.cs @@ -13,7 +13,7 @@ public class SaveTests /// Broken files whose damage is in a document-model structure read lazily (a name tree, an outline), not in the file structure: /// they open without a diagnostic and save byte for byte, damage included, so qpdf reports it again. /// - private static readonly HashSet DamagedInTheDocumentModel = new(StringComparer.Ordinal) { "name-tree-broken.pdf" }; + private static readonly HashSet DamagedInTheDocumentModel = new(StringComparer.Ordinal) { "name-tree-broken.pdf", "outline-broken.pdf" }; /// /// Well-formed files qpdf 12.4.2 warns about because it compares name tree keys as decoded text, not byte by byte as ISO 32000-2 diff --git a/tests/Corpus/README.md b/tests/Corpus/README.md index 4093ee04..a2b8bd39 100644 --- a/tests/Corpus/README.md +++ b/tests/Corpus/README.md @@ -66,6 +66,8 @@ Verification was run with qpdf 12.4.2 (`qpdf --check`), poppler (`pdfinfo`, `pdf | `metadata-xmp.pdf` | Catalog `/Metadata` stream (`/Type /Metadata /Subtype /XML`) with a minimal XMP packet whose `dc:title` is `Broadside`, plus a trailer `/Info` dictionary with the same `/Title`. | 14.3.2, 14.3.3 | `pdfinfo` shows `Title: Broadside` | clean | | `name-tree-deep.pdf` | `/Names << /Dests ... >>` name tree four levels deep (root `/Kids`, two levels of intermediate nodes, 20 leaves) holding 200 keys in byte order: `(a)` before `(ab)` (a key that is a prefix of another), PDFDocEncoding keys whose byte order differs from their text order (`<18>`, the breve, sorts first; `<80>` bullet before `` e-acute), and UTF-16BE keys with the byte order marker (`` also reads as "a"). Each value is `[3 0 R /XYZ 0 i null]`, `i` the key's position. | 7.9.6, Annex J.3.3, 12.3.2.4 | `qpdf --check` | qpdf 12.4.2 warns `keys are not sorted` on the root (object 31) because it compares keys as decoded text; the clause compares bytes, so for Broadside the file is clean | | `number-tree-deep.pdf` | Twelve pages and a `/PageLabels` number tree three levels deep (root `/Kids`, two intermediate nodes, three leaves with `/Limits` and `/Nums`) with keys 0, 1, 2, 4, 5, 7, 8, 10, 11, so most pages fall between two keys. | 7.9.7, 12.4.2 | `qpdf --check`; `pdfinfo` reports 12 pages | clean | +| `destinations-all.pdf` | A `/Names << /Dests >>` tree with one entry per Table 149 form: `XYZ` with numbers, with three nulls and with zoom 0; `Fit`; `FitH` with a number and with null; `FitV`; `FitR`; `FitB`; `FitBH`; `FitBV`; a value in the dictionary form `<< /D [3 0 R /Fit] /Note ... >>`; a value that is an indirect array. The PDF 1.1 catalog `/Dests` dictionary keyed by name (`/Chap6 [3 0 R /FitV 72]`), and an outline whose items refer to `/Dest /Chap6` (name) and `/Dest (alpha)` (string). | 12.3.2.2, 12.3.2.4, 7.7.2, 12.3.3 | `qpdf --check`; `qpdf --json --json-key=outlines` lists both items | clean | +| `outline-full.pdf` | An outline three levels deep: Part I (open, `/Count 2`) holding Chapter 1 (closed, `/Count -1`, holding Section 1.1) and Chapter 2 (a URI action); Part II (closed, `/Count -2`) holding Chapter 3 (UTF-16BE title `Chapter 3 – Übersicht`, `/C [1 0 0]`, `/F 3` bold italic, `/A << /S /GoTo /D (alpha) >>`) and Chapter 4 (`/SE` to a structure element, `/Dest [3 0 R /FitB]`). Outline `/Count 4`. | 12.3.3 Tables 150-152, 12.6.4.2, 12.6.4.8 | `qpdf --check`; `qpdf --json --json-key=outlines` shows the tree with Part I and Chapter 1 open/closed as stated | clean | The crypt filter `/Length` entries in the R4 and R6 files are `16` and `32` (bytes), the form Acrobat and qpdf write and that Table 25 describes for the standard security handler; the same table also says the key "shall have the value of 128/256". Readers should accept both forms. @@ -84,6 +86,7 @@ Each file is `empty-page.pdf` (or `text-standard14.pdf`) with exactly one defect | `encrypted-owner-key-variant.pdf` | R3 40-bit RC4 whose `O` entry was computed rehashing only the first n bytes in Algorithm 3 step c (what qpdf and PDFBox write), not the whole digest the clause describes. | 7.6.4.4.2 Algorithm 3 step c | qpdf: clean, and `qpdf --password=owner` accepts the owner password. | Opens with the empty user password with no diagnostic. Opened with the owner password `owner`, record `OwnerPasswordKeyVariant` (Warning) and grant owner access. | | `encrypted-rc4-length-missing.pdf` | R3 (`/V 2`) RC4 with a 128-bit key but no `/Length` entry, so the key is 40 bits by Table 20's default. The case of qpdf's `bad-encryption-length.pdf`, which the real-world corpus gate (issue #47) found reported as "password required". | 7.6.2 Table 20 | qpdf (exit 3): `object 6 0 ... dictionary key /Length: operation for integer attempted on object of type null: returning 0`, then opens it (qpdf assumes 128 bits when Length is missing). pdfinfo and pdftotext: `Command Line Error: Incorrect password`. | No key of the default 40 bits authenticates, so 128 bits are tried: the empty user password authenticates, record `EncryptionKeyLengthInvalid` (Warning, no offset or object); `PdfSecurity.KeyLength` is 128 and the content decrypts to `RC4 128-bit (R3), no Length`. Strict mode throws it at open. | | `name-tree-broken.pdf` | A `/Dests` name tree broken six ways: leaf 7's `/Limits [(a) (c)]` do not hold its key `(d)`; leaf 8's keys are out of order (`(f)` before `(e)`); intermediate node 6 has no `/Limits`; `(g)` is in leaf 8 and again in leaf 9; node 6's `/Kids` list the root 4 (a cycle); leaf 9's `/Names` has an odd length (a dangling `(i)`). | 7.9.6 | qpdf (exit 3): `keys are not sorted in validate` (object 4), `items array doesn't have enough elements` (object 9), `loop detected while traversing name/number tree` (object 4). pdfinfo: clean. | Opens with no diagnostic (the tree is read lazily). Walking the tree records, once per node and in this order: `NameTreeLimitsInvalid` 7, `NameTreeKeysUnsorted` 8, `NameTreeLimitsInvalid` 6, `NameTreeCycle` 4 (Error), `NameTreeNodeInvalid` 9, `NameTreeDuplicateKey` 9. Keys `a b d f e g h` resolve (`(g)` to leaf 8's value, the first in tree order); `(i)` has no value. Strict mode throws `NameTreeLimitsInvalid` 7 from the first lookup that needs the whole tree. | +| `outline-broken.pdf` | An outline broken six ways: item 5 has both `/Dest` and `/A`; item 6 has no `/Title`; item 7's `/Next` points back at item 6 (a cycle in the sibling chain); item 8's `/First` points at its ancestor 5; the outline's `/Last` names 6, not 7 where the chain ends; item 7 has a child but `/Count 0`; the outline's `/Count -5` is negative. | 12.3.3 Tables 150-151 | qpdf (exit 3): `Loop detected loop in /Outlines tree` (objects 5, 6 and 7). pdfinfo: clean. | Opens with no diagnostic (the outline is read lazily). Walking it records, in this order: `OutlineDestAndAction` 5, `OutlineItemInvalid` 6 (title read as empty), `OutlineCycle` 6 (Error), `OutlineLinkInconsistent` 4, `OutlineCycle` 5 (Error), `OutlineCountInvalid` 4, `OutlineCountInvalid` 7. The tree read is One (child One.One, no grandchildren), an untitled item, Three (child Three.One). Strict mode throws `OutlineDestAndAction` 5 from the walk. | ## Password-protected files diff --git a/tests/Corpus/destinations-all.pdf b/tests/Corpus/destinations-all.pdf new file mode 100644 index 0000000000000000000000000000000000000000..25bf3e03c333eef6544e10e1de010ef9acca02d5 GIT binary patch literal 1281 zcmZWpO>f#j5WV|X%moP!WOq$$gA^e(NfA<8f@p=BAP!5sgsof~t(TPW>pSE12X=fw zc;@Y!H#2YDTRzT);wJJ0aL9Ilyt_MKzdnu%*n_k($=-l1<(taEN5Bf$LjJ`ULOrV7 z=5Sktr_<^^aImM7O>~OLu*`cZjftOV+I1W~`=;X@HY0*>v3Pb$EeM!StAmvJe2~-` zh0s#o4;5>9pPgaD5g!U4qKS`uE0t#_^XjCd+J=`JsCZp-o4!nr2RSI!0Q>#?f*>S< z^pqr9=dIEP!#Zvsc&uDXVTTc@!$>J{6XV5=+W|I_v`j0bMh^(2a3*&?$F`Z5I>$J**F zl?g~|jozKC8sKc9fBv{MT4;U|ZUVK4LIq|!jSz%dYkp8H!7j>VZ6?rly>=^`X_H%siW#u)6913ge`iSlswRPI8f_CC36-|WKscy< z>HNReON#X*M`G8-RKoetd>XT!?kCDqcX_exKyH0>z**Wf+Z>!66 zHfrzTHn_*@2VEA70@y$`s$PpZcQ6`)rkE^bsLL<8X2-jV(GCTm)XP_w{M!{RjQrO}795 literal 0 HcmV?d00001 diff --git a/tests/Corpus/generate.py b/tests/Corpus/generate.py index 48e09520..aea94a0f 100644 --- a/tests/Corpus/generate.py +++ b/tests/Corpus/generate.py @@ -1270,6 +1270,92 @@ def dest(top: int) -> bytes: ]) +def gen_destinations_all() -> bytes: + """12.3.2.2 Table 149 and 12.3.2.4: a Dests name tree with one entry per explicit form (XYZ with + numbers, with nulls and with zoom 0; Fit; FitH with a number and with null; FitV; FitR; FitB; + FitBH; FitBV), a value in the dictionary form << /D [...] >> with an extra attribute, and a value + that is an indirect array; the PDF 1.1 catalog /Dests dictionary keyed by name (/Chap6); and an + outline whose items refer to a destination by name (/Dest /Chap6) and by string (/Dest (alpha)).""" + names = [ + (b"alpha", b"[3 0 R /XYZ 0 792 null]"), + (b"fit", b"[3 0 R /Fit]"), + (b"fitb", b"[3 0 R /FitB]"), + (b"fitbh", b"[3 0 R /FitBH 700]"), + (b"fitbv", b"[3 0 R /FitBV 36]"), + (b"fith", b"[3 0 R /FitH 650]"), + (b"fith-null", b"[3 0 R /FitH null]"), + (b"fitr", b"[3 0 R /FitR 10 20 300 400.5]"), + (b"fitv", b"[3 0 R /FitV 50]"), + (b"indirect", b"9 0 R"), + (b"with-d", b"<< /D [3 0 R /Fit] /Note (an additional attribute) >>"), + (b"xyz", b"[3 0 R /XYZ 72 720 1.5]"), + (b"xyz-null", b"[3 0 R /XYZ null null null]"), + (b"xyz-zero", b"[3 0 R /XYZ 10 20 0]"), + ] + assert [k for k, _ in names] == sorted(k for k, _ in names) + pairs = b" ".join(b"(" + k + b") " + v for k, v in names) + return simple_file([ + (1, catalog(b" /Names << /Dests 4 0 R >> /Dests 5 0 R /Outlines 6 0 R")), + (2, pages()), + (3, page()), + (4, b"<< /Names [" + pairs + b"] >>"), + (5, b"<< /Chap6 [3 0 R /FitV 72] >>"), + (6, b"<< /Type /Outlines /First 7 0 R /Last 8 0 R /Count 2 >>"), + (7, b"<< /Title (Chapter 6) /Parent 6 0 R /Next 8 0 R /Dest /Chap6 >>"), + (8, b"<< /Title (Alpha) /Parent 6 0 R /Prev 7 0 R /Dest (alpha) >>"), + (9, b"[3 0 R /FitH 500]"), + ]) + + +def gen_outline_full() -> bytes: + """12.3.3 Tables 150-152: an outline three levels deep. Part I (open, Count 2) holds Chapter 1 + (closed, Count -1, holding Section 1.1) and Chapter 2 (a URI action); Part II (closed, Count -2) + holds Chapter 3 (UTF-16BE title, red /C [1 0 0], bold italic /F 3, a GoTo action to the named + destination (alpha)) and Chapter 4 (an /SE structure element and an explicit destination). + The outline's Count is 4: the two parts and Part I's two children.""" + utf16_title = b"" + return simple_file([ + (1, catalog(b" /Outlines 4 0 R /PageMode /UseOutlines /StructTreeRoot 12 0 R" + b" /Names << /Dests << /Names [(alpha) [3 0 R /XYZ 0 792 null]] >> >>")), + (2, pages()), + (3, page()), + (4, b"<< /Type /Outlines /First 5 0 R /Last 9 0 R /Count 4 >>"), + (5, b"<< /Title (Part I) /Parent 4 0 R /Next 9 0 R /First 6 0 R /Last 8 0 R /Count 2" + b" /Dest [3 0 R /Fit] >>"), + (6, b"<< /Title (Chapter 1) /Parent 5 0 R /Next 8 0 R /First 7 0 R /Last 7 0 R /Count -1" + b" /Dest [3 0 R /FitH 700] >>"), + (7, b"<< /Title (Section 1.1) /Parent 6 0 R /Dest [3 0 R /XYZ 72 700 null] >>"), + (8, b"<< /Title (Chapter 2) /Parent 5 0 R /Prev 6 0 R" + b" /A << /S /URI /URI (https://example.org/chapter-2) >> >>"), + (9, b"<< /Title (Part II) /Parent 4 0 R /Prev 5 0 R /First 10 0 R /Last 11 0 R /Count -2 >>"), + (10, b"<< /Title " + utf16_title + b" /Parent 9 0 R /Next 11 0 R /C [1 0 0] /F 3" + b" /A << /S /GoTo /D (alpha) >> >>"), + (11, b"<< /Title (Chapter 4) /Parent 9 0 R /Prev 10 0 R /SE 13 0 R /Dest [3 0 R /FitB] >>"), + (12, b"<< /Type /StructTreeRoot /K 13 0 R >>"), + (13, b"<< /Type /StructElem /S /H1 /P 12 0 R >>"), + ]) + + +def gen_outline_broken() -> bytes: + """12.3.3 Tables 150-151, broken: item 5 has both /Dest and /A; item 6 has no /Title; item 7's + /Next points back at item 6 (a cycle in the sibling chain); item 8's /First points at its + ancestor 5; the outline's /Last names item 6, not 7 where the chain ends; item 7 has a child + but Count 0 (neither open nor closed); the outline's Count is negative.""" + return simple_file([ + (1, catalog(b" /Outlines 4 0 R")), + (2, pages()), + (3, page()), + (4, b"<< /Type /Outlines /First 5 0 R /Last 6 0 R /Count -5 >>"), + (5, b"<< /Title (One) /Parent 4 0 R /Next 6 0 R /First 8 0 R /Last 8 0 R /Count 1" + b" /Dest [3 0 R /Fit] /A << /S /URI /URI (https://example.org/) >> >>"), + (6, b"<< /Parent 4 0 R /Prev 5 0 R /Next 7 0 R /Dest [3 0 R /Fit] >>"), + (7, b"<< /Title (Three) /Parent 4 0 R /Prev 6 0 R /Next 6 0 R /First 9 0 R /Last 9 0 R" + b" /Count 0 >>"), + (8, b"<< /Title (One.One) /Parent 5 0 R /First 5 0 R /Last 5 0 R >>"), + (9, b"<< /Title (Three.One) /Parent 7 0 R >>"), + ]) + + XMP = (b'\n' b'\n' b' \n' @@ -1337,6 +1423,9 @@ def gen_metadata_xmp() -> bytes: "name-tree-deep.pdf": gen_name_tree_deep, "number-tree-deep.pdf": gen_number_tree_deep, "name-tree-broken.pdf": gen_name_tree_broken, + "destinations-all.pdf": gen_destinations_all, + "outline-full.pdf": gen_outline_full, + "outline-broken.pdf": gen_outline_broken, } diff --git a/tests/Corpus/outline-broken.pdf b/tests/Corpus/outline-broken.pdf new file mode 100644 index 0000000000000000000000000000000000000000..b1acbe2ad8c4bb1012bffb7d4ceeaa08c0cdff4a GIT binary patch literal 1031 zcmZWo%WlFj5WMFr_JRb5;v|ryR47tgid6Lh0(wF{q-B9rX^b3G(SCi`ao+YJve&z_ zGvjP;Ih$WO!@zRD2LAD7O{c&%zb6ECAIT`;2Vl$SfEl=yumZL?%Op4!Jn6L0hHbU9u}2 zD+nzG{*)4Pa)IV!wyxhorIctJt#xx0XsXS@3(rjDlZNtQua(;kUzH`DUgYbri*F467a`NXUn3uqRqm=sZ*pvcE~9seO|qZ#2`jhy<~NqZ(EA#>${?_0gz I!(wjz11@w4E&u=k literal 0 HcmV?d00001 diff --git a/tests/Corpus/outline-full.pdf b/tests/Corpus/outline-full.pdf new file mode 100644 index 0000000000000000000000000000000000000000..2d77825785749f1f2656e407b324a6b3593def5a GIT binary patch literal 1700 zcmZuyU2obj6n)RHxGzZb0c_`kz*HfvK-Q{ji-1Yn5Dyu+kSQc6F%#Rb-}OhnOQATn z?>*<9du)2kc`#r@-(o-^{q@_rzX!7Ud*MK4p$Oyj2xJ)^c@8#iSOIyvia1K}+11Z- z@g+Ur{%<)i7s*;=*S*+eoUhVU05j3A;Tc0E#+>IukM!KOAI6tccn4cYC;tB9Cl36H z4aqf*cRQF)_1ogfK{Ayon~XJ4@*EvQf-r3O_E_NZBdimscD(< zKVSepD}%1l(W@u@uYVHal7AwE-@@}H=EF2QlD!safXNy*kd1BO>i%^bs8EfnT1h6& zR#=3|Lx~SYOS@K_+Sf$64;Dc{sq0WW8smpiin37O#j%IqHl_Hc4zAny$J95a^BJz= zLb1n}@e}-*Jia?EeP=wY3{aATt)z(^B>^}4&W`upF+T%AS3IJpm&J`%1>Q3L zZc$*ag(905j6Bcr;2o+ttVq5fDd*T24?t_qcJYX}<{Srarq-NGQHj=^$GRA!5AyjA z_N^5=_PTQuuY=22Hy^Xz4i{!mYPE?hjAEXtpO|&@kE2$2ovNP)<#W_B7kJYtC7I*7 KR Date: Fri, 9 Oct 2026 16:22:03 -0500 Subject: [PATCH 032/152] feat(graphics): sampled, exponential, stitching and PostScript calculator functions (#78) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Functions (ISO 32000-2 §7.10, Annex B) compiled once from their COS objects and evaluated without allocation, for tint transforms (#77), transfer functions and soft masks (#56) and shadings (#79). - Public: PdfDocument.GetFunction, PdfFunction (live view: Domain, Range, InputCount, OutputCount, IsValid, MinimumVersion, Evaluate single and batch), PdfSampledFunction, PdfExponentialFunction, PdfStitchingFunction, PdfPostScriptFunction, PdfFunctionType. - Internal consumer seam: PdfDocument.Functions (FunctionCache) with GetEvaluator(value, FunctionForms, m, n) for Identity and function arrays; FunctionEvaluator returns a FunctionStatus and never reports per sample. - Type 0: every BitsPerSample, unpadded bit stream, multilinear interpolation (simplex beyond 8 inputs), Order 3 evaluated linearly with an Information diagnostic, sample-count cap. Type 2: N = 1/2 fast paths, non-finite x^N gives C0. Type 3: every interval case of Example 1, depth limit 8, cycles. Type 4: single-pass compiler to a flat instruction list with jumps, static stack check, evaluator over a 100-entry stack on the call stack; PostScript errors repaired and reported once per function. - Domain and Range clipped for every type; NaN and infinity never leave. - COS containers get an internal monotonic Version; a compiled function recompiles when a container it read changes. - Corpus file functions.pdf (six Separation tint transforms), fuzz targets function-type4 and function-sampled, FunctionBenchmarks, conformance rows 7.10.1-7.10.5 and Annex B. Co-Authored-By: Claude Opus 5.5 --- .../FunctionBenchmarks.cs | 100 ++++ docs/conformance/iso-32000-2.md | 8 +- .../Graphics/Functions/CompiledFunction.cs | 32 + .../Graphics/Functions/FunctionCache.cs | 178 ++++++ .../Graphics/Functions/FunctionCompilation.cs | 245 ++++++++ .../Graphics/Functions/FunctionCompiler.cs | 270 +++++++++ .../Graphics/Functions/FunctionDependency.cs | 27 + .../Graphics/Functions/FunctionEvaluator.cs | 151 +++++ .../Graphics/Functions/FunctionForms.cs | 23 + .../Graphics/Functions/FunctionNames.cs | 49 ++ .../Graphics/Functions/FunctionStatus.cs | 25 + .../Graphics/Functions/PostScriptCompiler.cs | 388 ++++++++++++ .../Graphics/Functions/PostScriptEvaluator.cs | 563 ++++++++++++++++++ .../Functions/PostScriptInstruction.cs | 141 +++++ .../Graphics/Functions/PostScriptLexer.cs | 163 +++++ .../Graphics/Functions/SampledCompiler.cs | 226 +++++++ .../Graphics/Functions/SampledEvaluator.cs | 160 +++++ .../Graphics/Functions/SimpleEvaluators.cs | 154 +++++ .../Graphics/PdfExponentialFunction.cs | 29 + src/Broadside/Graphics/PdfFunction.cs | 182 ++++++ src/Broadside/Graphics/PdfFunctionType.cs | 18 + .../Graphics/PdfPostScriptFunction.cs | 33 + src/Broadside/Graphics/PdfSampledFunction.cs | 51 ++ .../Graphics/PdfStitchingFunction.cs | 49 ++ src/Broadside/Objects/CosArray.cs | 24 +- src/Broadside/Objects/CosDictionary.cs | 29 +- src/Broadside/Objects/CosStream.cs | 7 + src/Broadside/Parsing/DiagnosticCodes.cs | 11 + src/Broadside/PdfDocument.cs | 24 + src/Broadside/PublicAPI.Unshipped.txt | 40 ++ tests/Broadside.Fuzz/FuzzTargets.cs | 121 ++++ tests/Broadside.Fuzz/README.md | 4 +- tests/Broadside.TestSupport/Corpus.cs | 1 + .../Graphics/CorpusFunctionTests.cs | 61 ++ .../Graphics/ExponentialFunctionTests.cs | 124 ++++ .../Graphics/FunctionAllocationTests.cs | 90 +++ .../Graphics/FunctionConcurrencyTests.cs | 32 + .../Graphics/FunctionTesting.cs | 51 ++ .../Graphics/FunctionViewTests.cs | 158 +++++ .../Graphics/PostScriptFunctionTests.cs | 351 +++++++++++ .../Graphics/SampledFunctionTests.cs | 323 ++++++++++ .../Graphics/StitchingFunctionTests.cs | 186 ++++++ ...pus_file_names_match_snapshot.verified.txt | 1 + tests/Corpus/README.md | 1 + tests/Corpus/functions.pdf | Bin 0 -> 2084 bytes tests/Corpus/generate.py | 38 ++ 46 files changed, 4934 insertions(+), 8 deletions(-) create mode 100644 bench/Broadside.Benchmarks/FunctionBenchmarks.cs create mode 100644 src/Broadside/Graphics/Functions/CompiledFunction.cs create mode 100644 src/Broadside/Graphics/Functions/FunctionCache.cs create mode 100644 src/Broadside/Graphics/Functions/FunctionCompilation.cs create mode 100644 src/Broadside/Graphics/Functions/FunctionCompiler.cs create mode 100644 src/Broadside/Graphics/Functions/FunctionDependency.cs create mode 100644 src/Broadside/Graphics/Functions/FunctionEvaluator.cs create mode 100644 src/Broadside/Graphics/Functions/FunctionForms.cs create mode 100644 src/Broadside/Graphics/Functions/FunctionNames.cs create mode 100644 src/Broadside/Graphics/Functions/FunctionStatus.cs create mode 100644 src/Broadside/Graphics/Functions/PostScriptCompiler.cs create mode 100644 src/Broadside/Graphics/Functions/PostScriptEvaluator.cs create mode 100644 src/Broadside/Graphics/Functions/PostScriptInstruction.cs create mode 100644 src/Broadside/Graphics/Functions/PostScriptLexer.cs create mode 100644 src/Broadside/Graphics/Functions/SampledCompiler.cs create mode 100644 src/Broadside/Graphics/Functions/SampledEvaluator.cs create mode 100644 src/Broadside/Graphics/Functions/SimpleEvaluators.cs create mode 100644 src/Broadside/Graphics/PdfExponentialFunction.cs create mode 100644 src/Broadside/Graphics/PdfFunction.cs create mode 100644 src/Broadside/Graphics/PdfFunctionType.cs create mode 100644 src/Broadside/Graphics/PdfPostScriptFunction.cs create mode 100644 src/Broadside/Graphics/PdfSampledFunction.cs create mode 100644 src/Broadside/Graphics/PdfStitchingFunction.cs create mode 100644 tests/Broadside.Tests/Graphics/CorpusFunctionTests.cs create mode 100644 tests/Broadside.Tests/Graphics/ExponentialFunctionTests.cs create mode 100644 tests/Broadside.Tests/Graphics/FunctionAllocationTests.cs create mode 100644 tests/Broadside.Tests/Graphics/FunctionConcurrencyTests.cs create mode 100644 tests/Broadside.Tests/Graphics/FunctionTesting.cs create mode 100644 tests/Broadside.Tests/Graphics/FunctionViewTests.cs create mode 100644 tests/Broadside.Tests/Graphics/PostScriptFunctionTests.cs create mode 100644 tests/Broadside.Tests/Graphics/SampledFunctionTests.cs create mode 100644 tests/Broadside.Tests/Graphics/StitchingFunctionTests.cs create mode 100644 tests/Corpus/functions.pdf diff --git a/bench/Broadside.Benchmarks/FunctionBenchmarks.cs b/bench/Broadside.Benchmarks/FunctionBenchmarks.cs new file mode 100644 index 00000000..4da94dc4 --- /dev/null +++ b/bench/Broadside.Benchmarks/FunctionBenchmarks.cs @@ -0,0 +1,100 @@ +using System.Text; +using BenchmarkDotNet.Attributes; +using Broadside.Graphics; +using Broadside.Objects; + +namespace Broadside.Benchmarks; + +/// +/// Evaluates functions (ISO 32000-2 §7.10) 1,000 times each, as a shading or tint conversion does per pixel. Evaluation is a hot +/// path: Allocated must read -; Broadside.Tests.Graphics.FunctionAllocationTests fails the build if it does not. +/// +[MemoryDiagnoser] +public class FunctionBenchmarks +{ + private const int Points = 1_000; + + private static readonly Dictionary> Functions = new() + { + ["Type4LogoGreen"] = static () => Program( + "<< /FunctionType 4 /Domain [0 1] /Range [0 1 0 1 0 1 0 1] >>", + "{dup 0.84 mul exch 0.00 exch dup 0.44 mul exch 0.21 mul}"), + ["Type4DoubleDot"] = static () => Program( + "<< /FunctionType 4 /Domain [-1 1 -1 1] /Range [-1 1] >>", + "{360 mul sin 2 div exch 360 mul sin 2 div add}"), + ["Type4Hexachrome"] = static () => Program( + "<< /FunctionType 4 /Domain [0 1 0 1 0 1 0 1 0 1 0 1] /Range [0 1 0 1 0 1 0 1] >>", + "{ 5 index 1 index 0.6 mul add 5 index 3 index 0.5 mul add 5 index 4 index 0.9 mul add 3 index 0.8 mul add " + + "5 index 10 4 roll pop pop pop pop pop pop dup 0.99 gt { pop 1 } if }"), + ["Type0OneInThreeOut"] = static () => new CosStream( + Dictionary("<< /FunctionType 0 /Domain [0 1] /Range [0 1 0 1 0 1] /Size [256] /BitsPerSample 8 >>"), + Enumerable.Range(0, 768).Select(static i => (byte)(i * 7)).ToArray()), + ["Type0TwoIn"] = static () => new CosStream( + Dictionary("<< /FunctionType 0 /Domain [0 1 0 1] /Range [0 1 0 1 0 1] /Size [16 16] /BitsPerSample 8 >>"), + Enumerable.Range(0, 768).Select(static i => (byte)(i * 11)).ToArray()), + ["Type2"] = static () => Dictionary("<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0] /C1 [1 0.5 0.25] /N 1.7 >>"), + ["Type3"] = static () => Dictionary( + "<< /FunctionType 3 /Domain [0 1] /Bounds [0.25 0.5 0.75] /Encode [0 1 1 0 0 1 1 0] /Functions [" + + "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 1] /C1 [1 0 0] /N 1 >> << /FunctionType 2 /Domain [0 1] /C0 [0 1 0] /C1 [1 1 1] /N 2 >> " + + "<< /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 1 0] /N 1 >> << /FunctionType 2 /Domain [0 1] /C0 [0 0 0] /C1 [1 1 1] /N 3 >>] >>"), + }; + + private PdfDocument? _document; + private PdfFunction? _function; + private float[] _inputs = []; + private float[] _outputs = []; + + /// The function to evaluate. + [Params("Type4LogoGreen", "Type4DoubleDot", "Type4Hexachrome", "Type0OneInThreeOut", "Type0TwoIn", "Type2", "Type3")] + public string Function { get; set; } = ""; + + [GlobalSetup] + public void Setup() + { + _document = PdfDocument.Create(); + _function = _document.GetFunction(Functions[Function]()) ?? throw new InvalidOperationException("Not a function."); + if (!_function.IsValid || _document.Diagnostics.Count > 0) + { + throw new InvalidOperationException($"{Function} does not compile cleanly."); + } + + int m = _function.InputCount; + _inputs = new float[Points * m]; + for (int i = 0; i < _inputs.Length; i++) + { + _inputs[i] = (i * 0.618034f) % 1f; + } + + _outputs = new float[Points * _function.OutputCount]; + } + + [GlobalCleanup] + public void Cleanup() => _document?.Dispose(); + + /// One evaluation per call, 1,000 points. + [Benchmark(Baseline = true)] + public float EvaluateEach() + { + PdfFunction function = _function!; + int m = function.InputCount; + int n = function.OutputCount; + for (int k = 0; k < Points; k++) + { + function.Evaluate(_inputs.AsSpan(k * m, m), _outputs.AsSpan(k * n, n)); + } + + return _outputs[^1]; + } + + /// The same 1,000 points as one batch. + [Benchmark] + public float EvaluateBatch() + { + _function!.Evaluate(_inputs, _outputs, Points); + return _outputs[^1]; + } + + private static CosDictionary Dictionary(string syntax) => (CosDictionary)CosObject.Parse(Encoding.ASCII.GetBytes(syntax)); + + private static CosStream Program(string dictionary, string code) => new(Dictionary(dictionary), Encoding.ASCII.GetBytes(code)); +} diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index 22181c28..2d25a969 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -58,7 +58,11 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.9.5 | Rectangles | done | `PdfRectangle` | `Broadside.Tests.Document.PageAttributeTests.Rectangles_given_by_any_two_opposite_corners_are_normalized`, `Broadside.Tests.Document.PageAttributeTests.A_box_and_its_numbers_may_be_indirect_objects`, `Broadside.Tests.Document.PageAttributeTests.A_malformed_box_reads_as_its_default_with_a_diagnostic` | Any two opposite corners, normalized | | 7.9.6 | Name trees | not started | | | | | 7.9.7 | Number trees | not started | | | | -| 7.10 | Functions | not started | | | | +| 7.10.1 | General | done | `PdfFunction`, `PdfFunctionType`, `PdfDocument`, `FunctionEvaluator`, `FunctionCache` | `Broadside.Tests.Graphics.FunctionViewTests.The_same_object_gives_the_same_view`, `Broadside.Tests.Graphics.FunctionViewTests.Entries_are_read_live_and_evaluation_follows_a_change_to_the_dictionary`, `Broadside.Tests.Graphics.FunctionViewTests.A_batch_evaluates_points_one_after_the_other`, `Broadside.Tests.Graphics.FunctionViewTests.An_object_that_is_not_a_function_gives_no_view`, `Broadside.Tests.Graphics.FunctionViewTests.Odd_and_reversed_domain_entries_are_repaired`, `Broadside.Tests.Graphics.FunctionViewTests.Consumers_get_identity_and_arrays_of_one_output_functions_where_their_entry_allows_them`, `Broadside.Tests.Graphics.ExponentialFunctionTests.Inputs_are_clipped_to_the_domain_and_outputs_to_the_range`, `Broadside.Tests.Graphics.PostScriptFunctionTests.Inputs_are_clipped_to_the_domain_before_the_program_runs`, `Broadside.Tests.Graphics.FunctionConcurrencyTests.Concurrent_evaluations_agree_with_a_single_threaded_one`, `Broadside.Tests.Graphics.FunctionAllocationTests.Evaluating_a_function_allocates_nothing` | Table 38: Domain clipped before, Range after, for every type; NaN and infinity never leave; missing Domain/Range repaired from the type or the consumer's arity; one view per indirect reference or direct object, recompiled when a container it read changes (COS `Version`); zero allocation per evaluation. functions.pdf | +| 7.10.2 | Type 0 (sampled) functions | partial | `PdfSampledFunction`, `SampledCompiler`, `SampledEvaluator` | `Broadside.Tests.Graphics.SampledFunctionTests.Every_sample_of_a_table_comes_back_at_its_grid_point`, `Broadside.Tests.Graphics.SampledFunctionTests.Between_two_samples_the_output_is_their_average`, `Broadside.Tests.Graphics.SampledFunctionTests.Bilinear_interpolation_weights_the_four_corners_of_the_cell`, `Broadside.Tests.Graphics.SampledFunctionTests.The_example_2_table_of_21_by_31_four_bit_samples_takes_326_bytes`, `Broadside.Tests.Graphics.SampledFunctionTests.A_dimension_of_size_1_maps_every_input_to_its_one_sample`, `Broadside.Tests.Graphics.SampledFunctionTests.A_non_integer_encode_reaches_between_samples`, `Broadside.Tests.Graphics.SampledFunctionTests.Inputs_at_the_domain_ends_read_the_first_and_last_samples_and_beyond_them_are_clipped`, `Broadside.Tests.Graphics.SampledFunctionTests.Decode_maps_samples_and_the_range_clips_the_result`, `Broadside.Tests.Graphics.SampledFunctionTests.Order_3_is_evaluated_linearly_and_noted_once`, `Broadside.Tests.Graphics.SampledFunctionTests.Order_3_with_fewer_than_4_samples_in_a_dimension_is_ignored_silently`, `Broadside.Tests.Graphics.SampledFunctionTests.Simplex_interpolation_beyond_eight_inputs_reproduces_a_linear_function`, `Broadside.Tests.Graphics.SampledFunctionTests.A_size_that_would_need_too_many_samples_is_rejected_without_allocating_them`, `Broadside.Tests.Graphics.CorpusFunctionTests.Each_tint_transform_evaluates_to_the_colour_the_page_shows` | All BitsPerSample values (and other widths 1-32 with a diagnostic), no padding at row ends, multilinear interpolation (simplex beyond 8 inputs between samples), truncated data zero-filled; Order 3 (cubic spline) is evaluated linearly with FunctionOrderUnsupported (Information): pending | +| 7.10.3 | Type 2 (exponential interpolation) functions | done | `PdfExponentialFunction`, `ExponentialEvaluator` | `Broadside.Tests.Graphics.ExponentialFunctionTests.Interpolates_between_C0_and_C1_by_x_to_the_N`, `Broadside.Tests.Graphics.ExponentialFunctionTests.C0_and_C1_default_to_0_and_1`, `Broadside.Tests.Graphics.ExponentialFunctionTests.N_of_1_is_linear_interpolation`, `Broadside.Tests.Graphics.ExponentialFunctionTests.A_non_integer_N_with_a_domain_reaching_below_zero_is_noted_and_negative_inputs_give_C0`, `Broadside.Tests.Graphics.ExponentialFunctionTests.A_negative_N_at_zero_gives_C0`, `Broadside.Tests.Graphics.ExponentialFunctionTests.A_missing_N_makes_the_function_invalid_with_outputs_of_zero`, `Broadside.Tests.Graphics.ExponentialFunctionTests.C0_and_C1_of_different_lengths_use_the_shorter` | Domain restrictions checked at compile; a non-finite x^N gives C0 | +| 7.10.4 | Type 3 (stitching) functions | done | `PdfStitchingFunction`, `StitchingEvaluator` | `Broadside.Tests.Graphics.StitchingFunctionTests.Each_interval_of_example_1_selects_its_function_and_encodes_the_input`, `Broadside.Tests.Graphics.StitchingFunctionTests.An_encode_pair_in_reverse_order_turns_the_function_around`, `Broadside.Tests.Graphics.StitchingFunctionTests.The_range_of_the_stitching_function_clips_after_the_sub_functions_clip_their_own`, `Broadside.Tests.Graphics.StitchingFunctionTests.Stitching_functions_nest_eight_deep_but_not_nine`, `Broadside.Tests.Graphics.StitchingFunctionTests.A_stitching_function_that_contains_itself_is_invalid`, `Broadside.Tests.Graphics.StitchingFunctionTests.Bounds_out_of_order_are_used_as_given_with_a_diagnostic` | Every interval case of Example 1 (Domain0 = Bounds0 picks the first function, unlike pdf.js and PDFBox); nesting limited to 8; cycles are FunctionCycle | +| 7.10.5 | Type 4 (PostScript calculator) functions | done | `PdfPostScriptFunction`, `PostScriptLexer`, `PostScriptCompiler`, `PostScriptEvaluator` | `Broadside.Tests.Graphics.PostScriptFunctionTests.The_DoubleDot_spot_function_of_the_specification`, `Broadside.Tests.Graphics.PostScriptFunctionTests.The_LogoGreen_tint_transform_maps_a_tint_to_four_process_colorants`, `Broadside.Tests.Graphics.PostScriptFunctionTests.The_DeviceN_example_inserts_a_zero_component`, `Broadside.Tests.Graphics.PostScriptFunctionTests.A_hexachrome_tint_transform_maps_six_colorants_to_four`, `Broadside.Tests.Graphics.PostScriptFunctionTests.The_stack_holds_100_entries`, `Broadside.Tests.Graphics.PostScriptFunctionTests.Overflowing_the_stack_fails_the_evaluation_with_outputs_of_zero_clipped_to_the_range`, `Broadside.Tests.Graphics.PostScriptFunctionTests.Fewer_results_than_outputs_are_padded_with_zero_and_more_are_cut_to_the_topmost`, `Broadside.Tests.Graphics.PostScriptFunctionTests.A_boolean_result_is_1_or_0`, `Broadside.Tests.Graphics.PostScriptFunctionTests.Syntax_a_reader_can_repair_is_read_with_a_diagnostic`, `Broadside.Tests.Graphics.PostScriptFunctionTests.A_program_outside_the_subset_is_invalid`, `Broadside.Tests.Graphics.PostScriptFunctionTests.Braces_nest_256_deep_including_the_program_but_not_257` | Covers 7.10.5.1-7.10.5.3: compiled once to a flat instruction list with jumps, run over a 100-entry stack on the call stack (no allocation); double-precision arithmetic; static stack-depth check at compile | | 7.11 | File specifications | not started | | | | | 7.12 | Extensions dictionary | not started | | | | | 8.1 | Graphics: General | not started | | | | @@ -135,7 +139,7 @@ Clause numbers at the second level; split rows to the third level as clauses are | 14.12 | Document parts | not started | | | | | 14.13 | Associated files | not started | | | | | Annex A | Operator summary | not started | | | | -| Annex B | Operators in Type 4 functions | not started | | | | +| Annex B | Operators in Type 4 functions | done | `PostScriptEvaluator`, `PostScriptCompiler` | `Broadside.Tests.Graphics.PostScriptFunctionTests.Each_operator_matches_the_PLRM_examples`, `Broadside.Tests.Graphics.PostScriptFunctionTests.An_undefined_result_is_zero_and_noted_once`, `Broadside.Tests.Graphics.PostScriptFunctionTests.An_operand_of_the_wrong_type_is_converted_and_noted`, `Broadside.Tests.Graphics.PostScriptFunctionTests.Underflowing_the_stack_fails_the_evaluation` | B.2-B.5 with PLRM semantics (round halves up, logical bitshift, atan in [0, 360)); PostScript errors repaired and reported once per function (FunctionEvaluationRepaired) | | Annex C | Advice on maximising portability | not started | | | | | Annex D | Character sets and encodings | partial | `CosString` | `Broadside.Tests.Objects.TextStringTests.Decodes_pdfdocencoding_when_there_is_no_byte_order_marker` | D.3 PDFDocEncoding decodes text strings; the font encodings of D.2 and D.4 to D.6 pending | | Annex E | Extending PDF | not started | | | | diff --git a/src/Broadside/Graphics/Functions/CompiledFunction.cs b/src/Broadside/Graphics/Functions/CompiledFunction.cs new file mode 100644 index 00000000..48e69bbf --- /dev/null +++ b/src/Broadside/Graphics/Functions/CompiledFunction.cs @@ -0,0 +1,32 @@ +namespace Broadside.Graphics.Functions; + +/// An evaluator and the containers it was compiled from; stale once any of them has changed. +/// ISO 32000-2 §7.10; ADR 0004. Immutable apart from the once-only runtime report flag. +internal sealed class CompiledFunction(FunctionEvaluator evaluator, FunctionDependency[] dependencies) +{ + private int _reported; + + /// Gets the evaluator. + public FunctionEvaluator Evaluator { get; } = evaluator; + + /// Gets a value indicating whether every container the evaluator was compiled from is unchanged. + public bool IsCurrent + { + get + { + foreach (FunctionDependency dependency in dependencies) + { + if (!dependency.IsCurrent) + { + return false; + } + } + + return true; + } + } + + /// Claims the one runtime report this compilation makes. + /// for the first caller only. + public bool ClaimReport() => Interlocked.Exchange(ref _reported, 1) == 0; +} diff --git a/src/Broadside/Graphics/Functions/FunctionCache.cs b/src/Broadside/Graphics/Functions/FunctionCache.cs new file mode 100644 index 00000000..3126764f --- /dev/null +++ b/src/Broadside/Graphics/Functions/FunctionCache.cs @@ -0,0 +1,178 @@ +using System.Globalization; +using Broadside.Caching; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Graphics.Functions; + +/// +/// A document's functions: one view per function object (and expected arity), compiled once and shared by +/// every consumer and thread. +/// +/// +/// +/// ISO 32000-2 §7.10. Keyed by the indirect reference when the function is reached through one, else by the direct object instance, +/// plus its FunctionType (a view stands for one type) and the arity hints (they only matter for repairs). Built through +/// , so concurrent first uses compile once. +/// +/// +/// Consumers (tint transforms, transfer functions, shadings) call once per content run and evaluate the +/// result per sample; the evaluator reports nothing, so the consumer reports one +/// per function and page when an evaluation's status is not +/// . +/// +/// +internal sealed class FunctionCache +{ + private readonly PdfDocument _document; + private readonly DiagnosticSink _diagnostics; + private readonly OnceCache _functions = new(); + private readonly Func _resolve; + + /// Initializes a new instance of the class. + /// The document. + /// The document's diagnostics. + public FunctionCache(PdfDocument document, DiagnosticSink diagnostics) + { + _document = document; + _diagnostics = diagnostics; + _resolve = document.Resolve; + } + + /// Returns the view of a function object. + /// A function dictionary or stream, or a reference to one. + /// The number of inputs the consumer passes (repairs a missing Domain); 0 when unknown. + /// The number of outputs the consumer reads (repairs a missing Range); 0 when unknown. + /// The view; , with a diagnostic, when is not a function of a known type. + public PdfFunction? Get(CosObject value, int expectedInputs = 0, int expectedOutputs = 0) + { + CosObject resolved = _document.Resolve(value); + var reference = value as CosReference; + if (FunctionCompiler.ReadType(resolved, _resolve) is not { } type) + { + string what = FunctionCompiler.DictionaryOf(resolved) is null ? "is not a dictionary or a stream" : "has no FunctionType 0, 2, 3 or 4"; + _diagnostics.Report(DiagnosticCodes.FunctionInvalid, DiagnosticSeverity.Error, $"The function {what}.", offset: null, reference); + return null; + } + + var key = new Key((object?)reference ?? resolved, type, expectedInputs, expectedOutputs); + return _functions.GetOrCreate( + key, + (Cache: this, Resolved: resolved, Reference: reference), + static (key, state) => new Created(state.Cache.Create(state.Resolved, state.Reference, key)), + static (_, _) => null); + } + + /// Returns an evaluator for an entry that may also hold Identity or an array of functions. + /// The entry's value. + /// The forms the entry accepts besides a single function. + /// m, when the consumer knows it; 0 otherwise. + /// n, when the consumer knows it; 0 otherwise. + /// + /// The evaluator (possibly invalid: check ), or with a diagnostic + /// when the value is not a function in an accepted form. + /// + public FunctionEvaluator? GetEvaluator(CosObject value, FunctionForms forms, int expectedInputs, int expectedOutputs) + { + CosObject resolved = _document.Resolve(value); + var reference = value as CosReference; + if (resolved is CosName name && name.Equals(FunctionNames.Identity)) + { + if ((forms & FunctionForms.Identity) != 0) + { + return new IdentityEvaluator(Math.Clamp(expectedInputs > 0 ? expectedInputs : expectedOutputs, 1, FunctionEvaluator.MaxArity)); + } + + _diagnostics.Report(DiagnosticCodes.FunctionInvalid, DiagnosticSeverity.Error, "Identity is not allowed here; a function is required.", offset: null, reference); + return null; + } + + if (resolved is CosArray array) + { + return (forms & FunctionForms.Array) != 0 + ? CombineArray(array, reference, expectedInputs, expectedOutputs) + : ReportNotAllowed(reference, "An array of functions is not allowed here; a single function is required."); + } + + return Get(value, expectedInputs, expectedOutputs)?.Evaluator; + } + + /// Compiles a function for a view. + /// The function's dictionary or stream (direct). + /// Its reference, when it has one. + /// The view's type. + /// The arity hint for inputs. + /// The arity hint for outputs. + /// The compiled function. + internal CompiledFunction Compile(CosObject function, CosReference? reference, PdfFunctionType type, int expectedInputs, int expectedOutputs) + { + var compilation = new FunctionCompilation(_document, _diagnostics) { Reference = reference }; + FunctionEvaluator evaluator = FunctionCompiler.Compile(function, compilation, type, expectedInputs, expectedOutputs); + return new CompiledFunction(evaluator, compilation.Dependencies()); + } + + /// Resolves an object through the document. + /// The object. + /// The direct object. + internal CosObject Resolve(CosObject? value) => _document.Resolve(value); + + /// Records the one runtime diagnostic of a compiled function. + /// The view. + /// The status of the evaluation that went wrong. + internal void ReportEvaluation(PdfFunction function, FunctionStatus status) + { + string message = status == FunctionStatus.Failed + ? "The function could not be evaluated; its outputs are 0, clipped to its range." + : "The function's evaluation met an error (an undefined result, an operand of the wrong type or the wrong number of results); it was repaired."; + _diagnostics.Report( + DiagnosticCodes.FunctionEvaluationRepaired, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"Type {(int)function.FunctionType}: {message}"), + offset: null, + function.Reference); + } + + private PdfFunction Create(CosObject function, CosReference? reference, Key key) + { + CompiledFunction compiled = Compile(function, reference, key.Type, key.Inputs, key.Outputs); + return key.Type switch + { + PdfFunctionType.Sampled => new PdfSampledFunction(this, function, reference, compiled, key.Inputs, key.Outputs), + PdfFunctionType.Exponential => new PdfExponentialFunction(this, function, reference, compiled, key.Inputs, key.Outputs), + PdfFunctionType.Stitching => new PdfStitchingFunction(this, function, reference, compiled, key.Inputs, key.Outputs), + _ => new PdfPostScriptFunction(this, function, reference, compiled, key.Inputs, key.Outputs), + }; + } + + private ArrayEvaluator? CombineArray(CosArray array, CosReference? reference, int expectedInputs, int expectedOutputs) + { + if (array.Count == 0 || array.Count > FunctionEvaluator.MaxArity || (expectedOutputs > 0 && array.Count != expectedOutputs)) + { + return ReportNotAllowed(reference, "The array of functions is empty, too long, or does not have one function per output."); + } + + var functions = new FunctionEvaluator[array.Count]; + for (int j = 0; j < functions.Length; j++) + { + FunctionEvaluator? function = Get(array[j], expectedInputs, expectedOutputs: 1)?.Evaluator; + if (function is not { IsValid: true, OutputCount: 1 } || (j > 0 && function.InputCount != functions[0].InputCount)) + { + return ReportNotAllowed(reference, "An element of the array of functions is invalid, does not have one output, or has a different number of inputs."); + } + + functions[j] = function; + } + + return new ArrayEvaluator(FunctionCompilation.UnboundedPairs(functions[0].InputCount), functions); + } + + private ArrayEvaluator? ReportNotAllowed(CosReference? reference, string message) + { + _diagnostics.Report(DiagnosticCodes.FunctionInvalid, DiagnosticSeverity.Error, message, offset: null, reference); + return null; + } + + /// The cache key: the function's identity, its type and the arity hints. + private readonly record struct Key(object Identity, PdfFunctionType Type, int Inputs, int Outputs); +} diff --git a/src/Broadside/Graphics/Functions/FunctionCompilation.cs b/src/Broadside/Graphics/Functions/FunctionCompilation.cs new file mode 100644 index 00000000..6dbff2df --- /dev/null +++ b/src/Broadside/Graphics/Functions/FunctionCompilation.cs @@ -0,0 +1,245 @@ +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Graphics.Functions; + +/// +/// The state of compiling one function (and the functions it contains): the document it reads through, the diagnostics it reports, +/// the containers it read (for staleness), and the stitching functions being compiled (for cycles and depth). +/// +/// ISO 32000-2 §7.10. Used on one thread; a compilation is never shared. +internal sealed class FunctionCompilation +{ + /// How deeply stitching functions may nest before the innermost is rejected. + public const int MaxDepth = 8; + + private readonly PdfDocument _document; + private readonly DiagnosticSink _diagnostics; + private readonly List _dependencies = []; + private readonly HashSet _active = new(ReferenceEqualityComparer.Instance); + + /// Initializes a new instance of the class. + /// The document the function belongs to. + /// The document's diagnostics. + public FunctionCompilation(PdfDocument document, DiagnosticSink diagnostics) + { + _document = document; + _diagnostics = diagnostics; + } + + /// Gets or sets the reference of the function being compiled, for diagnostics; for a direct one. + public CosReference? Reference { get; set; } + + /// Gets the number of functions being compiled, outermost first. + public int Depth => _active.Count; + + /// Gets the containers read so far, with their versions. + /// The dependencies. + public FunctionDependency[] Dependencies() => [.. _dependencies]; + + /// Marks as being compiled. + /// The function's dictionary or stream. + /// when it is already being compiled further out: the function contains itself. + public bool Enter(CosObject function) => _active.Add(function); + + /// Marks as compiled. + /// The function's dictionary or stream. + public void Leave(CosObject function) => _active.Remove(function); + + /// Resolves through the document and records it when it is a container. + /// A direct object or a reference. + /// The direct object; for a missing one. + public CosObject Resolve(CosObject? value) + { + CosObject resolved = _document.Resolve(value); + Track(resolved); + return resolved; + } + + /// Records as read, when it is a container. + /// The object. + public void Track(CosObject value) + { + if (value is CosDictionary or CosArray or CosStream) + { + _dependencies.Add(new FunctionDependency(value, FunctionDependency.VersionOf(value))); + } + } + + /// Decodes a stream's data through its filters. + /// The stream. + /// The decoded data. + public ReadOnlyMemory Decode(CosStream stream) => _document.DecodeStream(stream); + + /// Records a diagnostic against the function being compiled. + /// The code. + /// The severity. + /// What was wrong and what was done. + public void Report(string code, DiagnosticSeverity severity, string message) => + _diagnostics.Report(code, severity, message, offset: null, Reference); + + /// Records a repaired entry (, Warning). + /// What was wrong and what was done. + public void Repaired(string message) => Report(DiagnosticCodes.FunctionEntryInvalid, DiagnosticSeverity.Warning, message); + + /// Records that the function cannot be used (, Error). + /// Why. + public void Invalid(string message) => Report(DiagnosticCodes.FunctionInvalid, DiagnosticSeverity.Error, message); + + /// Reads an entry that holds an array of numbers. + /// The function dictionary. + /// The key. + /// The numbers; when absent, or (with a diagnostic) when not an array of numbers. + public double[]? ReadNumbers(CosDictionary dictionary, CosName key) + { + if (!dictionary.TryGetValue(key, out CosObject? value)) + { + return null; + } + + if (Resolve(value) is not CosArray array) + { + Repaired($"{key.Value} is not an array; it is ignored."); + return null; + } + + double[] numbers = new double[array.Count]; + for (int i = 0; i < numbers.Length; i++) + { + if (Resolve(array[i]) is not CosNumber number) + { + Repaired($"{key.Value} holds something other than a number; it is ignored."); + return null; + } + + numbers[i] = number.ToDouble(); + } + + return numbers; + } + + /// Reads an entry that holds a number. + /// The function dictionary. + /// The key. + /// The number; when absent or not a number. + public double? ReadNumber(CosDictionary dictionary, CosName key) => + dictionary.TryGetValue(key, out CosObject? value) && Resolve(value) is CosNumber number ? number.ToDouble() : null; + + /// Reads the Domain entry (Table 38). + /// The function dictionary. + /// The number of inputs to assume, with a diagnostic, when Domain is missing; 0 when it cannot be inferred. + /// 2 × m numbers; (with a diagnostic) when there is no usable domain. + public double[]? ReadDomain(CosDictionary dictionary, int inferredInputs) + { + double[]? domain = ReadPairs(dictionary, FunctionNames.Domain); + if (domain is { Length: > 0 }) + { + if (domain.Length / 2 > FunctionEvaluator.MaxArity) + { + Invalid(string.Create(CultureInfo.InvariantCulture, $"Domain has {domain.Length / 2} inputs; at most {FunctionEvaluator.MaxArity} are supported.")); + return null; + } + + return domain; + } + + if (inferredInputs <= 0) + { + Invalid("Domain is missing and the number of inputs cannot be inferred."); + return null; + } + + Repaired(string.Create(CultureInfo.InvariantCulture, $"Domain is missing or empty; [0 1] is assumed for each of {inferredInputs} inputs.")); + return UnitPairs(inferredInputs); + } + + /// Reads the Range entry (Table 38). + /// The function dictionary. + /// 2 × n numbers, or when absent. + public double[]? ReadRange(CosDictionary dictionary) + { + double[]? range = ReadPairs(dictionary, FunctionNames.Range); + return range is { Length: > 0 } ? range : null; + } + + /// Fits a range to outputs: extra pairs are dropped and missing ones do not clip. + /// The range read, or . + /// n. + /// The fitted range, or when there is none. + public double[]? FitRange(double[]? range, int outputs) + { + if (range is null || range.Length == 2 * outputs) + { + return range; + } + + Repaired(string.Create(CultureInfo.InvariantCulture, $"Range has {range.Length / 2} pairs for {outputs} outputs; it is fitted to the outputs.")); + double[] fitted = new double[2 * outputs]; + for (int j = 0; j < outputs; j++) + { + bool present = (2 * j) + 1 < range.Length; + fitted[2 * j] = present ? range[2 * j] : double.NegativeInfinity; + fitted[(2 * j) + 1] = present ? range[(2 * j) + 1] : double.PositiveInfinity; + } + + return fitted; + } + + /// pairs [0 1]. + /// The number of pairs. + /// The pairs. + public static double[] UnitPairs(int count) + { + double[] pairs = new double[2 * count]; + for (int i = 0; i < count; i++) + { + pairs[(2 * i) + 1] = 1; + } + + return pairs; + } + + /// pairs [−∞ +∞], which clip nothing. + /// The number of pairs. + /// The pairs. + public static double[] UnboundedPairs(int count) + { + double[] pairs = new double[2 * count]; + for (int i = 0; i < count; i++) + { + pairs[2 * i] = double.NegativeInfinity; + pairs[(2 * i) + 1] = double.PositiveInfinity; + } + + return pairs; + } + + /// Reads an array of pairs: an odd last element is dropped and a decreasing pair is noted. + private double[]? ReadPairs(CosDictionary dictionary, CosName key) + { + double[]? numbers = ReadNumbers(dictionary, key); + if (numbers is null) + { + return null; + } + + if (numbers.Length % 2 != 0) + { + Repaired($"{key.Value} has an odd number of elements; the last is ignored."); + numbers = numbers[..^1]; + } + + for (int i = 0; i < numbers.Length; i += 2) + { + if (numbers[i] > numbers[i + 1]) + { + Repaired($"{key.Value} has a pair whose first number is greater than its second; values are clipped to the interval between them."); + break; + } + } + + return numbers; + } +} diff --git a/src/Broadside/Graphics/Functions/FunctionCompiler.cs b/src/Broadside/Graphics/Functions/FunctionCompiler.cs new file mode 100644 index 00000000..c987c54b --- /dev/null +++ b/src/Broadside/Graphics/Functions/FunctionCompiler.cs @@ -0,0 +1,270 @@ +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Graphics.Functions; + +/// Turns a function dictionary or stream into a , repairing what it can. +/// +/// ISO 32000-2 §7.10. Lenient: every deviation is a diagnostic, and a function that cannot be used compiles to an +/// . Strict mode throws from the first diagnostic of severity Warning or Error (ADR 0005). +/// +internal static class FunctionCompiler +{ + /// Reads the FunctionType of a function dictionary or stream. + /// A direct object. + /// Resolves an indirect FunctionType. + /// The type, or when is not a function. + public static PdfFunctionType? ReadType(CosObject function, Func resolve) + { + CosDictionary? dictionary = DictionaryOf(function); + if (dictionary is null || !dictionary.TryGetValue(FunctionNames.FunctionType, out CosObject? value) || resolve(value) is not CosInteger type) + { + return null; + } + + return type.Value switch + { + 0 => PdfFunctionType.Sampled, + 2 => PdfFunctionType.Exponential, + 3 => PdfFunctionType.Stitching, + 4 => PdfFunctionType.PostScriptCalculator, + _ => null, + }; + } + + /// The dictionary of a function: the dictionary itself, or a stream's dictionary. + /// A direct object. + /// The dictionary, or for any other object. + public static CosDictionary? DictionaryOf(CosObject function) => function switch + { + CosStream stream => stream.Dictionary, + CosDictionary dictionary => dictionary, + _ => null, + }; + + /// Compiles a function. + /// The function: a dictionary, a stream or a reference to one. + /// The compilation. + /// The type the caller's view stands for, or for any. + /// The number of inputs the consumer passes, used only to repair a missing Domain; 0 when unknown. + /// The number of outputs the consumer reads, used only to repair a missing Range; 0 when unknown. + /// The evaluator; an when the function cannot be used. + public static FunctionEvaluator Compile( + CosObject function, + FunctionCompilation compilation, + PdfFunctionType? expectedType, + int expectedInputs, + int expectedOutputs) + { + CosReference? outerReference = compilation.Reference; + if (function is CosReference reference) + { + compilation.Reference = reference; + } + + CosObject resolved = compilation.Resolve(function); + try + { + CosDictionary? dictionary = DictionaryOf(resolved); + if (dictionary is null) + { + compilation.Invalid("The function is not a dictionary or a stream."); + return Invalid(expectedInputs, expectedOutputs); + } + + if (resolved is CosStream) + { + compilation.Track(dictionary); + } + + if (compilation.Depth >= FunctionCompilation.MaxDepth) + { + compilation.Report(DiagnosticCodes.FunctionTooDeep, DiagnosticSeverity.Error, string.Create(CultureInfo.InvariantCulture, $"Functions nest more than {FunctionCompilation.MaxDepth} deep; the innermost is not used.")); + return Invalid(expectedInputs, expectedOutputs); + } + + if (!compilation.Enter(resolved)) + { + compilation.Report(DiagnosticCodes.FunctionCycle, DiagnosticSeverity.Error, "A stitching function contains itself."); + return Invalid(expectedInputs, expectedOutputs); + } + + try + { + PdfFunctionType? type = ReadType(resolved, compilation.Resolve); + if (type is null) + { + compilation.Invalid("FunctionType is missing or is not 0, 2, 3 or 4."); + return Invalid(expectedInputs, expectedOutputs); + } + + if (expectedType is { } expected && expected != type) + { + compilation.Invalid("FunctionType changed since the function was first read; read it again with PdfDocument.GetFunction."); + return Invalid(expectedInputs, expectedOutputs); + } + + if (type is PdfFunctionType.Sampled or PdfFunctionType.PostScriptCalculator && resolved is not CosStream) + { + compilation.Invalid("A Type 0 or Type 4 function shall be a stream."); + return Invalid(expectedInputs, expectedOutputs); + } + + return type switch + { + PdfFunctionType.Sampled => SampledCompiler.Compile((CosStream)resolved, compilation, expectedOutputs), + PdfFunctionType.Exponential => CompileExponential(dictionary, compilation), + PdfFunctionType.Stitching => CompileStitching(dictionary, compilation, expectedOutputs), + _ => PostScriptCompiler.Compile((CosStream)resolved, compilation, expectedInputs, expectedOutputs), + }; + } + finally + { + compilation.Leave(resolved); + } + } + finally + { + compilation.Reference = outerReference; + } + } + + /// An invalid function with the arity the consumer expects. + /// m, or 0. + /// n, or 0. + /// The range, when known. + /// The evaluator. + public static FunctionEvaluator Invalid(int inputs, int outputs, double[]? range = null) => + new InvalidEvaluator(FunctionCompilation.UnitPairs(Math.Clamp(inputs, 0, FunctionEvaluator.MaxArity)), range, Math.Clamp(outputs, 0, FunctionEvaluator.MaxArity)); + + /// Compiles a Type 2 function (§7.10.3, Table 40). + private static FunctionEvaluator CompileExponential(CosDictionary dictionary, FunctionCompilation compilation) + { + double[]? domain = OneInput(compilation.ReadDomain(dictionary, inferredInputs: 1), compilation, "Type 2"); + double[] c0 = compilation.ReadNumbers(dictionary, FunctionNames.C0) ?? [0.0]; + double[] c1 = compilation.ReadNumbers(dictionary, FunctionNames.C1) ?? [1.0]; + int outputs = Math.Min(c0.Length, c1.Length); + if (c0.Length != c1.Length) + { + compilation.Repaired(string.Create(CultureInfo.InvariantCulture, $"C0 has {c0.Length} numbers and C1 {c1.Length}; the first {outputs} of each are used.")); + } + + double[]? range = compilation.ReadRange(dictionary); + if (domain is null || outputs == 0 || outputs > FunctionEvaluator.MaxArity) + { + if (domain is not null) + { + compilation.Invalid("C0 and C1 give no usable number of outputs."); + } + + return Invalid(1, outputs, range); + } + + if (compilation.ReadNumber(dictionary, FunctionNames.N) is not { } exponent || !double.IsFinite(exponent)) + { + compilation.Invalid("N, the interpolation exponent, is missing or is not a number."); + return Invalid(1, outputs, range); + } + + double low = Math.Min(domain[0], domain[1]); + double high = Math.Max(domain[0], domain[1]); + if (exponent != Math.Floor(exponent) && low < 0) + { + compilation.Repaired("N is not an integer but Domain allows negative inputs; such inputs give C0."); + } + else if (exponent < 0 && low <= 0 && high >= 0) + { + compilation.Repaired("N is negative but Domain allows the input 0; that input gives C0."); + } + + return new ExponentialEvaluator(domain, compilation.FitRange(range, outputs), c0[..outputs], c1[..outputs], exponent); + } + + /// Compiles a Type 3 function (§7.10.4, Table 41). + private static FunctionEvaluator CompileStitching(CosDictionary dictionary, FunctionCompilation compilation, int expectedOutputs) + { + double[]? domain = OneInput(compilation.ReadDomain(dictionary, inferredInputs: 1), compilation, "Type 3"); + double[]? range = compilation.ReadRange(dictionary); + int fallbackOutputs = range is null ? expectedOutputs : range.Length / 2; + if (domain is null) + { + return Invalid(1, fallbackOutputs, range); + } + + if (!dictionary.TryGetValue(FunctionNames.Functions, out CosObject? value) || compilation.Resolve(value) is not CosArray { Count: > 0 } array) + { + compilation.Invalid("Functions is missing, empty or not an array."); + return Invalid(1, fallbackOutputs, range); + } + + int k = array.Count; + var functions = new FunctionEvaluator[k]; + for (int i = 0; i < k; i++) + { + FunctionEvaluator function = Compile(array[i], compilation, expectedType: null, expectedInputs: 1, expectedOutputs: fallbackOutputs); + if (!function.IsValid || function.InputCount != 1 || (i > 0 && function.OutputCount != functions[0].OutputCount)) + { + compilation.Invalid(string.Create(CultureInfo.InvariantCulture, $"Function {i} of Functions is invalid, does not take one input, or has a different number of outputs from the others.")); + return Invalid(1, fallbackOutputs, range); + } + + functions[i] = function; + } + + int outputs = functions[0].OutputCount; + double[]? bounds = compilation.ReadNumbers(dictionary, FunctionNames.Bounds); + if (bounds is null && k == 1) + { + compilation.Repaired("Bounds is missing; with one function it is empty."); + bounds = []; + } + + if (bounds is null || bounds.Length < k - 1) + { + compilation.Invalid(string.Create(CultureInfo.InvariantCulture, $"Bounds is missing or has fewer than the {k - 1} numbers {k} functions need.")); + return Invalid(1, outputs, range); + } + + if (bounds.Length > k - 1) + { + compilation.Repaired(string.Create(CultureInfo.InvariantCulture, $"Bounds has {bounds.Length} numbers; the first {k - 1} are used.")); + bounds = bounds[..(k - 1)]; + } + + double low = Math.Min(domain[0], domain[1]); + double high = Math.Max(domain[0], domain[1]); + for (int i = 0; i < bounds.Length; i++) + { + if (bounds[i] < low || bounds[i] > high || (i > 0 && bounds[i] <= bounds[i - 1])) + { + compilation.Repaired("Bounds is not increasing or lies outside Domain; it is used as given."); + break; + } + } + + double[] encode = compilation.ReadNumbers(dictionary, FunctionNames.Encode) ?? []; + if (encode.Length != 2 * k) + { + compilation.Repaired(string.Create(CultureInfo.InvariantCulture, $"Encode has {encode.Length} numbers for {k} functions; missing pairs are [0 1] and extra numbers are ignored.")); + double[] fitted = FunctionCompilation.UnitPairs(k); + encode.AsSpan(0, Math.Min(encode.Length, fitted.Length)).CopyTo(fitted); + encode = fitted; + } + + return new StitchingEvaluator(domain, compilation.FitRange(range, outputs), functions, bounds, encode); + } + + /// Keeps the first pair of a 1-input function's Domain. + private static double[]? OneInput(double[]? domain, FunctionCompilation compilation, string type) + { + if (domain is null || domain.Length == 2) + { + return domain; + } + + compilation.Repaired($"A {type} function takes one input; Domain pairs after the first are ignored."); + return domain[..2]; + } +} diff --git a/src/Broadside/Graphics/Functions/FunctionDependency.cs b/src/Broadside/Graphics/Functions/FunctionDependency.cs new file mode 100644 index 00000000..8ea001a3 --- /dev/null +++ b/src/Broadside/Graphics/Functions/FunctionDependency.cs @@ -0,0 +1,27 @@ +using Broadside.Objects; + +namespace Broadside.Graphics.Functions; + +/// A container a compiled function was built from, and its Version at the time. +/// A , or . +/// The container's version when it was read. +/// +/// ISO 32000-2 §7.10; ADR 0004 (live views). A compiled function is a snapshot of the COS objects it read; it is stale as soon as +/// one of them has changed through the public API, and is then compiled again. +/// +internal readonly record struct FunctionDependency(CosObject Container, int Version) +{ + /// Gets a value indicating whether the container is unchanged since it was read. + public bool IsCurrent => VersionOf(Container) == Version; + + /// The current version of a container; 0 for objects that cannot change. + /// The object. + /// Its version. + public static int VersionOf(CosObject value) => value switch + { + CosDictionary dictionary => dictionary.Version, + CosArray array => array.Version, + CosStream stream => stream.Version, + _ => 0, + }; +} diff --git a/src/Broadside/Graphics/Functions/FunctionEvaluator.cs b/src/Broadside/Graphics/Functions/FunctionEvaluator.cs new file mode 100644 index 00000000..90c57438 --- /dev/null +++ b/src/Broadside/Graphics/Functions/FunctionEvaluator.cs @@ -0,0 +1,151 @@ +namespace Broadside.Graphics.Functions; + +/// +/// A function compiled once from its dictionary or stream: immutable, safe to evaluate from any number of threads at once, never +/// allocating, never throwing for any input. +/// +/// +/// +/// ISO 32000-2 §7.10.1. The base class owns the rules every function type shares: inputs are clipped to the domain before the +/// type's own evaluation runs, and outputs are clipped to the range (when there is one) after it. A non-finite value never leaves: +/// it becomes 0 before range clipping, and values beyond the float range saturate when converted. +/// +/// +/// Arithmetic runs in double precision. Inputs are read from the first elements of the input span and the +/// first elements of the output span are written; callers size the spans (the public +/// checks them). +/// +/// +internal abstract class FunctionEvaluator +{ + /// The most inputs or outputs a function may have (an implementation limit, matching the 32 colourants of DeviceN). + public const int MaxArity = 32; + + private readonly double[] _domain; + private readonly double[]? _range; + + /// Initializes the shared part of an evaluator. + /// The domain, 2 × m numbers. A pair given in decreasing order clips to the interval between its ends. + /// The range, 2 × n numbers, or for no output clipping. + /// n. + protected FunctionEvaluator(double[] domain, double[]? range, int outputCount) + { + _domain = domain; + _range = range; + InputCount = domain.Length / 2; + OutputCount = outputCount; + } + + /// Gets m, the number of inputs. + public int InputCount { get; } + + /// Gets n, the number of outputs. + public int OutputCount { get; } + + /// Gets a value indicating whether the function could be compiled; an invalid one fails every evaluation. + public virtual bool IsValid => true; + + /// Evaluates the function at one point. + /// At least values. + /// At least values; receives the outputs. + /// How the evaluation went. + public FunctionStatus Evaluate(ReadOnlySpan input, Span output) + { + int m = InputCount; + Span clipped = stackalloc double[m]; + for (int i = 0; i < m; i++) + { + clipped[i] = Clip(input[i], _domain[2 * i], _domain[(2 * i) + 1]); + } + + output = output[..OutputCount]; + FunctionStatus status = EvaluateCore(clipped, output); + for (int j = 0; j < output.Length; j++) + { + double value = output[j]; + if (!double.IsFinite(value)) + { + value = 0; + status = Worse(status, FunctionStatus.Repaired); + } + + output[j] = _range is null ? value : Clip(value, _range[2 * j], _range[(2 * j) + 1]); + } + + return status; + } + + /// Evaluates the function at one point, in single precision. + /// At least values. + /// At least values; receives the outputs. + /// How the evaluation went. + public FunctionStatus Evaluate(ReadOnlySpan input, Span output) + { + Span x = stackalloc double[InputCount]; + Span y = stackalloc double[OutputCount]; + for (int i = 0; i < x.Length; i++) + { + x[i] = input[i]; + } + + FunctionStatus status = Evaluate(x, y); + for (int j = 0; j < y.Length; j++) + { + output[j] = (float)Math.Clamp(y[j], float.MinValue, float.MaxValue); + } + + return status; + } + + /// Evaluates the function at points stored one after the other. + /// At least × values, point after point. + /// At least × values; receives the outputs, point after point. + /// The number of points. + /// The worst status of the evaluations. + public FunctionStatus Evaluate(ReadOnlySpan inputs, Span outputs, int count) + { + int m = InputCount; + int n = OutputCount; + FunctionStatus status = FunctionStatus.Ok; + for (int k = 0; k < count; k++) + { + status = Worse(status, Evaluate(inputs.Slice(k * m, m), outputs.Slice(k * n, n))); + } + + return status; + } + + /// Clips to the interval between and ; NaN becomes the lower end. + /// The value. + /// One end, normally the lower. + /// The other end, normally the upper. + /// The clipped value. + internal static double Clip(double value, double first, double second) + { + double low = Math.Min(first, second); + double high = Math.Max(first, second); + return value >= low ? (value <= high ? value : high) : low; + } + + /// The Interpolate function of §7.10.1: the line through (xmin, ymin) and (xmax, ymax) at x; ymin when xmin = xmax. + /// x. + /// xmin. + /// xmax. + /// ymin. + /// ymax. + /// The interpolated value. + internal static double Interpolate(double x, double xMin, double xMax, double yMin, double yMax) => + xMax == xMin ? yMin : yMin + ((x - xMin) * (yMax - yMin) / (xMax - xMin)); + + /// The worse of two statuses. + /// One status. + /// The other. + /// The worse. + internal static FunctionStatus Worse(FunctionStatus left, FunctionStatus right) => left >= right ? left : right; + + /// The type's own evaluation, over inputs already clipped to the domain; the base clips the outputs. + /// Exactly clipped inputs. + /// Exactly outputs to write. + /// How the evaluation went. + protected abstract FunctionStatus EvaluateCore(ReadOnlySpan input, Span output); +} diff --git a/src/Broadside/Graphics/Functions/FunctionForms.cs b/src/Broadside/Graphics/Functions/FunctionForms.cs new file mode 100644 index 00000000..571bf71f --- /dev/null +++ b/src/Broadside/Graphics/Functions/FunctionForms.cs @@ -0,0 +1,23 @@ +namespace Broadside.Graphics.Functions; + +/// Which forms other than a single function object a consumer's entry accepts. +/// +/// ISO 32000-2 §8.4.5 Table 57 (TR, TR2: a function, an array of four functions or the name Identity), +/// §11.6.5.1 Table 142 (soft mask TR: a function or Identity), §8.7.4.5.2-8.7.4.5.4 Tables 78-80 (shading Function: a function +/// or an array of n 1-output functions). Tint transforms (§8.6.6.4, §8.6.6.5) accept a single function only. +/// +[Flags] +internal enum FunctionForms +{ + /// A single function dictionary or stream. + Single = 0, + + /// The name Identity is accepted: an m-in m-out function that returns its inputs. + Identity = 1, + + /// + /// An array of n functions of m inputs and one output each is accepted, combined into one m-in n-out function. A per-component + /// array (a TR array of four) is not this form; its consumer evaluates the elements separately. + /// + Array = 2, +} diff --git a/src/Broadside/Graphics/Functions/FunctionNames.cs b/src/Broadside/Graphics/Functions/FunctionNames.cs new file mode 100644 index 00000000..4d9bc023 --- /dev/null +++ b/src/Broadside/Graphics/Functions/FunctionNames.cs @@ -0,0 +1,49 @@ +using Broadside.Objects; + +namespace Broadside.Graphics.Functions; + +/// The keys of function dictionaries (ISO 32000-2 §7.10, Tables 38-41) and the Identity name. +internal static class FunctionNames +{ + /// /FunctionType (Table 38). + public static readonly CosName FunctionType = new("FunctionType"); + + /// /Domain (Table 38). + public static readonly CosName Domain = new("Domain"); + + /// /Range (Table 38). + public static readonly CosName Range = new("Range"); + + /// /Size (Table 39). + public static readonly CosName Size = new("Size"); + + /// /BitsPerSample (Table 39). + public static readonly CosName BitsPerSample = new("BitsPerSample"); + + /// /Order (Table 39). + public static readonly CosName Order = new("Order"); + + /// /Encode (Tables 39 and 41). + public static readonly CosName Encode = new("Encode"); + + /// /Decode (Table 39). + public static readonly CosName Decode = new("Decode"); + + /// /C0 (Table 40). + public static readonly CosName C0 = new("C0"); + + /// /C1 (Table 40). + public static readonly CosName C1 = new("C1"); + + /// /N (Table 40). + public static readonly CosName N = new("N"); + + /// /Functions (Table 41). + public static readonly CosName Functions = new("Functions"); + + /// /Bounds (Table 41). + public static readonly CosName Bounds = new("Bounds"); + + /// /Identity, which some entries accept in place of a function (§8.4.5 Table 57, §11.6.5.1 Table 142). + public static readonly CosName Identity = new("Identity"); +} diff --git a/src/Broadside/Graphics/Functions/FunctionStatus.cs b/src/Broadside/Graphics/Functions/FunctionStatus.cs new file mode 100644 index 00000000..2d1de83c --- /dev/null +++ b/src/Broadside/Graphics/Functions/FunctionStatus.cs @@ -0,0 +1,25 @@ +namespace Broadside.Graphics.Functions; + +/// How one evaluation of a function went. Evaluation never throws and never reports; the caller reports from this. +/// +/// ISO 32000-2 §7.10. A consumer that evaluates many samples reports at most one diagnostic per function and page +/// (DiagnosticCodes.FunctionEvaluationRepaired through DiagnosticSink.ReportOnce) when the status is not +/// . +/// +internal enum FunctionStatus +{ + /// Evaluated as the specification defines. + Ok = 0, + + /// + /// A deviation was repaired on the way: a Type 4 division by zero, an operand of the wrong type, the wrong number or kind of + /// results, an undefined result (square root of a negative number), or a non-finite intermediate value. + /// + Repaired = 1, + + /// + /// The function could not be evaluated (it is invalid, or a Type 4 program overflowed or underflowed its stack); every output is + /// 0 clipped to the range. + /// + Failed = 2, +} diff --git a/src/Broadside/Graphics/Functions/PostScriptCompiler.cs b/src/Broadside/Graphics/Functions/PostScriptCompiler.cs new file mode 100644 index 00000000..0a5a4287 --- /dev/null +++ b/src/Broadside/Graphics/Functions/PostScriptCompiler.cs @@ -0,0 +1,388 @@ +using System.Globalization; +using System.Text; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Graphics.Functions; + +/// Compiles Type 4 (PostScript calculator) functions into a flat instruction list. +/// +/// +/// ISO 32000-2 §7.10.5, Table 42, Annex B. One pass, no recursion: b {e} if becomes JumpIfFalse L; e; L: and +/// b {e1} {e2} ifelse becomes JumpIfFalse L1; e1; Jump L2; L1: e2; L2:, with the open bodies on an explicit stack +/// (at most 256 deep, braces of the program included; writers stay within 255). +/// +/// +/// Repaired with a diagnostic: a program without its opening or closing brace, text after the closing brace, a number written with an +/// exponent. Invalid: an operator outside Table 42, a body not followed by if or ifelse, any other syntax +/// (strings, arrays, names, radix numbers). A static pass over the stack depth notes a program that provably underflows, overflows or +/// leaves the wrong number of results; it still runs, with the run-time checks. +/// +/// +internal static class PostScriptCompiler +{ + /// The most nested braces, the program's own included. + public const int MaxNesting = 256; + + /// Compiles a Type 4 function. + /// The function stream. + /// The compilation. + /// The consumer's number of inputs, for a missing Domain; 0 when unknown. + /// The consumer's number of outputs, for a missing Range; 0 when unknown. + /// The evaluator. + public static FunctionEvaluator Compile(CosStream stream, FunctionCompilation compilation, int expectedInputs, int expectedOutputs) + { + CosDictionary dictionary = stream.Dictionary; + double[]? domain = compilation.ReadDomain(dictionary, expectedInputs); + if (domain is null) + { + return FunctionCompiler.Invalid(expectedInputs, expectedOutputs); + } + + int m = domain.Length / 2; + double[]? range = compilation.ReadRange(dictionary); + int n; + if (range is not null) + { + n = range.Length / 2; + } + else if (expectedOutputs > 0) + { + compilation.Repaired("Range is missing; the number of outputs comes from where the function is used and outputs are not clipped."); + n = expectedOutputs; + } + else + { + compilation.Invalid("Range is missing, so the number of outputs is unknown."); + return FunctionCompiler.Invalid(m, 0); + } + + if (n > FunctionEvaluator.MaxArity) + { + compilation.Invalid(string.Create(CultureInfo.InvariantCulture, $"Range has {n} outputs; at most {FunctionEvaluator.MaxArity} are supported.")); + return FunctionCompiler.Invalid(m, 0); + } + + PostScriptInstruction[]? code = Parse(compilation.Decode(stream).Span, compilation); + if (code is null) + { + return FunctionCompiler.Invalid(m, n, range); + } + + CheckStack(code, m, n, compilation); + return new PostScriptEvaluator(domain, range, n, code); + } + + /// Parses the program into instructions; (with a diagnostic) when it is not a valid program. + /// The program text. + /// The compilation, for diagnostics. + /// The instructions. + internal static PostScriptInstruction[]? Parse(ReadOnlySpan text, FunctionCompilation compilation) + { + var lexer = new PostScriptLexer(text); + var code = new List(); + var bodies = new List(); + bool exponents = false; + PostScriptToken token = lexer.Next(); + bool braced = token.Kind == PostScriptTokenKind.OpenBrace; + if (braced) + { + token = lexer.Next(); + } + else + { + compilation.Report(DiagnosticCodes.FunctionProgramSyntaxInvalid, DiagnosticSeverity.Warning, "The program does not start with {; it is read as if it did."); + } + + while (true) + { + switch (token.Kind) + { + case PostScriptTokenKind.End: + if (bodies.Count > 0) + { + return Invalid(compilation, "The program ends inside the body of an if or ifelse."); + } + + if (braced) + { + compilation.Report(DiagnosticCodes.FunctionProgramSyntaxInvalid, DiagnosticSeverity.Warning, "The program does not end with }; it is read as if it did."); + } + + return Finish(code, exponents, compilation); + + case PostScriptTokenKind.OpenBrace: + if (bodies.Count + 2 > MaxNesting) + { + return Invalid(compilation, string.Create(CultureInfo.InvariantCulture, $"Braces nest more than {MaxNesting} deep.")); + } + + bodies.Add(new Body(code.Count, First: true)); + code.Add(new PostScriptInstruction(PostScriptOpCode.JumpIfFalse)); + break; + + case PostScriptTokenKind.CloseBrace: + if (bodies.Count == 0) + { + if (lexer.Next().Kind != PostScriptTokenKind.End || !braced) + { + compilation.Report(DiagnosticCodes.FunctionProgramSyntaxInvalid, DiagnosticSeverity.Warning, "There is text after the } that closes the program; it is ignored."); + } + + return Finish(code, exponents, compilation); + } + + Body body = bodies[^1]; + bodies.RemoveAt(bodies.Count - 1); + PostScriptToken next = lexer.Next(); + if (body.First && IsName(lexer, next, "if"u8)) + { + code[body.Jump] = code[body.Jump] with { Target = code.Count }; + } + else if (body.First && next.Kind == PostScriptTokenKind.OpenBrace) + { + code[body.Jump] = code[body.Jump] with { Target = code.Count + 1 }; + bodies.Add(new Body(code.Count, First: false)); + code.Add(new PostScriptInstruction(PostScriptOpCode.Jump)); + } + else if (!body.First && IsName(lexer, next, "ifelse"u8)) + { + code[body.Jump] = code[body.Jump] with { Target = code.Count }; + } + else + { + return Invalid(compilation, body.First ? "A { } body is not followed by if or by a second body and ifelse." : "Two { } bodies are not followed by ifelse."); + } + + break; + + case PostScriptTokenKind.Integer: + code.Add(new PostScriptInstruction(PostScriptOpCode.PushInteger, Literal: token.Number)); + break; + + case PostScriptTokenKind.Real: + exponents |= token.HasExponent; + code.Add(new PostScriptInstruction(PostScriptOpCode.PushReal, Literal: token.Number)); + break; + + case PostScriptTokenKind.Name: + ReadOnlySpan name = lexer.TextOf(token); + if (name.SequenceEqual("true"u8) || name.SequenceEqual("false"u8)) + { + code.Add(new PostScriptInstruction(PostScriptOpCode.PushBoolean, Literal: name[0] == 't' ? 1 : 0)); + } + else if (Operator(name) is { } opCode) + { + code.Add(new PostScriptInstruction(opCode)); + } + else + { + return Invalid(compilation, $"'{Encoding.Latin1.GetString(name)}' is not an operator of Type 4 functions, or is not after a {{ }} body."); + } + + break; + + default: + return Invalid(compilation, $"'{Encoding.Latin1.GetString(lexer.TextOf(token))}' is not allowed in a Type 4 function."); + } + + token = lexer.Next(); + } + } + + private static PostScriptInstruction[] Finish(List code, bool exponents, FunctionCompilation compilation) + { + if (exponents) + { + compilation.Report(DiagnosticCodes.FunctionProgramSyntaxInvalid, DiagnosticSeverity.Warning, "A number is written with an exponent, which PDF syntax does not allow; it is read."); + } + + return [.. code]; + } + + private static PostScriptInstruction[]? Invalid(FunctionCompilation compilation, string message) + { + compilation.Invalid(message); + return null; + } + + private static bool IsName(PostScriptLexer lexer, PostScriptToken token, ReadOnlySpan name) => + token.Kind == PostScriptTokenKind.Name && lexer.TextOf(token).SequenceEqual(name); + + private static PostScriptOpCode? Operator(ReadOnlySpan name) => Encoding.ASCII.GetString(name) switch + { + "abs" => PostScriptOpCode.Abs, + "add" => PostScriptOpCode.Add, + "atan" => PostScriptOpCode.Atan, + "ceiling" => PostScriptOpCode.Ceiling, + "cos" => PostScriptOpCode.Cos, + "cvi" => PostScriptOpCode.Cvi, + "cvr" => PostScriptOpCode.Cvr, + "div" => PostScriptOpCode.Div, + "exp" => PostScriptOpCode.Exp, + "floor" => PostScriptOpCode.Floor, + "idiv" => PostScriptOpCode.Idiv, + "ln" => PostScriptOpCode.Ln, + "log" => PostScriptOpCode.Log, + "mod" => PostScriptOpCode.Mod, + "mul" => PostScriptOpCode.Mul, + "neg" => PostScriptOpCode.Neg, + "round" => PostScriptOpCode.Round, + "sin" => PostScriptOpCode.Sin, + "sqrt" => PostScriptOpCode.Sqrt, + "sub" => PostScriptOpCode.Sub, + "truncate" => PostScriptOpCode.Truncate, + "and" => PostScriptOpCode.And, + "bitshift" => PostScriptOpCode.Bitshift, + "eq" => PostScriptOpCode.Eq, + "ge" => PostScriptOpCode.Ge, + "gt" => PostScriptOpCode.Gt, + "le" => PostScriptOpCode.Le, + "lt" => PostScriptOpCode.Lt, + "ne" => PostScriptOpCode.Ne, + "not" => PostScriptOpCode.Not, + "or" => PostScriptOpCode.Or, + "xor" => PostScriptOpCode.Xor, + "copy" => PostScriptOpCode.Copy, + "dup" => PostScriptOpCode.Dup, + "exch" => PostScriptOpCode.Exch, + "index" => PostScriptOpCode.Index, + "pop" => PostScriptOpCode.Pop, + "roll" => PostScriptOpCode.Roll, + _ => null, + }; + + /// + /// Follows the stack depth through every path (jumps only go forward, so one pass in order sees every path) and notes a + /// program that provably underflows, overflows or ends with other than n values. Stops quietly where the depth stops being + /// known: copy, index or roll with a computed operand, or branches that leave different depths. + /// + private static void CheckStack(PostScriptInstruction[] code, int m, int n, FunctionCompilation compilation) + { + const int unreached = -1; + int[] depths = new int[code.Length + 1]; + Array.Fill(depths, unreached); + depths[0] = m; + for (int pc = 0; pc < code.Length; pc++) + { + int depth = depths[pc]; + if (depth == unreached) + { + continue; + } + + PostScriptInstruction instruction = code[pc]; + if (!Effect(code, pc, out int needed, out int change)) + { + return; + } + + if (depth < needed) + { + compilation.Report(DiagnosticCodes.FunctionProgramStackInvalid, DiagnosticSeverity.Warning, "The program takes more values from the stack than it holds."); + return; + } + + int after = depth + change; + if (after > PostScriptEvaluator.StackLimit) + { + compilation.Report(DiagnosticCodes.FunctionProgramStackInvalid, DiagnosticSeverity.Warning, string.Create(CultureInfo.InvariantCulture, $"The program needs more than the {PostScriptEvaluator.StackLimit} stack entries a reader provides.")); + return; + } + + bool merged = instruction.OpCode switch + { + PostScriptOpCode.Jump => Merge(depths, instruction.Target, after), + PostScriptOpCode.JumpIfFalse => Merge(depths, instruction.Target, after) && Merge(depths, pc + 1, after), + _ => Merge(depths, pc + 1, after), + }; + if (!merged) + { + return; + } + } + + if (depths[code.Length] is int final and not unreached && final != n) + { + compilation.Report(DiagnosticCodes.FunctionProgramStackInvalid, DiagnosticSeverity.Warning, string.Create(CultureInfo.InvariantCulture, $"The program leaves {final} values on the stack but Range has {n} outputs.")); + } + } + + private static bool Merge(int[] depths, int target, int depth) + { + if (depths[target] == -1) + { + depths[target] = depth; + return true; + } + + return depths[target] == depth; + } + + /// How many values an instruction needs and how it changes the depth; when that is not known. + private static bool Effect(PostScriptInstruction[] code, int pc, out int needed, out int change) + { + (needed, change) = code[pc].OpCode switch + { + PostScriptOpCode.PushReal or PostScriptOpCode.PushInteger or PostScriptOpCode.PushBoolean => (0, 1), + PostScriptOpCode.Jump => (0, 0), + PostScriptOpCode.JumpIfFalse or PostScriptOpCode.Pop => (1, -1), + PostScriptOpCode.Abs or PostScriptOpCode.Ceiling or PostScriptOpCode.Cos or PostScriptOpCode.Cvi or PostScriptOpCode.Cvr + or PostScriptOpCode.Floor or PostScriptOpCode.Ln or PostScriptOpCode.Log or PostScriptOpCode.Neg or PostScriptOpCode.Round + or PostScriptOpCode.Sin or PostScriptOpCode.Sqrt or PostScriptOpCode.Truncate or PostScriptOpCode.Not => (1, 0), + PostScriptOpCode.Dup => (1, 1), + PostScriptOpCode.Exch => (2, 0), + PostScriptOpCode.Copy or PostScriptOpCode.Index or PostScriptOpCode.Roll => (-1, 0), + _ => (2, -1), + }; + if (needed >= 0) + { + return true; + } + + // copy, index and roll: known only when their operands are literal integers pushed just before (and nothing jumps between). + bool Literal(int at, out int value) + { + value = 0; + if (at < 0 || code[at].OpCode != PostScriptOpCode.PushInteger || JumpsInto(code, at + 1, pc)) + { + return false; + } + + value = (int)code[at].Literal; + return value >= 0; + } + + switch (code[pc].OpCode) + { + case PostScriptOpCode.Copy when Literal(pc - 1, out int count): + (needed, change) = (count + 1, count - 1); + return true; + case PostScriptOpCode.Index when Literal(pc - 1, out int index): + (needed, change) = (index + 2, 0); + return true; + case PostScriptOpCode.Roll when Literal(pc - 2, out int count) && code[pc - 1].OpCode == PostScriptOpCode.PushInteger: + (needed, change) = (count + 2, -2); + return true; + default: + return false; + } + } + + private static bool JumpsInto(PostScriptInstruction[] code, int first, int last) + { + foreach (PostScriptInstruction instruction in code) + { + if (instruction.OpCode is PostScriptOpCode.Jump or PostScriptOpCode.JumpIfFalse && instruction.Target >= first && instruction.Target <= last) + { + return true; + } + } + + return false; + } + + /// A body being compiled: where its jump is, and whether it is the first body (of if or ifelse). + private readonly record struct Body(int Jump, bool First); +} diff --git a/src/Broadside/Graphics/Functions/PostScriptEvaluator.cs b/src/Broadside/Graphics/Functions/PostScriptEvaluator.cs new file mode 100644 index 00000000..83c2320e --- /dev/null +++ b/src/Broadside/Graphics/Functions/PostScriptEvaluator.cs @@ -0,0 +1,563 @@ +using System.Runtime.CompilerServices; + +namespace Broadside.Graphics.Functions; + +/// Runs a compiled Type 4 program over an operand stack on the call stack. +/// +/// +/// ISO 32000-2 §7.10.5; the operators mean what PLRM §8.2 says. The stack holds entries (§7.10.5.3: "at +/// least 100"), each a real, a 32-bit integer or a boolean. The inputs are pushed as reals, first input deepest; the top n entries +/// left are the outputs, deepest first. +/// +/// +/// Integer arithmetic stays integer while the result fits in 32 bits (add, sub, mul, abs, neg, +/// idiv), as PostScript does. round rounds halves up (−6.5 to −6); sin and cos take degrees and are exact +/// at multiples of 90; atan returns degrees in [0, 360); bitshift shifts in zeros on either side, as PLRM says. The +/// errors PostScript raises are repaired and reported through : an undefined result (division by +/// zero, the square root or logarithm of a number out of their domain, 0 0 atan) is 0, an operand of the wrong type is +/// converted (a boolean to 1 or 0, a real to an integer by truncation), a number used as a condition is true when it is not 0, the +/// wrong number of results is cut to the topmost or padded with 0, and a boolean result is 1 or 0. A stack overflow or underflow, or +/// a copy, index or roll outside the stack, fails the evaluation (). +/// +/// +internal sealed class PostScriptEvaluator : FunctionEvaluator +{ + /// The number of operand stack entries. + public const int StackLimit = 100; + + private const byte Real = 0; + private const byte Integer = 1; + private const byte Boolean = 2; + + private readonly PostScriptInstruction[] _code; + + /// Initializes a new instance of the class. + /// m pairs. + /// n pairs, or when missing (repaired). + /// n. + /// The compiled program. + public PostScriptEvaluator(double[] domain, double[]? range, int outputCount, PostScriptInstruction[] code) + : base(domain, range, outputCount) + { + _code = code; + } + + /// + [SkipLocalsInit] + protected override FunctionStatus EvaluateCore(ReadOnlySpan input, Span output) + { + Span values = stackalloc double[StackLimit]; + Span kinds = stackalloc byte[StackLimit]; + int sp = 0; + for (; sp < input.Length; sp++) + { + values[sp] = input[sp]; + kinds[sp] = Real; + } + + bool repaired = false; + ReadOnlySpan code = _code; + int pc = 0; + while (pc < code.Length) + { + PostScriptInstruction instruction = code[pc++]; + int a = sp - 2; + int b = sp - 1; + switch (instruction.OpCode) + { + case PostScriptOpCode.PushReal: + case PostScriptOpCode.PushInteger: + case PostScriptOpCode.PushBoolean: + if (sp == StackLimit) + { + return Fail(output); + } + + values[sp] = instruction.Literal; + kinds[sp++] = instruction.OpCode switch + { + PostScriptOpCode.PushReal => Real, + PostScriptOpCode.PushInteger => Integer, + _ => Boolean, + }; + break; + + case PostScriptOpCode.JumpIfFalse: + if (sp < 1) + { + return Fail(output); + } + + sp--; + repaired |= kinds[sp] != Boolean; + if (values[sp] == 0 || double.IsNaN(values[sp])) + { + pc = instruction.Target; + } + + break; + + case PostScriptOpCode.Jump: + pc = instruction.Target; + break; + + case PostScriptOpCode.Add: + case PostScriptOpCode.Sub: + case PostScriptOpCode.Mul: + { + if (sp < 2) + { + return Fail(output); + } + + Numeric(kinds, a, ref repaired); + Numeric(kinds, b, ref repaired); + double x = values[a]; + double y = values[b]; + double result = instruction.OpCode switch + { + PostScriptOpCode.Add => x + y, + PostScriptOpCode.Sub => x - y, + _ => x * y, + }; + if (!double.IsFinite(result)) + { + result = 0; + repaired = true; + } + + SetNumber(values, kinds, a, result, kinds[a] == Integer && kinds[b] == Integer); + sp--; + break; + } + + case PostScriptOpCode.Div: + case PostScriptOpCode.Atan: + case PostScriptOpCode.Exp: + { + if (sp < 2) + { + return Fail(output); + } + + Numeric(kinds, a, ref repaired); + Numeric(kinds, b, ref repaired); + double x = values[a]; + double y = values[b]; + double result = instruction.OpCode switch + { + PostScriptOpCode.Div => y == 0 ? double.NaN : x / y, + PostScriptOpCode.Atan => x == 0 && y == 0 ? double.NaN : Degrees(x, y), + _ => Math.Pow(x, y), + }; + if (!double.IsFinite(result)) + { + result = 0; + repaired = true; + } + + values[a] = result; + kinds[a] = Real; + sp--; + break; + } + + case PostScriptOpCode.Idiv: + case PostScriptOpCode.Mod: + { + if (sp < 2) + { + return Fail(output); + } + + long x = ToInteger(values, kinds, a, ref repaired); + long y = ToInteger(values, kinds, b, ref repaired); + double result = 0; + if (y == 0) + { + repaired = true; + } + else + { + result = instruction.OpCode == PostScriptOpCode.Idiv ? x / y : x % y; + } + + SetNumber(values, kinds, a, result, integer: true); + sp--; + break; + } + + case PostScriptOpCode.Abs: + case PostScriptOpCode.Neg: + case PostScriptOpCode.Ceiling: + case PostScriptOpCode.Floor: + case PostScriptOpCode.Round: + case PostScriptOpCode.Truncate: + { + if (sp < 1) + { + return Fail(output); + } + + Numeric(kinds, b, ref repaired); + double x = values[b]; + double result = instruction.OpCode switch + { + PostScriptOpCode.Abs => Math.Abs(x), + PostScriptOpCode.Neg => -x, + PostScriptOpCode.Ceiling => Math.Ceiling(x), + PostScriptOpCode.Floor => Math.Floor(x), + PostScriptOpCode.Round => Math.Floor(x + 0.5), + _ => Math.Truncate(x), + }; + SetNumber(values, kinds, b, result, kinds[b] == Integer); + break; + } + + case PostScriptOpCode.Sqrt: + case PostScriptOpCode.Sin: + case PostScriptOpCode.Cos: + case PostScriptOpCode.Ln: + case PostScriptOpCode.Log: + case PostScriptOpCode.Cvr: + { + if (sp < 1) + { + return Fail(output); + } + + Numeric(kinds, b, ref repaired); + double x = values[b]; + double result = instruction.OpCode switch + { + PostScriptOpCode.Sqrt => x >= 0 ? Math.Sqrt(x) : double.NaN, + PostScriptOpCode.Sin => double.SinPi(x % 360 / 180), + PostScriptOpCode.Cos => double.CosPi(x % 360 / 180), + PostScriptOpCode.Ln => x > 0 ? Math.Log(x) : double.NaN, + PostScriptOpCode.Log => x > 0 ? Math.Log10(x) : double.NaN, + _ => x, + }; + if (!double.IsFinite(result)) + { + result = 0; + repaired = true; + } + + values[b] = result; + kinds[b] = Real; + break; + } + + case PostScriptOpCode.Cvi: + { + if (sp < 1) + { + return Fail(output); + } + + double x = values[b]; + if (kinds[b] == Boolean) + { + repaired = true; + } + else if (kinds[b] == Real) + { + if (!(x > int.MinValue - 1.0 && x < int.MaxValue + 1.0)) + { + repaired = true; + x = double.IsNaN(x) ? 0 : Math.Clamp(x, int.MinValue, int.MaxValue); + } + + x = Math.Truncate(x); + } + + values[b] = x; + kinds[b] = Integer; + break; + } + + case PostScriptOpCode.Eq: + case PostScriptOpCode.Ne: + { + if (sp < 2) + { + return Fail(output); + } + + bool equal = (kinds[a] == Boolean) == (kinds[b] == Boolean) && values[a] == values[b]; + values[a] = equal == (instruction.OpCode == PostScriptOpCode.Eq) ? 1 : 0; + kinds[a] = Boolean; + sp--; + break; + } + + case PostScriptOpCode.Ge: + case PostScriptOpCode.Gt: + case PostScriptOpCode.Le: + case PostScriptOpCode.Lt: + { + if (sp < 2) + { + return Fail(output); + } + + Numeric(kinds, a, ref repaired); + Numeric(kinds, b, ref repaired); + double x = values[a]; + double y = values[b]; + bool result = instruction.OpCode switch + { + PostScriptOpCode.Ge => x >= y, + PostScriptOpCode.Gt => x > y, + PostScriptOpCode.Le => x <= y, + _ => x < y, + }; + values[a] = result ? 1 : 0; + kinds[a] = Boolean; + sp--; + break; + } + + case PostScriptOpCode.And: + case PostScriptOpCode.Or: + case PostScriptOpCode.Xor: + { + if (sp < 2) + { + return Fail(output); + } + + bool logical = kinds[a] == Boolean && kinds[b] == Boolean; + int x = ToInteger(values, kinds, a, ref repaired, logical); + int y = ToInteger(values, kinds, b, ref repaired, logical); + int result = instruction.OpCode switch + { + PostScriptOpCode.And => x & y, + PostScriptOpCode.Or => x | y, + _ => x ^ y, + }; + values[a] = result; + kinds[a] = logical ? Boolean : Integer; + sp--; + break; + } + + case PostScriptOpCode.Not: + if (sp < 1) + { + return Fail(output); + } + + if (kinds[b] == Boolean) + { + values[b] = values[b] == 0 ? 1 : 0; + } + else + { + values[b] = ~ToInteger(values, kinds, b, ref repaired); + kinds[b] = Integer; + } + + break; + + case PostScriptOpCode.Bitshift: + { + if (sp < 2) + { + return Fail(output); + } + + uint x = (uint)ToInteger(values, kinds, a, ref repaired); + int shift = ToInteger(values, kinds, b, ref repaired); + uint result = shift switch + { + >= 32 or <= -32 => 0, + >= 0 => x << shift, + _ => x >> -shift, + }; + values[a] = (int)result; + kinds[a] = Integer; + sp--; + break; + } + + case PostScriptOpCode.Dup: + if (sp < 1 || sp == StackLimit) + { + return Fail(output); + } + + values[sp] = values[b]; + kinds[sp++] = kinds[b]; + break; + + case PostScriptOpCode.Exch: + if (sp < 2) + { + return Fail(output); + } + + (values[a], values[b]) = (values[b], values[a]); + (kinds[a], kinds[b]) = (kinds[b], kinds[a]); + break; + + case PostScriptOpCode.Pop: + if (sp < 1) + { + return Fail(output); + } + + sp--; + break; + + case PostScriptOpCode.Copy: + { + if (sp < 1) + { + return Fail(output); + } + + int count = ToInteger(values, kinds, b, ref repaired); + sp--; + if (count < 0 || count > sp || sp + count > StackLimit) + { + return Fail(output); + } + + values.Slice(sp - count, count).CopyTo(values[sp..]); + kinds.Slice(sp - count, count).CopyTo(kinds[sp..]); + sp += count; + break; + } + + case PostScriptOpCode.Index: + { + if (sp < 1) + { + return Fail(output); + } + + int index = ToInteger(values, kinds, b, ref repaired); + if (index < 0 || index >= b) + { + return Fail(output); + } + + values[b] = values[b - 1 - index]; + kinds[b] = kinds[b - 1 - index]; + break; + } + + case PostScriptOpCode.Roll: + { + if (sp < 2) + { + return Fail(output); + } + + int count = ToInteger(values, kinds, a, ref repaired); + int shift = ToInteger(values, kinds, b, ref repaired); + sp -= 2; + if (count < 0 || count > sp) + { + return Fail(output); + } + + if (count > 1) + { + Roll(values.Slice(sp - count, count), kinds.Slice(sp - count, count), (int)(((shift % (long)count) + count) % count)); + } + + break; + } + + default: + return Fail(output); + } + } + + int n = output.Length; + repaired |= sp != n; + int first = Math.Max(sp - n, 0); + for (int j = 0; j < n; j++) + { + int at = first + j; + if (at < sp) + { + repaired |= kinds[at] == Boolean; + output[j] = values[at]; + } + else + { + output[j] = 0; + } + } + + return repaired ? FunctionStatus.Repaired : FunctionStatus.Ok; + } + + private static FunctionStatus Fail(Span output) + { + output.Clear(); + return FunctionStatus.Failed; + } + + /// Makes the entry a number: a boolean becomes the integer 1 or 0 (a typecheck error in PostScript). + private static void Numeric(Span kinds, int at, ref bool repaired) + { + if (kinds[at] == Boolean) + { + kinds[at] = Integer; + repaired = true; + } + } + + /// Stores a numeric result: an integer when both operands were and the result fits in 32 bits, else a real. + private static void SetNumber(Span values, Span kinds, int at, double result, bool integer) + { + values[at] = result; + kinds[at] = integer && result >= int.MinValue && result <= int.MaxValue ? Integer : Real; + } + + /// Reads an entry as a 32-bit integer: a real is truncated and clamped, a boolean is 1 or 0 (noted unless allowed). + private static int ToInteger(Span values, Span kinds, int at, ref bool repaired, bool booleanAllowed = false) + { + double value = values[at]; + if (kinds[at] == Integer) + { + return (int)value; + } + + if (kinds[at] == Boolean) + { + repaired |= !booleanAllowed; + return value == 0 ? 0 : 1; + } + + repaired = true; + return double.IsNaN(value) ? 0 : (int)Math.Clamp(Math.Truncate(value), int.MinValue, int.MaxValue); + } + + /// The angle of (den, num) in degrees, in [0, 360). + private static double Degrees(double numerator, double denominator) + { + double degrees = Math.Atan2(numerator, denominator) * (180 / Math.PI); + return degrees < 0 ? degrees + 360 : degrees; + } + + /// Rotates the entries places toward the top (PLRM roll with a positive j). + private static void Roll(Span values, Span kinds, int shift) + { + if (shift == 0) + { + return; + } + + values.Reverse(); + values[..shift].Reverse(); + values[shift..].Reverse(); + kinds.Reverse(); + kinds[..shift].Reverse(); + kinds[shift..].Reverse(); + } +} diff --git a/src/Broadside/Graphics/Functions/PostScriptInstruction.cs b/src/Broadside/Graphics/Functions/PostScriptInstruction.cs new file mode 100644 index 00000000..cc2aee55 --- /dev/null +++ b/src/Broadside/Graphics/Functions/PostScriptInstruction.cs @@ -0,0 +1,141 @@ +namespace Broadside.Graphics.Functions; + +/// The instructions a Type 4 program compiles to: the operators of Table 42 plus pushes and jumps. +/// ISO 32000-2 §7.10.5.2, Table 42, Annex B. true and false compile to . +internal enum PostScriptOpCode : byte +{ + /// Push the literal as a real. + PushReal, + + /// Push the literal as an integer. + PushInteger, + + /// Push the literal (0 or 1) as a boolean. + PushBoolean, + + /// Pop a boolean; jump to the target when it is false (the start of {…} if or {…} {…} ifelse). + JumpIfFalse, + + /// Jump to the target (the end of the first body of ifelse). + Jump, + + /// abs (B.2). + Abs, + + /// add (B.2). + Add, + + /// atan (B.2). + Atan, + + /// ceiling (B.2). + Ceiling, + + /// cos (B.2). + Cos, + + /// cvi (B.2). + Cvi, + + /// cvr (B.2). + Cvr, + + /// div (B.2). + Div, + + /// exp (B.2). + Exp, + + /// floor (B.2). + Floor, + + /// idiv (B.2). + Idiv, + + /// ln (B.2). + Ln, + + /// log (B.2). + Log, + + /// mod (B.2). + Mod, + + /// mul (B.2). + Mul, + + /// neg (B.2). + Neg, + + /// round (B.2). + Round, + + /// sin (B.2). + Sin, + + /// sqrt (B.2). + Sqrt, + + /// sub (B.2). + Sub, + + /// truncate (B.2). + Truncate, + + /// and (B.3). + And, + + /// bitshift (B.3). + Bitshift, + + /// eq (B.3). + Eq, + + /// ge (B.3). + Ge, + + /// gt (B.3). + Gt, + + /// le (B.3). + Le, + + /// lt (B.3). + Lt, + + /// ne (B.3). + Ne, + + /// not (B.3). + Not, + + /// or (B.3). + Or, + + /// xor (B.3). + Xor, + + /// copy (B.5). + Copy, + + /// dup (B.5). + Dup, + + /// exch (B.5). + Exch, + + /// index (B.5). + Index, + + /// pop (B.5). + Pop, + + /// roll (B.5). + Roll, +} + +/// One instruction of a compiled Type 4 program. +/// What to do. +/// The instruction index a jump goes to. +/// The value a push pushes. +internal readonly record struct PostScriptInstruction(PostScriptOpCode OpCode, int Target = 0, double Literal = 0); diff --git a/src/Broadside/Graphics/Functions/PostScriptLexer.cs b/src/Broadside/Graphics/Functions/PostScriptLexer.cs new file mode 100644 index 00000000..14d2dac1 --- /dev/null +++ b/src/Broadside/Graphics/Functions/PostScriptLexer.cs @@ -0,0 +1,163 @@ +using System.Buffers; +using System.Globalization; + +namespace Broadside.Graphics.Functions; + +/// The kinds of token in a Type 4 program. +internal enum PostScriptTokenKind +{ + /// The end of the program text. + End, + + /// {. + OpenBrace, + + /// }. + CloseBrace, + + /// An integer that fits in 32 bits. + Integer, + + /// A real, or an integer too large for 32 bits (a real in PostScript). + Real, + + /// A run of regular characters that is not a number: an operator name, or something unknown. + Name, + + /// A delimiter the subset does not allow (strings, arrays, dictionaries, literal names) or a malformed number. + Invalid, +} + +/// One token of a Type 4 program. +/// The kind. +/// The offset of its first byte. +/// Its length in bytes. +/// The value of a number. +/// Whether a real was written with an exponent, which PDF number syntax does not have. +internal readonly record struct PostScriptToken(PostScriptTokenKind Kind, int Start, int Length, double Number = 0, bool HasExponent = false); + +/// Splits the text of a Type 4 function into tokens. +/// +/// ISO 32000-2 §7.10.5.2: operands follow PDF conventions (§7.3.3 numbers, no radix notation), white-space and comments follow §7.2.3 +/// and §7.2.4, and braces delimit the program and the bodies of if and ifelse. A real written with an exponent, which +/// PostScript allows and PDF does not, is read (and flagged). +/// +internal ref struct PostScriptLexer +{ + private static readonly SearchValues Delimiters = SearchValues.Create("\0\t\n\f\r ()<>[]{}/%"u8); + + private readonly ReadOnlySpan _text; + private int _position; + + /// Initializes a new instance of the struct. + /// The decoded stream data. + public PostScriptLexer(ReadOnlySpan text) + { + _text = text; + _position = 0; + } + + /// The bytes of a token. + /// The token. + /// Its bytes. + public readonly ReadOnlySpan TextOf(PostScriptToken token) => _text.Slice(token.Start, token.Length); + + /// Reads the next token. + /// The token; at the end. + public PostScriptToken Next() + { + SkipWhiteSpaceAndComments(); + if (_position >= _text.Length) + { + return new PostScriptToken(PostScriptTokenKind.End, _position, 0); + } + + int start = _position; + byte first = _text[_position]; + switch (first) + { + case (byte)'{': + _position++; + return new PostScriptToken(PostScriptTokenKind.OpenBrace, start, 1); + case (byte)'}': + _position++; + return new PostScriptToken(PostScriptTokenKind.CloseBrace, start, 1); + case (byte)'(' or (byte)')' or (byte)'<' or (byte)'>' or (byte)'[' or (byte)']' or (byte)'/': + _position++; + return new PostScriptToken(PostScriptTokenKind.Invalid, start, 1); + } + + int length = _text[start..].IndexOfAny(Delimiters); + length = length < 0 ? _text.Length - start : length; + _position = start + length; + return Classify(_text.Slice(start, length), start); + } + + private static PostScriptToken Classify(ReadOnlySpan word, int start) + { + int digits = 0; + int dots = 0; + int exponent = -1; + for (int i = 0; i < word.Length; i++) + { + byte c = word[i]; + if (c is >= (byte)'0' and <= (byte)'9') + { + digits++; + } + else if (c == '.' && exponent < 0) + { + dots++; + } + else if (c is (byte)'+' or (byte)'-' && (i == 0 || i == exponent + 1)) + { + // A sign, at the start or right after the exponent marker. + } + else if (c is (byte)'e' or (byte)'E' && exponent < 0 && digits > 0) + { + exponent = i; + } + else + { + // Not a number. A radix number (16#FF) starts like one but is not PDF syntax. + return new PostScriptToken(digits > 0 && word.Contains((byte)'#') ? PostScriptTokenKind.Invalid : PostScriptTokenKind.Name, start, word.Length); + } + } + + if (digits == 0 || dots > 1 || exponent == word.Length - 1) + { + return new PostScriptToken(digits == 0 && dots == 0 && exponent < 0 && word.Length > 1 ? PostScriptTokenKind.Name : PostScriptTokenKind.Invalid, start, word.Length); + } + + if (!double.TryParse(word, NumberStyles.Float, CultureInfo.InvariantCulture, out double value) || !double.IsFinite(value)) + { + return new PostScriptToken(PostScriptTokenKind.Invalid, start, word.Length); + } + + bool integer = dots == 0 && exponent < 0 && value is >= int.MinValue and <= int.MaxValue; + return new PostScriptToken(integer ? PostScriptTokenKind.Integer : PostScriptTokenKind.Real, start, word.Length, value, exponent >= 0); + } + + private void SkipWhiteSpaceAndComments() + { + while (_position < _text.Length) + { + byte c = _text[_position]; + if (c is 0 or (byte)'\t' or (byte)'\n' or (byte)'\f' or (byte)'\r' or (byte)' ') + { + _position++; + } + else if (c == '%') + { + while (_position < _text.Length && _text[_position] is not ((byte)'\r' or (byte)'\n')) + { + _position++; + } + } + else + { + return; + } + } + } +} diff --git a/src/Broadside/Graphics/Functions/SampledCompiler.cs b/src/Broadside/Graphics/Functions/SampledCompiler.cs new file mode 100644 index 00000000..166720ef --- /dev/null +++ b/src/Broadside/Graphics/Functions/SampledCompiler.cs @@ -0,0 +1,226 @@ +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Graphics.Functions; + +/// Compiles Type 0 (sampled) functions: reads the entries and decodes the whole sample table once. +/// +/// ISO 32000-2 §7.10.2, Table 39. The samples are one bit stream, most significant bit first, with no padding anywhere (not even at +/// the end of a row, unlike image data), the first dimension varying fastest and the n values of one point adjacent. They are mapped +/// through Decode at compile time (Decode is linear, so decoding before interpolating gives the same result) and kept in single +/// precision. +/// +internal static class SampledCompiler +{ + /// The most sample values (n × the product of Size) a function may have: a guard against allocation bombs. + public const long MaxSampleValues = 1 << 24; + + /// Compiles a Type 0 function. + /// The function stream. + /// The compilation. + /// The consumer's number of outputs, for a missing Range; 0 when unknown. + /// The evaluator. + public static FunctionEvaluator Compile(CosStream stream, FunctionCompilation compilation, int expectedOutputs) + { + CosDictionary dictionary = stream.Dictionary; + int[]? size = ReadSize(dictionary, compilation); + if (size is null) + { + return FunctionCompiler.Invalid(0, expectedOutputs); + } + + int m = size.Length; + double[]? domain = compilation.ReadDomain(dictionary, inferredInputs: m); + if (domain is null) + { + return FunctionCompiler.Invalid(m, expectedOutputs); + } + + domain = Fit(domain, m, FunctionCompilation.UnitPairs(m), compilation, "Domain"); + double[]? range = compilation.ReadRange(dictionary); + int n; + if (range is not null) + { + n = range.Length / 2; + } + else if (expectedOutputs > 0) + { + compilation.Repaired("Range is missing; the number of outputs comes from where the function is used and outputs are not clipped."); + n = expectedOutputs; + } + else + { + compilation.Invalid("Range is missing, so the number of outputs is unknown."); + return FunctionCompiler.Invalid(m, 0); + } + + if (n > FunctionEvaluator.MaxArity) + { + compilation.Invalid(string.Create(CultureInfo.InvariantCulture, $"Range has {n} outputs; at most {FunctionEvaluator.MaxArity} are supported.")); + return FunctionCompiler.Invalid(m, 0); + } + + if (ReadBitsPerSample(dictionary, compilation) is not { } bitsPerSample) + { + return FunctionCompiler.Invalid(m, n, range); + } + + ReadOrder(dictionary, size, compilation); + double[] defaultEncode = new double[2 * m]; + for (int i = 0; i < m; i++) + { + defaultEncode[(2 * i) + 1] = size[i] - 1; + } + + double[] encode = Fit(compilation.ReadNumbers(dictionary, FunctionNames.Encode) ?? defaultEncode, m, defaultEncode, compilation, "Encode"); + double[] defaultDecode = range ?? FunctionCompilation.UnitPairs(n); + double[] decode = Fit(compilation.ReadNumbers(dictionary, FunctionNames.Decode) ?? defaultDecode, n, defaultDecode, compilation, "Decode"); + + long values = n; + foreach (int dimension in size) + { + values *= dimension; + if (values > MaxSampleValues) + { + compilation.Invalid(string.Create(CultureInfo.InvariantCulture, $"Size calls for more than {MaxSampleValues} sample values; the function is not used.")); + return FunctionCompiler.Invalid(m, n, range); + } + } + + float[] samples = ReadSamples(compilation.Decode(stream).Span, (int)values, n, bitsPerSample, decode, compilation); + return new SampledEvaluator(domain, range, size, encode, samples, n); + } + + /// Reads Size: m positive integers; reals are truncated with a diagnostic. + private static int[]? ReadSize(CosDictionary dictionary, FunctionCompilation compilation) + { + double[]? numbers = compilation.ReadNumbers(dictionary, FunctionNames.Size); + if (numbers is not { Length: > 0 } || numbers.Length > FunctionEvaluator.MaxArity) + { + compilation.Invalid(string.Create(CultureInfo.InvariantCulture, $"Size is missing, empty, or has more than {FunctionEvaluator.MaxArity} dimensions.")); + return null; + } + + int[] size = new int[numbers.Length]; + bool truncated = false; + for (int i = 0; i < size.Length; i++) + { + double value = Math.Truncate(numbers[i]); + truncated |= value != numbers[i]; + if (!(value >= 1 && value <= MaxSampleValues)) + { + compilation.Invalid("Size holds a number of samples that is not a positive integer, or is too large."); + return null; + } + + size[i] = (int)value; + } + + if (truncated) + { + compilation.Repaired("Size holds numbers that are not integers; they are truncated."); + } + + return size; + } + + /// Reads BitsPerSample: one of the eight values, or (with a diagnostic) any other width from 1 to 32. + private static int? ReadBitsPerSample(CosDictionary dictionary, FunctionCompilation compilation) + { + double? value = compilation.ReadNumber(dictionary, FunctionNames.BitsPerSample); + if (value is not { } bits || bits != Math.Floor(bits) || bits < 1 || bits > 32) + { + compilation.Invalid("BitsPerSample is missing or is not an integer from 1 to 32."); + return null; + } + + int result = (int)bits; + if (result is not (1 or 2 or 4 or 8 or 12 or 16 or 24 or 32)) + { + compilation.Repaired(string.Create(CultureInfo.InvariantCulture, $"BitsPerSample {result} is not 1, 2, 4, 8, 12, 16, 24 or 32; samples are read with {result} bits.")); + } + + return result; + } + + /// Reads Order: 3 is evaluated linearly (noted when a cubic spline was possible); other values are repaired to 1. + private static void ReadOrder(CosDictionary dictionary, int[] size, FunctionCompilation compilation) + { + double? order = compilation.ReadNumber(dictionary, FunctionNames.Order); + if (order is null or 1) + { + return; + } + + if (order != 3) + { + compilation.Repaired("Order is neither 1 nor 3; linear interpolation is used."); + } + else if (Array.TrueForAll(size, static dimension => dimension >= 4)) + { + // §7.10.2: with fewer than 4 samples in a dimension Order 3 "shall be ignored", so only a possible spline is noted. + compilation.Report( + DiagnosticCodes.FunctionOrderUnsupported, + DiagnosticSeverity.Information, + "Order 3 (cubic spline interpolation) is not implemented; linear interpolation is used."); + } + } + + /// Fits an array of pairs to pairs, taking missing ones from . + private static double[] Fit(double[] values, int pairs, double[] defaults, FunctionCompilation compilation, string key) + { + if (values.Length == 2 * pairs) + { + return values; + } + + compilation.Repaired(string.Create(CultureInfo.InvariantCulture, $"{key} has {values.Length} numbers where {2 * pairs} are needed; missing pairs take their defaults and extra numbers are ignored.")); + double[] fitted = (double[])defaults.Clone(); + values.AsSpan(0, Math.Min(values.Length & ~1, fitted.Length)).CopyTo(fitted); + return fitted; + } + + /// Reads samples of bits each and decodes them. + private static float[] ReadSamples(ReadOnlySpan data, int count, int n, int bits, double[] decode, FunctionCompilation compilation) + { + long required = (((long)count * bits) + 7) / 8; + if (data.Length < required) + { + compilation.Report( + DiagnosticCodes.FunctionSampleDataTruncated, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The sample data has {data.Length} bytes where {required} are needed; the missing samples are 0.")); + } + + double maximum = (1UL << bits) - 1; + ulong mask = (1UL << bits) - 1; + double[] scale = new double[n]; + for (int j = 0; j < n; j++) + { + scale[j] = (decode[(2 * j) + 1] - decode[2 * j]) / maximum; + } + + float[] samples = new float[count]; + ulong buffer = 0; + int buffered = 0; + int position = 0; + for (int k = 0; k < count; k++) + { + while (buffered < bits) + { + buffer = (buffer << 8) | (position < data.Length ? data[position] : 0UL); + position++; + buffered += 8; + } + + buffered -= bits; + ulong raw = (buffer >> buffered) & mask; + int j = k % n; + samples[k] = (float)(decode[2 * j] + (raw * scale[j])); + } + + return samples; + } +} diff --git a/src/Broadside/Graphics/Functions/SampledEvaluator.cs b/src/Broadside/Graphics/Functions/SampledEvaluator.cs new file mode 100644 index 00000000..6b326aba --- /dev/null +++ b/src/Broadside/Graphics/Functions/SampledEvaluator.cs @@ -0,0 +1,160 @@ +namespace Broadside.Graphics.Functions; + +/// A Type 0 (sampled) function: inputs encoded into a sample table and interpolated between the surrounding samples. +/// +/// +/// ISO 32000-2 §7.10.2. For each input, e_i = Interpolate(x′_i, Domain, Encode) clipped to [0, Size_i − 1]; the outputs interpolate +/// the (already decoded) samples around e. The clause asks only for "interpolation"; this is the multilinear form (the weighted sum +/// of the 2^a corners of the cell, a being the number of inputs that fall between samples; inputs on a sample, or in a dimension of +/// Size 1, add no corners). Beyond eight such inputs the 256-corner cell gives way to simplex interpolation over a + 1 corners +/// (Kuhn's triangulation of the cell), which agrees with multilinear interpolation on the samples themselves and on every function +/// that is linear in each cell. +/// +/// Nothing is allocated per evaluation: the cell lives in stack buffers of m entries. +/// +internal sealed class SampledEvaluator : FunctionEvaluator +{ + /// The most inputs between samples that are interpolated multilinearly (2^8 corners). + private const int MaxMultilinearAxes = 8; + + private readonly int[] _last; + private readonly int[] _strides; + private readonly double[] _domainStart; + private readonly double[] _encodeStart; + private readonly double[] _encodeScale; + private readonly float[] _samples; + private readonly int _n; + + /// Initializes a new instance of the class. + /// m pairs. + /// n pairs, or when missing (repaired). + /// m positive sizes. + /// m pairs. + /// n × the product of the sizes decoded samples, first dimension fastest, a point's n values adjacent. + /// n. + public SampledEvaluator(double[] domain, double[]? range, int[] size, double[] encode, float[] samples, int outputCount) + : base(domain, range, outputCount) + { + int m = size.Length; + _n = outputCount; + _samples = samples; + _last = new int[m]; + _strides = new int[m]; + _domainStart = new double[m]; + _encodeStart = new double[m]; + _encodeScale = new double[m]; + int stride = 1; + for (int i = 0; i < m; i++) + { + _last[i] = size[i] - 1; + _strides[i] = stride; + stride *= size[i]; + _domainStart[i] = domain[2 * i]; + _encodeStart[i] = encode[2 * i]; + double width = domain[(2 * i) + 1] - domain[2 * i]; + _encodeScale[i] = width == 0 ? 0 : (encode[(2 * i) + 1] - encode[2 * i]) / width; + } + } + + /// + protected override FunctionStatus EvaluateCore(ReadOnlySpan input, Span output) + { + int m = input.Length; + Span axes = stackalloc int[m]; + Span fractions = stackalloc double[m]; + int origin = 0; + int active = 0; + for (int i = 0; i < m; i++) + { + double e = _encodeStart[i] + ((input[i] - _domainStart[i]) * _encodeScale[i]); + int last = _last[i]; + e = e >= 0 ? (e <= last ? e : last) : 0; + if (last == 0) + { + continue; + } + + int cell = Math.Min((int)e, last - 1); + double fraction = e - cell; + origin += cell * _strides[i]; + if (fraction > 0) + { + fractions[i] = fraction; + axes[active++] = i; + } + } + + output.Clear(); + axes = axes[..active]; + if (active <= MaxMultilinearAxes) + { + Multilinear(origin, axes, fractions, output); + } + else + { + Simplex(origin, axes, fractions, output); + } + + return FunctionStatus.Ok; + } + + private void Multilinear(int origin, ReadOnlySpan axes, ReadOnlySpan fractions, Span output) + { + int corners = 1 << axes.Length; + for (int corner = 0; corner < corners; corner++) + { + double weight = 1; + int index = origin; + for (int t = 0; t < axes.Length; t++) + { + int axis = axes[t]; + if ((corner & (1 << t)) != 0) + { + weight *= fractions[axis]; + index += _strides[axis]; + } + else + { + weight *= 1 - fractions[axis]; + } + } + + Accumulate(index, weight, output); + } + } + + private void Simplex(int origin, Span axes, ReadOnlySpan fractions, Span output) + { + // Order the axes by decreasing fraction (insertion sort: m <= 32), then walk from the origin corner one axis at a time. + for (int t = 1; t < axes.Length; t++) + { + int axis = axes[t]; + int s = t - 1; + while (s >= 0 && fractions[axes[s]] < fractions[axis]) + { + axes[s + 1] = axes[s]; + s--; + } + + axes[s + 1] = axis; + } + + int index = origin; + Accumulate(index, 1 - fractions[axes[0]], output); + for (int t = 0; t < axes.Length; t++) + { + index += _strides[axes[t]]; + double next = t + 1 < axes.Length ? fractions[axes[t + 1]] : 0; + Accumulate(index, fractions[axes[t]] - next, output); + } + } + + private void Accumulate(int point, double weight, Span output) + { + int first = point * _n; + for (int j = 0; j < output.Length; j++) + { + output[j] += weight * _samples[first + j]; + } + } +} diff --git a/src/Broadside/Graphics/Functions/SimpleEvaluators.cs b/src/Broadside/Graphics/Functions/SimpleEvaluators.cs new file mode 100644 index 00000000..52a369f2 --- /dev/null +++ b/src/Broadside/Graphics/Functions/SimpleEvaluators.cs @@ -0,0 +1,154 @@ +namespace Broadside.Graphics.Functions; + +/// A function that could not be compiled: every evaluation fails and writes 0, clipped to the range when there is one. +/// ISO 32000-2 §7.10; ADR 0005. Consumers apply their own fallback (a tint transform's default, skipping a shading). +internal sealed class InvalidEvaluator(double[] domain, double[]? range, int outputCount) : FunctionEvaluator(domain, range, outputCount) +{ + /// + public override bool IsValid => false; + + /// + protected override FunctionStatus EvaluateCore(ReadOnlySpan input, Span output) + { + output.Clear(); + return FunctionStatus.Failed; + } +} + +/// The name Identity where an entry accepts it: m inputs returned unchanged as m outputs. +/// ISO 32000-2 §8.4.5 Table 57 (TR), §11.6.5.1 Table 142 (soft mask TR). +internal sealed class IdentityEvaluator(int count) : FunctionEvaluator(FunctionCompilation.UnboundedPairs(count), range: null, count) +{ + /// + protected override FunctionStatus EvaluateCore(ReadOnlySpan input, Span output) + { + input.CopyTo(output); + return FunctionStatus.Ok; + } +} + +/// An array of n functions of m inputs and one output each, evaluated as one m-in n-out function. +/// ISO 32000-2 §8.7.4.5.2-8.7.4.5.4 Tables 78-80 (shading Function: "an array of n 2-in, 1-out functions" for Type 1, 1-in for Types 2 and 3). +internal sealed class ArrayEvaluator(double[] domain, FunctionEvaluator[] functions) : FunctionEvaluator(domain, range: null, functions.Length) +{ + /// + protected override FunctionStatus EvaluateCore(ReadOnlySpan input, Span output) + { + FunctionStatus status = FunctionStatus.Ok; + for (int j = 0; j < functions.Length; j++) + { + status = Worse(status, functions[j].Evaluate(input, output.Slice(j, 1))); + } + + return status; + } +} + +/// A Type 2 (exponential interpolation) function: y_j = C0_j + x^N × (C1_j − C0_j). +/// +/// ISO 32000-2 §7.10.3, Table 40. N = 1 and N = 2 avoid . When x^N is not finite (x = 0 with a negative N, a +/// negative x with a non-integer N: the domain should have excluded both) the outputs are C0 and the status is +/// . +/// +internal sealed class ExponentialEvaluator : FunctionEvaluator +{ + private readonly double[] _c0; + private readonly double[] _difference; + private readonly double _exponent; + + /// Initializes a new instance of the class. + /// One pair. + /// n pairs, or . + /// C0, n numbers. + /// C1, n numbers. + /// N. + public ExponentialEvaluator(double[] domain, double[]? range, double[] c0, double[] c1, double exponent) + : base(domain, range, c0.Length) + { + _c0 = c0; + _difference = new double[c0.Length]; + for (int j = 0; j < c0.Length; j++) + { + _difference[j] = c1[j] - c0[j]; + } + + _exponent = exponent; + } + + /// + protected override FunctionStatus EvaluateCore(ReadOnlySpan input, Span output) + { + double x = input[0]; + double power = _exponent switch + { + 1 => x, + 2 => x * x, + _ => Math.Pow(x, _exponent), + }; + if (!double.IsFinite(power)) + { + _c0.CopyTo(output); + return FunctionStatus.Repaired; + } + + for (int j = 0; j < output.Length; j++) + { + output[j] = _c0[j] + (power * _difference[j]); + } + + return FunctionStatus.Ok; + } +} + +/// A Type 3 (stitching) function: one of k 1-input functions chosen by the subdomain x falls in, over an encoded input. +/// +/// ISO 32000-2 §7.10.4, Table 41. Intervals are closed on the left and open on the right, except that the last is closed on the +/// right and, when Domain0 = Bounds0, the first is the single point Domain0 and the second is open on the left. A degenerate interval +/// maps to its Encode's first number, which gives the clause's rules for Bounds0 = Domain0 (x′ = Encode0) and Bounds(k−2) = Domain1 +/// (x′ = Encode2(k−1)). Each sub-function clips to its own domain and range. +/// +internal sealed class StitchingEvaluator : FunctionEvaluator +{ + private readonly FunctionEvaluator[] _functions; + private readonly double[] _bounds; + private readonly double[] _encode; + private readonly double _domain0; + private readonly double _domain1; + + /// Initializes a new instance of the class. + /// One pair. + /// n pairs, or . + /// k 1-input functions with n outputs each. + /// k − 1 bounds. + /// 2 × k numbers. + public StitchingEvaluator(double[] domain, double[]? range, FunctionEvaluator[] functions, double[] bounds, double[] encode) + : base(domain, range, functions[0].OutputCount) + { + _functions = functions; + _bounds = bounds; + _encode = encode; + _domain0 = domain[0]; + _domain1 = domain[1]; + } + + /// + protected override FunctionStatus EvaluateCore(ReadOnlySpan input, Span output) + { + double x = input[0]; + int last = _functions.Length - 1; + int i = 0; + if (last == 0 || _bounds[0] != _domain0 || x != _domain0) + { + while (i < last && x >= _bounds[i]) + { + i++; + } + } + + double low = i == 0 ? _domain0 : _bounds[i - 1]; + double high = i == last ? _domain1 : _bounds[i]; + Span encoded = stackalloc double[1]; + encoded[0] = Interpolate(x, low, high, _encode[2 * i], _encode[(2 * i) + 1]); + return _functions[i].Evaluate(encoded, output); + } +} diff --git a/src/Broadside/Graphics/PdfExponentialFunction.cs b/src/Broadside/Graphics/PdfExponentialFunction.cs new file mode 100644 index 00000000..452f75b5 --- /dev/null +++ b/src/Broadside/Graphics/PdfExponentialFunction.cs @@ -0,0 +1,29 @@ +using Broadside.Graphics.Functions; +using Broadside.Objects; + +namespace Broadside.Graphics; + +/// A Type 2 (exponential interpolation) function (PDF 1.3): y_j = C0_j + x^N × (C1_j − C0_j). +/// ISO 32000-2 §7.10.3, Table 40. One input; n outputs, n being the length of and . +public sealed class PdfExponentialFunction : PdfFunction +{ + internal PdfExponentialFunction(FunctionCache cache, CosObject cosObject, CosReference? reference, CompiledFunction compiled, int expectedInputs, int expectedOutputs) + : base(cache, cosObject, reference, compiled, expectedInputs, expectedOutputs) + { + } + + /// + public override PdfFunctionType FunctionType => PdfFunctionType.Exponential; + + /// Gets the C0 entry, the outputs at x = 0; [0.0] when absent. + /// ISO 32000-2 §7.10.3, Table 40. + public IReadOnlyList C0 => ReadNumbers(FunctionNames.C0) ?? [0.0]; + + /// Gets the C1 entry, the outputs at x = 1; [1.0] when absent. + /// ISO 32000-2 §7.10.3, Table 40. + public IReadOnlyList C1 => ReadNumbers(FunctionNames.C1) ?? [1.0]; + + /// Gets the N entry, the interpolation exponent; when missing (the function is then invalid). + /// ISO 32000-2 §7.10.3, Table 40. + public double? Exponent => ReadNumber(FunctionNames.N); +} diff --git a/src/Broadside/Graphics/PdfFunction.cs b/src/Broadside/Graphics/PdfFunction.cs new file mode 100644 index 00000000..54843eec --- /dev/null +++ b/src/Broadside/Graphics/PdfFunction.cs @@ -0,0 +1,182 @@ +using Broadside.Graphics.Functions; +using Broadside.Objects; + +namespace Broadside.Graphics; + +/// +/// A function object: a live view over a function dictionary or stream that evaluates the function it describes. +/// +/// +/// +/// ISO 32000-2 §7.10. Get one with ; the subclass says which of the four types it is +/// (, , , +/// ). Entries such as are read from the COS object on every call (ADR 0004). +/// +/// +/// Evaluation runs on a form compiled once from the COS objects: inputs are clipped to the domain, outputs to the range (§7.10.1). +/// When any object it was compiled from changes through the public API, the next evaluation compiles it again. Evaluation is safe +/// from any number of threads while nobody mutates the document, allocates nothing, never returns NaN or infinity, and never throws +/// for anything in the file: a function that cannot be used ( is ) yields 0 clipped to +/// its range. Deviations are recorded as the document's diagnostics: those found compiling, once; an error met while evaluating (a +/// Type 4 division by zero, for instance), once per compiled function. In strict mode both throw DiagnosticException. +/// +/// +public abstract class PdfFunction +{ + private readonly FunctionCache _cache; + private readonly int _expectedInputs; + private readonly int _expectedOutputs; + private CompiledFunction _compiled; + + private protected PdfFunction(FunctionCache cache, CosObject cosObject, CosReference? reference, CompiledFunction compiled, int expectedInputs, int expectedOutputs) + { + _cache = cache; + CosObject = cosObject; + Reference = reference; + _compiled = compiled; + _expectedInputs = expectedInputs; + _expectedOutputs = expectedOutputs; + } + + /// Gets the function object: a (Types 2 and 3) or a (Types 0 and 4). + public CosObject CosObject { get; } + + /// Gets the function dictionary: the dictionary itself, or the stream's dictionary. + /// ISO 32000-2 §7.10.1: "function dictionary" means either. + public CosDictionary Dictionary => CosObject is CosStream stream ? stream.Dictionary : (CosDictionary)CosObject; + + /// Gets the indirect reference the function was reached through, or for a direct object. + public CosReference? Reference { get; } + + /// Gets the function's type, its FunctionType entry. + /// ISO 32000-2 §7.10.1, Table 38. + public abstract PdfFunctionType FunctionType { get; } + + /// Gets the earliest PDF version that has this type of function: 1.2 for Type 0, 1.3 for the others. + /// ISO 32000-2 §7.10.1 (ADR 0003: a writer raises the file's version to this). + public PdfVersion MinimumVersion => FunctionType == PdfFunctionType.Sampled ? new PdfVersion(1, 2) : new PdfVersion(1, 3); + + /// Gets the Domain entry: 2 × m numbers, an interval per input; empty when it is missing or not numbers. + /// ISO 32000-2 §7.10.1, Table 38. Read from the dictionary on every call. + public IReadOnlyList Domain => ReadNumbers(FunctionNames.Domain) ?? []; + + /// Gets the Range entry: 2 × n numbers, an interval per output; when absent. + /// ISO 32000-2 §7.10.1, Table 38. Required for Types 0 and 4. Read from the dictionary on every call. + public IReadOnlyList? Range => ReadNumbers(FunctionNames.Range); + + /// Gets m, the number of input values, as compiled. + /// ISO 32000-2 §7.10.1. From Domain (or, repaired, from the type: Size, or 1 for Types 2 and 3). + public int InputCount => Evaluator.InputCount; + + /// Gets n, the number of output values, as compiled. + /// ISO 32000-2 §7.10.1. From Range (Types 0 and 4), C0 and C1 (Type 2) or the stitched functions (Type 3). + public int OutputCount => Evaluator.OutputCount; + + /// Gets a value indicating whether the function could be compiled. An invalid function evaluates to 0 clipped to its range. + public bool IsValid => Evaluator.IsValid; + + /// Gets the compiled form, compiling again when what it was compiled from has changed. + internal FunctionEvaluator Evaluator => Current().Evaluator; + + /// Evaluates the function at one point. + /// The m input values; values beyond are ignored. + /// Receives the n output values in its first elements. + /// or is shorter than the function needs. + /// ISO 32000-2 §7.10.1: inputs are clipped to the domain and outputs to the range. + public void Evaluate(ReadOnlySpan input, Span output) + { + CompiledFunction compiled = Current(); + FunctionEvaluator evaluator = compiled.Evaluator; + if (input.Length < evaluator.InputCount) + { + throw new ArgumentException("The function takes more inputs than were given.", nameof(input)); + } + + if (output.Length < evaluator.OutputCount) + { + throw new ArgumentException("The function has more outputs than there is room for.", nameof(output)); + } + + Report(compiled, evaluator.Evaluate(input, output)); + } + + /// Evaluates the function at points stored one after the other. + /// At least × values: the inputs of each point in turn. + /// At least × values: receives the outputs of each point in turn. + /// The number of points. + /// is negative. + /// or is too short for points. + /// ISO 32000-2 §7.10.1. The same as evaluating each point, with one staleness check for the whole run. + public void Evaluate(ReadOnlySpan inputs, Span outputs, int count) + { + ArgumentOutOfRangeException.ThrowIfNegative(count); + CompiledFunction compiled = Current(); + FunctionEvaluator evaluator = compiled.Evaluator; + if (inputs.Length < (long)count * evaluator.InputCount) + { + throw new ArgumentException("There are fewer inputs than the points need.", nameof(inputs)); + } + + if (outputs.Length < (long)count * evaluator.OutputCount) + { + throw new ArgumentException("There is less room for outputs than the points need.", nameof(outputs)); + } + + Report(compiled, evaluator.Evaluate(inputs, outputs, count)); + } + + /// Reads an entry of numbers from the dictionary as it is now. + /// The key. + /// The numbers, or when absent or not an array of numbers. + private protected double[]? ReadNumbers(CosName key) + { + if (!Dictionary.TryGetValue(key, out CosObject? value) || _cache.Resolve(value) is not CosArray array) + { + return null; + } + + double[] numbers = new double[array.Count]; + for (int i = 0; i < numbers.Length; i++) + { + if (_cache.Resolve(array[i]) is not CosNumber number) + { + return null; + } + + numbers[i] = number.ToDouble(); + } + + return numbers; + } + + /// Reads a number entry from the dictionary as it is now. + /// The key. + /// The number, or when absent or not a number. + private protected double? ReadNumber(CosName key) => + Dictionary.TryGetValue(key, out CosObject? value) && _cache.Resolve(value) is CosNumber number ? number.ToDouble() : null; + + /// Gets the function cache, for views that reach other functions. + private protected FunctionCache Cache => _cache; + + private CompiledFunction Current() + { + CompiledFunction compiled = Volatile.Read(ref _compiled); + if (compiled.IsCurrent) + { + return compiled; + } + + compiled = _cache.Compile(CosObject, Reference, FunctionType, _expectedInputs, _expectedOutputs); + Volatile.Write(ref _compiled, compiled); + return compiled; + } + + private void Report(CompiledFunction compiled, FunctionStatus status) + { + // An invalid function was reported when it was compiled; only a valid one reports what went wrong while evaluating. + if (status != FunctionStatus.Ok && compiled.Evaluator.IsValid && compiled.ClaimReport()) + { + _cache.ReportEvaluation(this, status); + } + } +} diff --git a/src/Broadside/Graphics/PdfFunctionType.cs b/src/Broadside/Graphics/PdfFunctionType.cs new file mode 100644 index 00000000..b70152ad --- /dev/null +++ b/src/Broadside/Graphics/PdfFunctionType.cs @@ -0,0 +1,18 @@ +namespace Broadside.Graphics; + +/// The kind of a function object, its FunctionType entry. +/// ISO 32000-2 §7.10.1, Table 38. Type 1 is not defined. +public enum PdfFunctionType +{ + /// A sampled function (PDF 1.2): a table of sample values with interpolation (§7.10.2). + Sampled = 0, + + /// An exponential interpolation function (PDF 1.3) between two sets of coefficients (§7.10.3). + Exponential = 2, + + /// A stitching function (PDF 1.3): 1-input functions applied over subdomains of one domain (§7.10.4). + Stitching = 3, + + /// A PostScript calculator function (PDF 1.3): a program in a subset of the PostScript language (§7.10.5). + PostScriptCalculator = 4, +} diff --git a/src/Broadside/Graphics/PdfPostScriptFunction.cs b/src/Broadside/Graphics/PdfPostScriptFunction.cs new file mode 100644 index 00000000..80a334fb --- /dev/null +++ b/src/Broadside/Graphics/PdfPostScriptFunction.cs @@ -0,0 +1,33 @@ +using Broadside.Graphics.Functions; +using Broadside.Objects; + +namespace Broadside.Graphics; + +/// A Type 4 (PostScript calculator) function (PDF 1.3): a program in a small subset of the PostScript language. +/// +/// +/// ISO 32000-2 §7.10.5, Table 42, Annex B; the operators mean what the PostScript Language Reference, Third Edition, §8.2 says. The +/// inputs are the initial operand stack (the first input deepest) and the values left on it are the outputs. The stack holds 100 +/// entries. +/// +/// +/// The program is compiled once to a flat instruction list (conditionals become jumps) and run over a stack on the call stack, so +/// evaluation allocates nothing. Arithmetic is in double precision (PostScript interpreters use single precision; results differ +/// only in the last bits, which eq and ne on computed values can see). Errors the language would raise are repaired +/// and noted once: division by zero and other undefined results give 0, an operand of the wrong type is converted, the wrong number +/// of results is padded with 0 or cut to the topmost; stack overflow or underflow makes every output 0. +/// +/// +public sealed class PdfPostScriptFunction : PdfFunction +{ + internal PdfPostScriptFunction(FunctionCache cache, CosObject cosObject, CosReference? reference, CompiledFunction compiled, int expectedInputs, int expectedOutputs) + : base(cache, cosObject, reference, compiled, expectedInputs, expectedOutputs) + { + } + + /// + public override PdfFunctionType FunctionType => PdfFunctionType.PostScriptCalculator; + + /// Gets the stream holding the program; when the function object is a dictionary (the function is then invalid). + public CosStream? Stream => CosObject as CosStream; +} diff --git a/src/Broadside/Graphics/PdfSampledFunction.cs b/src/Broadside/Graphics/PdfSampledFunction.cs new file mode 100644 index 00000000..5ebe8e9c --- /dev/null +++ b/src/Broadside/Graphics/PdfSampledFunction.cs @@ -0,0 +1,51 @@ +using Broadside.Graphics.Functions; +using Broadside.Objects; + +namespace Broadside.Graphics; + +/// A Type 0 (sampled) function (PDF 1.2): an m-dimensional table of samples with n values each, interpolated. +/// +/// +/// ISO 32000-2 §7.10.2, Table 39. The samples are the stream's data: one bit stream of -bit values with no +/// padding, the first input dimension varying fastest. Inputs are mapped through into the table, and sample values +/// through into the outputs. +/// +/// +/// Interpolation is multilinear between the 2^m surrounding samples (simplex interpolation between m + 1 of them when more than eight +/// inputs fall between samples). 3 (cubic spline) is evaluated linearly and noted once as a diagnostic. +/// Samples are held in single precision, so 24- and 32-bit samples resolve to about 2^-24 of their decoded range. +/// +/// +public sealed class PdfSampledFunction : PdfFunction +{ + internal PdfSampledFunction(FunctionCache cache, CosObject cosObject, CosReference? reference, CompiledFunction compiled, int expectedInputs, int expectedOutputs) + : base(cache, cosObject, reference, compiled, expectedInputs, expectedOutputs) + { + } + + /// + public override PdfFunctionType FunctionType => PdfFunctionType.Sampled; + + /// Gets the stream holding the samples; when the function object is a dictionary (the function is then invalid). + public CosStream? Stream => CosObject as CosStream; + + /// Gets the Size entry: the number of samples in each input dimension; empty when missing. + /// ISO 32000-2 §7.10.2, Table 39. + public IReadOnlyList Size => ReadNumbers(FunctionNames.Size) ?? []; + + /// Gets the BitsPerSample entry (1, 2, 4, 8, 12, 16, 24 or 32); when missing. + /// ISO 32000-2 §7.10.2, Table 39. + public int? BitsPerSample => ReadNumber(FunctionNames.BitsPerSample) is { } bits ? (int)Math.Clamp(bits, int.MinValue, int.MaxValue) : null; + + /// Gets the Order entry: 1 (linear, the default) or 3 (cubic spline). + /// ISO 32000-2 §7.10.2, Table 39. + public int Order => ReadNumber(FunctionNames.Order) is { } order ? (int)Math.Clamp(order, int.MinValue, int.MaxValue) : 1; + + /// Gets the Encode entry; when absent, its default [0 (Size0 − 1) 0 (Size1 − 1) …]. + /// ISO 32000-2 §7.10.2, Table 39. + public IReadOnlyList Encode => ReadNumbers(FunctionNames.Encode) ?? [.. Size.SelectMany(static size => new[] { 0, size - 1 })]; + + /// Gets the Decode entry; when absent, its default, the range (empty when that is missing too). + /// ISO 32000-2 §7.10.2, Table 39. + public IReadOnlyList Decode => ReadNumbers(FunctionNames.Decode) ?? Range ?? []; +} diff --git a/src/Broadside/Graphics/PdfStitchingFunction.cs b/src/Broadside/Graphics/PdfStitchingFunction.cs new file mode 100644 index 00000000..d96df02b --- /dev/null +++ b/src/Broadside/Graphics/PdfStitchingFunction.cs @@ -0,0 +1,49 @@ +using Broadside.Graphics.Functions; +using Broadside.Objects; + +namespace Broadside.Graphics; + +/// A Type 3 (stitching) function (PDF 1.3): k 1-input functions, each applied over its own subdomain of one domain. +/// +/// ISO 32000-2 §7.10.4, Table 41. The subdomains are the intervals cuts the domain into; a value in subdomain i +/// is mapped through the i-th pair of and passed to the i-th function of . +/// +public sealed class PdfStitchingFunction : PdfFunction +{ + internal PdfStitchingFunction(FunctionCache cache, CosObject cosObject, CosReference? reference, CompiledFunction compiled, int expectedInputs, int expectedOutputs) + : base(cache, cosObject, reference, compiled, expectedInputs, expectedOutputs) + { + } + + /// + public override PdfFunctionType FunctionType => PdfFunctionType.Stitching; + + /// Gets the functions of the Functions entry, in order; an element that is not a function is . + /// ISO 32000-2 §7.10.4, Table 41. Read from the dictionary on every call; each element's view is the document's shared one. + public IReadOnlyList Functions + { + get + { + if (!Dictionary.TryGetValue(FunctionNames.Functions, out CosObject? value) || Cache.Resolve(value) is not CosArray array) + { + return []; + } + + var functions = new PdfFunction?[array.Count]; + for (int i = 0; i < functions.Length; i++) + { + functions[i] = Cache.Get(array[i], expectedInputs: 1); + } + + return functions; + } + } + + /// Gets the Bounds entry: k − 1 increasing numbers inside the domain; empty when absent. + /// ISO 32000-2 §7.10.4, Table 41. + public IReadOnlyList Bounds => ReadNumbers(FunctionNames.Bounds) ?? []; + + /// Gets the Encode entry: a pair per function mapping its subdomain onto the function's domain; empty when absent. + /// ISO 32000-2 §7.10.4, Table 41. + public IReadOnlyList Encode => ReadNumbers(FunctionNames.Encode) ?? []; +} diff --git a/src/Broadside/Objects/CosArray.cs b/src/Broadside/Objects/CosArray.cs index 7a9e9367..bc8aefdb 100644 --- a/src/Broadside/Objects/CosArray.cs +++ b/src/Broadside/Objects/CosArray.cs @@ -32,6 +32,12 @@ public CosArray(IEnumerable items) private CosArray(List items, bool owned) => _items = owned ? items : [.. items]; + /// + /// Gets a number that changes on every change made through the public API (never by reading), so a cache of state derived from + /// this object can tell that it is stale by comparing the number it was built from. Does not cover the objects it contains. + /// + internal int Version { get; private set; } + /// public override bool IsDirty { @@ -70,6 +76,7 @@ public CosObject this[int index] ArgumentNullException.ThrowIfNull(value); _items[index] = value; _changed = true; + Version++; } } @@ -80,6 +87,7 @@ public void Add(CosObject item) ArgumentNullException.ThrowIfNull(item); _items.Add(item); _changed = true; + Version++; } /// Inserts an element and marks the array dirty. @@ -90,6 +98,7 @@ public void Insert(int index, CosObject item) ArgumentNullException.ThrowIfNull(item); _items.Insert(index, item); _changed = true; + Version++; } /// Removes the element at and marks the array dirty. @@ -98,6 +107,7 @@ public void RemoveAt(int index) { _items.RemoveAt(index); _changed = true; + Version++; } /// Removes the first element equal to ; marks the array dirty when one was removed. @@ -106,14 +116,24 @@ public void RemoveAt(int index) public bool Remove(CosObject item) { bool removed = _items.Remove(item); - _changed |= removed; + if (removed) + { + _changed = true; + Version++; + } + return removed; } /// Removes every element; marks the array dirty when it was not already empty. public void Clear() { - _changed |= _items.Count > 0; + if (_items.Count > 0) + { + _changed = true; + Version++; + } + _items.Clear(); } diff --git a/src/Broadside/Objects/CosDictionary.cs b/src/Broadside/Objects/CosDictionary.cs index b9157f57..2c3a323f 100644 --- a/src/Broadside/Objects/CosDictionary.cs +++ b/src/Broadside/Objects/CosDictionary.cs @@ -23,6 +23,12 @@ public sealed class CosDictionary : CosObject, IDictionary, private CosDictionary(OrderedDictionary entries) => _entries = entries; + /// + /// Gets a number that changes on every change made through the public API (never by reading), so a cache of state derived from + /// this object can tell that it is stale by comparing the number it was built from. Does not cover the objects it contains. + /// + internal int Version { get; private set; } + /// public override bool IsDirty { @@ -85,6 +91,7 @@ public CosObject this[CosName key] _entries[key] = value; _changed = true; + Version++; } } @@ -108,6 +115,7 @@ public void Add(CosName key, CosObject value) _entries.Add(key, value); _changed = true; + Version++; } /// Removes the entry for ; marks the dictionary dirty when one was removed. @@ -116,14 +124,24 @@ public void Add(CosName key, CosObject value) public bool Remove(CosName key) { bool removed = _entries.Remove(key); - _changed |= removed; + if (removed) + { + _changed = true; + Version++; + } + return removed; } /// Removes every entry; marks the dictionary dirty when it was not already empty. public void Clear() { - _changed |= _entries.Count > 0; + if (_entries.Count > 0) + { + _changed = true; + Version++; + } + _entries.Clear(); } @@ -155,7 +173,12 @@ void ICollection>.CopyTo(KeyValuePair>.Remove(KeyValuePair item) { bool removed = ((ICollection>)_entries).Remove(item); - _changed |= removed; + if (removed) + { + _changed = true; + Version++; + } + return removed; } diff --git a/src/Broadside/Objects/CosStream.cs b/src/Broadside/Objects/CosStream.cs index 25329f40..fbeb580f 100644 --- a/src/Broadside/Objects/CosStream.cs +++ b/src/Broadside/Objects/CosStream.cs @@ -50,6 +50,7 @@ public ReadOnlyMemory EncodedData _encodedData = value; _deferred = null; _changed = true; + Version++; } } @@ -64,6 +65,12 @@ internal void ReplaceLoadedData(ReadOnlyMemory encodedData) /// Gets the length of without reading it. internal int EncodedLength => _deferred is { } deferred ? deferred.Length : _encodedData.Length; + /// + /// Gets a number that changes on every change made through the public API (never by reading), so a cache of state derived from + /// this object can tell that it is stale by comparing the number it was built from. Does not cover the objects it contains. + /// + internal int Version { get; private set; } + /// public override bool IsDirty => _changed || Dictionary.IsDirty; } diff --git a/src/Broadside/Parsing/DiagnosticCodes.cs b/src/Broadside/Parsing/DiagnosticCodes.cs index 38370fe5..46dff647 100644 --- a/src/Broadside/Parsing/DiagnosticCodes.cs +++ b/src/Broadside/Parsing/DiagnosticCodes.cs @@ -132,4 +132,15 @@ internal static class DiagnosticCodes public const string PageResourcesMissing = nameof(PageResourcesMissing); public const string PageResourcesInvalid = nameof(PageResourcesInvalid); public const string PageUserUnitInvalid = nameof(PageUserUnitInvalid); + + // Functions (§7.10, issue #78). + public const string FunctionInvalid = nameof(FunctionInvalid); + public const string FunctionEntryInvalid = nameof(FunctionEntryInvalid); + public const string FunctionSampleDataTruncated = nameof(FunctionSampleDataTruncated); + public const string FunctionOrderUnsupported = nameof(FunctionOrderUnsupported); + public const string FunctionProgramSyntaxInvalid = nameof(FunctionProgramSyntaxInvalid); + public const string FunctionProgramStackInvalid = nameof(FunctionProgramStackInvalid); + public const string FunctionCycle = nameof(FunctionCycle); + public const string FunctionTooDeep = nameof(FunctionTooDeep); + public const string FunctionEvaluationRepaired = nameof(FunctionEvaluationRepaired); } diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 5c0e9ec2..e0eb2be8 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -1,6 +1,8 @@ using System.Buffers; using Broadside.Diagnostics; using Broadside.Filters; +using Broadside.Graphics; +using Broadside.Graphics.Functions; using Broadside.IO; using Broadside.Objects; using Broadside.Parsing; @@ -74,6 +76,7 @@ private PdfDocument( Revisions = revisions; Linearization = linearization; Pages = new PdfPageCollection(() => PageTreeReader.Read(this, diagnostics)); + Functions = new FunctionCache(this, diagnostics); } /// @@ -371,9 +374,30 @@ public void DecodeStream(CosStream stream, IBufferWriter output) _streams.Decode(stream, output); } + /// Returns the view of a function object of this document. + /// A function dictionary or stream, or an indirect reference to one. + /// + /// The view, shared by every caller asking for the same object; , with a diagnostic, when + /// is not a dictionary or stream with a FunctionType of 0, 2, 3 or 4. A function of a known + /// type that cannot be used is returned with . + /// + /// In strict mode, for the first deviation found in the function. + /// + /// ISO 32000-2 §7.10. The function is compiled once, here, and again only when an object it was compiled from changes. Deviations + /// are recorded on against when it is a reference. + /// + public PdfFunction? GetFunction(CosObject function) + { + ArgumentNullException.ThrowIfNull(function); + return Functions.Get(function); + } + /// public void Dispose() => _source.Dispose(); + /// Gets the document's functions, compiled once each (issue #78): the seam colour spaces, graphics states and shadings use. + internal FunctionCache Functions { get; } + /// Builds the bytes of a new one-page document and opens them (issue #44). /// The engine's configuration. /// The document. diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index a576dc7d..9abb0276 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -404,3 +404,43 @@ Broadside.Security.PublicKeySecurityHandler.Filter.get -> Broadside.Objects.CosN Broadside.Security.PublicKeySecurityHandler.PublicKeySecurityHandler() -> void Broadside.Security.PublicKeySecurityHandler.SubFilters.get -> System.Collections.Generic.IReadOnlyCollection! override Broadside.Security.PdfCertificateCredentials.ToString() -> string! +abstract Broadside.Graphics.PdfFunction.FunctionType.get -> Broadside.Graphics.PdfFunctionType +Broadside.Graphics.PdfExponentialFunction +Broadside.Graphics.PdfExponentialFunction.C0.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Graphics.PdfExponentialFunction.C1.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Graphics.PdfExponentialFunction.Exponent.get -> double? +Broadside.Graphics.PdfFunction +Broadside.Graphics.PdfFunction.CosObject.get -> Broadside.Objects.CosObject! +Broadside.Graphics.PdfFunction.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Graphics.PdfFunction.Domain.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Graphics.PdfFunction.Evaluate(System.ReadOnlySpan input, System.Span output) -> void +Broadside.Graphics.PdfFunction.Evaluate(System.ReadOnlySpan inputs, System.Span outputs, int count) -> void +Broadside.Graphics.PdfFunction.InputCount.get -> int +Broadside.Graphics.PdfFunction.IsValid.get -> bool +Broadside.Graphics.PdfFunction.MinimumVersion.get -> Broadside.PdfVersion +Broadside.Graphics.PdfFunction.OutputCount.get -> int +Broadside.Graphics.PdfFunction.Range.get -> System.Collections.Generic.IReadOnlyList? +Broadside.Graphics.PdfFunction.Reference.get -> Broadside.Objects.CosReference? +Broadside.Graphics.PdfFunctionType +Broadside.Graphics.PdfFunctionType.Exponential = 2 -> Broadside.Graphics.PdfFunctionType +Broadside.Graphics.PdfFunctionType.PostScriptCalculator = 4 -> Broadside.Graphics.PdfFunctionType +Broadside.Graphics.PdfFunctionType.Sampled = 0 -> Broadside.Graphics.PdfFunctionType +Broadside.Graphics.PdfFunctionType.Stitching = 3 -> Broadside.Graphics.PdfFunctionType +Broadside.Graphics.PdfPostScriptFunction +Broadside.Graphics.PdfPostScriptFunction.Stream.get -> Broadside.Objects.CosStream? +Broadside.Graphics.PdfSampledFunction +Broadside.Graphics.PdfSampledFunction.BitsPerSample.get -> int? +Broadside.Graphics.PdfSampledFunction.Decode.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Graphics.PdfSampledFunction.Encode.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Graphics.PdfSampledFunction.Order.get -> int +Broadside.Graphics.PdfSampledFunction.Size.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Graphics.PdfSampledFunction.Stream.get -> Broadside.Objects.CosStream? +Broadside.Graphics.PdfStitchingFunction +Broadside.Graphics.PdfStitchingFunction.Bounds.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Graphics.PdfStitchingFunction.Encode.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Graphics.PdfStitchingFunction.Functions.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfDocument.GetFunction(Broadside.Objects.CosObject! function) -> Broadside.Graphics.PdfFunction? +override Broadside.Graphics.PdfExponentialFunction.FunctionType.get -> Broadside.Graphics.PdfFunctionType +override Broadside.Graphics.PdfPostScriptFunction.FunctionType.get -> Broadside.Graphics.PdfFunctionType +override Broadside.Graphics.PdfSampledFunction.FunctionType.get -> Broadside.Graphics.PdfFunctionType +override Broadside.Graphics.PdfStitchingFunction.FunctionType.get -> Broadside.Graphics.PdfFunctionType diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 4a3ab467..efefa6c3 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -1,6 +1,7 @@ using System.Buffers; using Broadside.Diagnostics; using Broadside.Filters; +using Broadside.Graphics; using Broadside.IO; using Broadside.Objects; using Broadside.Parsing; @@ -37,6 +38,8 @@ internal static class FuzzTargets ["decrypt"] = Decrypt, ["mac-token"] = MacToken, ["public-key"] = PublicKey.Target, + ["function-type4"] = FunctionType4, + ["function-sampled"] = FunctionSampled, }; private static readonly CosName ContentsKey = new("Contents"); @@ -541,6 +544,124 @@ private static void Decrypt(ReadOnlySpan data) } } + /// + /// Compiles the input as a Type 4 program and evaluates it at fixed points. Byte 0 picks m (1 to 4 inputs, Domain [-1 1] each) + /// and n (1 to 4 outputs, Range [-10 10] each); the rest is the program. Compiling never throws in lenient mode; every output + /// must lie in the range, and once warm an evaluation must allocate nothing. + /// + /// ISO 32000-2 §7.10.5, Annex B. + private static void FunctionType4(ReadOnlySpan data) + { + if (data.IsEmpty) + { + return; + } + + int inputs = 1 + (data[0] % 4); + int outputs = 1 + ((data[0] >> 2) % 4); + var dictionary = new CosDictionary + { + [new CosName("FunctionType")] = new CosInteger(4), + [new CosName("Domain")] = Pairs(inputs, -1, 1), + [new CosName("Range")] = Pairs(outputs, -10, 10), + }; + EvaluateFunction(new CosStream(dictionary, data[1..].ToArray()), inputs, outputs, -10, 10); + } + + /// + /// Builds a Type 0 function from the input and evaluates it at fixed points. Byte 0 picks m (1 to 3) and n (1 to 4), byte 1 + /// BitsPerSample (one of the eight, or 3 or 5), Order (1 or 3) and whether Encode reverses the first input, bytes 2 to 4 the Size + /// of each input (1 to 8); the rest is the sample data, as short or long as it comes. Every output must lie in the Range [0 1]. + /// + /// ISO 32000-2 §7.10.2. + private static void FunctionSampled(ReadOnlySpan data) + { + if (data.Length < 5) + { + return; + } + + int[] widths = [1, 2, 4, 8, 12, 16, 24, 32, 3, 5]; + int inputs = 1 + (data[0] % 3); + int outputs = 1 + ((data[0] >> 2) % 4); + var size = new CosArray(); + for (int i = 0; i < inputs; i++) + { + size.Add(new CosInteger(1 + (data[2 + i] % 8))); + } + + var dictionary = new CosDictionary + { + [new CosName("FunctionType")] = new CosInteger(0), + [new CosName("Domain")] = Pairs(inputs, -1, 1), + [new CosName("Range")] = Pairs(outputs, 0, 1), + [new CosName("Size")] = size, + [new CosName("BitsPerSample")] = new CosInteger(widths[data[1] % widths.Length]), + [new CosName("Order")] = new CosInteger((data[1] & 0x10) != 0 ? 3 : 1), + }; + if ((data[1] & 0x20) != 0) + { + var encode = Pairs(inputs, 0, 1); + encode[0] = new CosInteger(1 + (data[2] % 8)); + encode[1] = new CosInteger(0); + dictionary[new CosName("Encode")] = encode; + } + + EvaluateFunction(new CosStream(dictionary, data[5..].ToArray()), inputs, outputs, 0, 1); + } + + private static CosArray Pairs(int count, int low, int high) + { + var pairs = new CosArray(); + for (int i = 0; i < count; i++) + { + pairs.Add(new CosInteger(low)); + pairs.Add(new CosInteger(high)); + } + + return pairs; + } + + /// Evaluates a function at inputs below, inside and above its domain; checks the outputs and that warm evaluations allocate nothing. + private static void EvaluateFunction(CosStream stream, int inputs, int outputs, double low, double high) + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.GetFunction(stream) ?? throw new InvalidOperationException("A function stream was not seen as a function."); + if (function.IsValid && (function.InputCount != inputs || function.OutputCount != outputs)) + { + throw new InvalidOperationException($"A valid function has {function.InputCount} inputs and {function.OutputCount} outputs; the dictionary says {inputs} and {outputs}."); + } + + float[] points = [-2f, -1f, -0.5f, 0f, 0.3f, 1f, 2f, float.NaN]; + Span input = stackalloc float[inputs]; + Span output = stackalloc float[outputs]; + long allocated = long.MaxValue; + for (int round = 0; round < 3 && allocated != 0; round++) + { + long before = GC.GetAllocatedBytesForCurrentThread(); + foreach (float point in points) + { + input.Fill(point); + input[0] = -point; + function.Evaluate(input, output); + foreach (float value in output[..function.OutputCount]) + { + if (!(value >= low && value <= high)) + { + throw new InvalidOperationException($"Output {value} is outside the range [{low} {high}]."); + } + } + } + + allocated = GC.GetAllocatedBytesForCurrentThread() - before; + } + + if (allocated != 0) + { + throw new InvalidOperationException($"Evaluating allocated {allocated} bytes in every round."); + } + } + /// Parses the input as a DER-encoded PDF MAC token (a CMS AuthenticatedData) and checks its structure. /// ISO/TS 32004 §6.2-6.3; RFC 5652 §9. private static void MacToken(ReadOnlySpan data) => _ = IntegrityVerifier.TryParseToken(data.ToArray(), out _); diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index 1a3db895..86d915f9 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. `function-type4` compiles the input after its first byte as a Type 4 (PostScript calculator) program (byte 0 picks 1 to 4 inputs and 1 to 4 outputs) and `function-sampled` builds a Type 0 (sampled) function whose Size, BitsPerSample, Order and Encode come from bytes 0 to 4 and whose samples are the rest (ISO 32000-2 §7.10); both evaluate at fixed points inside and outside the domain, require every output inside the range, and require warm evaluations to allocate nothing. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. @@ -42,6 +42,8 @@ mkdir -p artifacts/fuzz/seeds-xref-stream artifacts/fuzz/seeds-object-stream `mac-token` takes a DER token: seed it with the one in `encrypted-mac.pdf` (`python3 -c "import re,sys; d=open('tests/Corpus/encrypted-mac.pdf','rb').read(); sys.stdout.buffer.write(bytes.fromhex(re.search(rb'/MAC <([0-9A-F]+)>', d).group(1).decode()))" > artifacts/fuzz/seeds/mac-token.bin`). `decrypt` takes a selector byte and ciphertext: prefix the content stream of an encrypted corpus file with `\001` (AES-128) or `\003` (GCM). +`function-type4` and `function-sampled` take control bytes and a raw program or sample table; for libFuzzer and AFL seed them from `functions.pdf`: `{ printf '\014'; qpdf --show-object=17 --filtered-stream-data tests/Corpus/functions.pdf; } > artifacts/fuzz/seeds-type4/logo-green.bin` (1 input, 4 outputs) and `{ printf '\014\003\002\000\000'; qpdf --show-object=11 --filtered-stream-data tests/Corpus/functions.pdf; } > artifacts/fuzz/seeds-sampled/sampled.bin` (1 input, 4 outputs, 8 bits, Size 3). + For the `filter-*` targets whole files are weak seeds too (a whole PDF as a stream body); for real fuzzing extract stream bodies, for example `qpdf --show-object=4 --raw-stream-data tests/Corpus/lzw-stream.pdf > artifacts/fuzz/seeds/lzw.bin`. Smoke mode is a regression net, not a fuzzer: it has no coverage feedback and finds only shallow bugs. Use a real fuzzer for anything that parses. diff --git a/tests/Broadside.TestSupport/Corpus.cs b/tests/Broadside.TestSupport/Corpus.cs index e98e5c47..8f557e8b 100644 --- a/tests/Broadside.TestSupport/Corpus.cs +++ b/tests/Broadside.TestSupport/Corpus.cs @@ -40,6 +40,7 @@ public static class Corpus "outline.pdf", "name-tree-dests.pdf", "metadata-xmp.pdf", + "functions.pdf", ]; private static readonly string[] Malformed = diff --git a/tests/Broadside.Tests/Graphics/CorpusFunctionTests.cs b/tests/Broadside.Tests/Graphics/CorpusFunctionTests.cs new file mode 100644 index 00000000..05d827bd --- /dev/null +++ b/tests/Broadside.Tests/Graphics/CorpusFunctionTests.cs @@ -0,0 +1,61 @@ +using Broadside.Graphics; +using Broadside.Objects; +using Broadside.TestSupport; +using static Broadside.Tests.Graphics.FunctionTesting; + +namespace Broadside.Tests.Graphics; + +/// +/// functions.pdf: the tint transforms of six Separation spaces (ISO 32000-2 §8.6.6.4), one per function type plus a shared +/// indirect function, read from a file and evaluated at the tints the page paints with. The expected values are what poppler renders +/// (tests/Corpus/README.md). +/// +public class CorpusFunctionTests +{ + public static TheoryData TintTransforms => new() + { + { "CS0", PdfFunctionType.Sampled, 0.5f, [0.2f, 0.4f, 0f, 0f] }, + { "CS0", PdfFunctionType.Sampled, 0.25f, [0.1f, 0.2f, 0f, 0f] }, + { "CS1", PdfFunctionType.Exponential, 0.5f, [0.5f, 0.5f, 1f] }, + { "CS2", PdfFunctionType.Exponential, 0.5f, [0.75f] }, + { "CS3", PdfFunctionType.Stitching, 0.75f, [0.25f] }, + { "CS3", PdfFunctionType.Stitching, 0.25f, [0.5f] }, + { "CS4", PdfFunctionType.PostScriptCalculator, 0.5f, [0.42f, 0f, 0.22f, 0.105f] }, + { "CS5", PdfFunctionType.Exponential, 0.25f, [0.75f, 0.75f, 1f] }, + }; + + [Theory] + [MemberData(nameof(TintTransforms))] + public void Each_tint_transform_evaluates_to_the_colour_the_page_shows(string space, PdfFunctionType type, float tint, float[] expected) + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("functions.pdf")); + + PdfFunction function = document.Function(TintTransform(document, space)); + + Assert.Equal(type, function.FunctionType); + Assert.NotNull(function.Reference); + Near(expected, function.At(tint), 1e-6); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Two_spaces_that_share_an_indirect_function_share_its_view() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("functions.pdf")); + + PdfFunction linear = document.Function(TintTransform(document, "CS1")); + PdfFunction shared = document.Function(TintTransform(document, "CS5")); + + Assert.Same(linear, shared); + Assert.Equal(new CosReference(12, 0), shared.Reference); + } + + /// The fourth element of the Separation array named in the page's resources. + private static CosObject TintTransform(PdfDocument document, string space) + { + var resources = (CosDictionary)document.Resolve(document.Pages[0].Resources); + var spaces = (CosDictionary)document.Resolve(resources[new CosName("ColorSpace")]); + var separation = (CosArray)document.Resolve(spaces[new CosName(space)]); + return separation[3]; + } +} diff --git a/tests/Broadside.Tests/Graphics/ExponentialFunctionTests.cs b/tests/Broadside.Tests/Graphics/ExponentialFunctionTests.cs new file mode 100644 index 00000000..ae1e0952 --- /dev/null +++ b/tests/Broadside.Tests/Graphics/ExponentialFunctionTests.cs @@ -0,0 +1,124 @@ +using Broadside.Diagnostics; +using Broadside.Graphics; +using static Broadside.Tests.Graphics.FunctionTesting; + +namespace Broadside.Tests.Graphics; + +/// Type 2 (exponential interpolation) functions, ISO 32000-2 §7.10.3, Table 40. +public class ExponentialFunctionTests +{ + [Fact] + public void Interpolates_between_C0_and_C1_by_x_to_the_N() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Cos("<< /FunctionType 2 /Domain [0 1] /C0 [0 0.5] /C1 [1 0] /N 2 >>")); + + Assert.Equal(PdfFunctionType.Exponential, function.FunctionType); + Assert.Equal(1, function.InputCount); + Assert.Equal(2, function.OutputCount); + Near([0.25f, 0.375f], function.At(0.5f)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void C0_and_C1_default_to_0_and_1() + { + using PdfDocument document = PdfDocument.Create(); + var function = (PdfExponentialFunction)document.Function(Cos("<< /FunctionType 2 /Domain [0 1] /N 3 >>")); + + Assert.Equal([0.0], function.C0); + Assert.Equal([1.0], function.C1); + Assert.Equal(3.0, function.Exponent); + Near([0.125f], function.At(0.5f)); + Assert.Equal(new PdfVersion(1, 3), function.MinimumVersion); + } + + [Theory] + [InlineData(0f, 0.2f)] + [InlineData(0.25f, 0.4f)] + [InlineData(1f, 1f)] + public void N_of_1_is_linear_interpolation(float x, float expected) + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Cos("<< /FunctionType 2 /Domain [0 1] /C0 [0.2] /C1 [1] /N 1 >>")); + + Near([expected], function.At(x)); + } + + [Fact] + public void Inputs_are_clipped_to_the_domain_and_outputs_to_the_range() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Cos("<< /FunctionType 2 /Domain [0 2] /C0 [0 0] /C1 [1 -1] /N 1 /Range [0 1.5 -0.5 0] >>")); + + Near([1.5f, -0.5f], function.At(7f)); + Near([0f, 0f], function.At(-3f)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_non_integer_N_with_a_domain_reaching_below_zero_is_noted_and_negative_inputs_give_C0() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Cos("<< /FunctionType 2 /Domain [-1 1] /C0 [0.3] /C1 [1] /N 0.5 >>")); + + Assert.Equal(["FunctionEntryInvalid"], document.Codes()); + Near([0.3f + (0.5f * 0.7f)], function.At(0.25f)); + Near([0.3f], function.At(-0.25f)); + Assert.Equal(["FunctionEntryInvalid", "FunctionEvaluationRepaired"], document.Codes()); + } + + [Fact] + public void A_negative_N_at_zero_gives_C0() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Cos("<< /FunctionType 2 /Domain [0 1] /C0 [0.1 0.2] /C1 [1 1] /N -1 >>")); + + Near([0.1f, 0.2f], function.At(0f)); + Near([0.1f + (2 * 0.9f), 0.2f + (2 * 0.8f)], function.At(0.5f)); + Assert.Contains("FunctionEvaluationRepaired", document.Codes()); + } + + [Fact] + public void A_missing_N_makes_the_function_invalid_with_outputs_of_zero() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Cos("<< /FunctionType 2 /Domain [0 1] /C0 [0.5 0.5] /C1 [1 1] /Range [0.25 1 0 1] >>")); + + Assert.False(function.IsValid); + Assert.Equal(2, function.OutputCount); + Near([0.25f, 0f], function.At(0.5f)); + Diagnostic diagnostic = Assert.Single(document.Diagnostics, static d => d.Code == "FunctionInvalid"); + Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity); + } + + [Fact] + public void A_missing_domain_is_one_input_in_0_to_1() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Cos("<< /FunctionType 2 /N 1 >>")); + + Assert.True(function.IsValid); + Assert.Empty(function.Domain); + Near([1f], function.At(4f)); + Assert.Equal(["FunctionEntryInvalid"], document.Codes()); + } + + [Fact] + public void C0_and_C1_of_different_lengths_use_the_shorter() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Cos("<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0] /N 1 >>")); + + Assert.Equal(1, function.OutputCount); + Assert.Equal(["FunctionEntryInvalid"], document.Codes()); + } + + [Fact] + public void Strict_mode_throws_for_a_function_that_needs_repair() + { + using PdfDocument document = PdfDocument.Create(new PdfOptions().UseStrict()); + + Assert.Throws(() => document.GetFunction(Cos("<< /FunctionType 2 /N 1 >>"))); + } +} diff --git a/tests/Broadside.Tests/Graphics/FunctionAllocationTests.cs b/tests/Broadside.Tests/Graphics/FunctionAllocationTests.cs new file mode 100644 index 00000000..532031a9 --- /dev/null +++ b/tests/Broadside.Tests/Graphics/FunctionAllocationTests.cs @@ -0,0 +1,90 @@ +using Broadside.Graphics; +using Broadside.Objects; +using Broadside.Tests.Document; +using static Broadside.Tests.Graphics.FunctionTesting; + +namespace Broadside.Tests.Graphics; + +/// +/// Function evaluation is a hot path (every shading pixel, every tint) and allocates nothing (CLAUDE.md "Code conventions"; +/// ISO 32000-2 §7.10). This is the build-breaking half of that rule; FunctionBenchmarks is the measuring half. In the heavy +/// collection, like the other allocation tests that run many iterations, so tiered compilation triggered by parallel tests does not +/// show up in this thread's count. +/// +[Collection(HeavyTestCollection.Name)] +public class FunctionAllocationTests +{ + private const int Evaluations = 10_000; + + public static TheoryData Functions => [.. Samples.Keys]; + + private static Dictionary> Samples { get; } = new() + { + ["Type 0, 1 in, 3 out, 8-bit"] = static () => Stream( + "<< /FunctionType 0 /Domain [0 1] /Range [0 1 0 1 0 1] /Size [4] /BitsPerSample 8 >>", + [.. Enumerable.Range(0, 12).Select(static i => (byte)(i * 20))]), + ["Type 0, 2 in, 1 out, 16-bit"] = static () => Stream( + "<< /FunctionType 0 /Domain [0 1 0 1] /Range [0 1] /Size [3 3] /BitsPerSample 16 >>", + [.. Enumerable.Range(0, 18).Select(static i => (byte)(i * 13))]), + ["Type 2"] = static () => Cos("<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0] /C1 [1 0.5 0.25] /N 1.7 >>"), + ["Type 3"] = static () => Cos( + "<< /FunctionType 3 /Domain [0 1] /Bounds [0.5] /Encode [0 1 1 0] /Functions [" + + "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 1] /C1 [1 0 0] /N 1 >> << /FunctionType 2 /Domain [0 1] /C0 [0 1 0] /C1 [1 1 1] /N 2 >>] >>"), + ["Type 4, LogoGreen"] = static () => Program( + "<< /FunctionType 4 /Domain [0 1] /Range [0 1 0 1 0 1 0 1] >>", + "{dup 0.84 mul exch 0.00 exch dup 0.44 mul exch 0.21 mul}"), + ["Type 4, DoubleDot"] = static () => Program( + "<< /FunctionType 4 /Domain [-1 1 -1 1] /Range [-1 1] >>", + "{360 mul sin 2 div exch 360 mul sin 2 div add}"), + ["Type 4, hexachrome"] = static () => Program( + "<< /FunctionType 4 /Domain [0 1 0 1 0 1 0 1 0 1 0 1] /Range [0 1 0 1 0 1 0 1] >>", + HexachromeProgram), + }; + + /// + /// A 6-in 4-out hexachrome tint transform (§7.10.5.1 NOTE 1): c m y k orange green to C = c + 0.6 green, M = m + 0.5 orange, + /// Y = y + 0.9 orange + 0.8 green, K = k (snapped to 1 above 0.99). + /// + internal const string HexachromeProgram = + "{ 5 index 1 index 0.6 mul add 5 index 3 index 0.5 mul add 5 index 4 index 0.9 mul add 3 index 0.8 mul add " + + "5 index 10 4 roll pop pop pop pop pop pop dup 0.99 gt { pop 1 } if }"; + + [Theory] + [MemberData(nameof(Functions))] + public void Evaluating_a_function_allocates_nothing(string name) + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Samples[name]()); + float[] input = new float[function.InputCount]; + float[] output = new float[function.OutputCount]; + float[] inputs = new float[function.InputCount * 16]; + float[] outputs = new float[function.OutputCount * 16]; + Run(function, input, output, inputs, outputs, 1_000); + + long before = GC.GetAllocatedBytesForCurrentThread(); + Run(function, input, output, inputs, outputs, Evaluations); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.True(function.IsValid); + Assert.Empty(document.Diagnostics); + Assert.Equal(0, allocated); + } + + private static void Run(PdfFunction function, float[] input, float[] output, float[] inputs, float[] outputs, int count) + { + for (int k = 0; k < count; k++) + { + for (int i = 0; i < input.Length; i++) + { + input[i] = ((k * (i + 3)) % 101) / 100f; + } + + function.Evaluate(input, output); + } + + for (int k = 0; k < count / 16; k++) + { + function.Evaluate(inputs, outputs, 16); + } + } +} diff --git a/tests/Broadside.Tests/Graphics/FunctionConcurrencyTests.cs b/tests/Broadside.Tests/Graphics/FunctionConcurrencyTests.cs new file mode 100644 index 00000000..0db28a48 --- /dev/null +++ b/tests/Broadside.Tests/Graphics/FunctionConcurrencyTests.cs @@ -0,0 +1,32 @@ +using Broadside.Graphics; +using Broadside.Tests.Document; +using static Broadside.Tests.Graphics.FunctionTesting; + +namespace Broadside.Tests.Graphics; + +/// +/// A compiled function is shared by every thread that renders the document (CLAUDE.md thread-safety contract; ISO 32000-2 §7.10): +/// its scratch space lives on each caller's stack, so concurrent evaluations cannot disturb each other. Runs in the heavy +/// collection because it saturates the machine. +/// +[Collection(HeavyTestCollection.Name)] +public class FunctionConcurrencyTests +{ + [Fact] + public void Concurrent_evaluations_agree_with_a_single_threaded_one() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Program( + "<< /FunctionType 4 /Domain [-1 1 -1 1] /Range [-1 1] >>", + "{360 mul sin 2 div exch 360 mul sin 2 div add}")); + float[] expected = [.. Enumerable.Range(0, 1000).Select(i => function.At(i / 1000f, 1 - (i / 500f))[0])]; + + Parallel.For(0, 64, _ => + { + for (int i = 0; i < expected.Length; i++) + { + Assert.Equal(expected[i], function.At(i / 1000f, 1 - (i / 500f))[0]); + } + }); + } +} diff --git a/tests/Broadside.Tests/Graphics/FunctionTesting.cs b/tests/Broadside.Tests/Graphics/FunctionTesting.cs new file mode 100644 index 00000000..622c8d00 --- /dev/null +++ b/tests/Broadside.Tests/Graphics/FunctionTesting.cs @@ -0,0 +1,51 @@ +using System.Text; +using Broadside.Graphics; +using Broadside.Objects; + +namespace Broadside.Tests.Graphics; + +/// Builds function objects from PDF syntax and evaluates them through the public view. +internal static class FunctionTesting +{ + /// Parses one COS object written in PDF syntax. + public static CosObject Cos(string syntax) => CosObject.Parse(Encoding.Latin1.GetBytes(syntax)); + + /// A stream with and the given (unfiltered) data. + public static CosStream Stream(string dictionary, byte[] data) => new((CosDictionary)Cos(dictionary), data); + + /// A Type 4 function stream: plus the program text. + public static CosStream Program(string dictionary, string code) => Stream(dictionary, Encoding.ASCII.GetBytes(code)); + + /// A Type 4 function of inputs in [-1000 1000] and outputs in [-10^10 10^10]. + public static CosStream Calculator(string code, int inputs, int outputs) => + Program($"<< /FunctionType 4 /Domain [{Pairs(inputs, "-1000 1000")}] /Range [{Pairs(outputs, "-10000000000 10000000000")}] >>", code); + + /// The view of ; fails the test when the document does not see a function. + public static PdfFunction Function(this PdfDocument document, CosObject value) => + document.GetFunction(value) ?? throw new InvalidOperationException("Not a function."); + + /// Evaluates at one point. + public static float[] At(this PdfFunction function, params float[] input) + { + float[] output = new float[function.OutputCount]; + function.Evaluate(input, output); + return output; + } + + /// Asserts that two output vectors agree to within . + public static void Near(float[] expected, float[] actual, double tolerance = 1e-5) + { + Assert.Equal(expected.Length, actual.Length); + for (int i = 0; i < expected.Length; i++) + { + Assert.True( + Math.Abs(expected[i] - actual[i]) <= tolerance, + $"Output {i}: expected {expected[i]}, got {actual[i]} (all: [{string.Join(", ", actual)}])."); + } + } + + /// The codes of the document's diagnostics, in order. + public static string[] Codes(this PdfDocument document) => [.. document.Diagnostics.Select(static d => d.Code)]; + + private static string Pairs(int count, string pair) => string.Join(" ", Enumerable.Repeat(pair, count)); +} diff --git a/tests/Broadside.Tests/Graphics/FunctionViewTests.cs b/tests/Broadside.Tests/Graphics/FunctionViewTests.cs new file mode 100644 index 00000000..a3b9a5d5 --- /dev/null +++ b/tests/Broadside.Tests/Graphics/FunctionViewTests.cs @@ -0,0 +1,158 @@ +using Broadside.Diagnostics; +using Broadside.Graphics; +using Broadside.Graphics.Functions; +using Broadside.Objects; +using static Broadside.Tests.Graphics.FunctionTesting; + +namespace Broadside.Tests.Graphics; + +/// +/// What every function shares (ISO 32000-2 §7.10.1, Table 38) and how behaves as a live view +/// (ADR 0004): one view per object, recompiled after a change, batch evaluation, and the forms consumers accept. +/// +public class FunctionViewTests +{ + [Fact] + public void The_same_object_gives_the_same_view() + { + using PdfDocument document = PdfDocument.Create(); + CosObject dictionary = Cos("<< /FunctionType 2 /Domain [0 1] /N 1 >>"); + + Assert.Same(document.GetFunction(dictionary), document.GetFunction(dictionary)); + Assert.NotSame(document.GetFunction(dictionary), document.GetFunction(Cos("<< /FunctionType 2 /Domain [0 1] /N 1 >>"))); + } + + [Fact] + public void Entries_are_read_live_and_evaluation_follows_a_change_to_the_dictionary() + { + using PdfDocument document = PdfDocument.Create(); + var dictionary = (CosDictionary)Cos("<< /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 1 >>"); + PdfFunction function = document.Function(dictionary); + Near([0.5f], function.At(0.5f)); + + dictionary[new CosName("N")] = new CosInteger(2); + ((CosArray)dictionary[new CosName("C1")])[0] = new CosInteger(3); + + Assert.Equal(2.0, ((PdfExponentialFunction)function).Exponent); + Assert.Equal([3.0], ((PdfExponentialFunction)function).C1); + Near([0.75f], function.At(0.5f)); + } + + [Fact] + public void A_change_to_a_sampled_function_data_is_seen() + { + using PdfDocument document = PdfDocument.Create(); + CosStream stream = Stream("<< /FunctionType 0 /Domain [0 1] /Range [0 255] /Size [2] /BitsPerSample 8 >>", [0, 100]); + PdfFunction function = document.Function(stream); + Near([50f], function.At(0.5f)); + + stream.EncodedData = new byte[] { 0, 200 }; + + Near([100f], function.At(0.5f)); + } + + [Fact] + public void Changing_the_function_type_gives_a_new_view_and_invalidates_the_old_one() + { + using PdfDocument document = PdfDocument.Create(); + var dictionary = (CosDictionary)Cos("<< /FunctionType 2 /Domain [0 1] /N 1 /Functions [<< /FunctionType 2 /Domain [0 1] /N 2 >>] /Bounds [] /Encode [0 1] >>"); + PdfFunction exponential = document.Function(dictionary); + + dictionary[new CosName("FunctionType")] = new CosInteger(3); + PdfFunction stitching = document.Function(dictionary); + + Assert.IsType(stitching); + Near([0.25f], stitching.At(0.5f)); + Assert.False(exponential.IsValid); + } + + [Fact] + public void A_batch_evaluates_points_one_after_the_other() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Calculator("{ dup 2 mul exch 3 mul }", 1, 2)); + float[] inputs = [1f, 2f, 3f]; + float[] outputs = new float[6]; + + function.Evaluate(inputs, outputs, 3); + + Assert.Equal([2f, 3f, 4f, 6f, 6f, 9f], outputs); + Assert.Throws(() => function.Evaluate(inputs, new float[5], 3)); + Assert.Throws(() => function.Evaluate(inputs, outputs, 4)); + Assert.Throws(() => function.Evaluate(ReadOnlySpan.Empty, new float[2])); + Assert.Throws(() => function.Evaluate([1f], new float[1])); + } + + public static TheoryData NotFunctions => new() + { + "<< /FunctionType 1 /Domain [0 1] >>", + "<< /Domain [0 1] /N 1 >>", + "[0 1]", + "/Identity", + }; + + [Theory] + [MemberData(nameof(NotFunctions))] + public void An_object_that_is_not_a_function_gives_no_view(string syntax) + { + using PdfDocument document = PdfDocument.Create(); + + Assert.Null(document.GetFunction(Cos(syntax))); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("FunctionInvalid", diagnostic.Code); + } + + [Fact] + public void Odd_and_reversed_domain_entries_are_repaired() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Cos("<< /FunctionType 2 /Domain [1 0 5] /N 1 >>")); + + Near([1f], function.At(3f)); + Near([0f], function.At(-3f)); + + // Two repairs of one kind on one (direct) object: the sink keeps one diagnostic per code and object. + Assert.Equal(["FunctionEntryInvalid"], document.Codes()); + } + + [Fact] + public void Consumers_get_identity_and_arrays_of_one_output_functions_where_their_entry_allows_them() + { + using PdfDocument document = PdfDocument.Create(); + CosObject identity = Cos("/Identity"); + CosObject array = Cos("[<< /FunctionType 2 /Domain [0 1] /N 1 >> << /FunctionType 2 /Domain [0 1] /C0 [1] /C1 [0] /N 1 >>]"); + Span output = stackalloc float[2]; + + FunctionEvaluator? transfer = document.Functions.GetEvaluator(identity, FunctionForms.Identity, 1, 1); + Assert.NotNull(transfer); + Assert.Equal(FunctionStatus.Ok, transfer.Evaluate([0.3f], output)); + Assert.Equal(0.3f, output[0]); + + FunctionEvaluator? shading = document.Functions.GetEvaluator(array, FunctionForms.Array, 1, 2); + Assert.NotNull(shading); + Assert.Equal(2, shading.OutputCount); + Assert.Equal(FunctionStatus.Ok, shading.Evaluate([0.25f], output)); + Assert.Equal([0.25f, 0.75f], output.ToArray()); + Assert.Empty(document.Diagnostics); + + Assert.Null(document.Functions.GetEvaluator(identity, FunctionForms.Single, 1, 4)); + Assert.Null(document.Functions.GetEvaluator(array, FunctionForms.Single, 1, 2)); + Assert.Equal(["FunctionInvalid"], document.Codes()); + } + + [Fact] + public void A_missing_range_is_repaired_from_the_consumer_output_count() + { + using PdfDocument document = PdfDocument.Create(); + CosStream stream = Program("<< /FunctionType 4 /Domain [0 1] >>", "{ dup 2 mul }"); + + FunctionEvaluator? tint = document.Functions.GetEvaluator(stream, FunctionForms.Single, 1, 2); + + Assert.NotNull(tint); + Assert.True(tint.IsValid); + Span output = stackalloc float[2]; + Assert.Equal(FunctionStatus.Ok, tint.Evaluate([0.75f], output)); + Assert.Equal([0.75f, 1.5f], output.ToArray()); + Assert.Equal(["FunctionEntryInvalid"], document.Codes()); + } +} diff --git a/tests/Broadside.Tests/Graphics/PostScriptFunctionTests.cs b/tests/Broadside.Tests/Graphics/PostScriptFunctionTests.cs new file mode 100644 index 00000000..c873140e --- /dev/null +++ b/tests/Broadside.Tests/Graphics/PostScriptFunctionTests.cs @@ -0,0 +1,351 @@ +using System.Text; +using Broadside.Diagnostics; +using Broadside.Graphics; +using static Broadside.Tests.Graphics.FunctionTesting; + +namespace Broadside.Tests.Graphics; + +/// +/// Type 4 (PostScript calculator) functions, ISO 32000-2 §7.10.5 and Annex B, with the operator semantics and examples of the +/// PostScript Language Reference, Third Edition, §8.2. +/// +public class PostScriptFunctionTests +{ + /// Each row: a program body run on an empty stack, and the values it leaves. Expected values are PLRM's own examples where it gives one. + public static TheoryData OperatorExamples => new() + { + // B.2 Arithmetic operators. + { "3 4 add", [7f] }, + { "9.9 1.1 add", [11f] }, + { "2147483647 1 add", [2147483648f] }, + { "1 2 sub", [-1f] }, + { "2 3 mul", [6f] }, + { "3 2 div", [1.5f] }, + { "4 2 div", [2f] }, + { "-5 2 idiv", [-2f] }, + { "5 3 mod", [2f] }, + { "-5 3 mod", [-2f] }, + { "-3 abs", [3f] }, + { "4.5 neg", [-4.5f] }, + { "3.2 ceiling", [4f] }, + { "-4.8 ceiling", [-4f] }, + { "3.2 floor", [3f] }, + { "-4.8 floor", [-5f] }, + { "6.5 round", [7f] }, + { "-6.5 round", [-6f] }, + { "-4.8 round", [-5f] }, + { "-4.8 truncate", [-4f] }, + { "9 sqrt", [3f] }, + { "9 0.5 exp", [3f] }, + { "-9 -1 exp", [-0.111111f] }, + { "10 ln", [2.302585f] }, + { "100 log", [2f] }, + { "90 sin", [1f] }, + { "30 sin", [0.5f] }, + { "-90 sin", [-1f] }, + { "0 cos", [1f] }, + { "90 cos", [0f] }, + { "450 cos", [0f] }, + { "0 1 atan", [0f] }, + { "1 0 atan", [90f] }, + { "-100 0 atan", [270f] }, + { "4 4 atan", [45f] }, + { "-47.8 cvi", [-47f] }, + { "520.9 cvi", [520f] }, + { "3 cvr", [3f] }, + + // B.3 Relational, boolean and bitwise operators (booleans are turned into numbers with ifelse). + { "4.0 4 eq { 1 } { 0 } ifelse", [1f] }, + { "4 5 eq { 1 } { 0 } ifelse", [0f] }, + { "4 5 ne { 1 } { 0 } ifelse", [1f] }, + { "true 1 eq { 1 } { 0 } ifelse", [0f] }, + { "true true eq { 1 } { 0 } ifelse", [1f] }, + { "4.2 4 ge { 1 } { 0 } ifelse", [1f] }, + { "4 4 gt { 1 } { 0 } ifelse", [0f] }, + { "4 4 le { 1 } { 0 } ifelse", [1f] }, + { "3 4 lt { 1 } { 0 } ifelse", [1f] }, + { "true false and { 1 } { 0 } ifelse", [0f] }, + { "true false or { 1 } { 0 } ifelse", [1f] }, + { "true true xor { 1 } { 0 } ifelse", [0f] }, + { "true not { 1 } { 0 } ifelse", [0f] }, + { "false { 1 } { 0 } ifelse", [0f] }, + { "99 1 and", [1f] }, + { "52 7 and", [4f] }, + { "17 5 or", [21f] }, + { "5 3 xor", [6f] }, + { "12 3 xor", [15f] }, + { "52 not", [-53f] }, + { "7 3 bitshift", [56f] }, + { "142 -3 bitshift", [17f] }, + { "-1 -1 bitshift", [2147483647f] }, + { "1 32 bitshift", [0f] }, + + // B.4 Conditional operators. + { "1 true { 2 add } if", [3f] }, + { "1 false { 2 add } if", [1f] }, + { "true { true { 1 } { 2 } ifelse } { 3 } ifelse", [1f] }, + { "true { false { 1 } { 2 } ifelse } { 3 } ifelse", [2f] }, + { "false { true { 1 } { 2 } ifelse } { false { 3 } { 4 } ifelse } ifelse", [4f] }, + { "5 dup 3 gt { dup 4 gt { 10 add } if } { 100 add } ifelse", [15f] }, + + // B.5 Stack operators. + { "1 2 exch", [2f, 1f] }, + { "1 2 pop", [1f] }, + { "5 dup", [5f, 5f] }, + { "1 2 3 2 copy", [1f, 2f, 3f, 2f, 3f] }, + { "1 2 3 0 copy", [1f, 2f, 3f] }, + { "1 2 3 4 3 index", [1f, 2f, 3f, 4f, 1f] }, + { "1 2 3 0 index", [1f, 2f, 3f, 3f] }, + { "1 2 3 3 -1 roll", [2f, 3f, 1f] }, + { "1 2 3 3 1 roll", [3f, 1f, 2f] }, + { "1 2 3 3 4 roll", [3f, 1f, 2f] }, + { "1 2 3 3 0 roll", [1f, 2f, 3f] }, + { "9 1 2 3 3 -1 roll", [9f, 2f, 3f, 1f] }, + + // Comments and PDF number syntax. + { "% a comment\n4. .5 add", [4.5f] }, + }; + + [Theory] + [MemberData(nameof(OperatorExamples))] + public void Each_operator_matches_the_PLRM_examples(string body, float[] expected) + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Calculator($"{{ pop {body} }}", 1, expected.Length)); + + Near(expected, function.At(0f), 1e-5); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [InlineData(0.25f, 0f, 0.5f)] + [InlineData(0.25f, 0.25f, 1f)] + [InlineData(0f, 0f, 0f)] + [InlineData(-0.25f, 0.125f, -0.14644661f)] + [InlineData(4f, 0.25f, 0.5f)] + public void The_DoubleDot_spot_function_of_the_specification(float x, float y, float expected) + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Program( + "<< /FunctionType 4 /Domain [-1.0 1.0 -1.0 1.0] /Range [-1.0 1.0] >>", + "{360 mul sin\n2 div\nexch 360 mul sin\n2 div\nadd\n}")); + + Near([expected], function.At(x, y)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void The_LogoGreen_tint_transform_maps_a_tint_to_four_process_colorants() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Program( + "<< /FunctionType 4 /Domain [0.0 1.0] /Range [0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0] >>", + "{dup 0.84 mul\nexch 0.00 exch dup 0.44 mul exch 0.21 mul\n}")); + + Near([0.42f, 0f, 0.22f, 0.105f], function.At(0.5f)); + Near([0.84f, 0f, 0.44f, 0.21f], function.At(1f)); + Near([0.84f, 0f, 0.44f, 0.21f], function.At(3f)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void The_DeviceN_example_inserts_a_zero_component() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Program( + "<< /FunctionType 4 /Domain [0.0 1.0 0.0 1.0 0.0 1.0] /Range [0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0] >>", + "{ 0 exch }")); + + Near([0.1f, 0.2f, 0f, 0.3f], function.At(0.1f, 0.2f, 0.3f)); + Assert.Equal(PdfFunctionType.PostScriptCalculator, function.FunctionType); + Assert.Equal(3, function.InputCount); + } + + [Fact] + public void A_hexachrome_tint_transform_maps_six_colorants_to_four() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Program( + "<< /FunctionType 4 /Domain [0 1 0 1 0 1 0 1 0 1 0 1] /Range [0 1 0 1 0 1 0 1] >>", + FunctionAllocationTests.HexachromeProgram)); + + Near([0.25f, 0.45f, 0.95f, 0.4f], function.At(0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.25f)); + Near([1f, 1f, 1f, 1f], function.At(1f, 1f, 1f, 0.995f, 1f, 1f)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void The_stack_holds_100_entries() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction full = document.Function(Calculator($"{{ pop {Repeat("1 ", 100)}{Repeat("add ", 99)}}}", 1, 1)); + + Near([100f], full.At(0f)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Overflowing_the_stack_fails_the_evaluation_with_outputs_of_zero_clipped_to_the_range() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Program( + "<< /FunctionType 4 /Domain [0 1] /Range [0.5 1000] >>", + $"{{ pop {Repeat("1 ", 101)}{Repeat("add ", 100)}}}")); + + Assert.Equal(["FunctionProgramStackInvalid"], document.Codes()); + Near([0.5f], function.At(0f)); + Assert.Equal(["FunctionProgramStackInvalid", "FunctionEvaluationRepaired"], document.Codes()); + } + + [Fact] + public void Underflowing_the_stack_fails_the_evaluation() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Calculator("{ add }", 1, 1)); + + Near([0f], function.At(7f)); + Assert.Equal(["FunctionProgramStackInvalid", "FunctionEvaluationRepaired"], document.Codes()); + } + + [Fact] + public void Fewer_results_than_outputs_are_padded_with_zero_and_more_are_cut_to_the_topmost() + { + using PdfDocument fewerDocument = PdfDocument.Create(); + PdfFunction fewer = fewerDocument.Function(Calculator("{ 2 mul }", 1, 3)); + using PdfDocument moreDocument = PdfDocument.Create(); + PdfFunction more = moreDocument.Function(Calculator("{ dup 1 add dup 1 add }", 1, 2)); + + Near([4f, 0f, 0f], fewer.At(2f)); + Near([3f, 4f], more.At(2f)); + Assert.Equal(["FunctionProgramStackInvalid", "FunctionEvaluationRepaired"], fewerDocument.Codes()); + Assert.Equal(["FunctionProgramStackInvalid", "FunctionEvaluationRepaired"], moreDocument.Codes()); + } + + [Fact] + public void A_boolean_result_is_1_or_0() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Calculator("{ 0.5 gt }", 1, 1)); + + Near([1f], function.At(0.75f)); + Near([0f], function.At(0.25f)); + Assert.Equal(["FunctionEvaluationRepaired"], document.Codes()); + } + + [Theory] + [InlineData("{ 0 div }")] + [InlineData("{ 0 idiv }")] + [InlineData("{ 0 mod }")] + [InlineData("{ neg sqrt }")] + [InlineData("{ neg ln }")] + [InlineData("{ 0 mul log }")] + [InlineData("{ pop 0 0 atan }")] + public void An_undefined_result_is_zero_and_noted_once(string code) + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Calculator(code, 1, 1)); + + Near([0f], function.At(4f)); + Near([0f], function.At(5f)); + Assert.Equal(["FunctionEvaluationRepaired"], document.Codes()); + Assert.Equal(DiagnosticSeverity.Warning, document.Diagnostics[0].Severity); + } + + [Theory] + [InlineData("{ true add }", 3f)] + [InlineData("{ pop 2.7 3 idiv }", 0f)] + [InlineData("{ 7.9 bitshift }", 256f)] + [InlineData("{ pop 1 { 5 } { 6 } ifelse }", 5f)] + [InlineData("{ pop true 3 and }", 1f)] + public void An_operand_of_the_wrong_type_is_converted_and_noted(string code, float expected) + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Calculator(code, 1, 1)); + + Near([expected], function.At(2f)); + Assert.Equal(["FunctionEvaluationRepaired"], document.Codes()); + } + + [Fact] + public void Inputs_are_clipped_to_the_domain_before_the_program_runs() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Program("<< /FunctionType 4 /Domain [0 1] /Range [-10 10] >>", "{ 3 mul }")); + + Near([3f], function.At(5f)); + Near([0f], function.At(-5f)); + } + + [Theory] + [InlineData("dup mul", "FunctionProgramSyntaxInvalid")] + [InlineData("{ dup mul", "FunctionProgramSyntaxInvalid")] + [InlineData("{ dup mul } junk", "FunctionProgramSyntaxInvalid")] + [InlineData("{ dup mul } }", "FunctionProgramSyntaxInvalid")] + [InlineData("{ 1e0 mul }", "FunctionProgramSyntaxInvalid")] + public void Syntax_a_reader_can_repair_is_read_with_a_diagnostic(string code, string diagnostic) + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Calculator(code, 1, 1)); + + Assert.True(function.IsValid); + Assert.Equal(code.Contains("1e0", StringComparison.Ordinal) ? 3f : 9f, function.At(3f)[0]); + Assert.Equal([diagnostic], document.Codes()); + } + + public static TheoryData ProgramsOutsideTheSubset => new() + { + "{ 1 max }", + "{ dup exec }", + "{ (string) pop }", + "{ [1] pop }", + "{ /name pop }", + "{ 16#FF add }", + "{ { 1 } }", + "{ true { 1 } 2 }", + "{ true { 1 } { 2 } if }", + "{ true { 1 ifelse }", + "{ if }", + "{ 1 - }", + }; + + [Theory] + [MemberData(nameof(ProgramsOutsideTheSubset))] + public void A_program_outside_the_subset_is_invalid(string code) + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Calculator(code, 1, 2)); + + Assert.False(function.IsValid); + Assert.Equal(2, function.OutputCount); + Near([0f, 0f], function.At(1f)); + Assert.Equal(["FunctionInvalid"], document.Codes()); + } + + [Fact] + public void Braces_nest_256_deep_including_the_program_but_not_257() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction deep = document.Function(Calculator(Nested(255), 1, 1)); + Assert.True(deep.IsValid); + Near([1f], deep.At(0.5f)); + + PdfFunction deeper = document.Function(Calculator(Nested(256), 1, 1)); + Assert.False(deeper.IsValid); + Assert.Equal(["FunctionInvalid"], document.Codes()); + } + + [Fact] + public void A_missing_range_takes_the_output_count_from_nowhere_and_is_invalid() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Program("<< /FunctionType 4 /Domain [0 1] >>", "{ dup }")); + + Assert.False(function.IsValid); + Assert.Equal(["FunctionInvalid"], document.Codes()); + } + + private static string Repeat(string text, int count) => new StringBuilder().Insert(0, text, count).ToString(); + + /// A program of nested true { … } if bodies that leaves 1 on the stack. + private static string Nested(int levels) => $"{{ pop {Repeat("true { ", levels)}1 {Repeat("} if ", levels)}}}"; +} diff --git a/tests/Broadside.Tests/Graphics/SampledFunctionTests.cs b/tests/Broadside.Tests/Graphics/SampledFunctionTests.cs new file mode 100644 index 00000000..74c57659 --- /dev/null +++ b/tests/Broadside.Tests/Graphics/SampledFunctionTests.cs @@ -0,0 +1,323 @@ +using System.Globalization; +using Broadside.Graphics; +using static Broadside.Tests.Graphics.FunctionTesting; + +namespace Broadside.Tests.Graphics; + +/// Type 0 (sampled) functions, ISO 32000-2 §7.10.2, Table 39. +public class SampledFunctionTests +{ + private static readonly int[] AllBitsPerSample = [1, 2, 4, 8, 12, 16, 24, 32]; + + private static readonly int[][] Sizes = [[5], [3, 4], [3, 2, 3]]; + + public static TheoryData Shapes() + { + var data = new TheoryData(); + foreach (int bits in AllBitsPerSample) + { + foreach (int inputs in (int[])[1, 2, 3]) + { + foreach (int outputs in (int[])[1, 3, 4]) + { + data.Add(bits, inputs, outputs); + } + } + } + + return data; + } + + [Theory] + [MemberData(nameof(Shapes))] + public void Every_sample_of_a_table_comes_back_at_its_grid_point(int bits, int inputs, int outputs) + { + int[] size = Sizes[inputs - 1]; + ulong[] raw = Table(size, outputs, bits); + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Sampled(size, outputs, bits, raw)); + double maximum = Math.Pow(2, bits) - 1; + + foreach (int[] point in GridPoints(size)) + { + float[] x = [.. point.Select((g, i) => (float)g / (size[i] - 1))]; + int first = Index(point, size) * outputs; + float[] expected = [.. Enumerable.Range(0, outputs).Select(j => (float)(raw[first + j] / maximum))]; + Near(expected, function.At(x), 1e-6); + } + + Assert.Empty(document.Diagnostics); + } + + [Theory] + [MemberData(nameof(Shapes))] + public void Between_two_samples_the_output_is_their_average(int bits, int inputs, int outputs) + { + int[] size = Sizes[inputs - 1]; + ulong[] raw = Table(size, outputs, bits); + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Sampled(size, outputs, bits, raw)); + double maximum = Math.Pow(2, bits) - 1; + + // Halfway along the first dimension between grid points 1 and 2, on grid point 0 elsewhere. + float[] x = new float[inputs]; + x[0] = 1.5f / (size[0] - 1); + int left = Index([1, .. new int[inputs - 1]], size) * outputs; + int right = Index([2, .. new int[inputs - 1]], size) * outputs; + float[] expected = [.. Enumerable.Range(0, outputs).Select(j => (float)((raw[left + j] + raw[right + j]) / 2.0 / maximum))]; + + Near(expected, function.At(x), 1e-6); + } + + [Fact] + public void Bilinear_interpolation_weights_the_four_corners_of_the_cell() + { + // Size [2 2]: f(0,0) = 0, f(1,0) = 1, f(0,1) = 2, f(1,1) = 3 (as 8-bit samples over Decode [0 255]). + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Stream( + "<< /FunctionType 0 /Domain [0 1 0 1] /Range [0 255] /Size [2 2] /BitsPerSample 8 >>", + [0, 1, 2, 3])); + + Near([(0.75f * 0.5f * 0) + (0.25f * 0.5f * 1) + (0.75f * 0.5f * 2) + (0.25f * 0.5f * 3)], function.At(0.25f, 0.5f)); + } + + [Fact] + public void The_example_2_table_of_21_by_31_four_bit_samples_takes_326_bytes() + { + int[] size = [21, 31]; + ulong[] raw = new ulong[21 * 31]; + for (int row = 0; row < 31; row++) + { + for (int column = 0; column < 21; column++) + { + raw[(row * 21) + column] = (ulong)((column + row) % 16); + } + } + + byte[] data = Pack(raw, 4); + Assert.Equal(326, data.Length); + const string dictionary = "<< /FunctionType 0 /Domain [-1.0 1.0 -1.0 1.0] /Size [21 31] /Encode [0 20 0 30] /BitsPerSample 4 /Range [-1.0 1.0] /Decode [-1.0 1.0] >>"; + + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Stream(dictionary, data)); + Near([-1f], function.At(-1f, -1f)); + Near([-1f + (2f / 15)], function.At(-0.9f, -1f)); + Near([-1f + (2f * 5 / 15)], function.At(-0.9f, -0.8f + (0.2f / 3))); + Assert.Empty(document.Diagnostics); + + using PdfDocument shortDocument = PdfDocument.Create(); + PdfFunction truncated = shortDocument.Function(Stream(dictionary, data[..325])); + Assert.Equal(["FunctionSampleDataTruncated"], shortDocument.Codes()); + Near([-1f], truncated.At(1f, 1f)); + } + + [Fact] + public void A_dimension_of_size_1_maps_every_input_to_its_one_sample() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Stream( + "<< /FunctionType 0 /Domain [0 1 0 1] /Range [0 255] /Size [1 3] /BitsPerSample 8 >>", + [10, 20, 30])); + + Near([20f], function.At(0f, 0.5f)); + Near([25f], function.At(1f, 0.75f)); + Near([30f], function.At(0.3f, 1f)); + } + + [Fact] + public void A_non_integer_encode_reaches_between_samples() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Stream( + "<< /FunctionType 0 /Domain [0 1] /Range [0 255] /Size [3] /Encode [0 1.5] /BitsPerSample 8 >>", + [0, 100, 200])); + + Near([150f], function.At(1f)); + Near([75f], function.At(0.5f)); + } + + [Fact] + public void Inputs_at_the_domain_ends_read_the_first_and_last_samples_and_beyond_them_are_clipped() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Stream( + "<< /FunctionType 0 /Domain [-2 2] /Range [0 255] /Size [4] /BitsPerSample 8 >>", + [7, 9, 11, 250])); + + Near([7f], function.At(-2f)); + Near([250f], function.At(2f)); + Near([7f], function.At(-100f)); + Near([250f], function.At(float.PositiveInfinity)); + Near([7f], function.At(float.NaN)); + } + + [Fact] + public void Decode_maps_samples_and_the_range_clips_the_result() + { + using PdfDocument document = PdfDocument.Create(); + var function = (PdfSampledFunction)document.Function(Stream( + "<< /FunctionType 0 /Domain [0 1] /Range [0 1] /Decode [-1 3] /Size [2] /BitsPerSample 8 >>", + [0, 255])); + + Near([0f], function.At(0f)); + Near([0.5f], function.At(0.375f)); + Near([1f], function.At(1f)); + Assert.Equal([-1.0, 3.0], function.Decode); + Assert.Equal([0.0, 1.0], function.Encode); + Assert.Equal(8, function.BitsPerSample); + Assert.Equal(new PdfVersion(1, 2), function.MinimumVersion); + } + + [Fact] + public void Order_3_is_evaluated_linearly_and_noted_once() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Stream( + "<< /FunctionType 0 /Domain [0 1] /Range [0 255] /Size [4] /Order 3 /BitsPerSample 8 >>", + [0, 30, 60, 90])); + + Near([45f], function.At(0.5f)); + Assert.Equal(Broadside.Diagnostics.DiagnosticSeverity.Information, DiagnosticSeverityOf(document, "FunctionOrderUnsupported")); + Assert.Single(document.Diagnostics); + } + + [Fact] + public void Order_3_with_fewer_than_4_samples_in_a_dimension_is_ignored_silently() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Stream( + "<< /FunctionType 0 /Domain [0 1 0 1] /Range [0 255] /Size [4 3] /Order 3 /BitsPerSample 8 >>", + new byte[12])); + + Assert.True(function.IsValid); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Simplex_interpolation_beyond_eight_inputs_reproduces_a_linear_function() + { + // Ten inputs, Size 2 each, samples f(g) = sum of g_i × (i + 1), so f is linear and every interpolation scheme is exact. + const int inputs = 10; + int[] size = [.. Enumerable.Repeat(2, inputs)]; + ulong[] raw = [.. GridPoints(size).OrderBy(p => Index(p, size)).Select(static p => (ulong)p.Select(static (g, i) => g * (i + 1)).Sum())]; + string dictionary = string.Create(CultureInfo.InvariantCulture, $"<< /FunctionType 0 /Domain [{string.Join(" ", Enumerable.Repeat("0 1", inputs))}] /Range [0 65535] /Size [{string.Join(" ", size)}] /BitsPerSample 16 >>"); + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Stream(dictionary, Pack(raw, 16))); + + float[] x = [0.9f, 0.1f, 0.5f, 0.3f, 0.7f, 0.2f, 0.8f, 0.4f, 0.6f, 0.05f]; + Near([x.Select(static (v, i) => v * (i + 1)).Sum()], function.At(x), 1e-4); + } + + [Fact] + public void A_missing_range_without_a_hint_makes_the_function_invalid() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Stream("<< /FunctionType 0 /Domain [0 1] /Size [2] /BitsPerSample 8 >>", [0, 255])); + + Assert.False(function.IsValid); + Assert.Equal(["FunctionInvalid"], document.Codes()); + } + + [Fact] + public void A_size_that_would_need_too_many_samples_is_rejected_without_allocating_them() + { + using PdfDocument document = PdfDocument.Create(); + long before = GC.GetAllocatedBytesForCurrentThread(); + PdfFunction function = document.Function(Stream("<< /FunctionType 0 /Domain [0 1 0 1 0 1] /Range [0 1] /Size [100000 100000 100000] /BitsPerSample 8 >>", [1, 2, 3])); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.False(function.IsValid); + Assert.Equal(["FunctionInvalid"], document.Codes()); + Assert.True(allocated < 1_000_000, $"Allocated {allocated} bytes."); + } + + [Fact] + public void A_bit_width_outside_the_list_is_read_as_given_with_a_diagnostic() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Stream( + "<< /FunctionType 0 /Domain [0 1] /Range [0 7] /Decode [0 7] /Size [3] /BitsPerSample 3 >>", + Pack([5, 1, 7], 3))); + + Near([5f], function.At(0f)); + Near([1f], function.At(0.5f)); + Near([7f], function.At(1f)); + Assert.Equal(["FunctionEntryInvalid"], document.Codes()); + } + + [Fact] + public void A_type_0_dictionary_without_a_stream_is_invalid() + { + using PdfDocument document = PdfDocument.Create(); + var function = (PdfSampledFunction)document.Function(Cos("<< /FunctionType 0 /Domain [0 1] /Range [0 1] /Size [2] /BitsPerSample 8 >>")); + + Assert.False(function.IsValid); + Assert.Null(function.Stream); + Assert.Equal(["FunctionInvalid"], document.Codes()); + } + + private static Broadside.Diagnostics.DiagnosticSeverity DiagnosticSeverityOf(PdfDocument document, string code) => + Assert.Single(document.Diagnostics, d => d.Code == code).Severity; + + private static Broadside.Objects.CosStream Sampled(int[] size, int outputs, int bits, ulong[] raw) + { + string domain = string.Join(" ", size.Select(static _ => "0 1")); + string range = string.Join(" ", Enumerable.Repeat("0 1", outputs)); + return Stream(string.Create(CultureInfo.InvariantCulture, $"<< /FunctionType 0 /Domain [{domain}] /Range [{range}] /Size [{string.Join(" ", size)}] /BitsPerSample {bits} >>"), Pack(raw, bits)); + } + + /// A deterministic table of raw sample values spread over the whole bit width. + private static ulong[] Table(int[] size, int outputs, int bits) + { + int count = size.Aggregate(outputs, static (product, s) => product * s); + ulong maximum = (1UL << bits) - 1; + return [.. Enumerable.Range(0, count).Select(k => ((ulong)k * 2654435761UL) % (maximum + 1))]; + } + + /// Packs values of bits into bytes, most significant bit first, with no padding. + private static byte[] Pack(ulong[] values, int bits) + { + byte[] data = new byte[((values.Length * bits) + 7) / 8]; + long bit = 0; + foreach (ulong value in values) + { + for (int b = bits - 1; b >= 0; b--, bit++) + { + if (((value >> b) & 1) != 0) + { + data[bit / 8] |= (byte)(0x80 >> (int)(bit % 8)); + } + } + } + + return data; + } + + private static int Index(int[] point, int[] size) + { + int index = 0; + for (int i = point.Length - 1; i >= 0; i--) + { + index = (index * size[i]) + point[i]; + } + + return index; + } + + private static IEnumerable GridPoints(int[] size) + { + int count = size.Aggregate(1, static (product, s) => product * s); + for (int k = 0; k < count; k++) + { + int[] point = new int[size.Length]; + int rest = k; + for (int i = 0; i < size.Length; i++) + { + point[i] = rest % size[i]; + rest /= size[i]; + } + + yield return point; + } + } +} diff --git a/tests/Broadside.Tests/Graphics/StitchingFunctionTests.cs b/tests/Broadside.Tests/Graphics/StitchingFunctionTests.cs new file mode 100644 index 00000000..644c0f35 --- /dev/null +++ b/tests/Broadside.Tests/Graphics/StitchingFunctionTests.cs @@ -0,0 +1,186 @@ +using System.Globalization; +using Broadside.Graphics; +using Broadside.Objects; +using Broadside.Tests.Document; +using static Broadside.Tests.Graphics.FunctionTesting; + +namespace Broadside.Tests.Graphics; + +/// +/// Type 3 (stitching) functions, ISO 32000-2 §7.10.4, Table 41. Function i of the tests below returns 10 × i + x′, so an output +/// shows both which subdomain was chosen and the encoded input x′. +/// +public class StitchingFunctionTests +{ + public static TheoryData IntervalCases => new() + { + // k = 1: one interval [Domain0, Domain1]. + { "[0 1]", "[]", "[0 1]", 0f, 0f }, + { "[0 1]", "[]", "[0 1]", 0.4f, 0.4f }, + { "[0 1]", "[]", "[0 1]", 1f, 1f }, + + // k = 2, Domain0 < Bounds0 <= Domain1: [Domain0, Bounds0); [Bounds0, Domain1]. + { "[0 1]", "[0.5]", "[0 1 0 1]", 0f, 0f }, + { "[0 1]", "[0.5]", "[0 1 0 1]", 0.25f, 0.5f }, + { "[0 1]", "[0.5]", "[0 1 0 1]", 0.5f, 10f }, + { "[0 1]", "[0.5]", "[0 1 0 1]", 1f, 11f }, + + // k = 2, Domain0 = Bounds0 < Domain1: [Domain0, Bounds0]; (Bounds0, Domain1]. The point interval gives x' = Encode0. + { "[0 1]", "[0]", "[0.3 1 0 1]", 0f, 0.3f }, + { "[0 1]", "[0]", "[0.3 1 0 1]", 0.25f, 10.25f }, + { "[0 1]", "[0]", "[0.3 1 0 1]", 1f, 11f }, + + // k = 2, Bounds0 = Domain1: the last interval is the point Domain1 and x' = Encode2(k-1). + { "[0 1]", "[1]", "[0 1 0.7 1]", 0.75f, 0.75f }, + { "[0 1]", "[1]", "[0 1 0.7 1]", 1f, 10.7f }, + + // k = 3, Domain0 < Bounds0 < Bounds1 < Domain1: [D0, B0); [B0, B1); [B1, D1]. + { "[0 3]", "[1 2]", "[0 1 0 1 0 1]", 0f, 0f }, + { "[0 3]", "[1 2]", "[0 1 0 1 0 1]", 1f, 10f }, + { "[0 3]", "[1 2]", "[0 1 0 1 0 1]", 1.5f, 10.5f }, + { "[0 3]", "[1 2]", "[0 1 0 1 0 1]", 2f, 20f }, + { "[0 3]", "[1 2]", "[0 1 0 1 0 1]", 3f, 21f }, + + // k = 3, Domain0 = Bounds0 < Bounds1 < Domain1: [D0, B0]; (B0, B1); [B1, D1]. + { "[0 2]", "[0 1]", "[0.4 1 0 1 0 1]", 0f, 0.4f }, + { "[0 2]", "[0 1]", "[0.4 1 0 1 0 1]", 0.5f, 10.5f }, + { "[0 2]", "[0 1]", "[0.4 1 0 1 0 1]", 1f, 20f }, + { "[0 2]", "[0 1]", "[0.4 1 0 1 0 1]", 2f, 21f }, + + // Outside the domain: clipped first. + { "[0 3]", "[1 2]", "[0 1 0 1 0 1]", -5f, 0f }, + { "[0 3]", "[1 2]", "[0 1 0 1 0 1]", 9f, 21f }, + }; + + [Theory] + [MemberData(nameof(IntervalCases))] + public void Each_interval_of_example_1_selects_its_function_and_encodes_the_input(string domain, string bounds, string encode, float x, float expected) + { + using PdfDocument document = PdfDocument.Create(); + int k = bounds.Trim('[', ']').Split(' ', StringSplitOptions.RemoveEmptyEntries).Length + 1; + PdfFunction function = document.Function(Cos($"<< /FunctionType 3 /Domain {domain} /Functions [{Tagged(k)}] /Bounds {bounds} /Encode {encode} >>")); + + Near([expected], function.At(x)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void An_encode_pair_in_reverse_order_turns_the_function_around() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Cos("<< /FunctionType 3 /Domain [0 1] /Functions [<< /FunctionType 2 /Domain [0 1] /N 2 >>] /Bounds [] /Encode [1 0] >>")); + + Near([0.5625f], function.At(0.25f)); + Near([1f], function.At(0f)); + Near([0f], function.At(1f)); + } + + [Fact] + public void The_range_of_the_stitching_function_clips_after_the_sub_functions_clip_their_own() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Cos( + "<< /FunctionType 3 /Domain [0 1] /Range [0 0.6] /Bounds [] /Encode [0 1] " + + "/Functions [<< /FunctionType 2 /Domain [0 0.5] /C0 [0] /C1 [2] /N 1 /Range [0 0.8] >>] >>")); + + Near([0.6f], function.At(1f)); + Near([0.4f], function.At(0.2f)); + } + + [Fact] + public void The_view_exposes_bounds_encode_and_the_stitched_functions() + { + using PdfDocument document = PdfDocument.Create(); + var function = (PdfStitchingFunction)document.Function(Cos($"<< /FunctionType 3 /Domain [0 1] /Functions [{Tagged(2)}] /Bounds [0.5] /Encode [0 1 0 1] >>")); + + Assert.Equal([0.5], function.Bounds); + Assert.Equal([0.0, 1.0, 0.0, 1.0], function.Encode); + Assert.Collection( + function.Functions, + static f => Assert.Equal(PdfFunctionType.Exponential, f!.FunctionType), + static f => Assert.Equal([10.0], ((PdfExponentialFunction)f!).C0)); + } + + [Fact] + public void Sub_functions_with_different_output_counts_make_the_function_invalid() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Cos( + "<< /FunctionType 3 /Domain [0 1] /Bounds [0.5] /Encode [0 1 0 1] /Functions [" + + "<< /FunctionType 2 /Domain [0 1] /N 1 >> << /FunctionType 2 /Domain [0 1] /C0 [0 0] /C1 [1 1] /N 1 >>] >>")); + + Assert.False(function.IsValid); + Assert.Contains("FunctionInvalid", document.Codes()); + } + + [Fact] + public void Too_few_bounds_make_the_function_invalid() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Cos($"<< /FunctionType 3 /Domain [0 1] /Functions [{Tagged(3)}] /Bounds [0.5] /Encode [0 1 0 1 0 1] >>")); + + Assert.False(function.IsValid); + Assert.Equal(["FunctionInvalid"], document.Codes()); + } + + [Fact] + public void Bounds_out_of_order_are_used_as_given_with_a_diagnostic() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction function = document.Function(Cos($"<< /FunctionType 3 /Domain [0 1] /Functions [{Tagged(3)}] /Bounds [0.6 0.3] /Encode [0 1 0 1 0 1] >>")); + + Assert.True(function.IsValid); + Assert.Equal(["FunctionEntryInvalid"], document.Codes()); + Near([0.5f], function.At(0.3f)); + Near([20f + (0.3f / 0.7f)], function.At(0.6f)); + } + + [Fact] + public void Stitching_functions_nest_eight_deep_but_not_nine() + { + using PdfDocument document = PdfDocument.Create(); + + PdfFunction eight = document.Function(Cos(Nested(7))); + Assert.True(eight.IsValid); + Near([0.25f], eight.At(0.25f)); + Assert.Empty(document.Diagnostics); + + PdfFunction nine = document.Function(Cos(Nested(8))); + Assert.False(nine.IsValid); + Assert.Contains("FunctionTooDeep", document.Codes()); + } + + [Fact] + public void A_stitching_function_that_contains_itself_is_invalid() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] /Resources << >> >>", + "<< /FunctionType 3 /Domain [0 1] /Functions [5 0 R] /Bounds [] /Encode [0 1] >>", + "<< /FunctionType 3 /Domain [0 1] /Functions [4 0 R] /Bounds [] /Encode [0 1] >>"); + using PdfDocument document = PdfDocument.Open(file); + + PdfFunction function = document.Function(new CosReference(4, 0)); + + Assert.False(function.IsValid); + Assert.Equal(new CosReference(4, 0), Assert.Single(document.Diagnostics, static d => d.Code == "FunctionCycle").ObjectReference); + Assert.Empty(function.At(0.5f)); + } + + /// k Type 2 functions, function i returning 10 × i + x. + private static string Tagged(int k) => + string.Join(" ", Enumerable.Range(0, k).Select(static i => string.Create(CultureInfo.InvariantCulture, $"<< /FunctionType 2 /Domain [0 1] /C0 [{10 * i}] /C1 [{(10 * i) + 1}] /N 1 >>"))); + + /// stitching functions around one Type 2 identity function. + private static string Nested(int levels) + { + string function = "<< /FunctionType 2 /Domain [0 1] /N 1 >>"; + for (int i = 0; i < levels; i++) + { + function = $"<< /FunctionType 3 /Domain [0 1] /Functions [{function}] /Bounds [] /Encode [0 1] >>"; + } + + return function; + } +} diff --git a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt index f9e9b5e1..475355de 100644 --- a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt +++ b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt @@ -20,6 +20,7 @@ encrypted-user-password.pdf, filter-chain.pdf, flate-stream.pdf, + functions.pdf, hybrid-xref.pdf, incremental-update.pdf, inline-image.pdf, diff --git a/tests/Corpus/README.md b/tests/Corpus/README.md index f693ab10..819c037d 100644 --- a/tests/Corpus/README.md +++ b/tests/Corpus/README.md @@ -64,6 +64,7 @@ Verification was run with qpdf 12.4.2 (`qpdf --check`), poppler (`pdfinfo`, `pdf | `outline.pdf` | `/Outlines` root with two sibling items linked by `/First /Last /Next /Prev /Parent`, each with an explicit destination; `/PageMode /UseOutlines`. | 12.3.3, 12.3.2.2 | `qpdf --check`; `qpdf --json --json-key=outlines` lists both items with their destinations | clean | | `name-tree-dests.pdf` | `/Names << /Dests ... >>` name tree with a root `/Kids` node and two leaves carrying `/Limits` and `/Names` for `alpha`, `beta`, `gamma`. | 7.9.6, 12.3.2.3 | `qpdf --check` | clean | | `metadata-xmp.pdf` | Catalog `/Metadata` stream (`/Type /Metadata /Subtype /XML`) with a minimal XMP packet whose `dc:title` is `Broadside`, plus a trailer `/Info` dictionary with the same `/Title`. | 14.3.2, 14.3.3 | `pdfinfo` shows `Title: Broadside` | clean | +| `functions.pdf` | One page, six rectangles filled in six `/Separation` spaces whose tint transforms are functions: CS0 Type 0 (8-bit, 1 in, 4 out to DeviceCMYK, `/Size [3]`) at tint 0.5; CS1 Type 2 `/N 1` to DeviceRGB at 0.5; CS2 Type 2 `/N 2` to DeviceGray at 0.5; CS3 Type 3 stitching two Type 2 halves with `/Bounds [0.5] /Encode [0 1 1 0]` at 0.75; CS4 Type 4, the LogoGreen program of 8.6.6.4, at 0.5; CS5 shares CS1's indirect function (object 12) at 0.25. | 7.10.2-7.10.5, 8.6.6.4 | `qpdf --check`; `pdftoppm -r 72` rectangle centres (RGB): CS0 (202, 147, 208) = CMYK (0.2 0.4 0 0); CS1 (128, 128, 255); CS2 (191, 191, 191); CS3 (64, 64, 64); CS4 (134, 198, 183) = CMYK (0.42 0 0.22 0.105); CS5 (191, 191, 255) | clean | The crypt filter `/Length` entries in the R4 and R6 files are `16` and `32` (bytes), the form Acrobat and qpdf write and that Table 25 describes for the standard security handler; the same table also says the key "shall have the value of 128/256". Readers should accept both forms. diff --git a/tests/Corpus/functions.pdf b/tests/Corpus/functions.pdf new file mode 100644 index 0000000000000000000000000000000000000000..6607c66d1ae0a2925214e7b8f9ce1b07b1a769c0 GIT binary patch literal 2084 zcmbVNO>f&U4DH#!f|ni_TmDJ{6g|ZKIJDi0c$Xo_L35PELtX#v8tq8}MKGM$`}@U=Fvpo~Tv? zq~}WqgY%!tRSk=X;7g1mk5vP#<4A8@M@pjvLQNk3MXX9blW(vH5TCLT#?w&8s~UvW z5K{v1=c1NJRUkoPp2?k5`GFV0Jmvu;2AAawQoF=pb{WCME@PP5Wde-S(tgd)?wYc; z2aHx>17fJwL;wMGe6yfx4(5K?-=Y_ErMcgkfDw7!8BME+|GyLy;l_ z8lTcd1L@*!BuX~~N(?A8ktm;oqB^u2ZFNBPrHU;4TpYOKO(`qzbG|?9#0va7@uMt6 z_VVQk7-?+2w56nOxQ@?dCAhMF^T!!r>$`5$IoB=!enk0Lw@1a_ff)(fbkybnzou-8 z?U|_Y)Y>``B~`ed&vGLll@Peu?jE(UPOe%-u5Z3YvZvwSGyT zI=Sa%MF)f7ftd4ZBlH8(qzdaBU*zRav`4s_l}-IBl<5iT-3k{gd)Dn0UeWsM>JR?8 zUDiz)Boy`uWdST0vLJF9Gv}AqA1|hW?#@31w83;B&AZhf>m13;Qbm1cwvafUm>CO9 zj|7Z4!!bo;3r{UR-B*QNwME5pE~!j5oz=V3nZZJ!uP(ws0j&Q2C(uO!?1^v!#hn6- zP#7a(WA$PTIHvTA{yzfS>6VN;BKfsC9uPW-VSn6t;;q<{V*q+(-o^Tzu>_-#Y2Pb1CWbY`%5)4dbfOondJ*@vg7$KRtMV0nb4jb^rhX literal 0 HcmV?d00001 diff --git a/tests/Corpus/generate.py b/tests/Corpus/generate.py index 88922f6c..2101ede8 100644 --- a/tests/Corpus/generate.py +++ b/tests/Corpus/generate.py @@ -1206,6 +1206,43 @@ def gen_metadata_xmp() -> bytes: ], trailer_extra=b" /Info 5 0 R") +def gen_functions() -> bytes: + """7.10 functions as Separation tint transforms (8.6.6.4), one rectangle per colour space. + CS0: Type 0 (7.10.2), 8-bit, 1 in, 4 out (DeviceCMYK), Size [3], painted at 0.5 (the middle sample). + CS1: Type 2 (7.10.3) N 1 to DeviceRGB, at 0.5. CS2: Type 2 N 2 to DeviceGray, at 0.5. + CS3: Type 3 (7.10.4) stitching two Type 2 halves (N 1 and N 2) with Bounds [0.5] and Encode [0 1 1 0], at 0.75. + CS4: Type 4 (7.10.5), the LogoGreen example of 8.6.6.4, at 0.5. CS5 shares CS1's indirect function, at 0.25.""" + spaces = [(b"Sampled", b"DeviceCMYK", 11, b"0.5"), (b"Linear", b"DeviceRGB", 12, b"0.5"), + (b"Square", b"DeviceGray", 13, b"0.5"), (b"Stitched", b"DeviceGray", 14, b"0.75"), + (b"LogoGreen", b"DeviceCMYK", 17, b"0.5"), (b"Shared", b"DeviceRGB", 12, b"0.25")] + content = b"" + for i, (_, _, _, tint) in enumerate(spaces): + x = 50 + (i % 3) * 180 + y = 550 if i < 3 else 350 + content += b"/CS%d cs %s scn %d %d 150 150 re f\n" % (i, tint, x, y) + color_spaces = b" ".join(b"/CS%d %d 0 R" % (i, 5 + i) for i in range(len(spaces))) + objects = [ + (1, catalog()), + (2, pages()), + (3, page(contents=4, resources=False, extra=b" /Resources << /ColorSpace << " + color_spaces + b" >> >>")), + (4, stream(b"", content)), + ] + for i, (name, alternate, function, _) in enumerate(spaces): + objects.append((5 + i, b"[/Separation /%s /%s %d 0 R]" % (name, alternate, function))) + # Samples at t = 0, 0.5, 1: (0 0 0 0), (0.2 0.4 0 0), (1 0 0 0.2); 8-bit, Decode = Range = [0 1] x 4. + samples = bytes([0, 0, 0, 0, 51, 102, 0, 0, 255, 0, 0, 51]) + objects += [ + (11, stream(b"/FunctionType 0 /Domain [0 1] /Range [0 1 0 1 0 1 0 1] /Size [3] /BitsPerSample 8", samples)), + (12, b"<< /FunctionType 2 /Domain [0 1] /C0 [1 1 1] /C1 [0 0 1] /N 1 >>"), + (13, b"<< /FunctionType 2 /Domain [0 1] /C0 [1] /C1 [0] /N 2 >>"), + (14, b"<< /FunctionType 3 /Domain [0 1] /Functions [15 0 R 16 0 R] /Bounds [0.5] /Encode [0 1 1 0] >>"), + (15, b"<< /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 1 >>"), + (16, b"<< /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 2 >>"), + (17, stream(b"/FunctionType 4 /Domain [0.0 1.0] /Range [0.0 1.0 0.0 1.0 0.0 1.0 0.0 1.0]", + b"{dup 0.84 mul\nexch 0.00 exch dup 0.44 mul exch 0.21 mul\n}")), + ] + return simple_file(objects) + FILES = { "empty-page.pdf": gen_empty_page, "pdf20-header.pdf": gen_pdf20_header, @@ -1249,6 +1286,7 @@ def gen_metadata_xmp() -> bytes: "outline.pdf": gen_outline, "name-tree-dests.pdf": gen_name_tree_dests, "metadata-xmp.pdf": gen_metadata_xmp, + "functions.pdf": gen_functions, } From 22b1d9e79337d4b219b779bf883f84ceb42e938c Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:43:48 -0500 Subject: [PATCH 033/152] feat(model): PDF Declarations from document- and object-level XMP (#76) PdfDocument.Declarations and PdfObjectMetadata.Declarations read the pdfd:declarations bag (http and https namespaces, trimmed URIs, claim data) through #69's XMP packet. New corpus file declarations.pdf. Co-Authored-By: Claude Opus 5.5 --- src/Broadside/PdfDeclaration.cs | 118 ++++++++++++++++++ src/Broadside/PdfDocument.cs | 4 + src/Broadside/PdfObjectMetadata.cs | 4 + src/Broadside/PublicAPI.Unshipped.txt | 12 ++ tests/Broadside.TestSupport/Corpus.cs | 1 + .../Broadside.Tests/Files/DeclarationTests.cs | 45 +++++++ .../Files/FilesAndLayersCorpusTests.cs | 2 + ...pus_file_names_match_snapshot.verified.txt | 1 + tests/Corpus/README.md | 1 + tests/Corpus/declarations.pdf | Bin 0 -> 2166 bytes tests/Corpus/generate.py | 45 +++++++ 11 files changed, 233 insertions(+) create mode 100644 src/Broadside/PdfDeclaration.cs create mode 100644 tests/Broadside.Tests/Files/DeclarationTests.cs create mode 100644 tests/Corpus/declarations.pdf diff --git a/src/Broadside/PdfDeclaration.cs b/src/Broadside/PdfDeclaration.cs new file mode 100644 index 00000000..3428f6d1 --- /dev/null +++ b/src/Broadside/PdfDeclaration.cs @@ -0,0 +1,118 @@ +namespace Broadside; + +/// +/// A PDF Declaration: a machine-readable assertion, stored in XMP, that the document (or one object) conforms to an external +/// standard or profile, such as ISO/TS 32005 or Well-Tagged PDF. +/// +/// +/// PDF Declarations §7 and §8 (PDF Association, 2019): the pdfd:declarations unordered array (namespace +/// http://pdfa.org/declarations/) in document-level XMP (the catalog's Metadata, ) +/// or object-level XMP (), whose scope is that object. There is no catalog key. The +/// https spelling of the namespace, which published documents also use, is read too; URIs are trimmed of XML white space. +/// Exposed, not validated (a PDF/A file also needs an extension schema, §9). +/// +public sealed class PdfDeclaration +{ + private static readonly string[] Namespaces = ["http://pdfa.org/declarations/", "https://pdfa.org/declarations/"]; + + internal PdfDeclaration(string conformsTo, IReadOnlyList claims) + { + ConformsTo = conformsTo; + Claims = claims; + } + + /// Gets the URI of the standard or profile the declaration asserts conformance with (pdfd:conformsTo), trimmed. + /// PDF Declarations §8.2.1, Table 2 (required); it mirrors dc:conformsTo. + public string ConformsTo { get; } + + /// Gets the claims made about the conformance (pdfd:claimData). + /// PDF Declarations §8.2.1, Table 2 (optional), and §8.2.2, Table 3. + public IReadOnlyList Claims { get; } + + /// + public override string ToString() => ConformsTo; + + /// Reads the declarations of an XMP packet; empty when it has none. Entries without pdfd:conformsTo are skipped. + internal static IReadOnlyList Read(XmpPacket? packet) + { + if (packet is null) + { + return []; + } + + var declarations = new List(); + foreach (string namespaceName in Namespaces) + { + if (packet.GetProperty(namespaceName, "declarations") is not { } property) + { + continue; + } + + foreach (XmpProperty item in property.Items) + { + if (Field(item, "conformsTo")?.Value?.Trim() is not { Length: > 0 } conformsTo) + { + continue; + } + + var claims = new List(); + foreach (XmpProperty claim in Field(item, "claimData")?.Items ?? []) + { + claims.Add(new PdfDeclarationClaim( + Field(claim, "claimBy")?.Value?.Trim(), + Field(claim, "claimDate")?.Value?.Trim(), + Field(claim, "claimCredentials")?.Value?.Trim(), + Field(claim, "claimReport")?.Value?.Trim())); + } + + declarations.Add(new PdfDeclaration(conformsTo, claims)); + } + } + + return declarations; + } + + private static XmpProperty? Field(XmpProperty structure, string name) + { + foreach (string namespaceName in Namespaces) + { + if (structure.GetField(namespaceName, name) is { } field) + { + return field; + } + } + + return null; + } +} + +/// One claim about a PDF Declaration: who made it, when, with what credentials, and where the report is. +/// PDF Declarations §8.2.2, Table 3. Every field is optional. +public sealed class PdfDeclarationClaim +{ + internal PdfDeclarationClaim(string? claimedBy, string? dateText, string? credentials, string? report) + { + ClaimedBy = claimedBy; + DateText = dateText; + Credentials = credentials; + Report = report; + } + + /// Gets the organisation, individual or software making the claim (pdfd:claimBy). + public string? ClaimedBy { get; } + + /// Gets the date the claim was made as written (pdfd:claimDate, an XMP date). + public string? DateText { get; } + + /// Gets parsed as an XMP date (ISO 16684-1), or . + public XmpDate? Date => XmpDate.TryParse(DateText, out XmpDate date) ? date : null; + + /// Gets the claimant's credentials (pdfd:claimCredentials). + public string? Credentials { get; } + + /// + /// Gets the URL of a report on the claim (pdfd:claimReport); a fragment such as #ef=report.html names an embedded + /// file of the document (ISO 32000-2 Annex O). + /// + public string? Report { get; } +} diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 3bf04874..f131fb28 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -487,6 +487,10 @@ public IReadOnlyList EmbeddedFiles ? new PdfCollection(this, dictionary, entry as CosReference) : null; + /// Gets the PDF Declarations of the whole document, from the XMP of the catalog's Metadata. + /// PDF Declarations §7 and §8. Declarations live only in XMP; there is no catalog key. Read on every call (the packet is parsed once). + public IReadOnlyList Declarations => PdfDeclaration.Read(Metadata?.Packet); + /// Gets the files associated with the whole document (the catalog's AF). /// ISO 32000-2 §7.7.2, Table 29 (PDF 2.0), and §14.13.3. Read on every call. public IReadOnlyList AssociatedFiles => ReadAssociatedFiles(Catalog, CatalogReference); diff --git a/src/Broadside/PdfObjectMetadata.cs b/src/Broadside/PdfObjectMetadata.cs index 19b7fa6a..e73d4441 100644 --- a/src/Broadside/PdfObjectMetadata.cs +++ b/src/Broadside/PdfObjectMetadata.cs @@ -109,6 +109,10 @@ internal PdfObjectMetadata(PdfDocument document, CosStream stream, CosReference? /// ISO 32000-2 §14.3.2 and ISO 16684-1. Parsed once per stream and document; a changed stream is parsed again. public XmpPacket? Packet => _document.ReadXmpPacket(Stream, Reference ?? OwnerReference); + /// Gets the PDF Declarations the packet makes about the owner object (object-level scope). + /// PDF Declarations §7: claims at the object level are limited to the data of that object. + public IReadOnlyList Declarations => PdfDeclaration.Read(Packet); + /// public override string ToString() => Location.ToString(); } diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index a066ac03..504c6771 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -180,8 +180,18 @@ Broadside.PdfCollectionView.Details = 0 -> Broadside.PdfCollectionView Broadside.PdfCollectionView.Hidden = 2 -> Broadside.PdfCollectionView Broadside.PdfCollectionView.Navigator = 3 -> Broadside.PdfCollectionView Broadside.PdfCollectionView.Tile = 1 -> Broadside.PdfCollectionView +Broadside.PdfDeclaration +Broadside.PdfDeclaration.Claims.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfDeclaration.ConformsTo.get -> string! +Broadside.PdfDeclarationClaim +Broadside.PdfDeclarationClaim.ClaimedBy.get -> string? +Broadside.PdfDeclarationClaim.Credentials.get -> string? +Broadside.PdfDeclarationClaim.Date.get -> Broadside.XmpDate? +Broadside.PdfDeclarationClaim.DateText.get -> string? +Broadside.PdfDeclarationClaim.Report.get -> string? Broadside.PdfDocument.AssociatedFiles.get -> System.Collections.Generic.IReadOnlyList! Broadside.PdfDocument.Collection.get -> Broadside.PdfCollection? +Broadside.PdfDocument.Declarations.get -> System.Collections.Generic.IReadOnlyList! Broadside.PdfDocument.EmbeddedFiles.get -> System.Collections.Generic.IReadOnlyList! Broadside.PdfDocument.EnumerateAssociatedFiles(bool deep = false) -> System.Collections.Generic.IEnumerable! Broadside.PdfDocument.EnumerateObjectMetadata(bool deep = false) -> System.Collections.Generic.IEnumerable! @@ -263,6 +273,7 @@ Broadside.PdfMetadataLocation.TilingPattern = 9 -> Broadside.PdfMetadataLocation Broadside.PdfMetadataLocation.Type3Font = 8 -> Broadside.PdfMetadataLocation Broadside.PdfNameDictionary.EmbeddedFiles.get -> Broadside.PdfNameTree? Broadside.PdfObjectMetadata +Broadside.PdfObjectMetadata.Declarations.get -> System.Collections.Generic.IReadOnlyList! Broadside.PdfObjectMetadata.Decode() -> System.ReadOnlyMemory Broadside.PdfObjectMetadata.Location.get -> Broadside.PdfMetadataLocation Broadside.PdfObjectMetadata.Owner.get -> Broadside.Objects.CosObject! @@ -415,6 +426,7 @@ override Broadside.PdfCollectionFolder.ToString() -> string! override Broadside.PdfCollectionIdRange.Equals(object? obj) -> bool override Broadside.PdfCollectionIdRange.GetHashCode() -> int override Broadside.PdfCollectionIdRange.ToString() -> string! +override Broadside.PdfDeclaration.ToString() -> string! override Broadside.PdfEmbeddedFileEntry.ToString() -> string! override Broadside.PdfObjectMetadata.ToString() -> string! override Broadside.PdfOptionalContentConfiguration.ToString() -> string! diff --git a/tests/Broadside.TestSupport/Corpus.cs b/tests/Broadside.TestSupport/Corpus.cs index 40d69cdb..da6ba603 100644 --- a/tests/Broadside.TestSupport/Corpus.cs +++ b/tests/Broadside.TestSupport/Corpus.cs @@ -52,6 +52,7 @@ public static class Corpus "collection-portfolio.pdf", "associated-files.pdf", "object-metadata.pdf", + "declarations.pdf", ]; private static readonly string[] Malformed = diff --git a/tests/Broadside.Tests/Files/DeclarationTests.cs b/tests/Broadside.Tests/Files/DeclarationTests.cs new file mode 100644 index 00000000..4cf2e2dc --- /dev/null +++ b/tests/Broadside.Tests/Files/DeclarationTests.cs @@ -0,0 +1,45 @@ +using Broadside.TestSupport; + +namespace Broadside.Tests.Files; + +/// PDF Declarations in document-level and object-level XMP. PDF Declarations §7 and §8. +public class DeclarationTests +{ + [Fact] + public void Document_declarations_come_from_the_catalog_XMP_with_trimmed_URIs_and_claims() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("declarations.pdf")); + + IReadOnlyList declarations = document.Declarations; + + Assert.Equal(["https://pdfa.org/declarations#iso32005", "http://pdfa.org/declarations/wtpdf/#reuse1.0"], declarations.Select(declaration => declaration.ConformsTo)); + PdfDeclarationClaim claim = Assert.Single(declarations[0].Claims); + Assert.Equal("Broadside corpus", claim.ClaimedBy); + Assert.Equal("2024-05-06", claim.DateText); + Assert.Equal(new DateTimeOffset(2024, 5, 6, 0, 0, 0, TimeSpan.Zero), claim.Date!.Value.Value); + Assert.Equal("Generated by generate.py", claim.Credentials); + Assert.Equal("#ef=report.html", claim.Report); + Assert.Empty(declarations[1].Claims); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void An_object_level_declaration_is_read_from_the_objects_metadata() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("declarations.pdf")); + + PdfObjectMetadata page = document.EnumerateObjectMetadata().Single(metadata => metadata.Location == PdfMetadataLocation.Page); + + Assert.Equal("http://pdfa.org/declarations/wtpdf/#accessibility1.0", Assert.Single(page.Declarations).ConformsTo); + } + + [Fact] + public void A_document_without_declarations_has_none() + { + using PdfDocument withMetadata = PdfDocument.Open(Corpus.Path("metadata-xmp.pdf")); + using PdfDocument withoutMetadata = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + + Assert.Empty(withMetadata.Declarations); + Assert.Empty(withoutMetadata.Declarations); + } +} diff --git a/tests/Broadside.Tests/Files/FilesAndLayersCorpusTests.cs b/tests/Broadside.Tests/Files/FilesAndLayersCorpusTests.cs index 26217bc4..df47c983 100644 --- a/tests/Broadside.Tests/Files/FilesAndLayersCorpusTests.cs +++ b/tests/Broadside.Tests/Files/FilesAndLayersCorpusTests.cs @@ -48,6 +48,7 @@ internal static void ReadEverything(PdfDocument document) } } + _ = document.Declarations; foreach (PdfEmbeddedFileEntry entry in document.EmbeddedFiles) { Touch(entry.File); @@ -67,6 +68,7 @@ internal static void ReadEverything(PdfDocument document) foreach (PdfObjectMetadata metadata in document.EnumerateObjectMetadata(deep: true)) { metadata.Decode(); + _ = metadata.Declarations; } static void Touch(PdfFileSpecification file) diff --git a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt index 95cd304f..9ec493ec 100644 --- a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt +++ b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt @@ -6,6 +6,7 @@ broken-xref-offsets.pdf, catalog-version-extensions.pdf, collection-portfolio.pdf, + declarations.pdf, embedded-files.pdf, empty-page.pdf, encrypted-aes-128.pdf, diff --git a/tests/Corpus/README.md b/tests/Corpus/README.md index 381a7106..6c8e5210 100644 --- a/tests/Corpus/README.md +++ b/tests/Corpus/README.md @@ -76,6 +76,7 @@ Verification was run with qpdf 12.4.2 (`qpdf --check`), poppler (`pdfinfo`, `pdf | `collection-portfolio.pdf` | Portable collection: `/Collection` with `View /D`, initial document `D (notes.txt)`, `Schema` (fields `name` S, `date` D, `pages` N with `V false`, `fname` F with `E true`, `size` Size, each with `O`), `Sort /S [/date /name] /A [false]`, `Colors`, `Split /V 30`, `Folders` root (ID 0, `Free [2 10]`) with one child (ID 1, `Reports`); EmbeddedFiles keys `<1>report.txt` and `notes.txt`; collection items with a subitem (`D`, `P`). | 7.11.6, 12.3.5 | `qpdf --check`, `pdfdetach -list` | clean; pdfdetach lists `report.txt`, `notes.txt` | | `associated-files.pdf` | PDF 2.0 (trailer `ID`): `AF` on the catalog (`Source`, embedded `text/plain` with `Params` `ModDate`), the page (`Data`), a form XObject (`Supplement`, embedded `application/mathml+xml`), an image XObject (`Data`), a Square annotation (no `AFRelationship`), the structure tree root and a `Document` structure element (`Alternative`), a `DPart` (`Source`), the catalog metadata stream (`Schema`); marked content `/AF /MF1 BDC` with an `MCAF` property list (errata Table 409a) and `/AF /MF2 BDC` whose resource is the bare array (§14.13.5 Example 2). | 14.13, 7.11.3 | `qpdf --check`, `pdfinfo` | clean; one Letter page | | `object-metadata.pdf` | `Metadata` streams (each XMP packet with its own `dc:title`) on the catalog, a page, an image XObject, a form XObject, an ICCBased colour space stream, an embedded TrueType program (`FontFile2`, `minimal_truetype()`), a tiling pattern, a shading dictionary, a marked-content property list, an optional content group, a Square annotation and an embedded file stream. | 14.3.2 | `qpdf --check`, `pdfinfo`, `pdftotext` | clean; `pdftotext` prints `HI` | +| `declarations.pdf` | PDF 2.0 (trailer `ID`): catalog XMP with a `pdfd:declarations` bag (namespace `http://pdfa.org/declarations/`) holding ISO/TS 32005 (`https://pdfa.org/declarations#iso32005`) with one `pdfd:claimData` claim (`claimBy`, `claimDate`, `claimCredentials`, `claimReport #ef=report.html`) as `rdf:parseType="Resource"`, and WTPDF reuse (white space around the URI) as a nested `rdf:Description`; the page XMP holds one object-level declaration (WTPDF accessibility) under the `https://pdfa.org/declarations/` namespace. | PDF Declarations 7, 8; 14.3.2 | `qpdf --check`, `pdfinfo -meta` | clean; `pdfinfo -meta` prints the catalog packet | The crypt filter `/Length` entries in the R4 and R6 files are `16` and `32` (bytes), the form Acrobat and qpdf write and that Table 25 describes for the standard security handler; the same table also says the key "shall have the value of 128/256". Readers should accept both forms. diff --git a/tests/Corpus/declarations.pdf b/tests/Corpus/declarations.pdf new file mode 100644 index 0000000000000000000000000000000000000000..83b50d2434f76f67d4d1002a400e43cdee001a19 GIT binary patch literal 2166 zcmds2&5qMB5WeRrtW-U=anenAEenV(thy_KwAzCcJFOv&BimJfUX25fz=1b_ z2jCSLyJ?$JU_nAcBA3{nZ@wAZ-+1abqpL>H#7_P5mye$uA7Lcow@$y0yt{S5katNm z$;1?SH)P5b3IH%c-k51Z!Gg~0Jc=BaQ{!mt#{^qH?**p{-M0+<0a(Q%*T_c)M`Jm4 zG+`wJ=sqsxWGGhX9s|DZ2k5*T0N;cuv5*NQ2$@GwCBe`{ti&-1AII76#k*a^+HU&I z_!@cFET8Hb@-YsKztWPCxzoQ`6(o7bG>X}j=L7fa`wuSSbl|=Y$9P;^vKfE2k?eN! z@-ErDOS;s(h@Aeax0)AoI5o7IXSwRF1}=dEV?7v~WzUTq)R#2vO-5HG24(|yrghQt zyybG)T(+7*PCdWd?Rq%yf}jD2hFa&EtQxth8Hz2(h^a*KLUWNL!%1SX&;!>ki3^%S zz9lnEh~=d$$%rJzN!fIO%piMJLu7LtlBtPRM$5PjQV^+_5zWBeU5Cxcz${N9@>IyV zx)YI!tzcU}3|`|(v;vI7zOmC@#m@%a(Pf0sMbP433#m6tB^=oHUDdm8Ob6 zWt*@hC3v!%Bb@@n7Etwv60=7DH3l{5?TZp7 z`?7|IY~U_U(ZZ-K`torzZ^<9M9U;d5?bGqo^8IUX$BDvzM_D9+E}(eKGp^U5uv2aQ zV-c++OC9K44&HyL9fqwCrD(tAgVfB2^21sOTHbeSe(U^XEjWWFevI>5L4{9C!ZRjq zkH6&`hT70Sg)r^d_V(u^bl>;W4sD&qN!X!D8q!W2(-!t|5T=Cq0VWZ89P+T$K9Sn) P+3(`EQ?EaHb>(~m-O8ur literal 0 HcmV?d00001 diff --git a/tests/Corpus/generate.py b/tests/Corpus/generate.py index c57e1ecd..c8621bad 100644 --- a/tests/Corpus/generate.py +++ b/tests/Corpus/generate.py @@ -1586,6 +1586,50 @@ def gen_object_metadata() -> bytes: return simple_file(objects, binary=True) +def declarations_xmp(namespace: bytes, body: bytes) -> bytes: + """An XMP packet (ISO 16684-1) holding a pdfd:declarations bag (PDF Declarations 7.1, 8.1).""" + return (b'\n' + b'\n' + b' \n' + b' \n' + b' \n' + body + + b' \n' + b' \n' + b' \n' + b'\n' + b'') + + +def gen_declarations() -> bytes: + """PDF Declarations 7-8: the catalog XMP holds two declarations, ISO/TS 32005 with one claim (claimBy, + claimDate, claimCredentials, claimReport as an Annex O #ef= fragment) written with rdf:parseType="Resource", + and WTPDF reuse written as a nested rdf:Description with white space around the URI; the page XMP holds one + object-level declaration under the https namespace TS 32005 Table 1 shows. PDF 2.0 with a trailer ID.""" + id0 = file_id("declarations").hex().encode() + document = declarations_xmp(b"http://pdfa.org/declarations/", + b' \n' + b' https://pdfa.org/declarations#iso32005\n' + b' \n' + b' Broadside corpus\n' + b' 2024-05-06\n' + b' Generated by generate.py\n' + b' #ef=report.html\n' + b' \n' + b' \n' + b' \n' + b' \n http://pdfa.org/declarations/wtpdf/#reuse1.0\n \n' + b' \n') + page_xmp = declarations_xmp(b"https://pdfa.org/declarations/", + b' http://pdfa.org/declarations/wtpdf/#accessibility1.0\n') + return simple_file([ + (1, catalog(b" /Metadata 4 0 R")), + (2, pages()), + (3, page(extra=b" /Metadata 5 0 R")), + (4, stream(b"/Type /Metadata /Subtype /XML", document)), + (5, stream(b"/Type /Metadata /Subtype /XML", page_xmp)), + ], version="2.0", binary=True, trailer_extra=b" /ID [<%s> <%s>]" % (id0, id0)) + + FILES = { "empty-page.pdf": gen_empty_page, "pdf20-header.pdf": gen_pdf20_header, @@ -1642,6 +1686,7 @@ def gen_object_metadata() -> bytes: "collection-portfolio.pdf": gen_collection_portfolio, "associated-files.pdf": gen_associated_files, "object-metadata.pdf": gen_object_metadata, + "declarations.pdf": gen_declarations, } From e4c3b924de6b692715928ce4207ebd7a323d42f2 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:45:00 -0500 Subject: [PATCH 034/152] test(model): optional content visibility allocates nothing; benchmark (#76) Co-Authored-By: Claude Opus 5.5 --- .../OptionalContentBenchmarks.cs | 72 +++++++++++++++++++ .../OptionalContentAllocationTests.cs | 56 +++++++++++++++ 2 files changed, 128 insertions(+) create mode 100644 bench/Broadside.Benchmarks/OptionalContentBenchmarks.cs create mode 100644 tests/Broadside.Tests/OptionalContent/OptionalContentAllocationTests.cs diff --git a/bench/Broadside.Benchmarks/OptionalContentBenchmarks.cs b/bench/Broadside.Benchmarks/OptionalContentBenchmarks.cs new file mode 100644 index 00000000..bec93f7f --- /dev/null +++ b/bench/Broadside.Benchmarks/OptionalContentBenchmarks.cs @@ -0,0 +1,72 @@ +using BenchmarkDotNet.Attributes; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Benchmarks; + +/// +/// Optional content visibility (ISO 32000-2 §8.11, issue #76): the check a content interpreter makes on every /OC marked-content +/// section and every optional XObject. Both must allocate nothing (Allocated = -) once memberships are compiled. +/// +[MemoryDiagnoser] +public class OptionalContentBenchmarks +{ + private static readonly CosName OC = new("OC"); + + private PdfDocument? _document; + private PdfOptionalContentProperties? _properties; + private PdfOptionalContentState? _state; + private PdfOptionalContentTracker? _tracker; + private CosObject[] _operands = []; + + [GlobalSetup] + public void Setup() + { + _document = PdfDocument.Open(Path.Combine(CorpusLocator.CorpusDirectory, "optional-content.pdf")); + _properties = _document.OptionalContent!; + _state = _properties.GetDefaultStates(); + _tracker = new PdfOptionalContentTracker(_properties, _state); + var resources = (CosDictionary)_document.Resolve(_document.Pages[0].Resources![new CosName("Properties")]); + _operands = [.. resources.Values]; + _ = IsVisible(); + _ = TrackSections(); + } + + [GlobalCleanup] + public void Cleanup() => _document?.Dispose(); + + /// Evaluates a group, a policy membership and a visibility-expression membership. + [Benchmark] + public int IsVisible() + { + int visible = 0; + foreach (CosObject operand in _operands) + { + if (_properties!.IsVisible(operand, _state!)) + { + visible++; + } + } + + return visible; + } + + /// Opens and closes nested /OC sections the way an interpreter does on BDC and EMC. + [Benchmark] + public int TrackSections() + { + int visible = 0; + foreach (CosObject operand in _operands) + { + _tracker!.BeginMarkedContent(OC, operand); + visible += _tracker.IsVisible ? 1 : 0; + } + + foreach (CosObject _ in _operands) + { + _tracker!.EndMarkedContent(); + } + + return visible; + } +} diff --git a/tests/Broadside.Tests/OptionalContent/OptionalContentAllocationTests.cs b/tests/Broadside.Tests/OptionalContent/OptionalContentAllocationTests.cs new file mode 100644 index 00000000..639fbf7a --- /dev/null +++ b/tests/Broadside.Tests/OptionalContent/OptionalContentAllocationTests.cs @@ -0,0 +1,56 @@ +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.OptionalContent; + +/// +/// The visibility checks a content interpreter makes per /OC section and per optional XObject allocate nothing once each +/// membership is compiled (ISO 32000-2 §8.11; CLAUDE.md hot-path rule). Benchmark: OptionalContentBenchmarks. +/// +public class OptionalContentAllocationTests +{ + [Fact] + public void Visibility_checks_and_section_tracking_allocate_nothing() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("optional-content.pdf")); + PdfOptionalContentProperties properties = document.OptionalContent!; + PdfOptionalContentState state = properties.GetDefaultStates(); + var tracker = new PdfOptionalContentTracker(properties, state); + var oc = new CosName("OC"); + CosObject[] operands = [.. ((CosDictionary)document.Resolve(document.Pages[0].Resources![new CosName("Properties")])).Values]; + for (int warmUp = 0; warmUp < 50; warmUp++) + { + Run(); + } + + long before = GC.GetAllocatedBytesForCurrentThread(); + int visible = 0; + for (int iteration = 0; iteration < 1000; iteration++) + { + visible += Run(); + } + + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.Equal(1000 * 3, visible); + Assert.Equal(0, allocated); + + int Run() + { + int count = 0; + foreach (CosObject operand in operands) + { + count += properties.IsVisible(operand, state) ? 1 : 0; + tracker.BeginMarkedContent(oc, operand); + } + + foreach (CosObject _ in operands) + { + count += tracker.IsVisible ? 1 : 0; + tracker.EndMarkedContent(); + } + + return count; + } + } +} From 0a74a8376e92afca1f3959f7af303a10487b5af7 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:46:47 -0500 Subject: [PATCH 035/152] ci(fuzz): scheduled libFuzzer run of every Phase 1 target (#48) - .github/workflows/fuzz.yml: weekly and on demand, one job per fuzz target, 75 min on every core by default (25 h wall-clock per run), libFuzzer through SharpFuzz and a libfuzzer-dotnet driver built from pinned, hash-checked source; per-target corpus cached between runs; findings fail the job and are uploaded with replays; summary table with CPU-hours. - tests/Broadside.Fuzz: --seeds mode (target-specific seeds cut from tests/Corpus and real-world PDFs), pdf.dict, run-libfuzzer.sh and build-libfuzzer-dotnet.sh; a bare start under the driver is --fuzz; no library code runs before LibFuzzer.Run (instrumented code faults otherwise); document walks every object and stream (DocumentWalker); filter-predictor tries rows far longer than the data. - fix(filters): a predictor row longer than the whole data passes the data through; Columns no longer sizes buffers and zero padding (libFuzzer OOM finding, up to 1 GiB from a few bytes). - fix(security): the signature container of an AttachedToSig PDF MAC is cut at its DER length instead of trimming trailing zeros, which also cut a container whose last byte is zero (the flaky SignatureIntegrityTests, 1 run in 256). - perf(security): Algorithm 2.B re-keys one AES cipher instead of creating one per round. - bench: OpenAndWalkBenchmarks over tests/Corpus and a SHA-256-pinned real-world subset. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/README.md | 12 + .github/workflows/fuzz.yml | 209 +++++++++++++ .../Broadside.Benchmarks.csproj | 3 +- .../OpenAndWalkBenchmarks.cs | 54 ++++ bench/Broadside.Benchmarks/RealWorldSubset.cs | 54 ++++ docs/plan/README.md | 2 + src/Broadside/Filters/Predictor.cs | 13 +- .../Security/Cryptography/AesCipher.cs | 21 +- src/Broadside/Security/IntegrityVerifier.cs | 20 +- .../Security/StandardSecurityHandler.cs | 9 +- tests/Broadside.Fuzz/Broadside.Fuzz.csproj | 1 + tests/Broadside.Fuzz/FuzzTargets.cs | 56 ++-- tests/Broadside.Fuzz/Program.cs | 28 +- tests/Broadside.Fuzz/README.md | 23 +- tests/Broadside.Fuzz/SeedWriter.cs | 285 ++++++++++++++++++ .../Broadside.Fuzz/build-libfuzzer-dotnet.sh | 23 ++ tests/Broadside.Fuzz/pdf.dict | 113 +++++++ tests/Broadside.Fuzz/run-libfuzzer.sh | 123 ++++++++ tests/Broadside.TestSupport/DocumentWalker.cs | 17 +- .../Broadside.Tests/Filters/PredictorTests.cs | 24 ++ .../Security/SignatureIntegrityTests.cs | 39 ++- 21 files changed, 1070 insertions(+), 59 deletions(-) create mode 100644 .github/workflows/fuzz.yml create mode 100644 bench/Broadside.Benchmarks/OpenAndWalkBenchmarks.cs create mode 100644 bench/Broadside.Benchmarks/RealWorldSubset.cs create mode 100644 tests/Broadside.Fuzz/SeedWriter.cs create mode 100755 tests/Broadside.Fuzz/build-libfuzzer-dotnet.sh create mode 100644 tests/Broadside.Fuzz/pdf.dict create mode 100755 tests/Broadside.Fuzz/run-libfuzzer.sh diff --git a/.github/workflows/README.md b/.github/workflows/README.md index 0b44bf48..963e7eb5 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -12,6 +12,18 @@ A newer push to the same PR or branch cancels the older run. NuGet packages are cached per OS, keyed on `Directory.Packages.props` and every `.csproj`. `DiffEngine_Disabled=true` keeps Verify from launching a diff tool. +## `fuzz.yml`: real fuzzing, weekly and on the "Run workflow" button + +Every fuzz target under libFuzzer through SharpFuzz, one parallel job per target (issue #48; `tests/Broadside.Fuzz/README.md`, "Scheduled runs in CI"). + +| Job | Runs on | What it does | +|---|---|---| +| `targets` | ubuntu | Builds the harness and turns `--list` (or the `targets` input) into the matrix; checks the `minutes` input (default 75, at most 300 so every job stays under GitHub's 6-hour limit). | +| `fuzz ()` | ubuntu | Builds the libfuzzer-dotnet driver from pinned, hash-checked source with clang; installs SharpFuzz.CommandLine 2.3.0; builds the harness in Release; fetches `pdf20examples` and `qpdf` with `tools/CorpusFetcher` (cached) as extra seeds; restores the target's libFuzzer corpus from the previous run (`actions/cache`, key `fuzz-corpus--`); runs `tests/Broadside.Fuzz/run-libfuzzer.sh` (which instruments a copy of `Broadside.dll`) for the given minutes on every core; saves the minimized corpus; uploads `stats.json` as `fuzz-stats-`, and on a finding fails and uploads `fuzz-findings-` (inputs, replays, worker logs). | +| `summary` | ubuntu | One table in the job summary: minutes, workers, CPU-hours, executions, corpus size and findings per target, and the cumulative fuzzing time of the run. | + +Schedule: Sundays 03:17 UTC. A scheduled run fuzzes for 20 targets x 75 minutes = 25 hours of wall-clock time, 100 CPU-hours on the 4-core runners. Runs on one branch never overlap (they would race to save the same cache). From a terminal: `gh workflow run fuzz.yml --ref main -f minutes=30 -f targets="document save"`. A finding is fixed in a PR that adds a regression test replaying the input (`tests/Broadside.Tests/Document/FuzzRegressionTests.cs`). + ## `docs.yml`: the documentation site Runs on pull requests and pushes to `main` that touch `site/**`, `src/**`, `docs/**`, `.config/**`, `check-docs.sh`, `Directory.Build.props`, `Directory.Packages.props`, `global.json` or the workflow itself, and on the "Run workflow" button. diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml new file mode 100644 index 00000000..bd04db40 --- /dev/null +++ b/.github/workflows/fuzz.yml @@ -0,0 +1,209 @@ +# Real fuzzing: every fuzz target under libFuzzer (SharpFuzz instrumentation, libfuzzer-dotnet driver) in parallel jobs, once a +# week and on the "Run workflow" button. One scheduled run gives each target 75 minutes on every core of its runner, so the run +# as a whole adds up to more than 24 hours of fuzzing (issue #48). Each target's corpus is cached between runs, so coverage +# accumulates. Findings fail the job and are uploaded with a replay of each. See .github/workflows/README.md and +# tests/Broadside.Fuzz/README.md ("Real fuzzing"). +name: Fuzz + +on: + schedule: + # Sundays 03:17 UTC, away from the top of the hour when scheduled runs queue. + - cron: "17 3 * * 0" + workflow_dispatch: + inputs: + minutes: + description: Minutes of fuzzing per target (each job must stay under GitHub's 6-hour limit, so at most 300) + default: "75" + targets: + description: Space-separated targets to fuzz (empty = every target from --list) + default: "" + +# One run at a time per branch: two runs would race to save the same corpus cache. +concurrency: + group: fuzz-${{ github.ref }} + cancel-in-progress: false + +permissions: + contents: read + +env: + DOTNET_NOLOGO: true + DOTNET_CLI_TELEMETRY_OPTOUT: true + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true + DOTNET_GENERATE_ASPNET_CERTIFICATE: false + SHARPFUZZ_VERSION: "2.3.0" + # Real-world seeds besides tests/Corpus: small pinned corpora fetched by tools/CorpusFetcher (files up to 256 KB are used). + SEED_CORPORA: pdf20examples,qpdf + +jobs: + # The matrix: every registered target, or the ones asked for. + targets: + name: targets + runs-on: ubuntu-latest + timeout-minutes: 20 + outputs: + targets: ${{ steps.list.outputs.targets }} + seconds: ${{ steps.list.outputs.seconds }} + steps: + - name: Check out + uses: actions/checkout@v7 + + - name: Set up .NET + uses: actions/setup-dotnet@v6 + with: + global-json-file: global.json + + - name: Build the fuzz harness + run: dotnet build tests/Broadside.Fuzz -c Release -warnaserror + + - name: List the targets + id: list + shell: bash + env: + REQUESTED: ${{ inputs.targets }} + MINUTES: ${{ inputs.minutes || '75' }} + run: | + all=$(dotnet artifacts/bin/Broadside.Fuzz/release/Broadside.Fuzz.dll --list) + if [ -n "${REQUESTED}" ]; then + for target in ${REQUESTED}; do + if ! grep -qx "${target}" <<< "${all}"; then + echo "::error::unknown fuzz target '${target}'" + exit 1 + fi + done + selected="${REQUESTED}" + else + selected="${all}" + fi + if ! [[ "${MINUTES}" =~ ^[0-9]+$ ]] || [ "${MINUTES}" -lt 1 ] || [ "${MINUTES}" -gt 300 ]; then + echo "::error::minutes must be between 1 and 300" + exit 1 + fi + echo "targets=$(printf '%s\n' ${selected} | jq -R . | jq -cs .)" >> "${GITHUB_OUTPUT}" + echo "seconds=$((MINUTES * 60))" >> "${GITHUB_OUTPUT}" + + fuzz: + name: fuzz (${{ matrix.target }}) + needs: targets + runs-on: ubuntu-latest + # Fuzzing time plus build, seeds and corpus merge; GitHub-hosted jobs stop at 360 minutes. + timeout-minutes: 355 + strategy: + fail-fast: false + matrix: + target: ${{ fromJSON(needs.targets.outputs.targets) }} + steps: + - name: Check out + uses: actions/checkout@v7 + + - name: Set up .NET + uses: actions/setup-dotnet@v6 + with: + global-json-file: global.json + + - name: Cache NuGet packages + uses: actions/cache@v6 + with: + path: ~/.nuget/packages + key: nuget-${{ runner.os }}-${{ hashFiles('Directory.Packages.props', '**/*.csproj') }} + restore-keys: nuget-${{ runner.os }}- + + - name: Install clang with libFuzzer + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends clang libclang-rt-dev + + - name: Build the libFuzzer driver + run: tests/Broadside.Fuzz/build-libfuzzer-dotnet.sh + + - name: Install SharpFuzz + run: dotnet tool install --global SharpFuzz.CommandLine --version "${SHARPFUZZ_VERSION}" + + # run-libfuzzer.sh instruments a copy of Broadside.dll; seeds and replays run on this plain build. + - name: Build the harness + run: dotnet build tests/Broadside.Fuzz -c Release -warnaserror + + - name: Cache the real-world seed corpora + uses: actions/cache@v6 + with: + path: corpus + key: seed-corpora-${{ env.SEED_CORPORA }}-${{ hashFiles('tools/CorpusFetcher/corpora.json') }} + + - name: Fetch the real-world seed corpora + run: dotnet run --project tools/CorpusFetcher -- --only "${SEED_CORPORA}" + + - name: Restore the fuzzing corpus + uses: actions/cache/restore@v6 + with: + path: artifacts/fuzz/${{ matrix.target }}/corpus + key: fuzz-corpus-${{ matrix.target }}-${{ github.run_id }} + restore-keys: fuzz-corpus-${{ matrix.target }}- + + - name: Fuzz + shell: bash + env: + TARGET: ${{ matrix.target }} + SECONDS_PER_TARGET: ${{ needs.targets.outputs.seconds }} + run: | + IFS=, read -ra corpora <<< "${SEED_CORPORA}" + tests/Broadside.Fuzz/run-libfuzzer.sh "${TARGET}" "${SECONDS_PER_TARGET}" "${corpora[@]/#/corpus/}" + + - name: Save the fuzzing corpus + if: always() + uses: actions/cache/save@v6 + with: + path: artifacts/fuzz/${{ matrix.target }}/corpus + key: fuzz-corpus-${{ matrix.target }}-${{ github.run_id }} + + - name: Upload the statistics + if: always() + uses: actions/upload-artifact@v7 + with: + name: fuzz-stats-${{ matrix.target }} + path: artifacts/fuzz/${{ matrix.target }}/stats.json + if-no-files-found: ignore + + - name: Upload findings + if: failure() + uses: actions/upload-artifact@v7 + with: + name: fuzz-findings-${{ matrix.target }} + path: | + artifacts/fuzz/${{ matrix.target }}/findings/** + artifacts/fuzz/${{ matrix.target }}/logs/** + if-no-files-found: ignore + + # One table for the whole run: time, CPU-hours, executions and findings per target, and the cumulative total. + summary: + name: summary + needs: fuzz + if: always() + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Download the statistics + uses: actions/download-artifact@v7 + with: + pattern: fuzz-stats-* + path: stats + merge-multiple: false + + - name: Write the summary + shell: bash + run: | + shopt -s nullglob + files=(stats/*/stats.json) + { + echo "## Fuzzing" + echo + if [ "${#files[@]}" -eq 0 ]; then + echo "No statistics were uploaded." + exit 0 + fi + echo "| Target | Minutes | Workers | CPU-hours | Executions | Corpus | Findings |" + echo "|---|---:|---:|---:|---:|---:|---|" + jq -rs 'sort_by(.target)[] | "| \(.target) | \(.wallSeconds / 60 | floor) | \(.workers) | \(.cpuHours) | \(.executions) | \(.corpusFiles) | \(if (.findings | length) == 0 then "none" else (.findings | join(", ")) end) |"' "${files[@]}" + jq -rs '"| **total** | \((map(.wallSeconds) | add) / 60 | floor) | | \(map(.cpuHours) | add * 100 | round / 100) | \(map(.executions) | add) | | \(map(.findings | length) | add) |"' "${files[@]}" + echo + jq -rs '"Cumulative fuzzing time: \((map(.wallSeconds) | add) / 3600 * 10 | round / 10) hours of wall-clock time across \(length) targets, \(map(.cpuHours) | add | round) CPU-hours."' "${files[@]}" + } >> "${GITHUB_STEP_SUMMARY}" diff --git a/bench/Broadside.Benchmarks/Broadside.Benchmarks.csproj b/bench/Broadside.Benchmarks/Broadside.Benchmarks.csproj index 72543caf..8a7e38c4 100644 --- a/bench/Broadside.Benchmarks/Broadside.Benchmarks.csproj +++ b/bench/Broadside.Benchmarks/Broadside.Benchmarks.csproj @@ -10,9 +10,10 @@ - + + diff --git a/bench/Broadside.Benchmarks/OpenAndWalkBenchmarks.cs b/bench/Broadside.Benchmarks/OpenAndWalkBenchmarks.cs new file mode 100644 index 00000000..4b687dc0 --- /dev/null +++ b/bench/Broadside.Benchmarks/OpenAndWalkBenchmarks.cs @@ -0,0 +1,54 @@ +using BenchmarkDotNet.Attributes; +using Broadside.Security; +using Broadside.TestSupport; + +namespace Broadside.Benchmarks; + +/// +/// The Phase 1 baseline (issue #48): open a file from memory and read everything the document model exposes, as the real-world +/// corpus gate does (): version, catalog, security, revisions, linearization and hint tables, every page's +/// boxes and resources, every object reachable from the trailer or numbered below Size, and every stream decoded through its +/// filters into a discarding writer. Runs over every file of tests/Corpus/ and over when the +/// real-world corpora are fetched. Opening allocates the document model by design, so Allocated is a baseline to watch, not +/// a zero to assert. Results are recorded under bench/baselines/phase1/. +/// +/// ISO 32000-2 §7.3 to §7.7. +[MemoryDiagnoser] +public class OpenAndWalkBenchmarks +{ + /// The two corpus files that open only with their user password (tests/Corpus/README.md, "Password-protected files"). + private static readonly Dictionary Passwords = new(StringComparer.Ordinal) + { + ["encrypted-user-password.pdf"] = "pässwort", + ["encrypted-rc4-user-password.pdf"] = "café", + }; + + private readonly PdfEngine _engine = new(); + private byte[] _bytes = []; + private PdfPassword? _password; + + /// A file name of tests/Corpus/, or a path under the real-world corpus directory (it contains a slash). + [ParamsSource(nameof(Files))] + public string File { get; set; } = ""; + + /// Every minimal-corpus file, then the real-world subset files present on this machine. + public static IEnumerable Files() => + [.. CorpusLocator.CorpusFiles().Select(Path.GetFileName).OfType(), .. RealWorldSubset.Available()]; + + [GlobalSetup] + public void Setup() + { + _bytes = File.Contains('/', StringComparison.Ordinal) + ? RealWorldSubset.Read(File) + : System.IO.File.ReadAllBytes(Path.Combine(CorpusLocator.CorpusDirectory, File)); + _password = Passwords.TryGetValue(File, out string? password) ? new PdfPassword(password) : null; + } + + [Benchmark] + public long OpenAndWalk() + { + using PdfDocument document = _password is null ? _engine.Open(_bytes) : _engine.Open(_bytes, _password); + DocumentWalkResult walk = DocumentWalker.Walk(document); + return walk.Objects + walk.DecodedBytes; + } +} diff --git a/bench/Broadside.Benchmarks/RealWorldSubset.cs b/bench/Broadside.Benchmarks/RealWorldSubset.cs new file mode 100644 index 00000000..5d6a57a5 --- /dev/null +++ b/bench/Broadside.Benchmarks/RealWorldSubset.cs @@ -0,0 +1,54 @@ +using System.Security.Cryptography; +using Broadside.TestSupport; + +namespace Broadside.Benchmarks; + +/// +/// The fixed real-world subset of the open-and-walk baseline (issue #48): files from the corpora tools/CorpusFetcher fetches +/// (pinned to commits in tools/CorpusFetcher/corpora.json), each pinned again here by SHA-256 so that a baseline number +/// always means the same bytes. Picked to cover what the minimal corpus does not: PDF 2.0 files from the PDF Association, real +/// linearized and incrementally updated files, RC4 and AES-256 encryption, a few hundred to a thousand objects, dozens of pages, +/// a megabyte of image data. Every file opens with no Warning or Error diagnostic. +/// +internal static class RealWorldSubset +{ + /// Path under the real-world corpus directory, and SHA-256 of the file. + private static readonly (string Path, string Sha256)[] Files = + [ + ("pdf20examples/Simple PDF 2.0 file.pdf", "296d2a0b2ce19b606f29265694f194a754fbc61783982b5b8d730e8637482236"), + ("pdf20examples/PDF 2.0 via incremental save.pdf", "9b25d59d07034634a990e79db6ef82b9f86769d9b94d8d8635f20d06aaec9d18"), + ("pdf20examples/pdf20-utf8-test.pdf", "a7ca717ef062df0a65e58487d26358c81424b76084a2000ca1c74b9e5776b7a1"), + ("qpdf/minimal-linearized.pdf", "75b49e60adac5dd53c07e01c20f488e86c81a12f402c3b1d5b2a5d3e1a7ca883"), + ("qpdf/lin9.pdf", "fe7ccf236f9710b581d227508dcdb41c023b795532d5715be4fbae14f033341f"), + ("qpdf/merge-implicit-ranges.pdf", "a0a47d34fe90cdae65c522574c1890d65b199304a50968dc36cf443679a556d5"), + ("qpdf/deterministic-id-in.pdf", "336eaa8e96c36348358c17faf294469035767f3c8294f3020ac090ed9a1eec97"), + ("qpdf/large-inline-image.pdf", "7da28b9cb83805404c4c5e8a99184b062175f017a2fb40a2bae08aa3f9763d95"), + ("pdfjs/issue7665.pdf", "cd1d57895ba287085780a752be15293983b5d3733e2d62428e6083331ca336ec"), + ("pdfjs/bug900822.pdf", "76ff1ee293cd3a447b737f882840af70e50627f3010170fe3c1581090be8fd61"), + ("pdfjs/160F-2019.pdf", "f41f0818365ffd14ca4e55c0556355193bd76632b970d60cc2dec554cac6f379"), + ("pdfjs/issue17808.pdf", "2b082b535fbabae9e066df04d2d68b984783e17559a1fe70258250078f3cf0fa"), + ("pdfjs/issue18911.pdf", "c62ce23251433be44fe4097cf328554cb436df1b6e78f24d926c4c42f70679b2"), + ("pdfbox/input/rendering/survey.pdf", "2e8b87ea72de7dd54176354706a5d7ff9e64a12624e603ffac64aa55743bf581"), + ]; + + /// The paths of the subset files present on this machine; none when the corpora are not fetched (CI's dry run). + public static IEnumerable Available() + { + string? directory = CorpusLocator.RealWorldCorpusDirectory; + return directory is null + ? [] + : Files.Where(file => File.Exists(System.IO.Path.Combine(directory, file.Path))).Select(file => file.Path); + } + + /// Reads one subset file and checks it is the pinned one. + /// The file's SHA-256 is not the pinned one: the baseline would not be comparable. + public static byte[] Read(string path) + { + string expected = Files.Single(file => file.Path == path).Sha256; + byte[] bytes = File.ReadAllBytes(System.IO.Path.Combine(CorpusLocator.RealWorldCorpusDirectory!, path)); + string actual = Convert.ToHexStringLower(SHA256.HashData(bytes)); + return actual == expected + ? bytes + : throw new InvalidDataException($"{path} has SHA-256 {actual}; the benchmark baseline pins {expected}. Re-fetch the corpus."); + } +} diff --git a/docs/plan/README.md b/docs/plan/README.md index dae4bbb1..97fe2841 100644 --- a/docs/plan/README.md +++ b/docs/plan/README.md @@ -57,6 +57,8 @@ Single track with internal parallelism once the lexer exists. Exit criteria: every file in the pdf.js and PDFBox corpora opens without an exception in lenient mode; strict mode agrees with veraPDF on the well-formed subset; fuzzing finds no crash in 24 h; round-trip serialization is byte-identical for untouched objects. +Evidence (issue #48): real fuzzing of every Phase 1 target runs weekly in [`.github/workflows/fuzz.yml`](../../.github/workflows/fuzz.yml) (more than 24 h of fuzzing per run, findings fail the run); the performance baseline the Phase 3I regression gate compares against, with allocation figures, is [`bench/baselines/phase1/`](../../bench/baselines/phase1/README.md). + ### Phase 2: Model and codecs (four tracks) **Track 2A Fonts** (§9): font dictionaries and encodings (§9.6), Type 1 (eexec, charstrings Type 1), CFF/Type 2 charstrings and CID-keyed CFF, TrueType (glyf, loca, cmap, post, hmtx; composite glyphs), OpenType wrapper, Type 3, Type 0 composite fonts with CIDFontType0/2, CMaps embedded and predefined (package), AFM metrics for the Standard 14, font-matching for substitution, ToUnicode. Glyph outline output as paths in glyph space. Font program parsers are extension points. diff --git a/src/Broadside/Filters/Predictor.cs b/src/Broadside/Filters/Predictor.cs index 22d328ca..703ffbdb 100644 --- a/src/Broadside/Filters/Predictor.cs +++ b/src/Broadside/Filters/Predictor.cs @@ -19,7 +19,8 @@ namespace Broadside.Filters; /// /// Lenient repairs, one PredictorInvalid diagnostic each: an unknown Predictor passes the data through unchanged; a PNG tag /// above 4 is read as None; a final partial row is padded with zeros. Parameters out of range take their defaults -/// (DecodeParmsInvalid); a row longer than the decoded-length limit passes the data through. +/// (DecodeParmsInvalid); a row longer than the decoded-length limit, or than the whole data, passes the data through, so +/// the output is never more than twice the input. /// /// internal static class Predictor @@ -61,6 +62,16 @@ public static void Decode(ReadOnlySpan data, IBufferWriter output, F return; } + if (rowLength > data.Length) + { + // Not one whole row: Columns, not the data, would size the row buffers and the zero padding of the last row, so a few + // bytes with a huge Columns would decode to up to the decoded-length limit. Passing them through keeps the output of + // any predicted data under twice its input (fuzzing finding, issue #48). + context.Report(DiagnosticCodes.PredictorInvalid, DiagnosticSeverity.Error, "The predictor's rows are longer than the whole data; the data is passed through unpredicted."); + output.Write(data); + return; + } + int bytesPerPixel = Math.Max(1, ((colors * bitsPerComponent) + 7) / 8); byte[] previous = ArrayPool.Shared.Rent((int)rowLength); byte[] current = ArrayPool.Shared.Rent((int)rowLength); diff --git a/src/Broadside/Security/Cryptography/AesCipher.cs b/src/Broadside/Security/Cryptography/AesCipher.cs index 9c5fdefc..95e1a3f3 100644 --- a/src/Broadside/Security/Cryptography/AesCipher.cs +++ b/src/Broadside/Security/Cryptography/AesCipher.cs @@ -16,7 +16,7 @@ namespace Broadside.Security.Cryptography; internal sealed class AesCipher : IDisposable { private readonly Aes? _aes; - private readonly ManagedAes? _managed; + private ManagedAes? _managed; private AesCipher(ReadOnlySpan key) { @@ -27,7 +27,7 @@ private AesCipher(ReadOnlySpan key) else { _aes = Aes.Create(); - _aes.Key = key.ToArray(); + _aes.SetKey(key); } } @@ -39,6 +39,23 @@ private AesCipher(ReadOnlySpan key) /// The cipher. Dispose it. public static AesCipher Create(ReadOnlySpan key) => new(key); + /// + /// Replaces the key, keeping the platform cipher object: Algorithm 2.B re-keys AES in every one of its 64 or more rounds, and a + /// new cipher per round costs as much as the round's encryption on some platforms. + /// + /// 16, 24 or 32 bytes. + public void SetKey(ReadOnlySpan key) + { + if (_aes is not null) + { + _aes.SetKey(key); + } + else + { + _managed = new ManagedAes(key); + } + } + /// Decrypts whole blocks in CBC mode without removing any padding. /// A multiple of 16 bytes. /// 16 bytes. diff --git a/src/Broadside/Security/IntegrityVerifier.cs b/src/Broadside/Security/IntegrityVerifier.cs index a950d482..49d6ef94 100644 --- a/src/Broadside/Security/IntegrityVerifier.cs +++ b/src/Broadside/Security/IntegrityVerifier.cs @@ -198,7 +198,7 @@ private PdfIntegrityStatus VerifyAttached(CosDictionary authCode, ReadOnlySpan container) + private static byte[] WithoutPadding(ReadOnlySpan container) { - // Signature containers are padded with zeros to fill their reserved space (ISO 32000-2 §12.8.3.3.1). - int end = container.Length; - while (end > 0 && container[end - 1] == 0) + // Signature containers are padded with zeros to fill their reserved space (ISO 32000-2 §12.8.3.3.1). The padding is + // whatever follows the container's outer DER element: trimming trailing zero bytes instead would also cut a container + // whose own last byte is zero (the token's MAC ends it, so one in 256). An unreadable length is left to the decoder. + try { - end--; + AsnDecoder.ReadEncodedValue(container, AsnEncodingRules.BER, out _, out _, out int consumed); + return container[..consumed].ToArray(); + } + catch (AsnContentException) + { + return container.ToArray(); } - - return container[..end].ToArray(); } private static byte[] Hash(HashAlgorithmName name, ReadOnlySpan data) => name.Name switch diff --git a/src/Broadside/Security/StandardSecurityHandler.cs b/src/Broadside/Security/StandardSecurityHandler.cs index cb5f4cae..53eed331 100644 --- a/src/Broadside/Security/StandardSecurityHandler.cs +++ b/src/Broadside/Security/StandardSecurityHandler.cs @@ -135,6 +135,7 @@ internal static void HashRevision6(ReadOnlySpan input, ReadOnlySpan int maxSequence = password.Length + 64 + userKey.Length; byte[] k1 = ArrayPool.Shared.Rent(maxSequence * 64); byte[] e = ArrayPool.Shared.Rent(maxSequence * 64); + using AesCipher aes = AesCipher.Create(k[..16]); try { for (int round = 1; ; round++) @@ -151,11 +152,9 @@ internal static void HashRevision6(ReadOnlySpan input, ReadOnlySpan first.CopyTo(k1.AsSpan(offset, sequence)); } - // b) E = AES-128-CBC(key K[0..16], IV K[16..32], no padding). - using (AesCipher aes = AesCipher.Create(k[..16])) - { - aes.EncryptCbc(k1.AsSpan(0, length), k[16..32], e); - } + // b) E = AES-128-CBC(key K[0..16], IV K[16..32], no padding), one cipher re-keyed each round. + aes.SetKey(k[..16]); + aes.EncryptCbc(k1.AsSpan(0, length), k[16..32], e); // c) The first 16 bytes of E as a big-endian integer, modulo 3: since 256 ≡ 1 (mod 3), the sum of the bytes. int sum = 0; diff --git a/tests/Broadside.Fuzz/Broadside.Fuzz.csproj b/tests/Broadside.Fuzz/Broadside.Fuzz.csproj index 06860c0b..ce9b11ed 100644 --- a/tests/Broadside.Fuzz/Broadside.Fuzz.csproj +++ b/tests/Broadside.Fuzz/Broadside.Fuzz.csproj @@ -19,6 +19,7 @@ + diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 4a3ab467..006be82f 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -5,6 +5,7 @@ using Broadside.Objects; using Broadside.Parsing; using Broadside.Security; +using Broadside.TestSupport; using SharpFuzz; namespace Broadside.Fuzz; @@ -39,15 +40,23 @@ internal static class FuzzTargets ["public-key"] = PublicKey.Target, }; - private static readonly CosName ContentsKey = new("Contents"); - private static readonly CosName InfoKey = new("Info"); + /// + /// Names the targets use, kept out of this class's static constructor: under libFuzzer, code of the instrumented library must + /// not run before Fuzzer.LibFuzzer.Run has attached the coverage memory, and looking up a target runs that constructor. + /// + private static class Names + { + public static readonly CosName Contents = new("Contents"); + public static readonly CosName Info = new("Info"); + } /// /// Opens the input as a whole file in lenient mode and reads everything the document model exposes: version, trailer, every - /// page's boxes, rotation, user unit and resources, the revisions, and the linearization dictionary and hint tables. A is the one documented outcome for a file - /// whose cross-reference information cannot be read at all (until issue #41 reconstructs it); any other exception is a finding. - /// Every box must be normalized and every rotation one of 0, 90, 180, 270; every revision must be a non-empty prefix of the input - /// at its own index. + /// page's boxes, rotation, user unit and resources, the revisions, and the linearization dictionary and hint tables, then walks + /// every object and decodes every stream (). A (no catalog even + /// after a scan) and the password, certificate and unsupported-encryption exceptions are the documented outcomes; any other + /// exception is a finding. Every box must be normalized and every rotation one of 0, 90, 180, 270; every revision must be a + /// non-empty prefix of the input at its own index. /// /// ISO 32000-2 §7.5.1 to §7.5.6, §7.7.2, §7.7.3, Annex F. private static void Document(ReadOnlySpan data) @@ -91,11 +100,14 @@ private static void Document(ReadOnlySpan data) throw new InvalidOperationException($"Rotation {page.Rotation} or user unit {page.UserUnit} is out of range."); } - _ = page.Resources; - if (page.Dictionary.TryGetValue(ContentsKey, out CosObject? contents) && document.Resolve(contents) is CosStream stream) - { - _ = document.DecodeStream(stream); - } + } + + // Then everything else the document model exposes: every object reachable from the trailer or numbered below Size, and + // every stream decoded through its filters (the walk the real-world corpus gate runs, issue #47). + DocumentWalkResult walk = DocumentWalker.Walk(document); + if (walk.Pages != document.Pages.Count || walk.Streams > walk.Objects) + { + throw new InvalidOperationException($"The walk saw {walk.Pages} pages and {walk.Streams} streams in {walk.Objects} objects; the document has {document.Pages.Count} pages."); } } @@ -238,8 +250,9 @@ private static void Lzw(ReadOnlySpan data) /// /// The LZW and Flate predictor functions over the input: the first four bytes select Predictor (1, 2, 10 to 15, or an invalid 3), - /// Colors (1 to 4), BitsPerComponent (1, 2, 4, 8, 16) and Columns (1 to 64); the rest is the filter's output to undo. The result - /// must be whole rows, and no more rows than the input holds. + /// Colors (1 to 4), BitsPerComponent (1, 2, 4, 8, 16) and Columns (1 to 64, or a power of two up to 2^30 when byte 3 is 192 or + /// more: rows far longer than the data, issue #48); the rest is the filter's output to undo. The output is never more than twice + /// the input, and when the data holds at least one row it is whole rows, no more than the input holds. /// /// ISO 32000-2 §7.4.4.3 Table 8 and §7.4.4.4. private static void PredictorTarget(ReadOnlySpan data) @@ -254,7 +267,7 @@ private static void PredictorTarget(ReadOnlySpan data) int predictor = predictors[data[0] % predictors.Length]; int colors = 1 + (data[1] % 4); int bitsPerComponent = depths[data[2] % depths.Length]; - int columns = 1 + (data[3] % 64); + long columns = data[3] >= 192 ? 1L << Math.Min(data[3] - 192, 30) : 1 + (data[3] % 64); var parameters = new CosDictionary { [new CosName("Predictor")] = new CosInteger(predictor), @@ -266,9 +279,14 @@ private static void PredictorTarget(ReadOnlySpan data) var output = new ArrayBufferWriter(); Predictor.Decode(body, output, new FilterContext { Parameters = parameters }); - int row = ((colors * bitsPerComponent * columns) + 7) / 8; - int rowsIn = predictor >= 10 ? (body.Length + row) / (row + 1) : (body.Length + row - 1) / row; - bool passedThrough = predictor is 1 or 3; + if (output.WrittenCount > (2L * body.Length) + 8) + { + throw new InvalidOperationException($"Predictor {predictor} with Columns {columns} turned {body.Length} bytes into {output.WrittenCount}."); + } + + long row = (((long)colors * bitsPerComponent * columns) + 7) / 8; + bool passedThrough = predictor is 1 or 3 || row > body.Length; + long rowsIn = passedThrough ? 0 : predictor >= 10 ? (body.Length + row) / (row + 1) : (body.Length + row - 1) / row; if (!passedThrough && (output.WrittenCount % row != 0 || output.WrittenCount > rowsIn * row)) { throw new InvalidOperationException($"Predictor {predictor} turned {body.Length} bytes into {output.WrittenCount}, not whole rows of {row}."); @@ -486,7 +504,7 @@ private static void EncryptedDocument(ReadOnlySpan data) _ = (document.Permissions, document.Security?.Integrity); foreach (PdfPage page in document.Pages) { - CosObject contents = document.Resolve(page.Dictionary.TryGetValue(ContentsKey, out CosObject? value) ? value : null); + CosObject contents = document.Resolve(page.Dictionary.TryGetValue(Names.Contents, out CosObject? value) ? value : null); IEnumerable streams = contents is CosArray array ? array : [contents]; foreach (CosObject item in streams) { @@ -497,7 +515,7 @@ private static void EncryptedDocument(ReadOnlySpan data) } } - if (document.Resolve(document.Trailer.TryGetValue(InfoKey, out CosObject? info) ? info : null) is CosDictionary dictionary) + if (document.Resolve(document.Trailer.TryGetValue(Names.Info, out CosObject? info) ? info : null) is CosDictionary dictionary) { foreach (KeyValuePair entry in dictionary) { diff --git a/tests/Broadside.Fuzz/Program.cs b/tests/Broadside.Fuzz/Program.cs index d7b0e646..3912de81 100644 --- a/tests/Broadside.Fuzz/Program.cs +++ b/tests/Broadside.Fuzz/Program.cs @@ -6,11 +6,13 @@ namespace Broadside.Fuzz; /// /// Entry point of the fuzz harness. The first argument selects the mode, the second the target (see ): /// -/// --fuzz [target]: run under libFuzzer through the libfuzzer-dotnet driver. The driver passes a single argument, so -/// the target may also come from the BROADSIDE_FUZZ_TARGET environment variable. +/// --fuzz [target]: run under libFuzzer through the libfuzzer-dotnet driver. The driver passes at most one argument +/// (with --target_path=dotnet that is the harness DLL, and the mode is implied), so the target may also come from the +/// BROADSIDE_FUZZ_TARGET environment variable. /// --afl <target>: run under afl-fuzz (SharpFuzz's AFL fork-server mode). /// --smoke <target> [seconds] [seed]: no fuzzer needed; corpus files plus random mutations for the given time (default 10 s). /// --run <target> <file>: run the target once on one input, to replay a finding. +/// --seeds <target> <directory> [pdf-directory...]: write the target's seed inputs for libFuzzer or AFL (see ). /// --list: print the target names. /// /// Exit code 0 means no finding, 1 a finding, 2 a usage error. See README.md next to this file. @@ -25,7 +27,14 @@ private static int Main(string[] args) { if (args.Length == 0) { - return Usage(); + // libfuzzer-dotnet starts the target as "dotnet " (--target_path=dotnet --target_arg=) and passes no + // further argument, so a bare start under the driver is --fuzz with the target from the environment. + if (Environment.GetEnvironmentVariable(LibFuzzerEnvironmentVariable) is null) + { + return Usage(); + } + + args = ["--fuzz"]; } switch (args[0]) @@ -101,6 +110,18 @@ private static int Main(string[] args) return 0; } + case "--seeds": + { + if (args.Length < 3 || !TryGetTarget(args[1], out _)) + { + return Usage(); + } + + int count = SeedWriter.Write(args[1], args[2], args[3..]); + Console.WriteLine(SeedWriter.Describe(args[1], count, args[2])); + return 0; + } + default: return Usage(); } @@ -145,6 +166,7 @@ private static int Usage() --afl run under afl-fuzz --smoke [seconds] [seed] corpus files plus random mutations, no fuzzer needed (default 10 s) --run run the target once on one input + --seeds [pdf-dir...] write the target's seed inputs from tests/Corpus and the PDFs under pdf-dir --list list the targets """); return 2; diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index 1a3db895..309113df 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, the revisions and a linearized file's parameter dictionary and hint tables, then walks every object reachable from the trailer or numbered below `Size` and decodes every stream through its filters with `DocumentWalker`, the walk the real-world corpus gate runs; a `DiagnosticException` is the one allowed outcome besides the encryption exceptions below, for a file in which even a scan finds no catalog (`CatalogNotFound`)) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. @@ -25,6 +25,8 @@ dotnet run -c Release --project tests/Broadside.Fuzz -- --run object-parser arti `--run ` executes the target once on one input, which is also how to replay a crash found by libFuzzer or AFL. +`--seeds [pdf-directory...]` writes the target's seed inputs for libFuzzer or AFL: whole files for the targets that read whole files, and for the others the parts of the files they read, cut out with the library and prefixed with the control bytes that select each file's own parameters (`filter-*`: the raw bodies of the streams whose first filter it is, `filter-lzw` behind its EarlyChange byte; `filter-predictor`: the Flate output of predicted streams behind the bytes that select their Predictor, Colors, BitsPerComponent and Columns; `xref-stream` and `object-stream`: decoded cross-reference and object streams behind W or N and First; `hint-tables`: the hint streams of linearized files behind their page count and shared table position; `mac-token`: standalone PDF MAC tokens; `decrypt`: the raw bodies of encrypted streams behind each selector byte). The sources are `tests/Corpus/*.pdf` plus every PDF under the extra directories, at most 256 KB each; seeds are named by their SHA-256. This replaces the hand-made seed recipes below for real fuzzing. + Whole corpus files are the right seeds for `lexer` and `object-parser`, which read any bytes as a file body, and for `document` and `save`, which read whole files. `hint-tables` reads raw hint stream data, for which whole files are a weak seed; for libFuzzer and AFL seed it with the hint stream of `linearized.pdf` behind its three control bytes (two pages, shared table at 44): ```sh @@ -48,6 +50,21 @@ Smoke mode is a regression net, not a fuzzer: it has no coverage feedback and fi ## Real fuzzing +### Scheduled runs in CI + +`.github/workflows/fuzz.yml` fuzzes every target under libFuzzer once a week (Sundays 03:17 UTC) and on the "Run workflow" button, one parallel job per target: 75 minutes on every core of the runner by default (the `minutes` input changes it, up to 300; `targets` picks a subset), which adds up to more than 24 hours of fuzzing per run. Each job builds the driver from pinned source (`build-libfuzzer-dotnet.sh`), installs SharpFuzz.CommandLine, builds the harness, fetches the `pdf20examples` and `qpdf` corpora with `tools/CorpusFetcher` as extra seeds, restores the target's corpus from the previous run's cache, and runs `run-libfuzzer.sh`. Findings fail the job and are uploaded as `fuzz-findings-` with a replay of each (`.txt`); the summary job tabulates minutes, CPU-hours, executions, corpus size and findings per target. + +The same scripts run on any Linux machine (or a Docker container from `mcr.microsoft.com/dotnet/sdk:10.0-noble` with `clang libclang-rt-dev jq` installed): + +```sh +tests/Broadside.Fuzz/build-libfuzzer-dotnet.sh +dotnet tool install --global SharpFuzz.CommandLine --version 2.3.0 +dotnet build -c Release tests/Broadside.Fuzz +tests/Broadside.Fuzz/run-libfuzzer.sh document 600 corpus/pdf20examples corpus/qpdf # 10 minutes on every core +``` + +`run-libfuzzer.sh` writes `--seeds` into `artifacts/fuzz//seeds/` with the plain build, instruments a copy of the build in `artifacts/fuzz/instrumented/`, runs libFuzzer on that copy with one worker per core (`FUZZ_WORKERS` overrides) on `artifacts/fuzz//corpus/` plus the seeds, with the PDF dictionary `pdf.dict`, a 10 s timeout per input (hangs are findings), inputs up to 256 KB and a 3 GiB managed heap cap per worker (`DOTNET_GCHeapHardLimit`, so a decompression bomb is an `OutOfMemoryException` finding rather than a swapping machine), then minimizes the corpus with `-merge=1`, replays every `crash-*`, `timeout-*` and `oom-*` input into a `.txt` next to it, and writes `stats.json`. A stack overflow kills the .NET process; the driver then exits during the input, which libFuzzer reports as a crash and saves. + ### 1. Instrument the library SharpFuzz rewrites the IL of the assembly under test so the fuzzer sees which branches each input reaches. Instrument `Broadside.dll` (and any other `src/` assembly the target exercises), never the harness itself: @@ -58,11 +75,11 @@ dotnet build -c Release tests/Broadside.Fuzz sharpfuzz artifacts/bin/Broadside.Fuzz/release/Broadside.dll ``` -The instrumented file replaces the original in place; rebuild to get a clean one back. +The instrumented file replaces the original in place; rebuild to get a clean one back. Instrumented code writes coverage into libFuzzer's shared memory, so it faults when started any other way: `--smoke`, `--run` and `--seeds` need the plain build (`run-libfuzzer.sh` keeps both). For the same reason the harness must not run library code before `Fuzzer.LibFuzzer.Run` (keep `Cos*` values out of `FuzzTargets`' static constructor). ### 2a. libFuzzer (`--fuzz`): the primary driver -`--fuzz [target]` calls `SharpFuzz.Fuzzer.LibFuzzer.Run`. It must be started by the [libfuzzer-dotnet](https://github.com/Metalnem/libfuzzer-dotnet) driver, a small native program that hosts libFuzzer and talks to the .NET process over shared memory; started any other way it exits 2 with a message. The driver passes one argument to the target, so when `--target_path` is `dotnet` that argument is the harness DLL and the target name comes from the `BROADSIDE_FUZZ_TARGET` environment variable. +`--fuzz [target]` calls `SharpFuzz.Fuzzer.LibFuzzer.Run`. It must be started by the [libfuzzer-dotnet](https://github.com/Metalnem/libfuzzer-dotnet) driver, a small native program that hosts libFuzzer and talks to the .NET process over shared memory; started any other way it exits 2 with a message. The driver passes one argument to the target, so when `--target_path` is `dotnet` that argument is the harness DLL, the harness takes a start with no mode under the driver as `--fuzz`, and the target name comes from the `BROADSIDE_FUZZ_TARGET` environment variable. Getting the driver: diff --git a/tests/Broadside.Fuzz/SeedWriter.cs b/tests/Broadside.Fuzz/SeedWriter.cs new file mode 100644 index 00000000..5baa6836 --- /dev/null +++ b/tests/Broadside.Fuzz/SeedWriter.cs @@ -0,0 +1,285 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.Globalization; +using System.Security.Cryptography; +using Broadside.Diagnostics; +using Broadside.Filters; +using Broadside.Objects; +using Broadside.Security; +using Broadside.TestSupport; + +namespace Broadside.Fuzz; + +/// +/// Writes the seed inputs of one target for libFuzzer or AFL (--seeds). Targets that read whole files get the PDF files as +/// they are; targets that read a stream body, decoded structure data or a token behind control bytes get those parts, cut out of +/// the files with the library itself and prefixed with the control bytes that select the file's own parameters, so the fuzzer starts +/// from inputs that reach deep into the code. The sources are tests/Corpus/*.pdf plus every PDF under the extra directories +/// (a fixed real-world subset in CI). Seeds are named by their SHA-256, so duplicates collapse, and none is longer than +/// (libFuzzer's -max_len in the scheduled workflow). +/// +internal static class SeedWriter +{ + /// The longest seed written, and the longest input the scheduled workflow lets libFuzzer generate. + public const int MaxSeedLength = 256 * 1024; + + private const string OwnerPassword = "owner"; + private const int MaxObjectNumber = 100_000; + + private static readonly CosName Type = new("Type"); + private static readonly CosName Filter = new("Filter"); + private static readonly CosName DecodeParms = new("DecodeParms"); + private static readonly CosName XRef = new("XRef"); + private static readonly CosName ObjStm = new("ObjStm"); + private static readonly CosName W = new("W"); + private static readonly CosName N = new("N"); + private static readonly CosName First = new("First"); + private static readonly CosName S = new("S"); + private static readonly CosName Size = new("Size"); + private static readonly CosName Predictor = new("Predictor"); + private static readonly CosName Colors = new("Colors"); + private static readonly CosName BitsPerComponent = new("BitsPerComponent"); + private static readonly CosName Columns = new("Columns"); + private static readonly CosName EarlyChange = new("EarlyChange"); + private static readonly CosName AuthCode = new("AuthCode"); + private static readonly CosName Mac = new("MAC"); + + private static readonly Dictionary FilterTargets = new(StringComparer.Ordinal) + { + ["filter-asciihex"] = "ASCIIHexDecode", + ["filter-ascii85"] = "ASCII85Decode", + ["filter-flate"] = "FlateDecode", + ["filter-runlength"] = "RunLengthDecode", + }; + + /// Writes the seeds of into . + /// The number of distinct seeds written. + public static int Write(string target, string output, IEnumerable extraDirectories) + { + Directory.CreateDirectory(output); + List sources = [.. CorpusLocator.CorpusFiles()]; + foreach (string directory in extraDirectories) + { + List found = [.. Directory.EnumerateFiles(directory, "*.pdf", SearchOption.AllDirectories)]; + found.Sort(StringComparer.Ordinal); + sources.AddRange(found); + } + + var written = new HashSet(StringComparer.Ordinal); + foreach (string source in sources) + { + if (new FileInfo(source).Length > MaxSeedLength) + { + continue; + } + + byte[] file = File.ReadAllBytes(source); + foreach (byte[] seed in SeedsOf(target, file)) + { + if (seed.Length is > 0 and <= MaxSeedLength) + { + string name = Convert.ToHexStringLower(SHA256.HashData(seed)); + if (written.Add(name)) + { + File.WriteAllBytes(Path.Combine(output, name), seed); + } + } + } + } + + return written.Count; + } + + private static IEnumerable SeedsOf(string target, byte[] file) => target switch + { + "filter-lzw" => Streams(file).Where(stream => FirstFilter(stream.Value) == "LZWDecode").Select(stream => Lzw(stream.Value)), + "filter-predictor" => Streams(file).Select(stream => PredictorSeed(stream.Value)).OfType(), + "xref-stream" => Streams(file).Select(stream => XrefStreamSeed(stream.Document, stream.Value)).OfType(), + "object-stream" => Streams(file).Select(stream => ObjectStreamSeed(stream.Document, stream.Value)).OfType(), + "hint-tables" => Streams(file).Select(stream => HintSeed(stream.Document, stream.Value)).OfType(), + "mac-token" => MacTokens(file), + "decrypt" => EncryptedBodies(file), + _ when FilterTargets.TryGetValue(target, out string? filter) => + Streams(file).Where(stream => FirstFilter(stream.Value) == filter).Select(stream => stream.Value.EncodedData.ToArray()), + _ => [file], + }; + + /// Every stream object of the file, numbers 1 to Size - 1, generation 0; nothing when the file does not open. + private static IEnumerable<(PdfDocument Document, CosStream Value)> Streams(byte[] file) + { + using PdfDocument? document = Open(file); + if (document is null) + { + yield break; + } + + long size = document.Trailer.TryGetValue(Size, out CosObject? entry) && entry is CosInteger integer ? integer.Value : 0; + for (int number = 1; number < Math.Min(size, MaxObjectNumber); number++) + { + if (document.Resolve(new CosReference(number, 0)) is CosStream stream) + { + yield return (document, stream); + } + } + } + + private static PdfDocument? Open(byte[] file) + { + try + { + return new PdfEngine().Open(file, new PdfPassword(OwnerPassword)); + } + catch (Exception exception) when (exception is DiagnosticException or PdfPasswordException or PdfEncryptionNotSupportedException or PdfCertificateException) + { + return null; + } + } + + private static string? FirstFilter(CosStream stream) => stream.Dictionary.TryGetValue(Filter, out CosObject? filter) + ? filter switch + { + CosName name => name.Value, + CosArray { Count: > 0 } array when array[0] is CosName name => name.Value, + _ => null, + } + : null; + + private static CosDictionary? Parameters(CosStream stream) => stream.Dictionary.TryGetValue(DecodeParms, out CosObject? parameters) + ? parameters switch + { + CosDictionary dictionary => dictionary, + CosArray { Count: > 0 } array => array[0] as CosDictionary, + _ => null, + } + : null; + + private static int Integer(CosDictionary? dictionary, CosName key, int fallback) => + dictionary is not null && dictionary.TryGetValue(key, out CosObject? value) && value is CosInteger integer + ? (int)Math.Clamp(integer.Value, int.MinValue, int.MaxValue) + : fallback; + + /// filter-lzw: the EarlyChange byte, then the raw body. + private static byte[] Lzw(CosStream stream) => [(byte)(Integer(Parameters(stream), EarlyChange, 1) & 1), .. stream.EncodedData.Span]; + + /// + /// filter-predictor: the four bytes that select the stream's own Predictor, Colors, BitsPerComponent and Columns, then + /// the output of its Flate stage before the predictor is undone. + /// + private static byte[]? PredictorSeed(CosStream stream) + { + CosDictionary? parameters = Parameters(stream); + int predictor = Integer(parameters, Predictor, 1); + if (FirstFilter(stream) != "FlateDecode" || predictor <= 1) + { + return null; + } + + int predictorIndex = Array.IndexOf([1, 2, 10, 11, 12, 13, 14, 15, 3], predictor); + int depthIndex = Array.IndexOf([1, 2, 4, 8, 16], Integer(parameters, BitsPerComponent, 8)); + var body = new ArrayBufferWriter(); + new FlateDecodeFilter().Decode(stream.EncodedData, body, new FilterContext()); + + return + [ + (byte)Math.Max(predictorIndex, 0), + (byte)((Integer(parameters, Colors, 1) - 1) & 3), + (byte)(depthIndex < 0 ? 3 : depthIndex), + (byte)((Integer(parameters, Columns, 1) - 1) & 63), + .. body.WrittenSpan, + ]; + } + + /// xref-stream: the three widths of W, the default-Index selector, then the decoded data. + private static byte[]? XrefStreamSeed(PdfDocument document, CosStream stream) + { + if (!XRef.Equals(stream.Dictionary.TryGetValue(Type, out CosObject? type) ? type : null) + || !stream.Dictionary.TryGetValue(W, out CosObject? widths) || widths is not CosArray { Count: 3 } array + || array.Any(width => width is not CosInteger { Value: >= 0 and <= 9 })) + { + return null; + } + + return [.. array.Select(width => (byte)((CosInteger)width).Value), 0, .. document.DecodeStream(stream).Span]; + } + + /// object-stream: N and First (when both fit a byte), then the decoded data. + private static byte[]? ObjectStreamSeed(PdfDocument document, CosStream stream) + { + int count = Integer(stream.Dictionary, N, -1); + int first = Integer(stream.Dictionary, First, -1); + if (!ObjStm.Equals(stream.Dictionary.TryGetValue(Type, out CosObject? type) ? type : null) || count is < 0 or > 255 || first is < 0 or > 255) + { + return null; + } + + return [(byte)count, (byte)first, .. document.DecodeStream(stream).Span]; + } + + /// hint-tables: in a linearized file, the page count, the shared object table position, then the hint data. + private static byte[]? HintSeed(PdfDocument document, CosStream stream) + { + int shared = Integer(stream.Dictionary, S, -1); + if (document.Linearization is null || shared is < 0 or > ushort.MaxValue || stream.Dictionary.ContainsKey(Type)) + { + return null; + } + + byte[] seed = [(byte)((document.Pages.Count - 1) & 15), 0, 0, .. document.DecodeStream(stream).Span]; + BinaryPrimitives.WriteUInt16BigEndian(seed.AsSpan(1), (ushort)shared); + return seed; + } + + /// mac-token: the DER token of a standalone PDF MAC (ISO/TS 32004). + private static IEnumerable MacTokens(byte[] file) + { + using PdfDocument? document = Open(file); + if (document?.Trailer.TryGetValue(AuthCode, out CosObject? authCode) == true + && document.Resolve(authCode) is CosDictionary dictionary + && dictionary.TryGetValue(Mac, out CosObject? mac) && document.Resolve(mac) is CosString token) + { + yield return token.Bytes.ToArray(); + } + } + + /// + /// decrypt: the raw (still encrypted) stream bodies of an encrypted file, each behind every crypt filter selector byte, + /// cut from the file bytes between stream and endstream because the document model only shows plaintext. + /// + private static IEnumerable EncryptedBodies(byte[] file) + { + if (file.AsSpan().IndexOf("/Encrypt"u8) < 0) + { + yield break; + } + + int position = 0; + while (true) + { + int keyword = file.AsSpan(position).IndexOf("stream"u8); + if (keyword < 0) + { + yield break; + } + + int start = position + keyword + "stream".Length; + start += file.AsSpan(start).StartsWith("\r\n"u8) ? 2 : file.AsSpan(start).StartsWith("\n"u8) ? 1 : 0; + int end = file.AsSpan(start).IndexOf("endstream"u8); + if (end < 0) + { + yield break; + } + + byte[] body = file.AsSpan(start, end).TrimEnd("\r\n"u8).ToArray(); + for (byte selector = 0; selector < 4 && body.Length > 0; selector++) + { + yield return [selector, .. body]; + } + + position = start + end + "endstream".Length; + } + } + + /// Formats a count for the console. + public static string Describe(string target, int count, string output) => + string.Create(CultureInfo.InvariantCulture, $"seeds: target '{target}', {count} seeds written to {output}"); +} diff --git a/tests/Broadside.Fuzz/build-libfuzzer-dotnet.sh b/tests/Broadside.Fuzz/build-libfuzzer-dotnet.sh new file mode 100755 index 00000000..b1e37385 --- /dev/null +++ b/tests/Broadside.Fuzz/build-libfuzzer-dotnet.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# Builds the libfuzzer-dotnet driver (https://github.com/Metalnem/libfuzzer-dotnet) from its source at a pinned commit, after +# checking the source's SHA-256, into artifacts/fuzz/libfuzzer-dotnet. Linux only: it needs clang with libFuzzer +# (Ubuntu: apt install clang libclang-rt-dev). Building from source rather than downloading the release binary keeps the +# driver auditable and lets it run on arm64 too. Override the compiler with CXX. +set -euo pipefail + +commit=bd39d4e88d715ab460a929943645be2a186cde52 +sha256=90f019e2e9ad3a0b93c7ecc2c5afb2fbfc8b5aab6aac51c7e0d349ec79354f36 +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +out="${root}/artifacts/fuzz" +mkdir -p "${out}" + +curl --fail --silent --show-error --location \ + --output "${out}/libfuzzer-dotnet.cc" \ + "https://raw.githubusercontent.com/Metalnem/libfuzzer-dotnet/${commit}/libfuzzer-dotnet.cc" +echo "${sha256} ${out}/libfuzzer-dotnet.cc" | sha256sum --check --strict + +# The driver reports a .NET exception with __builtin_trap. That is SIGILL on x86-64, which libFuzzer catches and saves the input +# for, but SIGTRAP on arm64, which libFuzzer does not handle (the run dies and the input is lost); calling abort instead raises +# SIGABRT, which libFuzzer handles everywhere. +"${CXX:-clang++}" -O2 -fsanitize=fuzzer -ftrap-function=abort "${out}/libfuzzer-dotnet.cc" -o "${out}/libfuzzer-dotnet" +echo "built ${out}/libfuzzer-dotnet" diff --git a/tests/Broadside.Fuzz/pdf.dict b/tests/Broadside.Fuzz/pdf.dict new file mode 100644 index 00000000..abc14f24 --- /dev/null +++ b/tests/Broadside.Fuzz/pdf.dict @@ -0,0 +1,113 @@ +# libFuzzer / AFL dictionary of PDF syntax (ISO 32000-2 §7.2-§7.6). Passed with -dict= by .github/workflows/fuzz.yml. +# Keywords and delimiters (§7.2, §7.3, §7.5) +"%PDF-1.7" +"%PDF-2.0" +"%%EOF" +"obj" +"endobj" +"stream" +"endstream" +"stream\x0d\x0a" +"\x0aendstream" +"xref" +"trailer" +"startxref" +"<<" +">>" +"[" +"]" +" R" +" 0 R" +" 0 obj" +"true" +"false" +"null" +"0000000000 65535 f\x0d\x0a" +"0000000009 00000 n\x0d\x0a" +# Names of the file structure (§7.5, Annex F) +"/Type" +"/Size" +"/Root" +"/Info" +"/ID" +"/Prev" +"/Catalog" +"/Pages" +"/Page" +"/Kids" +"/Count" +"/Parent" +"/MediaBox" +"/CropBox" +"/Rotate" +"/UserUnit" +"/Resources" +"/Contents" +"/XRef" +"/XRefStm" +"/W" +"/Index" +"/ObjStm" +"/N" +"/First" +"/Extends" +"/Linearized" +"/H" +"/L" +"/O" +"/E" +"/T" +"/S" +# Streams and filters (§7.3.8, §7.4) +"/Length" +"/Filter" +"/DecodeParms" +"/DL" +"/F" +"/FlateDecode" +"/LZWDecode" +"/ASCII85Decode" +"/ASCIIHexDecode" +"/RunLengthDecode" +"/Crypt" +"/Predictor" +"/Colors" +"/BitsPerComponent" +"/Columns" +"/EarlyChange" +"/Fl" +"/AHx" +"/A85" +"/LZW" +"/RL" +"~>" +# Encryption (§7.6, ISO/TS 32003, ISO/TS 32004) +"/Encrypt" +"/Standard" +"/Adobe.PubSec" +"/V" +"/R" +"/P" +"/U" +"/UE" +"/OE" +"/Perms" +"/CF" +"/StmF" +"/StrF" +"/EFF" +"/CFM" +"/AESV2" +"/AESV3" +"/AESV4" +"/V2" +"/Identity" +"/StdCF" +"/EncryptMetadata" +"/Recipients" +"/SubFilter" +"/AuthCode" +"/MAC" +"/MACLocation" +"/KDFSalt" +"/ByteRange" diff --git a/tests/Broadside.Fuzz/run-libfuzzer.sh b/tests/Broadside.Fuzz/run-libfuzzer.sh new file mode 100755 index 00000000..3e417da5 --- /dev/null +++ b/tests/Broadside.Fuzz/run-libfuzzer.sh @@ -0,0 +1,123 @@ +#!/usr/bin/env bash +# Fuzzes one target under libFuzzer for a fixed time (README.md, "Real fuzzing"; .github/workflows/fuzz.yml runs it per target). +# +# tests/Broadside.Fuzz/run-libfuzzer.sh [pdf-directory...] +# +# Before: the harness is built in Release (dotnet build -c Release tests/Broadside.Fuzz), the driver is built +# (tests/Broadside.Fuzz/build-libfuzzer-dotnet.sh) and the sharpfuzz tool is on PATH +# (dotnet tool install --global SharpFuzz.CommandLine --version 2.3.0). Linux only. The script fuzzes a copy of the build in +# artifacts/fuzz/instrumented/ whose Broadside.dll it instruments; seeds and replays run on the plain build, because +# instrumented code writes coverage into libFuzzer's shared memory and faults when started without the driver. +# +# Work directory artifacts/fuzz//: seeds/ (rewritten each run by --seeds from tests/Corpus and the PDF directories), +# corpus/ (what libFuzzer found; keep it between runs, CI caches it, and it is minimized with -merge=1 after each run), +# findings/ (crash-*, timeout-*, oom-* inputs, each with a .txt replay of what the harness reports), logs/ (one log per worker) +# and stats.json (time, workers, executions, corpus size, findings). Exit code 0 when nothing was found, 1 otherwise. +# +# Environment: FUZZ_WORKERS (parallel libFuzzer workers, default the processor count), LIBFUZZER_DOTNET (the driver, default +# artifacts/fuzz/libfuzzer-dotnet), DOTNET_GCHeapHardLimit (managed heap cap per worker, default 3 GiB, so a decompression +# bomb surfaces as an OutOfMemoryException finding instead of the machine swapping). +set -euo pipefail + +if [ "$#" -lt 2 ]; then + echo "usage: $0 [pdf-directory...]" >&2 + exit 2 +fi + +target="$1" +seconds="$2" +shift 2 +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +build="${root}/artifacts/bin/Broadside.Fuzz/release" +harness="${build}/Broadside.Fuzz.dll" +instrumented="${root}/artifacts/fuzz/instrumented" +driver="${LIBFUZZER_DOTNET:-${root}/artifacts/fuzz/libfuzzer-dotnet}" +workers="${FUZZ_WORKERS:-$(nproc)}" +work="${root}/artifacts/fuzz/${target}" +max_len=262144 + +mkdir -p "${work}/corpus" "${work}/findings" "${work}/logs" +rm -rf "${work}/seeds" +dotnet "${harness}" --seeds "${target}" "${work}/seeds" "$@" + +# Instrument a copy of the build (once per build: the copy is redone when the build is newer). +if [ ! -f "${instrumented}/Broadside.dll" ] || [ "${build}/Broadside.dll" -nt "${instrumented}/Broadside.dll" ]; then + rm -rf "${instrumented}" + mkdir -p "${instrumented}" + cp -R "${build}/." "${instrumented}/" + sharpfuzz "${instrumented}/Broadside.dll" +fi + +export BROADSIDE_FUZZ_TARGET="${target}" +export DOTNET_GCHeapHardLimit="${DOTNET_GCHeapHardLimit:-0xC0000000}" +fuzz_options=( + --target_path=dotnet + "--target_arg=${instrumented}/Broadside.Fuzz.dll" + -timeout=10 + -rss_limit_mb=4096 + "-max_len=${max_len}" + "-dict=${root}/tests/Broadside.Fuzz/pdf.dict" +) + +# -jobs writes fuzz-.log into the current directory. +started=${SECONDS} +set +e +(cd "${work}/logs" && "${driver}" "${fuzz_options[@]}" \ + "-max_total_time=${seconds}" \ + "-artifact_prefix=${work}/findings/" \ + "-jobs=${workers}" "-workers=${workers}" \ + -print_final_stats=1 \ + "${work}/corpus" "${work}/seeds") +fuzz_status=$? +set -e +elapsed=$((SECONDS - started)) + +# Keep the corpus small for the cache: only inputs that add coverage. On failure the unminimized corpus stays. +rm -rf "${work}/corpus-min" +mkdir -p "${work}/corpus-min" +if (cd "${work}/logs" && timeout 1800 "${driver}" "${fuzz_options[@]}" -merge=1 "${work}/corpus-min" "${work}/corpus" > merge.log 2>&1); then + rm -rf "${work}/corpus" + mv "${work}/corpus-min" "${work}/corpus" +else + echo "corpus merge failed; keeping the unminimized corpus (see ${work}/logs/merge.log)" + rm -rf "${work}/corpus-min" +fi + +# Executions per worker: the final statistics, or the last status line of a worker that stopped on a finding. +executions=0 +for log in "${work}"/logs/fuzz-*.log; do + [ -f "${log}" ] || continue + count=$(sed -n 's/^stat::number_of_executed_units: *\([0-9]*\)$/\1/p' "${log}" | tail -1) + if [ -z "${count}" ]; then + count=$(sed -n 's/^#\([0-9][0-9]*\)[[:space:]].*/\1/p' "${log}" | tail -1) + fi + executions=$((executions + ${count:-0})) +done +corpus_files=$(find "${work}/corpus" -type f | wc -l | tr -d ' ') +findings=() +while IFS= read -r -d '' finding; do + findings+=("$(basename "${finding}")") + # Replay each finding so the artifact carries the exception and stack trace, not just the input. + timeout 120 dotnet "${harness}" --run "${target}" "${finding}" > "${finding}.txt" 2>&1 || true +done < <(find "${work}/findings" -type f \( -name 'crash-*' -o -name 'timeout-*' -o -name 'oom-*' -o -name 'leak-*' \) ! -name '*.txt' -print0 | sort -z) + +jq -n \ + --arg target "${target}" \ + --argjson seconds "${elapsed}" \ + --argjson workers "${workers}" \ + --argjson executions "${executions}" \ + --argjson corpus "${corpus_files}" \ + --argjson status "${fuzz_status}" \ + --args '{target: $target, wallSeconds: $seconds, workers: $workers, cpuHours: (($seconds * $workers) / 3600 * 100 | round / 100), executions: $executions, corpusFiles: $corpus, libFuzzerExitCode: $status, findings: $ARGS.positional}' \ + "${findings[@]}" > "${work}/stats.json" +cat "${work}/stats.json" + +if [ "${#findings[@]}" -gt 0 ]; then + echo "::error::fuzz target ${target}: ${#findings[@]} finding(s); replay with: dotnet run -c Release --project tests/Broadside.Fuzz -- --run ${target} " + exit 1 +fi + +if [ "${fuzz_status}" -ne 0 ]; then + echo "::error::libFuzzer exited with ${fuzz_status} for ${target} without leaving a finding; see artifacts/fuzz/${target}/logs" + exit 1 +fi diff --git a/tests/Broadside.TestSupport/DocumentWalker.cs b/tests/Broadside.TestSupport/DocumentWalker.cs index 572aabdc..9cbe99c1 100644 --- a/tests/Broadside.TestSupport/DocumentWalker.cs +++ b/tests/Broadside.TestSupport/DocumentWalker.cs @@ -126,10 +126,15 @@ public void Visit(CosObject root) } } - /// Counts what the filter pipeline writes and keeps none of it, so decoding a large file holds no decoded data. + /// + /// Counts what the filter pipeline writes and keeps none of it, so decoding a large file holds no decoded data. The scratch + /// buffer is per thread and outlives the walk, so the open-and-walk benchmark's Allocated shows the library's + /// allocations, not the walker's. + /// private sealed class DiscardingWriter : IBufferWriter { - private byte[] _buffer = new byte[64 * 1024]; + [ThreadStatic] + private static byte[]? _scratch; public long Written { get; private set; } @@ -139,14 +144,14 @@ private sealed class DiscardingWriter : IBufferWriter public Span GetSpan(int sizeHint = 0) => Buffer(sizeHint); - private byte[] Buffer(int sizeHint) + private static byte[] Buffer(int sizeHint) { - if (sizeHint > _buffer.Length) + if (_scratch is null || sizeHint > _scratch.Length) { - _buffer = new byte[sizeHint]; + _scratch = new byte[Math.Max(sizeHint, 64 * 1024)]; } - return _buffer; + return _scratch; } } } diff --git a/tests/Broadside.Tests/Filters/PredictorTests.cs b/tests/Broadside.Tests/Filters/PredictorTests.cs index 4c880d48..990c34ab 100644 --- a/tests/Broadside.Tests/Filters/PredictorTests.cs +++ b/tests/Broadside.Tests/Filters/PredictorTests.cs @@ -100,8 +100,32 @@ public void Predictors_apply_after_lzw_too() { "/Predictor 12 /Columns 3", [2, 10, 20, 30, 0, 5], [10, 20, 30, 5, 0, 0], "PredictorInvalid" }, { "/Predictor 12 /Columns 0", [2, 10, 2, 5], [10, 15], "DecodeParmsInvalid" }, { "/Predictor 12 /Columns 1 /BitsPerComponent 3", [2, 10, 2, 5], [10, 15], "DecodeParmsInvalid" }, + { "/Predictor 12 /Columns 100000000", [2, 10, 20, 30], [2, 10, 20, 30], "PredictorInvalid" }, + { "/Predictor 2 /Colors 4 /Columns 2", [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], "PredictorInvalid" }, }; + // Found by libFuzzer (issue #48): Columns sized the row buffers and the zero padding of the last row, so a few bytes of data + // with a huge Columns allocated and wrote rows of up to the decoded-length limit (1 GiB) and ran out of memory. Data that + // cannot hold one whole row is now passed through, so the output is never more than twice the input. + [Theory] + [InlineData(12)] + [InlineData(2)] + public void A_row_longer_than_the_whole_data_allocates_nothing_in_proportion_to_the_row(int predictor) + { + byte[] file = FilterTesting.FileWithStream( + $"/Filter /FlateDecode /DecodeParms << /Predictor {predictor} /Colors 4 /BitsPerComponent 16 /Columns 100000000 >>", + FilterEncoders.Zlib([2, 10, 20, 30])); + _ = FilterTesting.DecodeWithCodes(file); + + long before = GC.GetAllocatedBytesForCurrentThread(); + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.Equal([2, 10, 20, 30], decoded); + Assert.Equal(["PredictorInvalid"], codes); + Assert.True(allocated < 1 << 20, $"Decoding 4 bytes allocated {allocated} bytes."); + } + [Theory] [MemberData(nameof(MalformedPredictions))] public void Malformed_predictor_data_or_parameters_are_repaired_with_a_diagnostic(string parameters, byte[] predicted, byte[] expected, string code) diff --git a/tests/Broadside.Tests/Security/SignatureIntegrityTests.cs b/tests/Broadside.Tests/Security/SignatureIntegrityTests.cs index f4d2a293..f33bddd1 100644 --- a/tests/Broadside.Tests/Security/SignatureIntegrityTests.cs +++ b/tests/Broadside.Tests/Security/SignatureIntegrityTests.cs @@ -20,19 +20,25 @@ public class SignatureIntegrityTests { private const string IntegrityInfoOid = "1.0.32004.1.0"; - [Fact] - public void A_mac_attached_to_a_signature_is_verified() + // The container is padded with zeros to its reserved space, and its last DER byte is the last byte of the token's MAC: both + // values are covered so that a reader trimming the padding cannot also trim the container (1 run in 256 used to fail). + [Theory] + [InlineData(false)] + [InlineData(true)] + public void A_mac_attached_to_a_signature_is_verified(bool containerEndsInZeroByte) { - using PdfDocument document = PdfDocument.Open(SignedFile(tamperSignature: false)); + using PdfDocument document = PdfDocument.Open(SignedFile(tamperSignature: false, containerEndsInZeroByte)); Assert.Equal(PdfIntegrityStatus.Verified, document.Security!.Integrity); Assert.Empty(document.Diagnostics); } - [Fact] - public void A_mac_attached_to_a_different_signature_value_does_not_match() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void A_mac_attached_to_a_different_signature_value_does_not_match(bool containerEndsInZeroByte) { - using PdfDocument document = PdfDocument.Open(SignedFile(tamperSignature: true)); + using PdfDocument document = PdfDocument.Open(SignedFile(tamperSignature: true, containerEndsInZeroByte)); Assert.Equal(PdfIntegrityStatus.Failed, document.Security!.Integrity); Diagnostic diagnostic = Assert.Single(document.Diagnostics); @@ -40,7 +46,7 @@ public void A_mac_attached_to_a_different_signature_value_does_not_match() Assert.Contains("signatureDigest", diagnostic.Message, StringComparison.Ordinal); } - private static byte[] SignedFile(bool tamperSignature) + private static byte[] SignedFile(bool tamperSignature, bool containerEndsInZeroByte) { byte[] original = Corpus.Bytes("encrypted-aes-256.pdf"); string text = Encoding.Latin1.GetString(original); @@ -79,15 +85,20 @@ private static byte[] SignedFile(bool tamperSignature) } byte[] fileKey = SHA256.HashData("broadside-corpus:encrypted-aes-256:file-key:0"u8); - byte[] token = Token(fileKey, salt, SHA256.HashData(covered), SHA256.HashData(signatureValue)); + byte[] token = Token(fileKey, salt, SHA256.HashData(covered), SHA256.HashData(signatureValue), containerEndsInZeroByte); signed.SignerInfos[0].AddUnsignedAttribute(new AsnEncodedData("1.0.32004.1.2", token)); - string contents = Convert.ToHexString(signed.Encode()).PadRight(2 * 4096, '0'); + byte[] container = signed.Encode(); + Assert.Equal(containerEndsInZeroByte, container[^1] == 0); + string contents = Convert.ToHexString(container).PadRight(2 * 4096, '0'); Encoding.Latin1.GetBytes(contents).CopyTo(file, l1 + 1); return file; } - /// ISO/TS 32004 §6.3: the AuthenticatedData token, written with the base class library's ASN.1 writer. - private static byte[] Token(byte[] fileKey, byte[] salt, byte[] dataDigest, byte[] signatureDigest) + /// + /// ISO/TS 32004 §6.3: the AuthenticatedData token, written with the base class library's ASN.1 writer. The token ends with the + /// MAC, so the MAC key is chosen (it is random in a real writer) to make the MAC's last byte zero or not, as asked. + /// + private static byte[] Token(byte[] fileKey, byte[] salt, byte[] dataDigest, byte[] signatureDigest, bool macEndsInZeroByte) { byte[] macKey = [.. Enumerable.Range(1, 32).Select(i => (byte)i)]; var infoWriter = new AsnWriter(AsnEncodingRules.DER); @@ -111,6 +122,12 @@ private static byte[] Token(byte[] fileKey, byte[] salt, byte[] dataDigest, byte byte[] attributesAsSet = setWriter.Encode(); byte[] mac = HMACSHA256.HashData(macKey, attributesAsSet); + for (int attempt = 1; (mac[^1] == 0) != macEndsInZeroByte; attempt++) + { + System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(macKey, attempt); + mac = HMACSHA256.HashData(macKey, attributesAsSet); + } + byte[] keyEncryptionKey = HKDF.DeriveKey(HashAlgorithmName.SHA256, fileKey, 32, salt, "PDFMAC"u8.ToArray()); var writer = new AsnWriter(AsnEncodingRules.DER); From d04f533433a9d0d1a2aee6a4d321db53ce354474 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:48:17 -0500 Subject: [PATCH 036/152] docs(conformance): 7.11, 8.11, 12.3.5, 14.3.2, 14.13, AN002, AN003, PDF Declarations rows (#76) Also an auto-state test (zoom and language recommendations). Co-Authored-By: Claude Opus 5.5 --- docs/conformance/iso-32000-2.md | 34 +++++++++++++++---- docs/conformance/pdf-declarations.md | 10 +++--- docs/conformance/pdf20-an002.md | 10 +++--- docs/conformance/pdf20-an003.md | 6 ++-- .../OptionalContent/OptionalContentTests.cs | 23 +++++++++++++ 5 files changed, 64 insertions(+), 19 deletions(-) diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index 183ac882..0e9be501 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -49,7 +49,7 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.7.1 | General | n/a | | | Introductory text | | 7.7.2 | Document catalog dictionary | partial | `PdfDocument`, `PdfVersion`, `PdfPageLayout`, `PdfPageMode`, `DictionaryView` | `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_catalog_version_written_as_a_number_is_read_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.A_malformed_catalog_version_is_ignored_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_catalog_without_its_type_is_read_with_a_diagnostic`, `Broadside.Tests.Document.CatalogEntryTests.Empty_page_pdf_has_the_default_layout_and_mode_and_no_viewer_preferences`, `Broadside.Tests.Document.CatalogEntryTests.Catalog_version_extensions_pdf_exposes_its_version_extensions_and_requirements`, `Broadside.Tests.Document.CatalogEntryTests.Pdf20_header_pdf_is_version_2_0_from_the_header_and_the_catalog`, `Broadside.Tests.Document.CatalogEntryTests.The_language_is_a_text_string`, `Broadside.Tests.Document.CatalogEntryTests.An_unknown_layout_mode_or_preferences_entry_reads_as_the_default_with_a_warning`, `Broadside.Tests.Document.CatalogEntryTests.Outline_pdf_opens_with_the_outline_visible`, `Broadside.Tests.Document.CatalogEntryTests.Reading_every_catalog_entry_changes_nothing` | Type, Version (effective version = later of header and catalog; `HeaderVersion`, `CatalogVersion`), Pages, PageLabels (12.4.2), ViewerPreferences (12.2), PageLayout, PageMode, Metadata (14.3.2), Lang, Extensions (7.12), Requirements (12.11) (#69); the other Table 29 entries arrive with their features (outlines, names, AcroForm, ...) | | 7.7.3 | Page tree | done | `PdfPage`, `PdfPageCollection`, `PageTreeReader` | `Broadside.Tests.Document.OpenDocumentTests.Page_tree_inherited_pdf_pages_inherit_media_box_and_resources_from_the_intermediate_node`, `Broadside.Tests.Document.PageTreeTests.Pages_come_in_kids_order_depth_first_across_intermediate_nodes`, `Broadside.Tests.Document.PageTreeTests.The_nearest_ancestor_wins_and_values_are_inherited_as_is_without_merging`, `Broadside.Tests.Document.PageTreeTests.A_change_to_an_ancestor_node_shows_through_the_pages_that_inherit_from_it`, `Broadside.Tests.Document.PageTreeTests.Page_count_comes_from_the_kids_not_the_count_entry_which_is_checked`, `Broadside.Tests.Document.PageTreeTests.A_node_referenced_twice_is_read_once_with_a_diagnostic`, `Broadside.Tests.Document.PageAttributeTests.Crop_bleed_trim_and_art_boxes_default_to_the_media_box_through_the_crop_box`, `Broadside.Tests.Document.PageAttributeTests.Rotation_is_a_multiple_of_90_normalized_into_0_to_270` | 7.7.3.1 to 7.7.3.4: Kids walk with cycle guard, Count checked not trusted, Resources/MediaBox/CropBox/Rotate inherited as-is from the nearest node; page boxes, Rotate and UserUnit from Table 31; other Table 31 entries arrive with their features | -| 7.7.4 | Name dictionary | partial | `PdfNameDictionary`, `PdfDocument` | `Broadside.Tests.Navigation.NameTreeTests.Name_tree_dests_pdf_maps_its_three_keys_to_their_destination_arrays_with_no_diagnostics`, `Broadside.Tests.Navigation.NameTreeTests.A_tree_root_that_is_not_a_dictionary_reads_as_absent_with_a_diagnostic` | `PdfDocument.Names`; every Table 32 entry is reachable as a name tree through `PdfNameDictionary.GetTree`, `Dests` by name; typed values arrive with their features (Dests destinations #70, EmbeddedFiles #76, JavaScript #73) | +| 7.7.4 | Name dictionary | partial | `PdfNameDictionary`, `PdfDocument`, `PdfEmbeddedFileEntry` | `Broadside.Tests.Files.EmbeddedFileTests.The_name_dictionary_exposes_the_EmbeddedFiles_tree`, `Broadside.Tests.Navigation.NameTreeTests.Name_tree_dests_pdf_maps_its_three_keys_to_their_destination_arrays_with_no_diagnostics`, `Broadside.Tests.Navigation.NameTreeTests.A_tree_root_that_is_not_a_dictionary_reads_as_absent_with_a_diagnostic` | `PdfDocument.Names`; every Table 32 entry is reachable as a name tree through `PdfNameDictionary.GetTree`, `Dests` by name; typed values arrive with their features (Dests destinations #70, EmbeddedFiles typed as `PdfDocument.EmbeddedFiles` (#76), JavaScript #73) | | 7.8 | Content streams and resources | not started | | | | | 7.9.1 | General | not started | | | | | 7.9.2 | String object types | partial | `CosString` | `Broadside.Tests.Objects.TextStringTests` | Text strings decode (PDFDocEncoding, UTF-16BE, UTF-8, language escapes removed); encoding text into a string pending | @@ -59,7 +59,12 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.9.6 | Name trees | done | `PdfNameTree`, `NameTreeReader`, `TreeReader`, `PdfDocument` | `Broadside.Tests.Navigation.NameTreeTests.Name_tree_dests_pdf_maps_its_three_keys_to_their_destination_arrays_with_no_diagnostics`, `Broadside.Tests.Navigation.NameTreeTests.Every_key_of_a_four_level_tree_resolves_and_enumeration_returns_them_once_in_byte_order`, `Broadside.Tests.Navigation.NameTreeTests.Keys_are_compared_byte_by_byte_and_a_text_lookup_tries_pdf_doc_encoding_first`, `Broadside.Tests.Navigation.NameTreeTests.A_text_lookup_falls_back_to_utf_16_and_then_to_every_key_decoded`, `Broadside.Tests.Navigation.NameTreeTests.A_lookup_reads_one_path_from_the_root_and_not_the_whole_tree`, `Broadside.Tests.Navigation.NameTreeTests.A_damaged_tree_reports_each_defect_once_per_node_and_every_key_still_resolves`, `Broadside.Tests.Navigation.NameTreeTests.Lookups_of_a_damaged_tree_fall_back_to_the_whole_tree_and_agree_with_enumeration_on_duplicates`, `Broadside.Tests.Navigation.NameTreeTests.Strict_mode_throws_from_the_lookup_that_meets_the_damage_not_from_open`, `Broadside.Tests.Navigation.NameTreeTests.Reading_a_tree_writes_nothing_and_a_change_to_a_node_shows_in_the_next_lookup`, `Broadside.Tests.Navigation.NameTreeTests.Malformed_nodes_and_keys_are_repaired_or_skipped_with_a_diagnostic` | Read only (writing trees is Phase 4). Lookups descend by Limits (binary search over kids and leaf), keys compared byte by byte (Annex J.3.3); text lookups try PDFDocEncoding, UTF-16BE, then every key decoded. Damage (stale or missing Limits, unsorted or duplicate keys, cycles, depth over 64, odd Names, non-string keys) is reported once per node (`NameTree*` codes) and lookups fall back to an index of the whole tree, rebuilt when a node changes (internal container `Version`); first occurrence in tree order wins. `name-tree-dests.pdf`, `name-tree-deep.pdf`, `name-tree-broken.pdf`. qpdf compares decoded text, not bytes, and reports `name-tree-deep.pdf` as unsorted. | | 7.9.7 | Number trees | done | `PdfNumberTree`, `NumberTreeReader`, `TreeReader`, `PdfDocument` | `Broadside.Tests.Navigation.NumberTreeTests.A_three_level_page_labels_tree_enumerates_its_keys_in_order_with_no_diagnostics`, `Broadside.Tests.Navigation.NumberTreeTests.Exact_lookups_find_keys_through_the_limits_and_miss_keys_between_them`, `Broadside.Tests.Navigation.NumberTreeTests.A_floor_lookup_finds_the_greatest_key_not_greater_than_the_one_asked_for`, `Broadside.Tests.Navigation.NumberTreeTests.Keys_that_are_not_integers_are_repaired_or_skipped_with_a_diagnostic`, `Broadside.Tests.Navigation.NumberTreeTests.A_cycle_through_the_kids_ends_with_a_diagnostic`, `Broadside.Tests.Navigation.NumberTreeTests.A_chain_deeper_than_the_cap_ends_with_a_diagnostic` | Read only. Same walker as 7.9.6 with 32-bit integer keys; `TryGetFloor` for ranges keyed by their first number (page labels, 12.4.2); an integral real key is used with a diagnostic, other keys skipped (`NumberTree*` codes). `number-tree-deep.pdf`. | | 7.10 | Functions | not started | | | | -| 7.11 | File specifications | not started | | | | +| 7.11.1 | General | done | `PdfFileSpecification`, `PdfDocument` | `Broadside.Tests.Files.FileSpecificationTests.A_value_that_is_neither_a_string_nor_a_dictionary_is_not_a_file_specification`, `Broadside.Tests.Files.FileSpecificationTests.A_dictionary_prefers_UF_over_F_and_names_its_embedded_stream_by_the_same_key` | String and dictionary forms through `PdfDocument.GetFileSpecification`; shared by annotations, actions and structure (#71, #73, #75) | +| 7.11.2 | File specification strings | done | `PdfFileSpecification` | `Broadside.Tests.Files.FileSpecificationTests.A_string_file_specification_splits_into_components_with_escaped_solidus_kept`, `Broadside.Tests.Files.FileSpecificationTests.A_relative_file_specification_keeps_its_parent_components_raw`, `Broadside.Tests.Files.FileSpecificationTests.An_unsafe_file_name_is_sanitised` | Components with `\/` unescaped, absolute/relative, `..` kept raw; `SafeFileName` sanitises the last component. Resolving against the file system is out of scope (the library never touches paths) | +| 7.11.3 | File specification dictionaries | done | `PdfFileSpecification`, `PdfFileRelationship` | `Broadside.Tests.Files.FileSpecificationTests.A_dictionary_prefers_UF_over_F_and_names_its_embedded_stream_by_the_same_key`, `Broadside.Tests.Files.FileSpecificationTests.Name_preference_falls_back_through_F_Unix_Mac_and_DOS`, `Broadside.Tests.Files.FileSpecificationTests.A_second_class_relationship_reads_as_other_with_its_name`, `Broadside.Tests.Files.FileSpecificationTests.An_EF_without_a_stream_is_reported_and_the_specification_is_still_readable`, `Broadside.Tests.Files.FileSpecificationTests.Strict_mode_throws_for_an_EF_without_a_stream`, `Broadside.Tests.Files.FileSpecificationTests.Reading_a_file_specification_leaves_every_object_clean` | Every Table 43 key; UF > F > Unix > Mac > DOS for names and EF; EP exposed raw (unwrapping encrypted payloads, 7.6.7, not done) | +| 7.11.4 | Embedded file streams | done | `PdfEmbeddedFile`, `PdfEmbeddedFileParameters`, `PdfRelatedFile`, `PdfCheckSumStatus`, `PdfEmbeddedFileEntry` | `Broadside.Tests.Files.EmbeddedFileTests.The_EmbeddedFiles_name_tree_lists_each_file_with_its_names_parameters_and_data`, `Broadside.Tests.Files.FileSpecificationTests.A_wrong_checksum_is_a_result_not_a_diagnostic`, `Broadside.Tests.Files.FileSpecificationTests.Related_files_pair_names_with_embedded_file_streams`, `Broadside.Tests.Files.FileSpecificationTests.A_malformed_related_files_array_keeps_its_well_formed_pairs_with_a_diagnostic`, `Broadside.Tests.Files.EmbeddedFileTests.An_entry_that_is_not_a_file_specification_is_skipped_with_a_diagnostic` | Tables 44, 45, related files (7.11.4.2); CheckSum verified with the managed MD5; `embedded-files.pdf`. EFF decryption is #42's | +| 7.11.5 | URL specifications | done | `PdfFileSpecification` | `Broadside.Tests.Files.FileSpecificationTests.A_URL_file_specification_is_recognised_by_its_file_system` | `IsUrl` when FS is URL; the URL is exposed, never fetched | +| 7.11.6 | Collection items | done | `PdfCollectionItem`, `PdfCollectionItemValue` | `Broadside.Tests.Files.CollectionTests.Collection_items_give_each_files_values_with_subitem_prefixes` | Tables 46, 47: values and subitem prefixes; date values read as `PdfDate` | | 7.12.1 | General | done | `PdfDeveloperExtension`, `PdfDocument` | `Broadside.Tests.Document.CatalogEntryTests.Catalog_version_extensions_pdf_exposes_its_version_extensions_and_requirements` | `PdfDocument.Extensions`; `catalog-version-extensions.pdf` | | 7.12.2 | Extensions dictionary | done | `PdfDeveloperExtension`, `PdfDocument` | `Broadside.Tests.Document.CatalogEntryTests.Catalog_version_extensions_pdf_exposes_its_version_extensions_and_requirements`, `Broadside.Tests.Document.CatalogEntryTests.A_malformed_extensions_entry_is_reported`, `Broadside.Tests.Document.CatalogEntryTests.Extensions_given_through_indirect_references_are_read_with_a_warning` | Prefix values as a dictionary or (PDF 2.0) an array of them; indirect objects read with `ExtensionsNotDirect` | | 7.12.3 | Developer extensions dictionary | done | `PdfDeveloperExtension` | `Broadside.Tests.Document.CatalogEntryTests.Catalog_version_extensions_pdf_exposes_its_version_extensions_and_requirements`, `Broadside.Tests.Document.CatalogEntryTests.A_malformed_extensions_entry_is_reported` | Missing BaseVersion or ExtensionLevel: `DeveloperExtensionInvalid`, value null | @@ -76,7 +81,10 @@ Clause numbers at the second level; split rows to the third level as clauses are | 8.8 | External objects | not started | | | | | 8.9 | Images | not started | | | | | 8.10 | Form XObjects | not started | | | | -| 8.11 | Optional content | not started | | | | +| 8.11.1 | General | n/a | | | Introductory text | +| 8.11.2 | Optional content groups | done | `PdfOptionalContentGroup`, `PdfOptionalContentMembership`, `PdfVisibilityExpression`, `PdfVisibilityPolicy`, `PdfVisibilityOperator`, `PdfOptionalContentProperties` | `Broadside.Tests.OptionalContent.OptionalContentTests.Groups_are_read_from_OCGs_in_order_with_names_intents_and_usage`, `Broadside.Tests.OptionalContent.OptionalContentTests.Visibility_of_each_section_XObject_and_annotation_follows_the_default_state_and_intent`, `Broadside.Tests.OptionalContent.OptionalContentTests.An_empty_configuration_intent_makes_all_content_visible`, `Broadside.Tests.OptionalContent.OptionalContentRepairTests.An_invalid_visibility_expression_or_policy_is_repaired`, `Broadside.Tests.OptionalContent.OptionalContentRepairTests.A_self_referencing_visibility_expression_terminates`, `Broadside.Tests.OptionalContent.OptionalContentRepairTests.A_membership_lists_its_groups_policy_and_parsed_expression` | 8.11.2.1-8.11.2.3: OCG, OCMD (P, VE compiled to an allocation-free program, depth 32 and cycle guard), Intent with no-effect semantics; fuzz target `optional-content` | +| 8.11.3 | Making graphical content optional | partial | `PdfOptionalContentTracker`, `PdfOptionalContentProperties` | `Broadside.Tests.OptionalContent.OptionalContentTests.A_tracker_hides_content_nested_inside_a_hidden_section`, `Broadside.Tests.OptionalContent.OptionalContentTests.An_unbalanced_EMC_is_ignored_by_the_tracker`, `Broadside.Tests.OptionalContent.OptionalContentRepairTests.An_inline_OC_property_list_is_honoured_with_a_diagnostic`, `Broadside.Tests.OptionalContent.OptionalContentAllocationTests.Visibility_checks_and_section_tracking_allocate_nothing` | Visibility seam for /OC BDC, XObject and annotation OC (8.11.3.2, 8.11.3.3); skipping hidden content while applying graphics state is the content interpreter and display list (#56, Phase 3) | +| 8.11.4 | Configuring optional content | done | `PdfOptionalContentProperties`, `PdfOptionalContentConfiguration`, `PdfOptionalContentState`, `PdfOptionalContentOrderItem`, `PdfOptionalContentUsage`, `PdfOptionalContentUsageApplication`, `PdfOptionalContentUsageContext`, `PdfOptionalContentBaseState`, `PdfOptionalContentListMode`, `PdfOptionalContentEvent` | `Broadside.Tests.OptionalContent.OptionalContentTests.The_default_configuration_is_typed`, `Broadside.Tests.OptionalContent.OptionalContentTests.The_order_tree_keeps_labels_and_unlabelled_nesting_as_written`, `Broadside.Tests.OptionalContent.OptionalContentTests.Alternate_configurations_are_typed_and_inherit_order_and_radio_buttons_from_D`, `Broadside.Tests.OptionalContent.OptionalContentTests.Default_states_follow_BaseState_then_ON_then_OFF_and_ignore_usage_without_AS`, `Broadside.Tests.OptionalContent.OptionalContentTests.An_Unchanged_base_state_keeps_the_current_states`, `Broadside.Tests.OptionalContent.OptionalContentTests.Auto_states_apply_zoom_and_language_recommendations_with_explicit_inputs`, `Broadside.Tests.OptionalContent.OptionalContentTests.A_set_OCG_state_array_turns_groups_on_off_and_toggles_honouring_radio_buttons`, `Broadside.Tests.OptionalContent.OptionalContentRepairTests.A_malformed_configuration_is_repaired_with_a_diagnostic`, `Broadside.Tests.OptionalContent.OptionalContentRepairTests.A_malformed_configuration_throws_in_strict_mode`, `Broadside.Tests.OptionalContent.OptionalContentRepairTests.Missing_OCGs_make_nothing_optional` | 8.11.4.1-8.11.4.5: OCProperties, D and Configs, usage (exposed), AS evaluated only on request with explicit inputs; `ApplyUsageStates` is the pdf.js/PDFBox parity option; `optional-content.pdf` | | 9.1 | Text: General | not started | | | | | 9.2 | Organisation and use of fonts | not started | | | | | 9.3 | Text state parameters and operators | not started | | | | @@ -104,7 +112,12 @@ Clause numbers at the second level; split rows to the third level as clauses are | 11.7 | Colour space and rendering issues | not started | | | | | 12.1 | Interactive features: General | not started | | | | | 12.2 | Viewer preferences | done | `PdfViewerPreferences`, `PdfPageMode`, `PdfReadingDirection`, `PdfPageBoundary`, `PdfPrintScaling`, `PdfDuplex`, `PdfPageRange` | `Broadside.Tests.Document.CatalogEntryTests.Viewer_preferences_pdf_types_every_table_147_entry`, `Broadside.Tests.Document.CatalogEntryTests.An_empty_viewer_preferences_dictionary_reads_every_default`, `Broadside.Tests.Document.CatalogEntryTests.A_malformed_viewer_preference_reads_as_its_default_with_a_warning`, `Broadside.Tests.Document.CatalogEntryTests.Unknown_viewer_preference_keys_are_ignored` | Tables 147 and 148 (Enforce, PDF 2.0); malformed entries read as their defaults with `ViewerPreferenceInvalid`; unknown keys ignored; `viewer-preferences.pdf` | -| 12.3 | Document-level navigation | not started | | | | +| 12.3.1 | General | not started | | | #70 | +| 12.3.2 | Destinations | not started | | | #70 | +| 12.3.3 | Document outline | not started | | | #70 | +| 12.3.4 | Thumbnail images | not started | | | File specification and folder `Thumb` streams are exposed raw | +| 12.3.5 | Collections | done | `PdfCollection`, `PdfCollectionField`, `PdfCollectionFieldType`, `PdfCollectionSort`, `PdfCollectionColors`, `PdfCollectionColor`, `PdfCollectionSplit`, `PdfCollectionSplitDirection`, `PdfCollectionFolder`, `PdfCollectionIdRange`, `PdfCollectionView`, `PdfEmbeddedFileEntry` | `Broadside.Tests.Files.CollectionTests.The_collection_exposes_view_initial_document_and_schema_fields`, `Broadside.Tests.Files.CollectionTests.Sort_pads_its_ascending_flags_with_true`, `Broadside.Tests.Files.CollectionTests.Colors_and_split_are_typed`, `Broadside.Tests.Files.CollectionTests.Folders_form_a_tree_and_files_are_placed_by_their_key_prefix`, `Broadside.Tests.Files.CollectionTests.A_navigator_view_without_a_navigator_reads_as_details_with_a_diagnostic`, `Broadside.Tests.Files.CollectionTests.Split_defaults_follow_the_view`, `Broadside.Tests.Files.CollectionTests.A_folder_cycle_and_a_duplicate_id_are_cut_with_diagnostics`, `Broadside.Tests.Files.EmbeddedFileTests.A_folder_prefix_in_the_key_gives_the_folder_id_and_the_bare_file_name` | 12.3.5.1-12.3.5.2, Tables 153-159: schema, sort, colours, split, folders (Child/Next walk with cycle guard, `` keys); Navigator exposed raw (12.3.6); `collection-portfolio.pdf` | +| 12.3.6 | Navigators | not started | | | A collection's `Navigator` is exposed raw (`PdfCollection.Navigator`); navigators are parse-and-preserve | | 12.4.1 | General | n/a | | | Introductory text | | 12.4.2 | Page labels | done | `PdfPageLabels`, `PdfPageLabelRange`, `PdfPageLabelStyle` | `Broadside.Tests.Document.PageLabelTests.Page_labels_pdf_labels_every_page_in_every_style`, `Broadside.Tests.Document.PageLabelTests.Page_labels_pdf_lists_its_ranges_in_page_order`, `Broadside.Tests.Document.PageLabelTests.Number_tree_deep_pdf_finds_each_page_s_range_through_kids_and_limits`, `Broadside.Tests.Document.PageLabelTests.Letters_repeat_rather_than_carry`, `Broadside.Tests.Document.PageLabelTests.Roman_numerals_follow_the_subtractive_form_and_add_an_m_per_thousand_beyond_3999`, `Broadside.Tests.Document.PageLabelTests.Every_roman_numeral_from_1_to_3999_is_canonical_and_reads_back_as_its_number`, `Broadside.Tests.Document.PageLabelTests.A_malformed_page_label_is_repaired_with_a_warning`, `Broadside.Tests.Document.PageLabelTests.Pages_before_the_first_range_are_numbered_in_decimal_with_a_warning`, `Broadside.Tests.Document.PageLabelTests.A_range_whose_value_is_not_a_dictionary_is_skipped_and_the_previous_range_continues` | Floor lookup through #70's `NumberTreeReader`; no key 0 numbers earlier pages in decimal (PDFBox/Acrobat); unknown style decimal; letters and roman capped at 64 characters (decimal beyond); `page-labels.pdf`, `number-tree-deep.pdf` | | 12.4.3 | Articles | not started | | | | @@ -131,7 +144,7 @@ Clause numbers at the second level; split rows to the third level as clauses are | 14.1 | Document interchange: General | not started | | | | | 14.2 | Procedure sets | not started | | | | | 14.3.1 | General | done | `PdfDocumentProperties`, `PdfDocument` | `Broadside.Tests.Document.DocumentInformationTests.The_properties_take_each_field_from_xmp_when_the_packet_has_it_and_from_info_otherwise`, `Broadside.Tests.Document.DocumentInformationTests.Metadata_xmp_pdf_yields_its_title_from_the_info_dictionary_and_from_xmp` | XMP preferred per field, Info otherwise | -| 14.3.2 | Metadata streams | partial | `PdfMetadata`, `XmpPacket`, `XmpProperty`, `XmpPropertyKind`, `XmpNamespaces`, `XmpDate` | `Broadside.Tests.Document.DocumentInformationTests.Metadata_xmp_pdf_yields_its_title_from_the_info_dictionary_and_from_xmp`, `Broadside.Tests.Document.DocumentInformationTests.Metadata_xmp_forms_pdf_types_the_common_properties_and_the_properties_prefer_xmp`, `Broadside.Tests.Document.DocumentInformationTests.A_malformed_packet_leaves_the_info_dictionary_readable_and_is_reported_once`, `Broadside.Tests.Document.DocumentInformationTests.A_packet_with_a_document_type_declaration_is_refused`, `Broadside.Tests.Document.DocumentInformationTests.A_metadata_stream_without_its_type_and_subtype_is_read_with_a_warning`, `Broadside.Tests.Document.DocumentInformationTests.The_parsed_packet_is_a_snapshot_until_the_stream_changes`, `Broadside.Tests.Document.XmpPacketTests.A_packet_reads_every_property_form_into_one_model`, `Broadside.Tests.Document.XmpPacketTests.A_document_type_declaration_is_refused_so_entities_never_expand`, `Broadside.Tests.Document.XmpPacketTests.A_packet_in_any_unicode_encoding_with_its_byte_order_mark_is_read` | Document-level metadata stream (catalog `Metadata`) with a managed ISO 16684-1 reader on the BCL `XmlReader` (DTD prohibited, no resolver); fuzz target `xmp`; object-level metadata (Table 348) is #76 | +| 14.3.2 | Metadata streams | done | `PdfMetadata`, `XmpPacket`, `XmpProperty`, `XmpPropertyKind`, `XmpNamespaces`, `XmpDate`, `PdfObjectMetadata`, `PdfMetadataLocation` | `Broadside.Tests.Document.DocumentInformationTests.Metadata_xmp_pdf_yields_its_title_from_the_info_dictionary_and_from_xmp`, `Broadside.Tests.Document.DocumentInformationTests.Metadata_xmp_forms_pdf_types_the_common_properties_and_the_properties_prefer_xmp`, `Broadside.Tests.Document.DocumentInformationTests.A_malformed_packet_leaves_the_info_dictionary_readable_and_is_reported_once`, `Broadside.Tests.Document.DocumentInformationTests.A_packet_with_a_document_type_declaration_is_refused`, `Broadside.Tests.Document.DocumentInformationTests.A_metadata_stream_without_its_type_and_subtype_is_read_with_a_warning`, `Broadside.Tests.Document.DocumentInformationTests.The_parsed_packet_is_a_snapshot_until_the_stream_changes`, `Broadside.Tests.Document.XmpPacketTests.A_packet_reads_every_property_form_into_one_model`, `Broadside.Tests.Document.XmpPacketTests.A_document_type_declaration_is_refused_so_entities_never_expand`, `Broadside.Tests.Document.XmpPacketTests.A_packet_in_any_unicode_encoding_with_its_byte_order_mark_is_read`, `Broadside.Tests.Files.ObjectMetadataTests.Enumeration_finds_each_metadata_stream_with_its_location`, `Broadside.Tests.Files.ObjectMetadataTests.Each_metadata_stream_knows_its_owner`, `Broadside.Tests.Files.ObjectMetadataTests.Structure_elements_threads_and_document_parts_carry_metadata_too`, `Broadside.Tests.Files.ObjectMetadataTests.A_deep_scan_finds_metadata_anywhere_else`, `Broadside.Tests.Files.ObjectMetadataTests.A_metadata_stream_without_Type_Metadata_and_Subtype_XML_is_reported` | Document-level metadata stream (catalog `Metadata`) with a managed ISO 16684-1 reader on the BCL `XmlReader` (DTD prohibited, no resolver); fuzz target `xmp`; object-level metadata (Table 348, #76): `EnumerateObjectMetadata(deep)` at every Application Note 003 location, `object-metadata.pdf` | | 14.3.3 | Document information dictionary | done | `PdfDocumentInformation`, `PdfTrapped`, `PdfDocument` | `Broadside.Tests.Document.DocumentInformationTests.Info_dictionary_pdf_types_every_table_349_entry`, `Broadside.Tests.Document.DocumentInformationTests.Hybrid_xref_pdf_reads_its_info_dictionary_from_an_object_stream`, `Broadside.Tests.Document.DocumentInformationTests.Info_values_that_are_not_text_strings_are_read_with_a_warning`, `Broadside.Tests.Document.DocumentInformationTests.Trapped_is_a_name_that_defaults_to_unknown`, `Broadside.Tests.Document.DocumentInformationTests.An_info_entry_that_is_not_a_dictionary_is_ignored_with_a_warning` | Every Table 349 key typed, custom keys through `GetText`/`GetDate`; `info-dictionary.pdf`; writing Info is Phase 4 | | 14.3.4 | Reconciling two sources of document metadata | partial | `PdfDocumentProperties` | `Broadside.Tests.Document.DocumentInformationTests.The_properties_take_each_field_from_xmp_when_the_packet_has_it_and_from_info_otherwise` | Reader side (processor discretion: XMP first, no diagnostic for disagreement); the writer rules are Phase 4 | | 14.4 | File identifiers | partial | `FileWriter`, `PdfFileIdentifier`, `PdfDocument` | `Broadside.Tests.Writing.SaveTests.Saving_twice_writes_the_same_bytes_and_keeps_the_first_file_identifier`, `Broadside.Tests.Writing.SaveTests.A_file_without_identifiers_gets_two_equal_ones_when_saved`, `Broadside.Tests.Writing.CreateTests.A_saved_created_document_reopens_with_two_equal_file_identifiers`, `Broadside.Tests.Document.DocumentInformationTests.Catalog_version_extensions_pdf_has_two_different_file_identifiers`, `Broadside.Tests.Document.DocumentInformationTests.An_encrypted_file_has_its_identifier_unencrypted`, `Broadside.Tests.Document.DocumentInformationTests.A_file_without_an_identifier_has_none`, `Broadside.Tests.Document.DocumentInformationTests.A_malformed_identifier_is_reported` | read: `PdfDocument.FileIdentifier` (IDs under 16 bytes kept with `FileIdentifierInvalid`, Table 15); written on save: the first identifier is kept, the second is the first 16 bytes of SHA-256 of the bytes before the cross-reference information (deterministic; MD5 is unavailable on browser-wasm); a file without identifiers gets two equal ones; incremental updates are Phase 4 | @@ -149,7 +162,16 @@ Clause numbers at the second level; split rows to the third level as clauses are | 14.11.6 | Trapping support | not started | | | | | 14.11.7 | Open prepress interface (OPI) | not started | | | | | 14.12 | Document parts | not started | | | | -| 14.13 | Associated files | not started | | | | +| 14.13.1 | General | done | `PdfAssociatedFile`, `PdfAssociatedFileLocation`, `PdfDocument` | `Broadside.Tests.Files.AssociatedFileTests.Enumeration_finds_each_associated_file_with_its_location`, `Broadside.Tests.Files.AssociatedFileTests.A_deep_scan_also_finds_associated_files_in_unlisted_places`, `Broadside.Tests.Files.AssociatedFileTests.Each_associated_file_knows_its_owner_and_page` | `EnumerateAssociatedFiles(deep)` over every location incl. metadata streams; `ReadAssociatedFiles(owner)` for any object; `associated-files.pdf` | +| 14.13.2 | Embedded associated files | done | `PdfDocument`, `PdfEmbeddedFile` | `Broadside.Tests.Files.AssociatedFileTests.A_malformed_AF_entry_is_repaired_with_a_diagnostic`, `Broadside.Tests.Files.AssociatedFileTests.Strict_mode_throws_for_an_AF_entry_that_is_not_an_array` | Subtype required (`EmbeddedFileSubtypeMissing`), ModDate when Params present (`EmbeddedFileParamsInvalid`); single dictionary and string entries repaired (`AssociatedFilesInvalid`) | +| 14.13.3 | Associated files linked to the PDF document's catalog | done | `PdfDocument` | `Broadside.Tests.Files.AssociatedFileTests.Catalog_and_page_accessors_read_AF_directly` | `PdfDocument.AssociatedFiles` | +| 14.13.4 | Associated files linked to a page dictionary | done | `PdfPage` | `Broadside.Tests.Files.AssociatedFileTests.Catalog_and_page_accessors_read_AF_directly` | `PdfPage.AssociatedFiles` | +| 14.13.5 | Associated files linked to graphics objects | done | `PdfDocument` | `Broadside.Tests.Files.AssociatedFileTests.A_marked_content_property_list_gives_its_files_from_MCAF_or_a_bare_array` | Errata Table 409a `MCAF` and the bare-array resource of the 2020 text; `ReadMarkedContentAssociatedFiles` for the interpreter (#56) | +| 14.13.6 | Associated files linked to structure elements | done | `PdfAssociatedFile` | `Broadside.Tests.Files.AssociatedFileTests.Enumeration_finds_each_associated_file_with_its_location` | Structure tree root and elements found by a K walk; typed elements are #75 | +| 14.13.7 | Associated files linked to XObjects | done | `PdfAssociatedFile` | `Broadside.Tests.Files.AssociatedFileTests.Enumeration_finds_each_associated_file_with_its_location` | Form and image XObjects, recursively through resources and annotation appearances | +| 14.13.8 | Associated files linked to DParts | done | `PdfAssociatedFile` | `Broadside.Tests.Files.AssociatedFileTests.Enumeration_finds_each_associated_file_with_its_location` | DPartRoot walk | +| 14.13.9 | Associated files linked to an annotation dictionary | done | `PdfAssociatedFile` | `Broadside.Tests.Files.AssociatedFileTests.Enumeration_finds_each_associated_file_with_its_location` | Typed annotations are #71 | +| 14.13.10 | Associated file examples | n/a | | | Examples only | | Annex A | Operator summary | not started | | | | | Annex B | Operators in Type 4 functions | not started | | | | | Annex C | Advice on maximising portability | not started | | | | diff --git a/docs/conformance/pdf-declarations.md b/docs/conformance/pdf-declarations.md index 830952c8..e19ad873 100644 --- a/docs/conformance/pdf-declarations.md +++ b/docs/conformance/pdf-declarations.md @@ -4,8 +4,8 @@ Clause titles verified against the document's table of contents. Split rows to d | Clause | Title | Status | Implementing types | Tests | Notes | |---|---|---|---|---|---| -| 5 | Relationship with PDF specifications and features | not started | | | | -| 6 | Established PDF Declarations | not started | | | | -| 7 | PDF Declaration syntax (namespace, example) | not started | | | | -| 8 | PDF Declaration requirements (schema, property value types) | not started | | | | -| 9 | PDF Declarations in a PDF/A context | not started | | | | +| 5 | Relationship with PDF specifications and features | n/a | | | Informative | +| 6 | Established PDF Declarations | n/a | | | Any URI is exposed; the pdfa.org list is not built in | +| 7 | PDF Declaration syntax (namespace, example) | done | `PdfDeclaration`, `PdfDocument`, `PdfObjectMetadata` | `Broadside.Tests.Files.DeclarationTests.Document_declarations_come_from_the_catalog_XMP_with_trimmed_URIs_and_claims`, `Broadside.Tests.Files.DeclarationTests.An_object_level_declaration_is_read_from_the_objects_metadata`, `Broadside.Tests.Files.DeclarationTests.A_document_without_declarations_has_none` | Document- and object-level scope; http and https namespaces; `declarations.pdf` | +| 8 | PDF Declaration requirements (schema, property value types) | done | `PdfDeclaration`, `PdfDeclarationClaim` | `Broadside.Tests.Files.DeclarationTests.Document_declarations_come_from_the_catalog_XMP_with_trimmed_URIs_and_claims` | Tables 1-3; parseType Resource and nested rdf:Description structures | +| 9 | PDF Declarations in a PDF/A context | n/a | | | Extension schema not validated (PDF/A input validation is out of scope) | diff --git a/docs/conformance/pdf20-an002.md b/docs/conformance/pdf20-an002.md index 66ad9723..45e30109 100644 --- a/docs/conformance/pdf20-an002.md +++ b/docs/conformance/pdf20-an002.md @@ -4,8 +4,8 @@ Clause titles verified against the document's table of contents. Split rows to d | Clause | Title | Status | Implementing types | Tests | Notes | |---|---|---|---|---|---| -| 2 | What are Associated Files | not started | | | | -| 3.1 | Requirements: general | not started | | | | -| 3.2 | PDF/A-3 restrictions | not started | | | | -| 4.1 | AF entry in the catalog | not started | | | | -| 4.2 | AF entry not in the catalog | not started | | | | +| 2 | What are Associated Files | done | `PdfAssociatedFile`, `PdfFileSpecification`, `PdfFileRelationship` | `Broadside.Tests.Files.AssociatedFileTests.Enumeration_finds_each_associated_file_with_its_location` | AFRelationship values typed, second-class names as Other | +| 3.1 | Requirements: general | done | `PdfDocument`, `PdfEmbeddedFile` | `Broadside.Tests.Files.AssociatedFileTests.A_malformed_AF_entry_is_repaired_with_a_diagnostic` | Subtype and Params ModDate checked for embedded AF; missing AFRelationship reads as Unspecified without a diagnostic (ISO 32000-2 says should) | +| 3.2 | PDF/A-3 restrictions | n/a | | | PDF/A input validation is out of scope (spec Out of Scope); AF anywhere is found by `EnumerateAssociatedFiles(deep: true)` | +| 4.1 | AF entry in the catalog | done | `PdfDocument` | `Broadside.Tests.Files.AssociatedFileTests.Catalog_and_page_accessors_read_AF_directly` | | +| 4.2 | AF entry not in the catalog | done | `PdfAssociatedFile`, `PdfAssociatedFileLocation` | `Broadside.Tests.Files.AssociatedFileTests.Enumeration_finds_each_associated_file_with_its_location`, `Broadside.Tests.Files.AssociatedFileTests.A_deep_scan_also_finds_associated_files_in_unlisted_places` | Every location, plus a deep scan; files reachable only through AF or FileAttachment annotations are found (§6.2) | diff --git a/docs/conformance/pdf20-an003.md b/docs/conformance/pdf20-an003.md index cc8fc10e..f01687f7 100644 --- a/docs/conformance/pdf20-an003.md +++ b/docs/conformance/pdf20-an003.md @@ -4,6 +4,6 @@ Clause titles verified against the document's table of contents. Split rows to d | Clause | Title | Status | Implementing types | Tests | Notes | |---|---|---|---|---|---| -| Explicit | Explicit metadata locations: document, image XObjects, document parts | not started | | | | -| Implicit | Implicit metadata locations: embedded fonts, tiling and shading patterns, marked content, structure elements | not started | | | | -| Other | Other uses: embedded files, Type 3 fonts, annotations, optional content, rich media, 3D artwork | not started | | | | +| Explicit | Explicit metadata locations: document, image XObjects, document parts | done | `PdfObjectMetadata`, `PdfMetadataLocation` | `Broadside.Tests.Files.ObjectMetadataTests.Enumeration_finds_each_metadata_stream_with_its_location`, `Broadside.Tests.Files.ObjectMetadataTests.Structure_elements_threads_and_document_parts_carry_metadata_too` | Also pages, form XObjects, ICC profiles and threads | +| Implicit | Implicit metadata locations: embedded fonts, tiling and shading patterns, marked content, structure elements | done | `PdfObjectMetadata`, `PdfMetadataLocation` | `Broadside.Tests.Files.ObjectMetadataTests.Enumeration_finds_each_metadata_stream_with_its_location`, `Broadside.Tests.Files.ObjectMetadataTests.Structure_elements_threads_and_document_parts_carry_metadata_too` | Font program streams (not font dictionaries), shading dictionaries (not shading patterns) | +| Other | Other uses: embedded files, Type 3 fonts, annotations, optional content, rich media, 3D artwork | partial | `PdfObjectMetadata`, `PdfMetadataLocation` | `Broadside.Tests.Files.ObjectMetadataTests.Enumeration_finds_each_metadata_stream_with_its_location`, `Broadside.Tests.Files.ObjectMetadataTests.A_deep_scan_finds_metadata_anywhere_else` | Embedded files, Type 3 fonts, annotations, OCGs, 3D streams; RichMedia assets only through the deep scan (rich media is parse-and-preserve) | diff --git a/tests/Broadside.Tests/OptionalContent/OptionalContentTests.cs b/tests/Broadside.Tests/OptionalContent/OptionalContentTests.cs index a3975569..85dc7a6b 100644 --- a/tests/Broadside.Tests/OptionalContent/OptionalContentTests.cs +++ b/tests/Broadside.Tests/OptionalContent/OptionalContentTests.cs @@ -249,6 +249,29 @@ public void Usage_states_can_be_applied_for_engine_parity_without_an_AS_entry() Assert.Equal([true, false, true, false], properties.Groups.Select(state.IsOn)); } + [Theory] + [InlineData(1.5, "en-US", true, true, false, false)] + [InlineData(3.0, "en-GB", false, false, true, false)] + [InlineData(1.0, "fr", true, false, false, true)] + public void Auto_states_apply_zoom_and_language_recommendations_with_explicit_inputs(double zoom, string language, bool a, bool b, bool c, bool d) + { + byte[] file = OptionalContentPdf.Build( + "/OCGs [4 0 R 5 0 R 6 0 R 7 0 R] /D << /AS [<< /Event /View /Category [/Zoom /Language] /OCGs [4 0 R 5 0 R 6 0 R 7 0 R] >> << /Event /Print /Category [/Print] /OCGs [4 0 R] >>] >>", + "<< /Type /OCG /Name (A) /Usage << /Zoom << /min 1 /max 2 >> /Print << /PrintState /OFF >> >> >>", + "<< /Type /OCG /Name (B) /Usage << /Language << /Lang (en-US) >> >> >>", + "<< /Type /OCG /Name (C) /Usage << /Language << /Lang (en) /Preferred /ON >> >> >>", + "<< /Type /OCG /Name (D) /Usage << /Language << /Lang (fr) >> >> >>"); + using PdfDocument document = PdfDocument.Open(file); + PdfOptionalContentProperties properties = document.OptionalContent!; + + PdfOptionalContentState state = properties.ApplyAutoStates( + properties.GetDefaultStates(), PdfOptionalContentEvent.View, new PdfOptionalContentUsageContext { Zoom = zoom, Language = language }); + + Assert.Equal([a, b, c, d], properties.Groups.Select(state.IsOn)); + Assert.False(properties.ApplyAutoStates(state, PdfOptionalContentEvent.Print, new PdfOptionalContentUsageContext()).IsOn(properties.Groups[0])); + Assert.Empty(document.Diagnostics); + } + [Fact] public void A_document_without_OCProperties_has_no_optional_content() { From cee86124796c01768124c5978976b0d68464b54e Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:48:35 -0500 Subject: [PATCH 037/152] docs(fuzz): describe the optional-content target (#76) Co-Authored-By: Claude Opus 5.5 --- tests/Broadside.Fuzz/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index 214b3090..ac8964b0 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters; a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. `xmp` reads the input as an XMP packet (ISO 16684-1) through the reader the document uses, and again from its first ` Date: Fri, 9 Oct 2026 16:58:14 -0500 Subject: [PATCH 038/152] test(structure): associated-files.pdf has a one-element structure tree (#76) Co-Authored-By: Claude Opus 5.5 --- tests/Broadside.Tests/LogicalStructure/StructureCorpusTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Broadside.Tests/LogicalStructure/StructureCorpusTests.cs b/tests/Broadside.Tests/LogicalStructure/StructureCorpusTests.cs index 3fc8fdcc..96253a98 100644 --- a/tests/Broadside.Tests/LogicalStructure/StructureCorpusTests.cs +++ b/tests/Broadside.Tests/LogicalStructure/StructureCorpusTests.cs @@ -36,7 +36,7 @@ public void A_well_formed_file_reads_its_structure_tree_with_no_diagnostics(stri int elements = StructureWalker.Walk(document); - Assert.Equal(fileName == "tagged-structure.pdf" ? 18 : -1, elements); + Assert.Equal(fileName switch { "tagged-structure.pdf" => 18, "associated-files.pdf" => 1, _ => -1 }, elements); Assert.Empty(document.Diagnostics); } From ead075c7f306bc5ee86712d091d8705bffba397d Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:07:55 -0500 Subject: [PATCH 039/152] test: measure allocations in steady state, one at a time (#48) The allocation-assertion tests measured one call after a fixed warm-up with GC.GetAllocatedBytesForCurrentThread and ran in parallel with the rest of the suite. Under load (FilterAllocationTests failed once at a load average of ~260) the counter also sees work unrelated to the hot path: unoptimized code still running because the background tier-1 compiler is starved (tier 0 does not stack-allocate non-escaping objects), ArrayPool.Shared arrays trimmed by a gen-2 collection another test caused, first-use runtime work. - Broadside.TestSupport.Allocations.Measure: warm up, then the fewest bytes over up to ten measured calls with a 20 ms pause between them, stopping at zero. A real per-item allocation shows on every call. - Every allocation test (lexer, filters, predictor, decryption, object cache) uses it and runs in the non-parallel Heavy collection. - adding-a-benchmark skill documents the helper. - RealWorldCorpusTests snapshot: one pdfium-tests file (FRC_3.5_P_4_Password_1.pdf, an xref stream shorter than one predictor row) now reports PredictorInvalid (72 -> 73 files). Five full runs of Broadside.Tests at load averages up to 467 passed. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/adding-a-benchmark/SKILL.md | 24 ++++---- tests/Broadside.TestSupport/Allocations.cs | 60 +++++++++++++++++++ .../Document/HeavyTestCollection.cs | 6 +- .../Document/LazyLoadingTests.cs | 11 +--- ...histograms_match_the_snapshot.verified.txt | 2 +- .../Filters/FilterAllocationTests.cs | 53 ++++++++-------- .../Broadside.Tests/Filters/PredictorTests.cs | 22 ------- .../Objects/LexerAllocationTests.cs | 8 +-- .../Security/DecryptionAllocationTests.cs | 15 +---- 9 files changed, 116 insertions(+), 85 deletions(-) create mode 100644 tests/Broadside.TestSupport/Allocations.cs diff --git a/.claude/skills/adding-a-benchmark/SKILL.md b/.claude/skills/adding-a-benchmark/SKILL.md index 609fe7bc..d4115c45 100644 --- a/.claude/skills/adding-a-benchmark/SKILL.md +++ b/.claude/skills/adding-a-benchmark/SKILL.md @@ -33,21 +33,25 @@ description: "Use when a PR touches a hot path (lexer, content interpreter, rast Two layers: 1. The benchmark. With `[MemoryDiagnoser]` the `Allocated` column must read `-` (0 B) for a hot path. Any number there is a regression, whatever the baseline says. Read it from the console table or from `BenchmarkDotNet.Artifacts/results/-report-github.md`. -2. A unit test next to the feature that fails the build on regressions, because BenchmarkDotNet only reports. After one warm-up call: +2. A unit test next to the feature that fails the build on regressions, because BenchmarkDotNet only reports. Measure through `Broadside.TestSupport.Allocations.Measure` and put the class in the non-parallel `Heavy` collection: ```csharp - [Fact] - public void Tokenizing_allocates_nothing() + [Collection(HeavyTestCollection.Name)] + public class TokenizerAllocationTests { - byte[] bytes = Corpus.Bytes("text-standard14.pdf"); - RunHotPath(bytes); // warm up: JIT, static init - long before = GC.GetAllocatedBytesForCurrentThread(); - RunHotPath(bytes); - Assert.Equal(0, GC.GetAllocatedBytesForCurrentThread() - before); + [Fact] + public void Tokenizing_allocates_nothing() + { + byte[] bytes = Corpus.Bytes("text-standard14.pdf"); + + long allocated = Allocations.Measure(() => RunHotPath(bytes)); // warm-up, then the cheapest of several calls + + Assert.Equal(0, allocated); + } } ``` - Put only the per-item work inside `RunHotPath`; one-time buffers (`ArrayPool` rentals, the output list) are allowed per call, so size the input to make per-token allocations visible. + Never measure one call after a fixed warm-up: under load that is flaky (issue #48), because the per-thread counter also sees unoptimized code still running while the background compiler is starved (tier 0 does not stack-allocate non-escaping objects), `ArrayPool.Shared` arrays trimmed by another test's gen-2 collection, and first-use runtime work. `Measure` warms up, then takes the fewest bytes over several calls with a short pause between them, stopping at zero; a real per-item allocation shows on every call. The `Heavy` collection keeps parallel tests' collections and compilation away from the measurement. Put only the per-item work inside the delegate and create the delegate before the call; one-time buffers (`ArrayPool` rentals, the output list) are allowed per call, so size the input to make per-token allocations visible. ## Running @@ -85,5 +89,5 @@ Track 3I (`docs/plan/README.md`) adds a CI job that runs the suite and compares - [ ] Class in `bench/Broadside.Benchmarks/`, `[MemoryDiagnoser]`, no job attributes - [ ] Inputs loaded in `[GlobalSetup]`; body is only the hot path; result returned - [ ] `--job dry` exits 0; `--job short` numbers quoted in the PR -- [ ] `Allocated` reads `-` on hot paths; `GC.GetAllocatedBytesForCurrentThread` test added next to the feature +- [ ] `Allocated` reads `-` on hot paths; an `Allocations.Measure` test in the `Heavy` collection added next to the feature - [ ] Names stable; any rename called out in the PR body diff --git a/tests/Broadside.TestSupport/Allocations.cs b/tests/Broadside.TestSupport/Allocations.cs new file mode 100644 index 00000000..0a5d93c2 --- /dev/null +++ b/tests/Broadside.TestSupport/Allocations.cs @@ -0,0 +1,60 @@ +namespace Broadside.TestSupport; + +/// +/// Measures what a hot path allocates in steady state, for the build-breaking allocation tests (CLAUDE.md, "Code conventions": +/// hot paths allocate nothing per token, operator, glyph or scanline). Every allocation test goes through +/// and runs in the non-parallel Heavy collection of its test project. +/// +/// +/// One measured call after a fixed warm-up is flaky under load (issue #48 saw it at a load average of 260), because +/// also counts what the runtime allocates on the thread for reasons that have +/// nothing to do with the code under test: (1) tiered compilation installs optimized code from a background thread after a delay, +/// and on a busy machine the measured call can still run unoptimized code, which does not stack-allocate the objects the optimizing +/// JIT proves do not escape; (2) a gen-2 collection caused by any other test trims ArrayPool<T>.Shared, emptying the +/// thread's cached arrays under memory pressure, so the next rent allocates a fresh array; (3) first-use runtime work (type loads, +/// static constructors) lands on whichever call comes first. None of these repeats on every call, while an allocation per token +/// or per row does. So the warm-up is followed by several measured calls, a short pause between them for the background compiler, +/// and the fewest bytes any of them allocated is the answer; it stops early at zero. +/// +public static class Allocations +{ + /// Calls before measuring: past tiered compilation's call-count threshold (30), so the methods are queued for tier 1. + public const int WarmUpCalls = 40; + + /// The most measured calls. + public const int Attempts = 10; + + private static readonly TimeSpan Pause = TimeSpan.FromMilliseconds(20); + + /// Returns the fewest bytes one call of allocated on this thread, after a warm-up. + /// The work to measure. Create the delegate (and anything it captures) before calling, not inside it. + /// Calls before measuring. + /// The bytes the cheapest measured call allocated. + public static long Measure(Action action, int warmUpCalls = WarmUpCalls) + { + ArgumentNullException.ThrowIfNull(action); + for (int call = 0; call < warmUpCalls; call++) + { + action(); + } + + long fewest = long.MaxValue; + for (int attempt = 0; attempt < Attempts; attempt++) + { + if (attempt > 0) + { + Thread.Sleep(Pause); + } + + long before = GC.GetAllocatedBytesForCurrentThread(); + action(); + fewest = Math.Min(fewest, GC.GetAllocatedBytesForCurrentThread() - before); + if (fewest == 0) + { + break; + } + } + + return fewest; + } +} diff --git a/tests/Broadside.Tests/Document/HeavyTestCollection.cs b/tests/Broadside.Tests/Document/HeavyTestCollection.cs index a9629534..b44f774f 100644 --- a/tests/Broadside.Tests/Document/HeavyTestCollection.cs +++ b/tests/Broadside.Tests/Document/HeavyTestCollection.cs @@ -1,8 +1,10 @@ namespace Broadside.Tests.Document; /// -/// Tests that saturate the machine (the multi-threaded stress theory, the 2 GiB file) run on their own, after the parallel tests, so -/// they neither slow nor disturb the allocation tests, which count the bytes their own thread allocates. +/// Tests that run on their own, one at a time, after the parallel tests: those that saturate the machine (the multi-threaded +/// stress theories, the 2 GiB file) and the allocation tests, which count the bytes their own thread allocates through +/// and are disturbed by the collections and compilation that parallel tests +/// cause (issue #48). /// [CollectionDefinition(Name, DisableParallelization = true)] public sealed class HeavyTestCollection diff --git a/tests/Broadside.Tests/Document/LazyLoadingTests.cs b/tests/Broadside.Tests/Document/LazyLoadingTests.cs index 75310d05..856f5a2f 100644 --- a/tests/Broadside.Tests/Document/LazyLoadingTests.cs +++ b/tests/Broadside.Tests/Document/LazyLoadingTests.cs @@ -11,6 +11,7 @@ namespace Broadside.Tests.Document; /// ISO 32000-2 §7.5.1 and §7.5.4: the cross-reference table "permits random access to indirect objects ... so that the entire PDF /// file need not be read". The parse count is observed through the engine's trace log (event 2, ObjectParsed). /// +[Collection(HeavyTestCollection.Name)] public class LazyLoadingTests { private const int PageCount = 40; @@ -74,15 +75,7 @@ public void Resolving_an_object_already_loaded_allocates_nothing() using PdfDocument document = PdfDocument.Open(ManyPages()); CosReference[] references = [.. Enumerable.Range(1, 2 + (3 * PageCount)).Select(number => new CosReference(number, 0))]; - // Warm up past tiered compilation, which allocates on its own. - for (int round = 0; round < 50; round++) - { - ResolveAll(document, references); - } - - long before = GC.GetAllocatedBytesForCurrentThread(); - ResolveAll(document, references); - Assert.Equal(0, GC.GetAllocatedBytesForCurrentThread() - before); + Assert.Equal(0, Allocations.Measure(() => ResolveAll(document, references))); static void ResolveAll(PdfDocument document, CosReference[] references) { diff --git a/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt b/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt index e91fe552..20332032 100644 --- a/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt +++ b/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt @@ -178,7 +178,7 @@ pdfium-tests: 840 files StartxrefInvalid: 99 StreamLengthInvalid: 92 XrefSectionInvalid: 84 - PredictorInvalid: 72 + PredictorInvalid: 73 HeaderInvalid: 29 FilterDataInvalid: 28 DecodeParmsInvalid: 24 diff --git a/tests/Broadside.Tests/Filters/FilterAllocationTests.cs b/tests/Broadside.Tests/Filters/FilterAllocationTests.cs index ba4fec35..b5b22612 100644 --- a/tests/Broadside.Tests/Filters/FilterAllocationTests.cs +++ b/tests/Broadside.Tests/Filters/FilterAllocationTests.cs @@ -2,6 +2,7 @@ using System.Text; using Broadside.Filters; using Broadside.Objects; +using Broadside.Tests.Document; using Broadside.TestSupport; namespace Broadside.Tests.Filters; @@ -10,6 +11,7 @@ namespace Broadside.Tests.Filters; /// Filters are a hot path and allocate nothing per byte, code or row (CLAUDE.md, "Code conventions"). This is the build-breaking /// half of that rule; the *Benchmarks classes in bench/Broadside.Benchmarks are the measuring half. ISO 32000-2 §7.4. /// +[Collection(HeavyTestCollection.Name)] public class FilterAllocationTests { public static TheoryData AllocationFreeFilters => new() { "ASCIIHexDecode", "ASCII85Decode", "LZWDecode", "RunLengthDecode" }; @@ -22,13 +24,7 @@ public void Decoding_through_the_contract_allocates_nothing(string name) var context = new FilterContext(); var output = new ArrayBufferWriter(400_000); - // Past tiered compilation's call-count threshold first, so the runtime's own bookkeeping is not counted. - for (int warmUp = 0; warmUp < 40; warmUp++) - { - Decode(filter, encoded, output, context); - } - - long allocated = Decode(filter, encoded, output, context); + long allocated = Allocations.Measure(() => Decode(filter, encoded, output, context)); Assert.True(output.WrittenCount >= 200_000); Assert.Equal(0, allocated); @@ -42,14 +38,9 @@ public void Flate_allocates_the_inflater_once_per_call_and_nothing_per_byte() var output = new ArrayBufferWriter(1_000_000); byte[] small = FilterEncoders.Zlib(FilterEncoders.SampleData(1_000)); byte[] large = FilterEncoders.Zlib(FilterEncoders.SampleData(900_000)); - for (int warmUp = 0; warmUp < 40; warmUp++) - { - Decode(filter, small, output, context); - Decode(filter, large, output, context); - } - long forSmall = Decode(filter, small, output, context); - long forLarge = Decode(filter, large, output, context); + long forSmall = Allocations.Measure(() => Decode(filter, small, output, context)); + long forLarge = Allocations.Measure(() => Decode(filter, large, output, context)); Assert.InRange(forLarge, 0, forSmall + 64); } @@ -63,6 +54,25 @@ public void Decoding_a_predicted_stream_through_a_document_allocates_per_stream_ Assert.InRange(forLarge, 0, forSmall + 64); } + // Found by libFuzzer (issue #48): Columns sized the row buffers and the zero padding of the last row, so a few bytes of data + // with a huge Columns allocated and wrote rows of up to the decoded-length limit (1 GiB) and ran out of memory. Data that + // cannot hold one whole row is now passed through, so the output is never more than twice the input. + [Theory] + [InlineData(12)] + [InlineData(2)] + public void A_row_longer_than_the_whole_data_allocates_nothing_in_proportion_to_the_row(int predictor) + { + byte[] file = FilterTesting.FileWithStream( + $"/Filter /FlateDecode /DecodeParms << /Predictor {predictor} /Colors 4 /BitsPerComponent 16 /Columns 100000000 >>", + FilterEncoders.Zlib([2, 10, 20, 30])); + (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); + long allocated = Allocations.Measure(() => FilterTesting.DecodeWithCodes(file), warmUpCalls: 1); + + Assert.Equal([2, 10, 20, 30], decoded); + Assert.Equal(["PredictorInvalid"], codes); + Assert.True(allocated < 1 << 20, $"Decoding 4 bytes allocated {allocated} bytes."); + } + private static long PredictedStreamAllocation(int rows) { byte[] predicted = new byte[rows * 5]; @@ -76,27 +86,20 @@ private static long PredictedStreamAllocation(int rows) using PdfDocument document = PdfDocument.Open(file); var stream = (CosStream)document.Resolve(FilterTesting.StreamReference); var output = new ArrayBufferWriter(rows * 4); - for (int warmUp = 0; warmUp < 40; warmUp++) + + long allocated = Allocations.Measure(() => { output.ResetWrittenCount(); document.DecodeStream(stream, output); - } - - output.ResetWrittenCount(); - - long before = GC.GetAllocatedBytesForCurrentThread(); - document.DecodeStream(stream, output); - long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + }); Assert.Equal(rows * 4, output.WrittenCount); return allocated; } - private static long Decode(IStreamFilter filter, byte[] encoded, ArrayBufferWriter output, FilterContext context) + private static void Decode(IStreamFilter filter, byte[] encoded, ArrayBufferWriter output, FilterContext context) { output.ResetWrittenCount(); - long before = GC.GetAllocatedBytesForCurrentThread(); filter.Decode(encoded, output, context); - return GC.GetAllocatedBytesForCurrentThread() - before; } private static (IStreamFilter Filter, byte[] Encoded) Encoded(string name, byte[] data) => name switch diff --git a/tests/Broadside.Tests/Filters/PredictorTests.cs b/tests/Broadside.Tests/Filters/PredictorTests.cs index 990c34ab..ab2beb7a 100644 --- a/tests/Broadside.Tests/Filters/PredictorTests.cs +++ b/tests/Broadside.Tests/Filters/PredictorTests.cs @@ -104,28 +104,6 @@ public void Predictors_apply_after_lzw_too() { "/Predictor 2 /Colors 4 /Columns 2", [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], "PredictorInvalid" }, }; - // Found by libFuzzer (issue #48): Columns sized the row buffers and the zero padding of the last row, so a few bytes of data - // with a huge Columns allocated and wrote rows of up to the decoded-length limit (1 GiB) and ran out of memory. Data that - // cannot hold one whole row is now passed through, so the output is never more than twice the input. - [Theory] - [InlineData(12)] - [InlineData(2)] - public void A_row_longer_than_the_whole_data_allocates_nothing_in_proportion_to_the_row(int predictor) - { - byte[] file = FilterTesting.FileWithStream( - $"/Filter /FlateDecode /DecodeParms << /Predictor {predictor} /Colors 4 /BitsPerComponent 16 /Columns 100000000 >>", - FilterEncoders.Zlib([2, 10, 20, 30])); - _ = FilterTesting.DecodeWithCodes(file); - - long before = GC.GetAllocatedBytesForCurrentThread(); - (byte[] decoded, string[] codes) = FilterTesting.DecodeWithCodes(file); - long allocated = GC.GetAllocatedBytesForCurrentThread() - before; - - Assert.Equal([2, 10, 20, 30], decoded); - Assert.Equal(["PredictorInvalid"], codes); - Assert.True(allocated < 1 << 20, $"Decoding 4 bytes allocated {allocated} bytes."); - } - [Theory] [MemberData(nameof(MalformedPredictions))] public void Malformed_predictor_data_or_parameters_are_repaired_with_a_diagnostic(string parameters, byte[] predicted, byte[] expected, string code) diff --git a/tests/Broadside.Tests/Objects/LexerAllocationTests.cs b/tests/Broadside.Tests/Objects/LexerAllocationTests.cs index 7c745ea7..aeb09c67 100644 --- a/tests/Broadside.Tests/Objects/LexerAllocationTests.cs +++ b/tests/Broadside.Tests/Objects/LexerAllocationTests.cs @@ -1,4 +1,5 @@ using Broadside.Objects; +using Broadside.Tests.Document; using Broadside.TestSupport; namespace Broadside.Tests.Objects; @@ -8,17 +9,16 @@ namespace Broadside.Tests.Objects; /// that rule; LexerBenchmarks in bench/Broadside.Benchmarks is the measuring half. It drives the internal lexer /// because no public seam exposes tokens. /// +[Collection(HeavyTestCollection.Name)] public class LexerAllocationTests { [Fact] public void Tokenizing_the_whole_corpus_allocates_nothing() { byte[] bytes = [.. Corpus.AllFileNames.SelectMany(Corpus.Bytes)]; - Tokenize(bytes); + int tokens = 0; - long before = GC.GetAllocatedBytesForCurrentThread(); - int tokens = Tokenize(bytes); - long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + long allocated = Allocations.Measure(() => tokens = Tokenize(bytes), warmUpCalls: 1); Assert.True(tokens > 1_000, $"Only {tokens} tokens; the input is too small to show per-token allocations."); Assert.Equal(0, allocated); diff --git a/tests/Broadside.Tests/Security/DecryptionAllocationTests.cs b/tests/Broadside.Tests/Security/DecryptionAllocationTests.cs index 9387b87d..0cd67338 100644 --- a/tests/Broadside.Tests/Security/DecryptionAllocationTests.cs +++ b/tests/Broadside.Tests/Security/DecryptionAllocationTests.cs @@ -1,4 +1,5 @@ using Broadside.Security.Cryptography; +using Broadside.Tests.Document; using Broadside.TestSupport; namespace Broadside.Tests.Security; @@ -7,7 +8,7 @@ namespace Broadside.Tests.Security; /// The decryption hot paths allocate nothing per call into a caller's buffer (CLAUDE.md, hot paths; the benchmarks are /// SecurityBenchmarks). ISO 32000-2 §7.6.3. /// -[Collection("Heavy")] +[Collection(HeavyTestCollection.Name)] public class DecryptionAllocationTests { private static readonly byte[] Key = [.. Enumerable.Range(0, 32).Select(i => (byte)i)]; @@ -42,15 +43,5 @@ public void Aes_cbc_into_a_buffer_allocates_nothing_per_block() } } - private static long Measure(Action action) - { - for (int i = 0; i < 40; i++) - { - action(); // past tiered compilation - } - - long before = GC.GetAllocatedBytesForCurrentThread(); - action(); - return GC.GetAllocatedBytesForCurrentThread() - before; - } + private static long Measure(Action action) => Allocations.Measure(action); } From c6ca5dd5334ed60e325a515197d048f8eda3784b Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:11:50 -0500 Subject: [PATCH 040/152] test(actions): actions-all and actions-preserved corpus files and the action base (#73) Co-Authored-By: Claude Opus 5.5 --- src/Broadside/Objects/ActionNames.cs | 119 ++++++++ .../Parsing/DiagnosticCodes.Actions.cs | 18 ++ src/Broadside/PdfAction.cs | 276 +++++++++++++++++- src/Broadside/PdfActionKind.cs | 89 ++++++ tests/Broadside.TestSupport/Corpus.cs | 2 + .../Actions/ActionTypeTests.cs | 56 ++++ tests/Corpus/README.md | 2 + tests/Corpus/actions-all.pdf | Bin 0 -> 8448 bytes tests/Corpus/actions-preserved.pdf | Bin 0 -> 3528 bytes tests/Corpus/generate.py | 146 +++++++++ 10 files changed, 702 insertions(+), 6 deletions(-) create mode 100644 src/Broadside/Objects/ActionNames.cs create mode 100644 src/Broadside/Parsing/DiagnosticCodes.Actions.cs create mode 100644 src/Broadside/PdfActionKind.cs create mode 100644 tests/Broadside.Tests/Actions/ActionTypeTests.cs create mode 100644 tests/Corpus/actions-all.pdf create mode 100644 tests/Corpus/actions-preserved.pdf diff --git a/src/Broadside/Objects/ActionNames.cs b/src/Broadside/Objects/ActionNames.cs new file mode 100644 index 00000000..f3f60c46 --- /dev/null +++ b/src/Broadside/Objects/ActionNames.cs @@ -0,0 +1,119 @@ +namespace Broadside.Objects; + +/// Names looked up by actions and additional-actions dictionaries (issue #73); kept apart from and so parallel tickets do not collide. +internal static class ActionNames +{ + /// /AA, an additional-actions dictionary (§12.6.3). + public static readonly CosName AA = new("AA"); + + /// /OpenAction, the catalog's open action or destination (§7.7.2, Table 29). + public static readonly CosName OpenAction = new("OpenAction"); + + /// /Base, the base URI of the catalog's URI dictionary (§12.6.4.8, Table 211). + public static readonly CosName Base = new("Base"); + + /// /JavaScript, the ECMAScript action type (§12.6.4.17) and the name dictionary's tree of document scripts (§7.7.4). + public static readonly CosName JavaScript = new("JavaScript"); + + /// /JS, a script (Tables 218 and 221). + public static readonly CosName JS = new("JS"); + + /// /NewWindow (Tables 203, 204 and 207). + public static readonly CosName NewWindow = new("NewWindow"); + + /// /T: a target dictionary (Tables 204, 205), the hide action's target (Table 214), the movie action's title (Table 213). + public static readonly CosName T = new("T"); + + /// /R: a target's relationship (Table 205), a rendition action's rendition (Table 218). + public static readonly CosName R = new("R"); + + /// /N: a target's embedded file name (Table 205), a named action's name (Table 216). + public static readonly CosName N = new("N"); + + /// /Dp, a go-to-document-part action's DPart (Table 206). + public static readonly CosName Dp = new("Dp"); + + /// /Win, the launch action's Windows parameters (Table 207). + public static readonly CosName Win = new("Win"); + + /// /Mac, the launch action's Mac OS parameters (Table 207). + public static readonly CosName Mac = new("Mac"); + + /// /Unix, the launch action's UNIX parameters (Table 207). + public static readonly CosName Unix = new("Unix"); + + /// /O: the Windows launch operation (Table 208), the page's open trigger (Table 198). + public static readonly CosName O = new("O"); + + /// /B, a thread action's bead (Table 209). + public static readonly CosName B = new("B"); + + /// /Sound, a sound action's sound object (Table 212). + public static readonly CosName Sound = new("Sound"); + + /// /Volume (Table 212). + public static readonly CosName Volume = new("Volume"); + + /// /Synchronous (Table 212). + public static readonly CosName Synchronous = new("Synchronous"); + + /// /Repeat (Table 212). + public static readonly CosName Repeat = new("Repeat"); + + /// /Mix (Table 212). + public static readonly CosName Mix = new("Mix"); + + /// /Annotation, a movie action's movie annotation (Table 213). + public static readonly CosName Annotation = new("Annotation"); + + /// /Operation, a movie action's operation (Table 213). + public static readonly CosName Operation = new("Operation"); + + /// /H, a hide action's flag (Table 214). + public static readonly CosName H = new("H"); + + /// /Fields (Tables 239 and 241). + public static readonly CosName Fields = new("Fields"); + + /// /Flags (Tables 239 and 241). + public static readonly CosName Flags = new("Flags"); + + /// /CharSet (Table 239). + public static readonly CosName CharSet = new("CharSet"); + + /// /State (Table 217). + public static readonly CosName State = new("State"); + + /// /PreserveRB (Table 217). + public static readonly CosName PreserveRB = new("PreserveRB"); + + /// /AN, a rendition action's screen annotation (Table 218). + public static readonly CosName AN = new("AN"); + + /// /OP, a rendition action's operation (Table 218). + public static readonly CosName OP = new("OP"); + + /// /Trans, the transition action type and its transition dictionary (Table 219). + public static readonly CosName Trans = new("Trans"); + + /// /TA, a target annotation (Tables 220 and 222). + public static readonly CosName TA = new("TA"); + + /// /V, a 3D view (Table 220). + public static readonly CosName V = new("V"); + + /// /TI, a rich-media instance (Table 222). + public static readonly CosName TI = new("TI"); + + /// /CMD, a rich-media command (Table 222). + public static readonly CosName CMD = new("CMD"); + + /// /ON, /OFF, /Toggle: the states of a set-OCG-state action (Table 217). + public static readonly CosName On = new("ON"); + + /// /OFF (Table 217). + public static readonly CosName Off = new("OFF"); + + /// /Toggle (Table 217). + public static readonly CosName Toggle = new("Toggle"); +} diff --git a/src/Broadside/Parsing/DiagnosticCodes.Actions.cs b/src/Broadside/Parsing/DiagnosticCodes.Actions.cs new file mode 100644 index 00000000..97a01ce8 --- /dev/null +++ b/src/Broadside/Parsing/DiagnosticCodes.Actions.cs @@ -0,0 +1,18 @@ +namespace Broadside.Parsing; + +/// Diagnostic codes for actions, trigger events and their catalog entries (issue #73). +internal static partial class DiagnosticCodes +{ + // Action dictionaries (§12.6.2, Table 196) and the per-type entries (§12.6.4, §12.7.6). + public const string ActionEntryInvalid = nameof(ActionEntryInvalid); + public const string ActionNextInvalid = nameof(ActionNextInvalid); + public const string ActionCycle = nameof(ActionCycle); + public const string ActionTreeTooDeep = nameof(ActionTreeTooDeep); + public const string ActionTargetCycle = nameof(ActionTargetCycle); + public const string ActionOutOfScope = nameof(ActionOutOfScope); + public const string UriInvalid = nameof(UriInvalid); + + // Trigger events (§12.6.3) and the catalog's OpenAction and URI entries (§7.7.2, Table 29). + public const string AdditionalActionsInvalid = nameof(AdditionalActionsInvalid); + public const string OpenActionInvalid = nameof(OpenActionInvalid); +} diff --git a/src/Broadside/PdfAction.cs b/src/Broadside/PdfAction.cs index 563717a2..4d2ba75f 100644 --- a/src/Broadside/PdfAction.cs +++ b/src/Broadside/PdfAction.cs @@ -7,15 +7,28 @@ namespace Broadside; /// An action: what happens when an outline item, a link or another trigger is activated. A live view over the action dictionary. /// /// -/// ISO 32000-2 §12.6.2, Table 196. is the S entry. The types this version models are -/// (§12.6.4.2) and (§12.6.4.8); every other type reads as a -/// , kept as it is and never performed (parse-and-preserve), and gains its own view as it is modelled. -/// The Next chain (PDF 1.2) is reachable through . +/// ISO 32000-2 §12.6.2, Table 196. is the S entry and the type it names in Table 201 +/// (§12.6.4.1); each type has its own sealed view, and a type the table does not list reads as a . The +/// Next entry (PDF 1.2) is , one level; walks the whole tree in execution +/// order, safely when it is a graph. +/// +/// +/// Actions are data: reading one never performs it, and the library has no way to perform one. Scripts (, +/// ), multimedia (, , +/// ) and 3D views () are out of scope: they are exposed as data +/// and preserved byte for byte when the document is saved, with an diagnostic +/// (ActionOutOfScope) when one is read. Views never write to the dictionaries they read. +/// +/// +/// Diagnostics are lazy: an action's missing or malformed entries are reported when the action is first read through a view, so in strict +/// mode the property or method that reads an invalid action throws, never . /// -/// Actions are data: reading one never performs it. /// public abstract class PdfAction { + /// The default depth limit of : how many Next levels below an action it follows. + public const int DefaultMaxTreeDepth = 64; + private protected PdfAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) { Document = document; @@ -35,11 +48,82 @@ private protected PdfAction(PdfDocument document, CosDictionary dictionary, CosR /// ISO 32000-2 §12.6.2, Table 196, and §12.6.4.1, Table 201. public CosName ActionType { get; } + /// Gets the type of action names in Table 201, or . + /// ISO 32000-2 §12.6.4.1, Table 201. + public abstract PdfActionKind Kind { get; } + + /// + /// Gets the actions performed after this one (Next, PDF 1.2), in order: none, the single action dictionary, or the + /// action dictionaries of the array. Each may have a Next of its own; see . + /// + /// + /// ISO 32000-2 §12.6.2, Table 196 and Note 1. Read from the dictionary on every call. An element that is not an action dictionary + /// is skipped with an ActionNextInvalid diagnostic, as is a Next that is neither a dictionary nor an array. + /// + public IReadOnlyList Next + { + get + { + if (!Dictionary.TryGetValue(NavigationNames.Next, out CosObject? next)) + { + return []; + } + + switch (Document.Resolve(next)) + { + case CosNull: + return []; + case CosDictionary: + return Create(Document, next, DiagnosticReference) is { } action ? [action] : []; + case CosArray array: + var actions = new List(array.Count); + foreach (CosObject element in array) + { + if (Document.Resolve(element) is not CosDictionary) + { + Report(DiagnosticCodes.ActionNextInvalid, $"An element of the {ActionType.Value} action's Next array is not an action dictionary; it is skipped."); + } + else if (Create(Document, element, DiagnosticReference) is { } action) + { + actions.Add(action); + } + } + + return actions; + default: + Report(DiagnosticCodes.ActionNextInvalid, $"The {ActionType.Value} action's Next entry shall be an action dictionary or an array of them; it is ignored."); + return []; + } + } + } + private protected PdfDocument Document { get; } /// Gets the reference diagnostics name: the action's own, or the object holding it. private protected CosReference? Owner { get; private init; } + /// Gets the object diagnostics about this action name: its own reference, else the object holding it. + private protected CosReference? DiagnosticReference => Reference ?? Owner; + + /// + /// Enumerates this action and every action after it, depth first in the order they would be performed: this action, then each action + /// of its followed by that action's own tree (§12.6.2, Note 1). + /// + /// How many Next levels below this action to follow; deeper actions are cut with an ActionTreeTooDeep diagnostic. + /// The actions, read lazily as the enumeration advances. + /// + /// ISO 32000-2 §12.6.2, Note 1: "self-referential actions ought not be executed more than once". Each action dictionary is yielded + /// once, at its first position: an action reached again (shared by two branches, or a cycle) is not repeated, and a cycle, legal + /// but anomalous, is recorded as an ActionCycle diagnostic of severity . The walk + /// is iterative and never writes to the dictionaries. + /// + /// is negative. + public IEnumerable EnumerateActionTree(int maxDepth = DefaultMaxTreeDepth) + { + ArgumentOutOfRangeException.ThrowIfNegative(maxDepth); + return WalkTree(maxDepth); + } + /// Reads an action dictionary. /// The document. /// The action dictionary or a reference to it. @@ -67,7 +151,25 @@ private protected PdfAction(PdfDocument document, CosDictionary dictionary, CosR PdfAction action = type.Value switch { "GoTo" => new PdfGoToAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "GoToR" => new PdfRemoteGoToAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "GoToE" => new PdfEmbeddedGoToAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "GoToDp" => new PdfGoToDocumentPartAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "Launch" => new PdfLaunchAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "Thread" => new PdfThreadAction(document, dictionary, reference, type) { Owner = diagnosticReference }, "URI" => new PdfUriAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "Sound" => new PdfSoundAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "Movie" => new PdfMovieAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "Hide" => new PdfHideAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "Named" => new PdfNamedAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "SubmitForm" => new PdfSubmitFormAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "ResetForm" => new PdfResetFormAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "ImportData" => new PdfImportDataAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "SetOCGState" => new PdfSetOcgStateAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "Rendition" => new PdfRenditionAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "Trans" => new PdfTransitionAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "GoTo3DView" => new PdfGoTo3DViewAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "JavaScript" => new PdfJavaScriptAction(document, dictionary, reference, type) { Owner = diagnosticReference }, + "RichMediaExecute" => new PdfRichMediaExecuteAction(document, dictionary, reference, type) { Owner = diagnosticReference }, _ => new PdfUnknownAction(document, dictionary, reference, type) { Owner = diagnosticReference }, }; action.Check(); @@ -79,8 +181,170 @@ private protected virtual void Check() { } - private protected void Report(string message) => Report(Document, message, Owner); + /// Reports a missing required entry or another "shall" the action breaks (ActionInvalid). + private protected void Report(string message) => Report(Document, message, DiagnosticReference); + + /// Reports a deviation under . + private protected void Report(string code, string message, DiagnosticSeverity severity = DiagnosticSeverity.Warning) => + Document.DiagnosticSink.Report(code, severity, message, objectReference: DiagnosticReference); + + /// Records that the action is out of scope: kept as data, never performed (ActionOutOfScope, Information). + private protected void ReportOutOfScope(string what) => + Report(DiagnosticCodes.ActionOutOfScope, $"A {ActionType.Value} action is kept as data and never performed: {what} is out of scope.", DiagnosticSeverity.Information); + + /// Returns the entry for , resolved; when absent or a reference to nothing. + private protected CosObject? Get(CosName key) => + Dictionary.TryGetValue(key, out CosObject? value) && Document.Resolve(value) is not CosNull and var resolved ? resolved : null; + + /// Returns the entry for as stored when it is an indirect reference. + private protected CosReference? GetReference(CosName key) => Dictionary.TryGetValue(key, out CosObject? value) ? value as CosReference : null; + + /// Reports an entry of the wrong type (ActionEntryInvalid), which is then read as absent. + private protected void ReportEntry(CosName key, string expected) => + Report(DiagnosticCodes.ActionEntryInvalid, $"The {ActionType.Value} action's {key.Value} entry shall be {expected}; it is ignored."); + + /// Reads a dictionary entry; another type reads as absent with a diagnostic. + private protected CosDictionary? ReadDictionary(CosName key) => Read(key, "a dictionary"); + + /// Reads a stream entry; another type reads as absent with a diagnostic. + private protected CosStream? ReadStream(CosName key) => Read(key, "a stream"); + + /// Reads a string entry as stored; another type reads as absent with a diagnostic. + private protected CosString? ReadString(CosName key) => Read(key, "a string"); + + /// Reads a name entry; another type reads as absent with a diagnostic. + private protected CosName? ReadName(CosName key) => Read(key, "a name"); + + /// Reads a boolean entry; another type reads as absent with a diagnostic. + private protected bool? ReadBoolean(CosName key) => Read(key, "a boolean")?.Value; + + /// Reads a text string entry (§7.9.2.2), decoded; another type reads as absent with a diagnostic. + private protected string? ReadText(CosName key) => ReadString(key)?.DecodeText(); + + /// Reads an integer entry that fits in 32 bits; anything else reads as absent with a diagnostic. + private protected int? ReadInteger(CosName key) + { + switch (Get(key)) + { + case null: + return null; + case CosInteger { Value: >= int.MinValue and <= int.MaxValue } integer: + return (int)integer.Value; + default: + ReportEntry(key, "an integer"); + return null; + } + } + + /// Reads a number entry; anything else reads as absent with a diagnostic. + private protected double? ReadNumber(CosName key) + { + switch (Get(key)) + { + case null: + return null; + case CosNumber number: + return number.ToDouble(); + default: + ReportEntry(key, "a number"); + return null; + } + } + + /// Reads a file specification entry (§7.11): a string or a dictionary, as stored after resolving; anything else reads as absent with a diagnostic. + private protected CosObject? ReadFileSpecification(CosName key) + { + switch (Get(key)) + { + case null: + return null; + case CosString or CosDictionary and var value: + return value; + default: + ReportEntry(key, "a file specification (a string or a dictionary)"); + return null; + } + } + + /// Reads a text string or text stream entry (§7.9.2.2, §7.9.3), decoded; anything else reads as absent with a diagnostic. + /// A stream is decoded through its filters into new memory: the stream itself is never changed. + private protected string? ReadScript(CosName key) + { + switch (Get(key)) + { + case null: + return null; + case CosString text: + return text.DecodeText(); + case CosStream stream: + return TextStringDecoder.Decode(Document.DecodeStream(stream).Span); + default: + ReportEntry(key, "a text string or a text stream"); + return null; + } + } + + /// Reads a destination entry (§12.3.2) with the remote flag for go-to actions of other documents. + private protected PdfDestination? ReadDestination(CosName key, bool isRemote) => + Dictionary.TryGetValue(key, out CosObject? value) ? PdfDestination.Create(Document, value, isRemote, DiagnosticReference) : null; private static void Report(PdfDocument document, string message, CosReference? reference) => document.DiagnosticSink.Report(DiagnosticCodes.ActionInvalid, DiagnosticSeverity.Warning, message, objectReference: reference); + + private T? Read(CosName key, string expected) + where T : CosObject + { + switch (Get(key)) + { + case null: + return null; + case T value: + return value; + default: + ReportEntry(key, expected); + return null; + } + } + + private IEnumerable WalkTree(int maxDepth) + { + var visited = new HashSet(ReferenceEqualityComparer.Instance) { Dictionary }; + var onPath = new HashSet(ReferenceEqualityComparer.Instance) { Dictionary }; + var frames = new Stack<(PdfAction Action, IReadOnlyList Next, int Index)>(); + yield return this; + frames.Push((this, Next, 0)); + while (frames.TryPop(out (PdfAction Action, IReadOnlyList Next, int Index) frame)) + { + if (frame.Index >= frame.Next.Count) + { + onPath.Remove(frame.Action.Dictionary); + continue; + } + + frames.Push(frame with { Index = frame.Index + 1 }); + PdfAction child = frame.Next[frame.Index]; + if (!visited.Add(child.Dictionary)) + { + if (onPath.Contains(child.Dictionary)) + { + frame.Action.Report( + DiagnosticCodes.ActionCycle, + $"The {frame.Action.ActionType.Value} action's Next leads back to an action it follows; the cycle is cut and that action is not repeated.", + DiagnosticSeverity.Information); + } + + continue; + } + + if (frames.Count > maxDepth) + { + frame.Action.Report(DiagnosticCodes.ActionTreeTooDeep, $"The action tree is deeper than {maxDepth} Next levels; the actions below are not read."); + continue; + } + + yield return child; + onPath.Add(child.Dictionary); + frames.Push((child, child.Next, 0)); + } + } } diff --git a/src/Broadside/PdfActionKind.cs b/src/Broadside/PdfActionKind.cs new file mode 100644 index 00000000..60bf8307 --- /dev/null +++ b/src/Broadside/PdfActionKind.cs @@ -0,0 +1,89 @@ +namespace Broadside; + +/// The action types of ISO 32000-2 Table 201, as named by an action dictionary's S entry. +/// ISO 32000-2 §12.6.4.1, Table 201. The version in each member's remarks is the version that introduced the type. +public enum PdfActionKind +{ + /// A type Table 201 does not list; the action is kept as it is and never performed. + Unknown = 0, + + /// GoTo: go to a destination in this document (PDF 1.1). + /// ISO 32000-2 §12.6.4.2. + GoTo, + + /// GoToR: go to a destination in another document (PDF 1.1). + /// ISO 32000-2 §12.6.4.3. + GoToR, + + /// GoToE: go to a destination in an embedded file (PDF 1.6). + /// ISO 32000-2 §12.6.4.4. + GoToE, + + /// GoToDp: go to a document part (PDF 2.0). + /// ISO 32000-2 §12.6.4.5. + GoToDp, + + /// Launch: launch an application or open a file (PDF 1.1). Never performed by the library. + /// ISO 32000-2 §12.6.4.6. + Launch, + + /// Thread: begin reading an article thread (PDF 1.1). + /// ISO 32000-2 §12.6.4.7. + Thread, + + /// URI: resolve a uniform resource identifier (PDF 1.1). + /// ISO 32000-2 §12.6.4.8. + Uri, + + /// Sound: play a sound (PDF 1.2; deprecated in PDF 2.0). Kept as data. + /// ISO 32000-2 §12.6.4.9. + Sound, + + /// Movie: play a movie (PDF 1.2; deprecated in PDF 2.0). Kept as data. + /// ISO 32000-2 §12.6.4.10. + Movie, + + /// Hide: set or clear annotations' Hidden flags (PDF 1.2). + /// ISO 32000-2 §12.6.4.11. + Hide, + + /// Named: a predefined action such as NextPage (PDF 1.2). + /// ISO 32000-2 §12.6.4.12. + Named, + + /// SubmitForm: send form data to a URL (PDF 1.2). Never performed by the library. + /// ISO 32000-2 §12.7.6.2. + SubmitForm, + + /// ResetForm: set fields to their default values (PDF 1.2). + /// ISO 32000-2 §12.7.6.3. + ResetForm, + + /// ImportData: import field values from a file (PDF 1.2). Never performed by the library. + /// ISO 32000-2 §12.7.6.4. + ImportData, + + /// SetOCGState: set the states of optional content groups (PDF 1.5). + /// ISO 32000-2 §12.6.4.13. + SetOcgState, + + /// Rendition: control the playing of multimedia content (PDF 1.5). Kept as data. + /// ISO 32000-2 §12.6.4.14. + Rendition, + + /// Trans: update the display with a transition (PDF 1.5). + /// ISO 32000-2 §12.6.4.15. + Transition, + + /// GoTo3DView: set the view of a 3D annotation (PDF 1.6). Kept as data. + /// ISO 32000-2 §12.6.4.16. + GoTo3DView, + + /// JavaScript: run an ECMAScript script (PDF 1.3). Kept as data; the library never runs scripts. + /// ISO 32000-2 §12.6.4.17. + JavaScript, + + /// RichMediaExecute: send a command to a rich media annotation's handler (PDF 2.0). Kept as data. + /// ISO 32000-2 §12.6.4.18. + RichMediaExecute, +} diff --git a/tests/Broadside.TestSupport/Corpus.cs b/tests/Broadside.TestSupport/Corpus.cs index 866d6558..0f158d19 100644 --- a/tests/Broadside.TestSupport/Corpus.cs +++ b/tests/Broadside.TestSupport/Corpus.cs @@ -59,6 +59,8 @@ public static class Corpus "tagged-structure.pdf", "destinations-all.pdf", "outline-full.pdf", + "actions-all.pdf", + "actions-preserved.pdf", ]; private static readonly string[] Malformed = diff --git a/tests/Broadside.Tests/Actions/ActionTypeTests.cs b/tests/Broadside.Tests/Actions/ActionTypeTests.cs new file mode 100644 index 00000000..6e4867f5 --- /dev/null +++ b/tests/Broadside.Tests/Actions/ActionTypeTests.cs @@ -0,0 +1,56 @@ +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Actions; + +/// Every action type of ISO 32000-2 Table 201 (§12.6.4, §12.7.6), read from actions-all.pdf. +public class ActionTypeTests +{ + private static readonly CosName A = new("A"); + + [Fact] + public void Actions_all_pdf_types_each_table_201_action_in_table_order() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("actions-all.pdf")); + + IReadOnlyList actions = LinkActions(document); + + Assert.Equal( + [ + PdfActionKind.GoTo, PdfActionKind.GoToR, PdfActionKind.GoToE, PdfActionKind.GoToDp, PdfActionKind.Launch, + PdfActionKind.Thread, PdfActionKind.Uri, PdfActionKind.Sound, PdfActionKind.Movie, PdfActionKind.Hide, + PdfActionKind.Named, PdfActionKind.SubmitForm, PdfActionKind.ResetForm, PdfActionKind.ImportData, + PdfActionKind.SetOcgState, PdfActionKind.Rendition, PdfActionKind.Transition, PdfActionKind.GoTo3DView, + PdfActionKind.JavaScript, PdfActionKind.RichMediaExecute, + ], + actions.Select(action => action.Kind)); + Assert.Equal( + [ + typeof(PdfGoToAction), typeof(PdfRemoteGoToAction), typeof(PdfEmbeddedGoToAction), typeof(PdfGoToDocumentPartAction), + typeof(PdfLaunchAction), typeof(PdfThreadAction), typeof(PdfUriAction), typeof(PdfSoundAction), typeof(PdfMovieAction), + typeof(PdfHideAction), typeof(PdfNamedAction), typeof(PdfSubmitFormAction), typeof(PdfResetFormAction), + typeof(PdfImportDataAction), typeof(PdfSetOcgStateAction), typeof(PdfRenditionAction), typeof(PdfTransitionAction), + typeof(PdfGoTo3DViewAction), typeof(PdfJavaScriptAction), typeof(PdfRichMediaExecuteAction), + ], + actions.Select(action => action.GetType())); + Assert.DoesNotContain(document.Diagnostics, diagnostic => diagnostic.Severity > Diagnostics.DiagnosticSeverity.Information); + } + + [Fact] + public void An_action_type_the_table_does_not_list_is_kept_as_an_unknown_action() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + var dictionary = new CosDictionary { [new CosName("S")] = new CosName("SetAppearance"), [new CosName("X")] = new CosInteger(1) }; + + PdfAction action = Assert.IsType(document.GetAction(dictionary)); + + Assert.Equal(PdfActionKind.Unknown, action.Kind); + Assert.Equal(new CosName("SetAppearance"), action.ActionType); + Assert.Same(dictionary, action.Dictionary); + Assert.Empty(document.Diagnostics); + } + + /// The actions of the link annotations 40 to 59, in page order. + internal static IReadOnlyList LinkActions(PdfDocument document) => + [.. Enumerable.Range(40, 20).Select(number => document.GetAction(((CosDictionary)document.Resolve(new CosReference(number, 0)))[A])!)]; +} diff --git a/tests/Corpus/README.md b/tests/Corpus/README.md index 1a5c7e78..4cac4d58 100644 --- a/tests/Corpus/README.md +++ b/tests/Corpus/README.md @@ -83,6 +83,8 @@ Verification was run with qpdf 12.4.2 (`qpdf --check`), poppler (`pdfinfo`, `pdf | `tagged-structure.pdf` | PDF 2.0 tagged page (`/MarkInfo << /Marked true >>`, `/StructParents 0`, `/Tabs /S`): Document > Chapter > [H1, Para, L (two LI with Lbl/LBody), Table (two TR with TH/TD)] owning MCIDs 0-9 in content order, a pagination `/Artifact` outside the tree, a Link annotation as an OBJR of Para (`/StructParent 1`), MCID 9 as an MCR dictionary. Root has ParentTree, ParentTreeNextKey 2, IDTree (`h1`, `tbl1`), RoleMap `/Para /P`, ClassMap `/Centered`, Namespaces [PDF 2.0, custom `https://example.com/broadside-corpus` with RoleMapNS `/Chapter [/Sect <2.0>]`]. H1 has both C and A (A wins for SpaceAfter); L has List, Table/TH/TD have Table attributes (TH A array with revision 0). | 14.6, 14.7.2-14.7.6, 14.8.4-14.8.6 | `qpdf --check`; `pdfinfo` (Tagged: yes); `pdftotext` | clean; `pdfinfo -struct` stops at Chapter ("StructElem object is wrong type"): poppler applies only RoleMap, not RoleMapNS (14.8.6.2) | | `destinations-all.pdf` | A `/Names << /Dests >>` tree with one entry per Table 149 form: `XYZ` with numbers, with three nulls and with zoom 0; `Fit`; `FitH` with a number and with null; `FitV`; `FitR`; `FitB`; `FitBH`; `FitBV`; a value in the dictionary form `<< /D [3 0 R /Fit] /Note ... >>`; a value that is an indirect array. The PDF 1.1 catalog `/Dests` dictionary keyed by name (`/Chap6 [3 0 R /FitV 72]`), and an outline whose items refer to `/Dest /Chap6` (name) and `/Dest (alpha)` (string). | 12.3.2.2, 12.3.2.4, 7.7.2, 12.3.3 | `qpdf --check`; `qpdf --json --json-key=outlines` lists both items | clean | | `outline-full.pdf` | An outline three levels deep: Part I (open, `/Count 2`) holding Chapter 1 (closed, `/Count -1`, holding Section 1.1) and Chapter 2 (a URI action); Part II (closed, `/Count -2`) holding Chapter 3 (UTF-16BE title `Chapter 3 – Übersicht`, `/C [1 0 0]`, `/F 3` bold italic, `/A << /S /GoTo /D (alpha) >>`) and Chapter 4 (`/SE` to a structure element, `/Dest [3 0 R /FitB]`). Outline `/Count 4`. | 12.3.3 Tables 150-152, 12.6.4.2, 12.6.4.8 | `qpdf --check`; `qpdf --json --json-key=outlines` shows the tree with Part I and Chapter 1 open/closed as stated | clean | +| `actions-all.pdf` | PDF 2.0. Every Table 201 action type in the `/A` of its own link annotation (objects 40-59, in table order): GoTo (`/D` + `/SD`, `/Next` an array of two whose first has its own `/Next`), GoToR (string `/F`, `/D [0 /Fit]`, `/NewWindow true`), GoToE (target dictionary `R P` > `R C N` > `R C P 0 A (attached)`), GoToDp, Launch (file specification dictionary + deprecated `/Win`), Thread (`/D 0 /B 0`), URI (relative `docs/index.html`, `/IsMap true`), Sound (`/Volume 0.25`), Movie (`/Operation /Pause`), Hide (annotation + field name, `/H false`), Named (`NextPage`, `/Next` a non-standard `/Print`), SubmitForm (URL file specification, mixed `/Fields`, `/Flags 13`, `/CharSet (utf-8)`), ResetForm (`/Flags 1`), ImportData, SetOCGState (`/PreserveRB false`), Rendition (`/OP 0` + `/JS`), Trans, GoTo3DView (`/V /F`), JavaScript (stream), RichMediaExecute (command + two arguments). Catalog `/OpenAction` (GoTo), `/AA` (WC WS DS WP DP), `/URI << /Base (https://example.com/) >>`, `/Names /JavaScript` (one script); page `/AA` (O C); link 60 with `/AA` E X D U PO PC PV PI; widget-field 69 with `/AA` K F V C Fo Bl. | 12.6.1-12.6.4, 12.7.6.2-12.7.6.4, 7.7.2, 7.7.4 | `qpdf --check`; `pdfinfo` reports `JavaScript: yes`, `Form: AcroForm` | clean | +| `actions-preserved.pdf` | Actions the library keeps as data, each an indirect object in bytes a canonical writer would change: 10 a script literal with escapes `\(`, `\"`, `\053`, `\r`, `\n` and a backslash-EOL continuation; 11 a script hex string; 12 a script in a Flate stream (27; the catalog's OpenAction); 13 `/S /Java#53cript` (the name dictionary's document script); 14 Sound with `/Volume .50` and a 4-sample raw sound (15); 16 Rendition with a rendition dictionary and a script stream (17); 18 Movie naming movie annotation 19; 20 RichMediaExecute with TA/TI/CMD; 23 and 24 go-to actions whose `/Next` entries name each other (a cycle). Links 30-37 hold them. | 12.6.2, 12.6.4.9, 12.6.4.10, 12.6.4.14, 12.6.4.17, 12.6.4.18, 7.3.4.2, 7.3.5 | `qpdf --check`; `pdfinfo` warns `parseAction: Circular next actions detected.` (the deliberate cycle) | clean (an `ActionCycle` Information when the tree of action 23 is walked) | The crypt filter `/Length` entries in the R4 and R6 files are `16` and `32` (bytes), the form Acrobat and qpdf write and that Table 25 describes for the standard security handler; the same table also says the key "shall have the value of 128/256". Readers should accept both forms. diff --git a/tests/Corpus/actions-all.pdf b/tests/Corpus/actions-all.pdf new file mode 100644 index 0000000000000000000000000000000000000000..ee45a03e30c18ebcbb1bf31480c291266a9a359c GIT binary patch literal 8448 zcmeHN-EZPZ5`WKM(OPLF@~{{KHn2MzDL~lGP7*92$=qdDx(;rFca3e?O@_Ir{ZsBw z-Kws}Ukx)S9eFru^AJM0y1KhQe)ZwJ^Tw0!+s)RQ%~~ve{{8IzduA=ZB!XEZE_oQg zFw5gFB4ce}m@#Xbi0E=DgE(TyI%n3;@gio{m_2ofV-m>U*u@32E-w|!<7m(MD}Uwl zWf~-sS-;L%<8kz<@#*}>bH)8QKgu>Qv5k+ijmvD0-ce~@S=v#yafuBtb3eOQ5{En! ztg)6d$$qdbvE!R06wPJ4vFI9id;`it)s$|FU+KY9BZvZd&Uyn>meLbSU#wHX{fs@i z4$-aY$V=lyq%zRrrlX(Xd9S6E+(UE0a!@H<~mtGhu+Z=a=tN#7?Zo5b*`YZg-!~v2^akQ7(iToW)O$UUrQ!KUA@7H zuJ8zr(V8a`P{f846{lG75b(}gsGx$Qd!@fe7+ejpc^1Aee0`am6P|i-Uhs|vmy$2n z!dD1MsHA@9sy30}fAdAH>Tv=$OIV+Lthyz}#ff!!!?)3Ljpjwaqj;DEp~w=kR7OXP z--xC}f3xnv3(5pU8ZbSfG;09Nh=lu1u@lNg8lxXReOic30^g>rk)%O{Qan>gVY~w_ zglKZ&Yg6t*9|CI+;a64B2wW%Lv503sUS<}=i`X^Saub3=uCrU7910#pz!RTi4k-;X z41Kr+&DKL4Za0Fpnr#OjeF2Y1<0#%{bS8k)L~zM;T-^q{LuW-KKk->_<-jnYo5-9WR0y{ec#uRoL}n=QVbMoVt*@LeHI4S=c@Xgs(?7K^eygtb25AA54Ym7RatTgPA5YeFGGV%ww-)isODGuC^f`5Urzv1P zF9jW@uVOYl7$0u{>N6)tFuF#Bz&{jW^dBaBKs8O1O5Yf`;uX6 zEYtWL8b2&t_Pud|xvI}O5iC&8a<%UjYiev<6&`JUJjV2~#6;Hw53EZXmzeI4NxCmF zd3gg{7v)XMY)9KzuRK-p9**tlJ(Q)M9f)fJfC~c=_1Ddtn4MB?)G;Pz)!EImKNJHHJ&wZ)vfK?`kn@OG5`&Bb%Z^pZ`S7 z!*Au*S9gfnvSStSe~oIY8Hqh+gEHbx}+vp)=W> z{rR6i|Ala_zv_99svE1K@5jJXbH6DCVr(#=8}eTcdSoy zk*d6DXH7DJy@;Bz|~W9d+o7M1>;+%)Nu zn~uPFUZInTt&Jv?ZffF8{iYq*$qbOrc+7e<^81FB%%Tq^=EJ*t{H9|XTk?HOoAIn_ z25psmNxQs;CrOisFpF+{M^NzH`Hu(Wn4nX?b6x-(x_bU_6h{&Vz-R^ddlkHFsX+xi zR#m|_G-H-ox#;UClRR2tA-hh1%=ihM-TO6C(#9=-d-w$X1E0gb1u{vw9e&-C5f&PJ< z<8&OhVg(H}fj=zDX%4=(sL|XGe^1L zZ``-jZX5e{I{3<~w$?HC=(yMw*ZBHvbM2rD;9ceGws5jqqqVUJt(q1_>f4*SfW>LKnWd2mD Q%;&mY_w3!ftLfzIFV^yT7XSbN literal 0 HcmV?d00001 diff --git a/tests/Corpus/actions-preserved.pdf b/tests/Corpus/actions-preserved.pdf new file mode 100644 index 0000000000000000000000000000000000000000..74a33ac072dc631c58b050cce832203517e488de GIT binary patch literal 3528 zcmcIn&2HO95bh}lJ;fk}0jWs5+@<(q*fk)_cB?qH1j!8wSOH2?8=HyD6)4J4a>}FR zA=;;C5ACTypQbarq_iRh7lBj30Ik`b*>Ar2W|rC+9G^btyFr741M2#1#9YX14rM|kyh%C1UHkowE%Z6CrNaqmT=|Z zejhOhd*U^)p`5El78~G*iFG;}b00WSF(iHUC#k_o-85H z7Sbkxwv{oAkc%)w2ptEVx~L*{1R<~!ltJ_!*h`t-Ju3S?2;wv2jhy$sn-yq1QRKQP*14675ct8K#P>-D64;rHQOqAYLmF8CHTT5)Q0{XVd6Iv$ek^=Wy+* z@u~X+r-N>d$jkwwavBYpv9JL~BXV;IV%M?DLwidG4LLdzroOn&_1rl(2MlGLo2JEP z;SRQ}S)e(yB0}98B02+27_x6vf;6nfDXeCr42DU3t2sYe%6Neg*<}YrF)uEAAWRRl z?zt&L7n+%TpQMu(rVWnH#}2=4yK;0^Q^J`jWlDOf<}?5^McBg`*zLHTwN+BvPFXE> zRhrXqL=yFUdyqD}r;)ZF)TJV2nvsk}NOCO7gzE?-fj z*>$&C3dxw}GDA|PsQF_Vs|mUmC~#V?2g~xGvuDje&;IB=|L(6r|M%Xr-cNu3`sADA z-=3s(g!i~4n;;;4>k-Wz>>+GDy4UC&3aYQOuNK|hjaKyk*6bHx zH(g>yx5c@=BfcPdRlfR8|7y&babjVwUr~>!Dvjrjs@iwdW0}#Tb0fMf`bS5vR&|-l zHw_2euz@#q@d4lSTo2yB+J<)seIQ-gICVfjsIrf{sHBQbc-Ykyo7=AO%-ij{ujkh= zbD!pZC7!=m#}|Zke4$s*7ef{C9;`3l!?(xExx#7JxDwp0oht;r|8HVOQ!QW7rsk>a y^Xl~wzGIz{XA!>cW%_5>DETO{7jU{OML&ItKF5nG%XOy+e4lUZ?40yZ8~*}1jf8Ok literal 0 HcmV?d00001 diff --git a/tests/Corpus/generate.py b/tests/Corpus/generate.py index 3c0d36ef..4ed76e9d 100644 --- a/tests/Corpus/generate.py +++ b/tests/Corpus/generate.py @@ -1446,6 +1446,150 @@ def gen_outline_broken() -> bytes: ]) +def link(action: bytes) -> bytes: + """12.5.6.5 Table 176: a link annotation with no border whose A entry is ``action``.""" + return b"<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /Border [0 0 0] /A " + action + b" >>" + + +def gen_actions_all() -> bytes: + """12.6 Actions: every action type of Table 201, each in the A entry of its own link annotation + (objects 40-59, in table order: GoTo with D and SD, GoToR with a string F and a page number, GoToE + with a nested target dictionary three levels deep (Table 205), GoToDp, Launch with a file + specification dictionary and the deprecated Win dictionary (Table 208), Thread with an index + into the catalog's Threads and a bead index, URI relative to the catalog's URI Base (Table 211) + with IsMap, Sound, Movie naming a movie annotation, Hide with an annotation and a field name, + Named NextPage with a non-standard /Print next, SubmitForm (12.7.6.2: URL file specification, + Fields mixing a reference and a name, Flags 13, CharSet), ResetForm (Flags 1), ImportData, + SetOCGState with PreserveRB false, Rendition with OP 0 and JS, Trans, GoTo3DView with the + name /F, JavaScript in a stream, RichMediaExecute with a command and two arguments). The GoTo + action's Next is an array of two actions, the first of which has a Next of its own. + Trigger events (12.6.3): the catalog's OpenAction (a go-to action) and AA (Table 200: WC WS DS WP + DP), the page's AA (Table 198: O C), a link annotation's AA (Table 197: E X D U PO PC PV PI) and + a widget merged with its text field (object 69) whose AA has Table 199's K F V C and Table 197's + Fo Bl. The name dictionary's JavaScript tree has one document-level script (7.7.4).""" + id0 = file_id("actions-all").hex().encode() + + def js(text: bytes) -> bytes: + return b"<< /S /JavaScript /JS (" + text + b") >>" + + catalog_aa = b" ".join(b"/%s %s" % (k, js(k + b"\\(\\);")) for k in [b"WC", b"WS", b"DS", b"WP", b"DP"]) + annot_aa = b" ".join(b"/%s %s" % (k, js(k + b"\\(\\);")) for k in [b"E", b"X", b"D", b"U", b"PO", b"PC", b"PV", b"PI"]) + field_aa = b" ".join(b"/%s %s" % (k, js(k + b"\\(\\);")) for k in [b"K", b"F", b"V", b"C", b"Fo", b"Bl"]) + appearance = b" /AP << /N 81 0 R >>" + annots = list(range(40, 60)) + [60, 68, 69, 72, 74, 77] + return simple_file([ + (1, catalog(b" /OpenAction << /S /GoTo /D [3 0 R /Fit] >>" + b" /AA << " + catalog_aa + b" >>" + b" /URI << /Base (https://example.com/) >>" + b" /Names << /JavaScript << /Names [(init) 79 0 R] >> >>" + b" /Threads [65 0 R] /OCProperties << /OCGs [70 0 R 71 0 R] /D << /Order [70 0 R 71 0 R] >> >>" + b" /AcroForm << /Fields [69 0 R] /CO [69 0 R] >> /StructTreeRoot 61 0 R /DPartRoot 63 0 R")), + (2, pages()), + (3, page(extra=b" /AA << /O << /S /Named /N /FirstPage >> /C " + js(b"pageClosed\\(\\);") + b" >>" + b" /B [66 0 R] /Annots [" + b" ".join(b"%d 0 R" % n for n in annots) + b"]")), + (40, link(b"<< /Type /Action /S /GoTo /D [3 0 R /XYZ 0 792 null] /SD [62 0 R /Fit]" + b" /Next [<< /S /Named /N /LastPage /Next " + js(b"nested\\(\\);") + b" >>" + b" << /S /URI /URI (https://example.com/next) >>] >>")), + (41, link(b"<< /S /GoToR /F (other.pdf) /D [0 /Fit] /NewWindow true >>")), + (42, link(b"<< /S /GoToE /D (Chapter 1) /NewWindow false" + b" /T << /R /P /T << /R /C /N (embedded.pdf) /T << /R /C /P 0 /A (attached) >> >> >> >>")), + (43, link(b"<< /S /GoToDp /Dp 82 0 R >>")), + (44, link(b"<< /S /Launch /F << /Type /Filespec /F (readme.txt) /UF (readme.txt) >>" + b" /Win << /F (notepad.exe) /D (C:\\\\Temp) /O (print) /P (readme.txt) >> /NewWindow true >>")), + (45, link(b"<< /S /Thread /D 0 /B 0 >>")), + (46, link(b"<< /S /URI /URI (docs/index.html) /IsMap true >>")), + (47, link(b"<< /S /Sound /Sound 67 0 R /Volume 0.25 /Synchronous true /Repeat false /Mix true >>")), + (48, link(b"<< /S /Movie /Annotation 68 0 R /Operation /Pause >>")), + (49, link(b"<< /S /Hide /T [40 0 R (email)] /H false >>")), + (50, link(b"<< /S /Named /N /NextPage /Next << /S /Named /N /Print >> >>")), + (51, link(b"<< /S /SubmitForm /F << /FS /URL /F (https://example.com/submit) >>" + b" /Fields [69 0 R (name.first)] /Flags 13 /CharSet (utf-8) >>")), + (52, link(b"<< /S /ResetForm /Fields [(email)] /Flags 1 >>")), + (53, link(b"<< /S /ImportData /F (data.fdf) >>")), + (54, link(b"<< /S /SetOCGState /State [/OFF 70 0 R /Toggle 71 0 R 70 0 R /ON 71 0 R] /PreserveRB false >>")), + (55, link(b"<< /S /Rendition /OP 0 /AN 72 0 R /R 73 0 R /JS (play\\(\\);) >>")), + (56, link(b"<< /S /Trans /Trans << /Type /Trans /S /Dissolve /D 0.5 >> >>")), + (57, link(b"<< /S /GoTo3DView /TA 74 0 R /V /F >>")), + (58, link(b"<< /S /JavaScript /JS 76 0 R >>")), + (59, link(b"<< /S /RichMediaExecute /TA 77 0 R /TI 78 0 R" + b" /CMD << /Type /RichMediaCommand /C (play) /A [(intro) 2 true] >> >>")), + (60, b"<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /Border [0 0 0] /AA << " + annot_aa + b" >> >>"), + (61, b"<< /Type /StructTreeRoot /K 62 0 R >>"), + (62, b"<< /Type /StructElem /S /P /P 61 0 R /Pg 3 0 R >>"), + (63, b"<< /Type /DPartRoot /DPartRootNode 64 0 R >>"), + (64, b"<< /Type /DPart /Parent 63 0 R /DParts [[82 0 R]] >>"), + (65, b"<< /Type /Thread /F 66 0 R /I << /Title (Article) >> >>"), + (66, b"<< /Type /Bead /T 65 0 R /N 66 0 R /V 66 0 R /P 3 0 R /R [0 0 100 100] >>"), + (67, stream(b"/Type /Sound /R 8000 /C 1 /B 8 /E /Raw", b"\x80\xa0\x80\x60")), + (68, b"<< /Type /Annot /Subtype /Movie /Rect [0 0 10 10] /T (Clip) /Movie << /F (clip.mov) >>" + appearance + b" >>"), + (69, b"<< /Type /Annot /Subtype /Widget /Rect [0 0 10 10] /P 3 0 R /FT /Tx /T (email)" + b" /AA << " + field_aa + b" >>" + appearance + b" >>"), + (70, b"<< /Type /OCG /Name (One) >>"), + (71, b"<< /Type /OCG /Name (Two) >>"), + (72, b"<< /Type /Annot /Subtype /Screen /Rect [0 0 10 10] /P 3 0 R" + appearance + b" >>"), + (73, b"<< /Type /Rendition /S /MR /C << /Type /MediaClip /S /MCD /D << /Type /Filespec /F (clip.mp4) >> /CT (video/mp4) >> >>"), + (74, b"<< /Type /Annot /Subtype /3D /Rect [0 0 10 10] /3DD 75 0 R" + appearance + b" >>"), + (75, stream(b"/Type /3D /Subtype /U3D", b"")), + (76, stream(b"", b'app.alert("stream");')), + (77, b"<< /Type /Annot /Subtype /RichMedia /Rect [0 0 10 10] /RichMediaContent << /Configurations [] >>" + + appearance + b" >>"), + (78, b"<< /Type /RichMediaInstance /Subtype /Video >>"), + (79, js(b"var initialised = true;")), + (82, b"<< /Type /DPart /Parent 64 0 R /Start 3 0 R >>"), + (81, stream(b"/Type /XObject /Subtype /Form /BBox [0 0 10 10]", b"")), + ], version="2.0", trailer_extra=b" /ID [<%s> <%s>]" % (id0, id0)) + + +def gen_actions_preserved() -> bytes: + """12.6 Actions that the library keeps as data and never performs (JavaScript 12.6.4.17, Sound + 12.6.4.9, Movie 12.6.4.10, Rendition 12.6.4.14, Rich-Media-Execute 12.6.4.18), each an indirect + object written in bytes a re-serializer would change, so that a save proves they are copied + byte for byte: object 10, a script in a literal string with escapes (\\( \\" \\053 \\r \\n, 7.3.4.2 + Table 3) and a backslash-EOL continuation; 11, a script in a hexadecimal string; 12, a script in a + Flate stream (object 27; the catalog's OpenAction); 13, a script action whose type is written /Java#53cript + (7.3.5: the same name as /JavaScript); 14, a sound action with /Volume .50 and a four-sample raw + sound (13.3, object 15); 16, a rendition action with a rendition dictionary and a script stream + (object 17); 18, a movie action naming the movie annotation 19; 20, a rich-media-execute action + with TA, TI and CMD; 23 and 24, two go-to actions whose Next entries name each other (a cycle). + Objects 30-37 are the link annotations holding them; object 13 is the name dictionary's + document-level script (7.7.4) and object 11 the page's open action (Table 198).""" + sound = bytes([0x80, 0xA0, 0x80, 0x60]) + script = b"app.alert('flate');" + links = list(range(30, 38)) + return simple_file([ + (1, catalog(b" /OpenAction 12 0 R /Names << /JavaScript << /Names [(doc) 13 0 R] >> >>")), + (2, pages()), + (3, page(extra=b" /AA << /O 11 0 R >> /Annots [" + b" ".join(b"%d 0 R" % n for n in links + [19, 21]) + b"]")), + (10, b"<< /S/JavaScript /JS (app.alert\\(\\\"hi\\\"\\);\\053\\r\\n// one \\\nline) >>"), + (11, b"<>>"), + (12, b"<< /S /JavaScript /JS 27 0 R >>"), + (13, b"<< /Type /Action /S /Java#53cript /JS (var x = 1;) >>"), + (14, b"<< /S /Sound /Sound 15 0 R /Volume .50 /Mix true >>"), + (15, stream(b"/Type /Sound /R 8000 /C 1 /B 8 /E /Raw", sound)), + (16, b"<< /S /Rendition /OP 4 /AN 21 0 R /R << /Type /Rendition /S /MR" + b" /C << /Type /MediaClip /S /MCD /D << /Type /Filespec /F (clip.mp4) >> /CT (video/mp4) >> >> /JS 17 0 R >>"), + (17, stream(b"", b"play();")), + (18, b"<< /S /Movie /Annotation 19 0 R /Operation /Play /Rate 2.0 >>"), + (19, b"<< /Type /Annot /Subtype /Movie /Rect [0 0 10 10] /Movie << /F (clip.mov) >> /AP << /N 25 0 R >> >>"), + (20, b"<< /S /RichMediaExecute /TA 22 0 R /TI 26 0 R /CMD << /C (rewind) /A 0.0 >> >>"), + (21, b"<< /Type /Annot /Subtype /Screen /Rect [0 0 10 10] /P 3 0 R /AP << /N 25 0 R >> >>"), + (22, b"<< /Type /Annot /Subtype /RichMedia /Rect [0 0 10 10] /RichMediaContent << >> /AP << /N 25 0 R >> >>"), + (23, b"<< /S /GoTo /D [3 0 R /Fit] /Next 24 0 R >>"), + (24, b"<< /S /GoTo /D [3 0 R /FitH 700] /Next [23 0 R] >>"), + (25, stream(b"/Type /XObject /Subtype /Form /BBox [0 0 10 10]", b"")), + (26, b"<< /Type /RichMediaInstance /Subtype /Video >>"), + (27, stream(b"/Filter /FlateDecode", flate(script))), + (30, link(b"10 0 R")), + (31, link(b"11 0 R")), + (32, link(b"13 0 R")), + (33, link(b"14 0 R")), + (34, link(b"16 0 R")), + (35, link(b"18 0 R")), + (36, link(b"20 0 R")), + (37, link(b"23 0 R")), + ]) + + XMP = (b'\n' b'\n' b' \n' @@ -1691,6 +1835,8 @@ def elem(s: bytes, parent: int, extra: bytes) -> bytes: "destinations-all.pdf": gen_destinations_all, "outline-full.pdf": gen_outline_full, "outline-broken.pdf": gen_outline_broken, + "actions-all.pdf": gen_actions_all, + "actions-preserved.pdf": gen_actions_preserved, } From ac93fd1be74c54670f83bdc0adfe0be51af2b864 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:19:15 -0500 Subject: [PATCH 041/152] ci(fuzz): cache key without commas; 80 minutes per target (#48) Co-Authored-By: Claude Opus 5.5 --- .github/workflows/README.md | 4 ++-- .github/workflows/fuzz.yml | 10 +++++----- tests/Broadside.Fuzz/README.md | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/README.md b/.github/workflows/README.md index 963e7eb5..638f8292 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -18,11 +18,11 @@ Every fuzz target under libFuzzer through SharpFuzz, one parallel job per target | Job | Runs on | What it does | |---|---|---| -| `targets` | ubuntu | Builds the harness and turns `--list` (or the `targets` input) into the matrix; checks the `minutes` input (default 75, at most 300 so every job stays under GitHub's 6-hour limit). | +| `targets` | ubuntu | Builds the harness and turns `--list` (or the `targets` input) into the matrix; checks the `minutes` input (default 80, at most 300 so every job stays under GitHub's 6-hour limit). | | `fuzz ()` | ubuntu | Builds the libfuzzer-dotnet driver from pinned, hash-checked source with clang; installs SharpFuzz.CommandLine 2.3.0; builds the harness in Release; fetches `pdf20examples` and `qpdf` with `tools/CorpusFetcher` (cached) as extra seeds; restores the target's libFuzzer corpus from the previous run (`actions/cache`, key `fuzz-corpus--`); runs `tests/Broadside.Fuzz/run-libfuzzer.sh` (which instruments a copy of `Broadside.dll`) for the given minutes on every core; saves the minimized corpus; uploads `stats.json` as `fuzz-stats-`, and on a finding fails and uploads `fuzz-findings-` (inputs, replays, worker logs). | | `summary` | ubuntu | One table in the job summary: minutes, workers, CPU-hours, executions, corpus size and findings per target, and the cumulative fuzzing time of the run. | -Schedule: Sundays 03:17 UTC. A scheduled run fuzzes for 20 targets x 75 minutes = 25 hours of wall-clock time, 100 CPU-hours on the 4-core runners. Runs on one branch never overlap (they would race to save the same cache). From a terminal: `gh workflow run fuzz.yml --ref main -f minutes=30 -f targets="document save"`. A finding is fixed in a PR that adds a regression test replaying the input (`tests/Broadside.Tests/Document/FuzzRegressionTests.cs`). +Schedule: Sundays 03:17 UTC. A scheduled run fuzzes for 19 targets x 80 minutes = 25.3 hours of wall-clock time, about 100 CPU-hours on the 4-core runners. Runs on one branch never overlap (they would race to save the same cache). From a terminal: `gh workflow run fuzz.yml --ref main -f minutes=30 -f targets="document save"`. A finding is fixed in a PR that adds a regression test replaying the input (`tests/Broadside.Tests/Document/FuzzRegressionTests.cs`). ## `docs.yml`: the documentation site diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index bd04db40..cee41f56 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -1,6 +1,6 @@ # Real fuzzing: every fuzz target under libFuzzer (SharpFuzz instrumentation, libfuzzer-dotnet driver) in parallel jobs, once a -# week and on the "Run workflow" button. One scheduled run gives each target 75 minutes on every core of its runner, so the run -# as a whole adds up to more than 24 hours of fuzzing (issue #48). Each target's corpus is cached between runs, so coverage +# week and on the "Run workflow" button. One scheduled run gives each target 80 minutes on every core of its runner, so the run +# as a whole adds up to more than 24 hours of fuzzing (19 targets: 25.3 hours of wall-clock time; issue #48). Each target's corpus is cached between runs, so coverage # accumulates. Findings fail the job and are uploaded with a replay of each. See .github/workflows/README.md and # tests/Broadside.Fuzz/README.md ("Real fuzzing"). name: Fuzz @@ -13,7 +13,7 @@ on: inputs: minutes: description: Minutes of fuzzing per target (each job must stay under GitHub's 6-hour limit, so at most 300) - default: "75" + default: "80" targets: description: Space-separated targets to fuzz (empty = every target from --list) default: "" @@ -61,7 +61,7 @@ jobs: shell: bash env: REQUESTED: ${{ inputs.targets }} - MINUTES: ${{ inputs.minutes || '75' }} + MINUTES: ${{ inputs.minutes || '80' }} run: | all=$(dotnet artifacts/bin/Broadside.Fuzz/release/Broadside.Fuzz.dll --list) if [ -n "${REQUESTED}" ]; then @@ -127,7 +127,7 @@ jobs: uses: actions/cache@v6 with: path: corpus - key: seed-corpora-${{ env.SEED_CORPORA }}-${{ hashFiles('tools/CorpusFetcher/corpora.json') }} + key: seed-corpora-${{ hashFiles('tools/CorpusFetcher/corpora.json', '.github/workflows/fuzz.yml') }} - name: Fetch the real-world seed corpora run: dotnet run --project tools/CorpusFetcher -- --only "${SEED_CORPORA}" diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index 309113df..7abc1c8b 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -52,7 +52,7 @@ Smoke mode is a regression net, not a fuzzer: it has no coverage feedback and fi ### Scheduled runs in CI -`.github/workflows/fuzz.yml` fuzzes every target under libFuzzer once a week (Sundays 03:17 UTC) and on the "Run workflow" button, one parallel job per target: 75 minutes on every core of the runner by default (the `minutes` input changes it, up to 300; `targets` picks a subset), which adds up to more than 24 hours of fuzzing per run. Each job builds the driver from pinned source (`build-libfuzzer-dotnet.sh`), installs SharpFuzz.CommandLine, builds the harness, fetches the `pdf20examples` and `qpdf` corpora with `tools/CorpusFetcher` as extra seeds, restores the target's corpus from the previous run's cache, and runs `run-libfuzzer.sh`. Findings fail the job and are uploaded as `fuzz-findings-` with a replay of each (`.txt`); the summary job tabulates minutes, CPU-hours, executions, corpus size and findings per target. +`.github/workflows/fuzz.yml` fuzzes every target under libFuzzer once a week (Sundays 03:17 UTC) and on the "Run workflow" button, one parallel job per target: 80 minutes on every core of the runner by default (the `minutes` input changes it, up to 300; `targets` picks a subset), which adds up to more than 24 hours of fuzzing per run. Each job builds the driver from pinned source (`build-libfuzzer-dotnet.sh`), installs SharpFuzz.CommandLine, builds the harness, fetches the `pdf20examples` and `qpdf` corpora with `tools/CorpusFetcher` as extra seeds, restores the target's corpus from the previous run's cache, and runs `run-libfuzzer.sh`. Findings fail the job and are uploaded as `fuzz-findings-` with a replay of each (`.txt`); the summary job tabulates minutes, CPU-hours, executions, corpus size and findings per target. The same scripts run on any Linux machine (or a Docker container from `mcr.microsoft.com/dotnet/sdk:10.0-noble` with `clang libclang-rt-dev jq` installed): From 7b38d764425d5bb47e1bab73e6825d7b0ccd45d9 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:28:43 -0500 Subject: [PATCH 042/152] feat(actions): every action type, Next chains and trigger events, scripts and multimedia kept as data (#73) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Types every Table 201 action (ISO 32000-2 §12.6.4, §12.7.6.2-12.7.6.4) as a live view over its dictionary, adds Next chains (one level live, plus a cycle-safe EnumerateActionTree), the four additional-actions views typed by owner (§12.6.3), the catalog's OpenAction, AA and URI Base, page AA and the name dictionary's document-level scripts. File entries use #76's PdfFileSpecification; SetOCGState applies to a PdfOptionalContentState snapshot. JavaScript, Rendition, Sound, Movie, GoTo3DView and RichMediaExecute are exposed as data, never performed (ActionOutOfScope, Information). Views never write: actions-preserved.pdf saves byte-identically after every action is read. New corpus files actions-all.pdf and actions-preserved.pdf; DocumentWalker and the document fuzz target walk every action; conformance rows 12.6.1-12.6.4 and 12.7.6.x. Co-Authored-By: Claude Opus 5.5 --- docs/conformance/iso-32000-2.md | 22 +- src/Broadside/PdfAction.cs | 32 ++- src/Broadside/PdfActionEnums.cs | 146 +++++++++++ src/Broadside/PdfActionTarget.cs | 68 +++++ src/Broadside/PdfAdditionalActions.cs | 209 +++++++++++++++ src/Broadside/PdfDocument.Actions.cs | 123 +++++++++ src/Broadside/PdfEmbeddedGoToAction.cs | 52 ++++ src/Broadside/PdfEmbeddedTarget.cs | 92 +++++++ src/Broadside/PdfFormActions.cs | 97 +++++++ src/Broadside/PdfGoTo3DViewAction.cs | 50 ++++ src/Broadside/PdfGoToAction.cs | 3 + src/Broadside/PdfGoToDocumentPartAction.cs | 29 +++ src/Broadside/PdfHideAction.cs | 37 +++ src/Broadside/PdfJavaScriptAction.cs | 41 +++ src/Broadside/PdfLaunchAction.cs | 86 +++++++ src/Broadside/PdfMovieAction.cs | 63 +++++ src/Broadside/PdfNameDictionary.cs | 42 +++ src/Broadside/PdfNamedAction.cs | 43 ++++ src/Broadside/PdfPage.cs | 5 + src/Broadside/PdfRemoteGoToAction.cs | 50 ++++ src/Broadside/PdfRenditionAction.cs | 68 +++++ src/Broadside/PdfRichMediaExecuteAction.cs | 74 ++++++ src/Broadside/PdfSetOcgStateAction.cs | 135 ++++++++++ src/Broadside/PdfSoundAction.cs | 59 +++++ src/Broadside/PdfThreadAction.cs | 73 ++++++ src/Broadside/PdfTransitionAction.cs | 29 +++ src/Broadside/PdfUnknownAction.cs | 3 + src/Broadside/PdfUriAction.cs | 85 ++++++- src/Broadside/PublicAPI.Unshipped.txt | 240 ++++++++++++++++++ tests/Broadside.Fuzz/Broadside.Fuzz.csproj | 1 + tests/Broadside.Fuzz/FuzzTargets.cs | 2 + tests/Broadside.Fuzz/README.md | 2 +- tests/Broadside.TestSupport/ActionWalker.cs | 172 +++++++++++++ tests/Broadside.TestSupport/DocumentWalker.cs | 3 +- .../Actions/ActionEntryTests.cs | 216 ++++++++++++++++ .../Actions/ActionTypeTests.cs | 2 +- .../Actions/MalformedActionTests.cs | 150 +++++++++++ .../Actions/PreservedActionTests.cs | 114 +++++++++ .../Actions/TriggerEventTests.cs | 174 +++++++++++++ ...histograms_match_the_snapshot.verified.txt | 16 +- .../LogicalStructure/StructureCorpusTests.cs | 1 + ...pus_file_names_match_snapshot.verified.txt | 2 + tests/Corpus/actions-all.pdf | Bin 8448 -> 8437 bytes tests/Corpus/generate.py | 2 +- 44 files changed, 2877 insertions(+), 36 deletions(-) create mode 100644 src/Broadside/PdfActionEnums.cs create mode 100644 src/Broadside/PdfActionTarget.cs create mode 100644 src/Broadside/PdfAdditionalActions.cs create mode 100644 src/Broadside/PdfDocument.Actions.cs create mode 100644 src/Broadside/PdfEmbeddedGoToAction.cs create mode 100644 src/Broadside/PdfEmbeddedTarget.cs create mode 100644 src/Broadside/PdfFormActions.cs create mode 100644 src/Broadside/PdfGoTo3DViewAction.cs create mode 100644 src/Broadside/PdfGoToDocumentPartAction.cs create mode 100644 src/Broadside/PdfHideAction.cs create mode 100644 src/Broadside/PdfJavaScriptAction.cs create mode 100644 src/Broadside/PdfLaunchAction.cs create mode 100644 src/Broadside/PdfMovieAction.cs create mode 100644 src/Broadside/PdfNamedAction.cs create mode 100644 src/Broadside/PdfRemoteGoToAction.cs create mode 100644 src/Broadside/PdfRenditionAction.cs create mode 100644 src/Broadside/PdfRichMediaExecuteAction.cs create mode 100644 src/Broadside/PdfSetOcgStateAction.cs create mode 100644 src/Broadside/PdfSoundAction.cs create mode 100644 src/Broadside/PdfThreadAction.cs create mode 100644 src/Broadside/PdfTransitionAction.cs create mode 100644 tests/Broadside.TestSupport/ActionWalker.cs create mode 100644 tests/Broadside.Tests/Actions/ActionEntryTests.cs create mode 100644 tests/Broadside.Tests/Actions/MalformedActionTests.cs create mode 100644 tests/Broadside.Tests/Actions/PreservedActionTests.cs create mode 100644 tests/Broadside.Tests/Actions/TriggerEventTests.cs diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index c2771b78..b774297f 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -47,9 +47,9 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.6.6 | Crypt filters | done | `DocumentDecryptor`, `CryptFilter`, `CryptMethod` | `Broadside.Tests.Security.CryptFilterTests.An_embedded_file_is_decrypted_with_eff_which_defaults_to_stmf`, `Broadside.Tests.Security.CryptFilterTests.Each_content_stream_decrypts_with_the_crypt_filter_it_names_or_the_default_one`, `Broadside.Tests.Security.CryptFilterTests.Metadata_is_left_as_it_is_when_encrypt_metadata_is_false`, `Broadside.Tests.Security.CryptFilterTests.The_owner_password_opens_a_document_whose_metadata_is_not_encrypted`, `Broadside.Tests.Security.CryptFilterTests.A_stream_that_names_a_crypt_filter_the_document_does_not_define_is_left_encrypted_with_a_diagnostic`, `Broadside.Tests.Security.CryptFilterTests.Metadata_in_plaintext_although_encrypt_metadata_is_true_is_read_as_it_is_with_a_diagnostic`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.An_unknown_crypt_filter_method_is_an_unsupported_algorithm` | CF, StmF, StrF, EFF (default StmF), Identity, CFM V2/AESV2/AESV3 (and AESV4, ISO/TS 32003); CFM None leaves data as is with CryptFilterMethodInvalid; AESV2 under V 5 read as AESV3 with a diagnostic; unknown CFM for StmF/StrF/EFF throws `PdfEncryptionNotSupportedException`; EncryptMetadata false leaves /Type /Metadata streams alone (plaintext XMP under EncryptMetadata true read with MetadataNotEncrypted); crypt filter Length not used (keys come from the handler); encrypted-crypt-filters.pdf | | 7.6.7 | Unencrypted wrapper document | not started | | | Collections of encrypted payloads (PDF 2.0); a wrapper opens as an ordinary unencrypted document | | 7.7.1 | General | n/a | | | Introductory text | -| 7.7.2 | Document catalog dictionary | partial | `PdfDocument`, `PdfVersion`, `PdfPageLayout`, `PdfPageMode`, `DictionaryView`, `PdfNameDictionary`, `PdfOutline` | `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_catalog_version_written_as_a_number_is_read_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.A_malformed_catalog_version_is_ignored_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_catalog_without_its_type_is_read_with_a_diagnostic`, `Broadside.Tests.Document.CatalogEntryTests.Empty_page_pdf_has_the_default_layout_and_mode_and_no_viewer_preferences`, `Broadside.Tests.Document.CatalogEntryTests.Catalog_version_extensions_pdf_exposes_its_version_extensions_and_requirements`, `Broadside.Tests.Document.CatalogEntryTests.Pdf20_header_pdf_is_version_2_0_from_the_header_and_the_catalog`, `Broadside.Tests.Document.CatalogEntryTests.The_language_is_a_text_string`, `Broadside.Tests.Document.CatalogEntryTests.An_unknown_layout_mode_or_preferences_entry_reads_as_the_default_with_a_warning`, `Broadside.Tests.Document.CatalogEntryTests.Outline_pdf_opens_with_the_outline_visible`, `Broadside.Tests.Document.CatalogEntryTests.Reading_every_catalog_entry_changes_nothing`, `Broadside.Tests.Navigation.NameTreeTests.Name_tree_dests_pdf_maps_its_three_keys_to_their_destination_arrays_with_no_diagnostics`, `Broadside.Tests.Navigation.OutlineTests.Outline_pdf_yields_two_closed_leaf_items_with_their_destinations_and_default_style` | Type, Version (effective version = later of header and catalog; `HeaderVersion`, `CatalogVersion`), Pages, PageLabels (12.4.2), ViewerPreferences (12.2), PageLayout, PageMode, Metadata (14.3.2), Lang, Extensions (7.12), Requirements (12.11) (#69); the other Table 29 entries arrive with their features (outlines, names, AcroForm, ...); Names (`PdfDocument.Names`), Dests (named destinations) and Outlines (`PdfDocument.Outline`) since #70 | +| 7.7.2 | Document catalog dictionary | partial | `PdfDocument`, `PdfVersion`, `PdfPageLayout`, `PdfPageMode`, `DictionaryView`, `PdfNameDictionary`, `PdfOutline`, `PdfDocumentAdditionalActions` | `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_catalog_version_written_as_a_number_is_read_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.A_malformed_catalog_version_is_ignored_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_catalog_without_its_type_is_read_with_a_diagnostic`, `Broadside.Tests.Document.CatalogEntryTests.Empty_page_pdf_has_the_default_layout_and_mode_and_no_viewer_preferences`, `Broadside.Tests.Document.CatalogEntryTests.Catalog_version_extensions_pdf_exposes_its_version_extensions_and_requirements`, `Broadside.Tests.Document.CatalogEntryTests.Pdf20_header_pdf_is_version_2_0_from_the_header_and_the_catalog`, `Broadside.Tests.Document.CatalogEntryTests.The_language_is_a_text_string`, `Broadside.Tests.Document.CatalogEntryTests.An_unknown_layout_mode_or_preferences_entry_reads_as_the_default_with_a_warning`, `Broadside.Tests.Document.CatalogEntryTests.Outline_pdf_opens_with_the_outline_visible`, `Broadside.Tests.Document.CatalogEntryTests.Reading_every_catalog_entry_changes_nothing`, `Broadside.Tests.Navigation.NameTreeTests.Name_tree_dests_pdf_maps_its_three_keys_to_their_destination_arrays_with_no_diagnostics`, `Broadside.Tests.Navigation.OutlineTests.Outline_pdf_yields_two_closed_leaf_items_with_their_destinations_and_default_style`, `Broadside.Tests.Actions.TriggerEventTests.The_open_action_is_a_go_to_action_and_the_document_has_no_open_destination`, `Broadside.Tests.Actions.TriggerEventTests.An_open_action_array_is_the_open_destination`, `Broadside.Tests.Actions.TriggerEventTests.An_open_action_that_is_a_name_is_read_as_a_named_destination_with_a_warning`, `Broadside.Tests.Actions.ActionEntryTests.A_relative_uri_is_resolved_against_the_catalog_base_without_being_fetched` | Type, Version (effective version = later of header and catalog; `HeaderVersion`, `CatalogVersion`), Pages, PageLabels (12.4.2), ViewerPreferences (12.2), PageLayout, PageMode, Metadata (14.3.2), Lang, Extensions (7.12), Requirements (12.11) (#69); the other Table 29 entries arrive with their features (outlines, names, AcroForm, ...); Names (`PdfDocument.Names`), Dests (named destinations) and Outlines (`PdfDocument.Outline`) since #70; OpenAction (`PdfDocument.OpenAction` / `OpenDestination`), AA (`PdfDocument.AdditionalActions`) and URI Base (`PdfDocument.UriBase`) since #73 | | 7.7.3 | Page tree | done | `PdfPage`, `PdfPageCollection`, `PageTreeReader` | `Broadside.Tests.Document.OpenDocumentTests.Page_tree_inherited_pdf_pages_inherit_media_box_and_resources_from_the_intermediate_node`, `Broadside.Tests.Document.PageTreeTests.Pages_come_in_kids_order_depth_first_across_intermediate_nodes`, `Broadside.Tests.Document.PageTreeTests.The_nearest_ancestor_wins_and_values_are_inherited_as_is_without_merging`, `Broadside.Tests.Document.PageTreeTests.A_change_to_an_ancestor_node_shows_through_the_pages_that_inherit_from_it`, `Broadside.Tests.Document.PageTreeTests.Page_count_comes_from_the_kids_not_the_count_entry_which_is_checked`, `Broadside.Tests.Document.PageTreeTests.A_node_referenced_twice_is_read_once_with_a_diagnostic`, `Broadside.Tests.Document.PageAttributeTests.Crop_bleed_trim_and_art_boxes_default_to_the_media_box_through_the_crop_box`, `Broadside.Tests.Document.PageAttributeTests.Rotation_is_a_multiple_of_90_normalized_into_0_to_270` | 7.7.3.1 to 7.7.3.4: Kids walk with cycle guard, Count checked not trusted, Resources/MediaBox/CropBox/Rotate inherited as-is from the nearest node; page boxes, Rotate and UserUnit from Table 31; other Table 31 entries arrive with their features | -| 7.7.4 | Name dictionary | partial | `PdfNameDictionary`, `PdfDocument`, `PdfEmbeddedFileEntry` | `Broadside.Tests.Navigation.NameTreeTests.Name_tree_dests_pdf_maps_its_three_keys_to_their_destination_arrays_with_no_diagnostics`, `Broadside.Tests.Navigation.NameTreeTests.A_tree_root_that_is_not_a_dictionary_reads_as_absent_with_a_diagnostic`, `Broadside.Tests.Files.EmbeddedFileTests.The_name_dictionary_exposes_the_EmbeddedFiles_tree` | `PdfDocument.Names`; every Table 32 entry is reachable as a name tree through `PdfNameDictionary.GetTree`; `Dests` values are typed as destinations through `PdfDocument.GetNamedDestination` (12.3.2.4); EmbeddedFiles (#76) and JavaScript (#73) arrive with their features | +| 7.7.4 | Name dictionary | partial | `PdfNameDictionary`, `PdfDocument`, `PdfEmbeddedFileEntry` | `Broadside.Tests.Navigation.NameTreeTests.Name_tree_dests_pdf_maps_its_three_keys_to_their_destination_arrays_with_no_diagnostics`, `Broadside.Tests.Navigation.NameTreeTests.A_tree_root_that_is_not_a_dictionary_reads_as_absent_with_a_diagnostic`, `Broadside.Tests.Files.EmbeddedFileTests.The_name_dictionary_exposes_the_EmbeddedFiles_tree`, `Broadside.Tests.Actions.TriggerEventTests.The_name_dictionary_holds_one_document_level_script` | `PdfDocument.Names`; every Table 32 entry is reachable as a name tree through `PdfNameDictionary.GetTree`; `Dests` values are typed as destinations through `PdfDocument.GetNamedDestination` (12.3.2.4); EmbeddedFiles typed by #76; JavaScript typed as `PdfJavaScriptAction` values (`PdfNameDictionary.JavaScript`, `JavaScriptActions`, #73); the other trees arrive with their features | | 7.8.1 | General | n/a | | | Introductory text: content streams and resource dictionaries are specified in 7.8.2 and 7.8.3 | | 7.8.2 | Content streams | done | `ContentReader`, `OperandArena`, `OperatorTable`, `ContentInterpreter`, `ContentProcessor`, `ContentOperator`, `ContentOperand`, `ContentOperands`, `ContentOperatorCode`, `PdfPage` | `Broadside.Tests.Content.ContentSyntaxTests`, `Broadside.Tests.Content.CorpusContentTests`, `Broadside.Tests.Content.ContentRunTests.A_contents_array_reads_as_its_parts_joined_by_white_space`, `Broadside.Tests.Content.ContentRunTests.A_contents_array_element_that_is_not_a_stream_is_skipped`, `Broadside.Tests.Content.ContentAllocationTests` | Issue #55. Operands are read in place (no object per operand, no string per keyword; zero allocation proven by `ContentAllocationTests` and `bench/Broadside.Benchmarks/ContentLexerBenchmarks.cs`); all 73 operators of Annex A recognised; glued keywords (`q1`, `0cm`, `Qq`) split when they decompose wholly into operators and numbers (`ContentGluedTokens`, Information); Table 33 BX/EX nest and silence unknown operators; outside them an unknown operator and its operands are ignored (`ContentUnknownOperator`); too few operands or wrong types skip the operator, too many use the last ones, leftovers at the end are dropped (`ContentOperandCount`, `ContentOperandType`); an inline image is read whole (BI dictionary, data to EI by L/Length or the pdf.js heuristic) and never tokenized. A Contents array is one stream with a line feed between parts (Table 31). Fuzz targets `content-lexer`, `content-interpreter`; `document` now runs every page. | | 7.8.3 | Resource dictionaries | partial | `ContentContext` | `Broadside.Tests.Content.ContentRunTests.The_context_describes_the_page_run` | The page's (inherited) Resources are the run's `ContentContext.Resources`; looking names up in ExtGState, Font, XObject, Properties (#56), ColorSpace (#77), Pattern and Shading (#79) arrives with those operators; forms without Resources inheriting the page's is #56. | @@ -153,8 +153,22 @@ Clause numbers at the second level; split rows to the third level as clauses are | 12.4.3 | Articles | not started | | | | | 12.4.4 | Presentations | not started | | | | | 12.5 | Annotations | not started | | | | -| 12.6 | Actions | partial | `PdfAction`, `PdfGoToAction`, `PdfUriAction`, `PdfUnknownAction` | `Broadside.Tests.Navigation.OutlineTests.Outline_full_pdf_yields_three_levels_with_open_and_closed_items_styles_and_actions`, `Broadside.Tests.Navigation.OutlineTests.Malformed_item_entries_read_as_their_defaults_with_a_diagnostic` | Minimal base (#70): Table 196 S, go-to (Table 202: D, SD) and URI (Table 210: URI as UTF-8, IsMap) actions; every other type is `PdfUnknownAction`, preserved; `ActionInvalid` for a missing S, D or URI. #73 adds the other types, Next chains and trigger events | -| 12.7 | Forms | not started | | | | +| 12.6.1 | General | n/a | | | Introductory text; the A entries it lists are read by `PdfOutlineItem.Action` and `PdfDocument.GetAction` (link, screen and widget annotations until #71/#74 type them) | +| 12.6.2 | Action dictionaries | done | `PdfAction`, `PdfActionKind`, `PdfUnknownAction` | `Broadside.Tests.Actions.ActionTypeTests.Actions_all_pdf_types_each_table_201_action_in_table_order`, `Broadside.Tests.Actions.ActionTypeTests.An_action_type_the_table_does_not_list_is_kept_as_an_unknown_action`, `Broadside.Tests.Actions.TriggerEventTests.The_action_tree_is_walked_depth_first_in_execution_order`, `Broadside.Tests.Actions.TriggerEventTests.A_cycle_of_next_actions_is_cut_with_information_and_a_shared_action_is_yielded_once`, `Broadside.Tests.Actions.TriggerEventTests.A_next_entry_with_elements_that_are_not_actions_skips_them_with_a_warning`, `Broadside.Tests.Actions.PreservedActionTests.Reading_every_action_changes_no_object` | Table 196: S (missing -> `ActionInvalid`, unknown -> `PdfUnknownAction`), Next as one dictionary or an array (`PdfAction.Next`, one level, live; bad elements `ActionNextInvalid`); `EnumerateActionTree` walks the tree depth first in execution order, iteratively, each dictionary once, cycles cut with `ActionCycle` (Information: Note 1 calls them anomalous, not invalid), depth cap 64 (`ActionTreeTooDeep`). Type Action is optional and never added | +| 12.6.3 | Trigger events | done | `PdfAdditionalActions`, `PdfAnnotationAdditionalActions`, `PdfPageAdditionalActions`, `PdfFieldAdditionalActions`, `PdfDocumentAdditionalActions` | `Broadside.Tests.Actions.TriggerEventTests.The_catalog_page_annotation_and_field_triggers_are_typed_by_their_owner`, `Broadside.Tests.Actions.TriggerEventTests.An_additional_actions_entry_that_is_not_a_dictionary_reads_as_none_with_a_warning`, `Broadside.Tests.Actions.TriggerEventTests.Documents_without_actions_have_no_open_action_and_no_additional_actions` | Tables 197-200 typed by owner (C is close for a page, calculate for a field); catalog `PdfDocument.AdditionalActions` and `PdfPage.AdditionalActions`; annotation and field AA through `PdfDocument.GetAnnotationAdditionalActions` / `GetFieldAdditionalActions` until #71/#74 wire their views; `Actions` lists unknown triggers too. Never created on read. Event ordering is viewer behaviour, documented only | +| 12.6.4 | Action types | done | `PdfActionKind`, `PdfGoToAction`, `PdfRemoteGoToAction`, `PdfEmbeddedGoToAction`, `PdfEmbeddedTarget`, `PdfGoToDocumentPartAction`, `PdfLaunchAction`, `PdfWindowsLaunchParameters`, `PdfThreadAction`, `PdfUriAction`, `PdfSoundAction`, `PdfMovieAction`, `PdfHideAction`, `PdfActionTarget`, `PdfNamedAction`, `PdfSetOcgStateAction`, `PdfOcgStateChange`, `PdfRenditionAction`, `PdfTransitionAction`, `PdfGoTo3DViewAction`, `PdfJavaScriptAction`, `PdfRichMediaExecuteAction`, `PdfRichMediaCommand` | `Broadside.Tests.Actions.ActionEntryTests.Go_to_actions_read_their_local_remote_and_embedded_destinations`, `Broadside.Tests.Actions.ActionEntryTests.Launch_and_thread_actions_read_their_files_platform_parameters_and_article_indexes`, `Broadside.Tests.Actions.ActionEntryTests.A_relative_uri_is_resolved_against_the_catalog_base_without_being_fetched`, `Broadside.Tests.Actions.ActionEntryTests.Multimedia_actions_are_exposed_as_data_with_their_defaults`, `Broadside.Tests.Actions.ActionEntryTests.Scripts_and_multimedia_are_recorded_as_out_of_scope_information_and_never_as_warnings`, `Broadside.Tests.Actions.ActionEntryTests.Hide_named_and_transition_actions_read_their_targets_names_and_transitions`, `Broadside.Tests.Actions.ActionEntryTests.A_set_ocg_state_action_lists_its_changes_and_applies_them_to_a_state_snapshot`, `Broadside.Tests.Actions.ActionEntryTests.A_javascript_action_reads_its_script_from_a_stream_and_is_never_run`, `Broadside.Tests.Actions.PreservedActionTests.Scripts_sounds_movies_renditions_and_rich_media_read_as_data_in_their_stored_forms`, `Broadside.Tests.Actions.PreservedActionTests.Saving_after_reading_every_action_keeps_their_bytes_and_their_values`, `Broadside.Tests.Actions.MalformedActionTests.An_action_missing_a_required_entry_is_read_with_a_warning`, `Broadside.Tests.Actions.MalformedActionTests.Entries_of_the_wrong_type_read_as_absent_or_default_with_a_warning`, `Broadside.Tests.Actions.MalformedActionTests.A_uri_that_is_not_utf8_or_not_a_string_is_read_with_a_warning`, `Broadside.Tests.Actions.MalformedActionTests.A_cycle_of_embedded_target_dictionaries_is_refused_with_a_warning`, `Broadside.Tests.Actions.MalformedActionTests.Strict_mode_throws_when_an_invalid_action_is_read_not_when_the_document_opens`, `Broadside.Tests.Actions.MalformedActionTests.Strict_mode_records_out_of_scope_scripts_without_throwing` | 12.6.4.1-12.6.4.18, every Table 201 type typed (corpus `actions-all.pdf`). Remote/embedded destinations are remote (page numbers of the other file, never resolved here); GoToE target dictionaries (Table 205) with cycle refusal (`ActionTargetCycle`); file entries are `PdfFileSpecification` (#76); SetOCGState applies to a `PdfOptionalContentState` snapshot without changing the document; URI decoded as UTF-8 with UTF-16/PDFDocEncoding/name repairs (`UriInvalid`) and `ResolveUri` against the catalog Base. Sound, Movie, Rendition, GoTo3DView, JavaScript and RichMediaExecute are typed and preserved (byte-identical save of `actions-preserved.pdf`), not executed (out of scope): `ActionOutOfScope` Information. Nothing is ever performed. Missing required entries `ActionInvalid`, wrong types `ActionEntryInvalid`, lazily at read | +| 12.7.1 | General | not started | | | | +| 12.7.2 | Interactive Forms | not started | | | | +| 12.7.3 | Interactive form dictionary | not started | | | | +| 12.7.4 | Field dictionaries | not started | | | Field AA (Table 199) is typed by `PdfDocument.GetFieldAdditionalActions` (#73, 12.6.3); #74 wires it to fields | +| 12.7.5 | Field types | not started | | | | +| 12.7.6.1 | General | n/a | | | Introductory text | +| 12.7.6.2 | Submit-form action | done | `PdfSubmitFormAction`, `PdfSubmitFormFlags`, `PdfActionTarget` | `Broadside.Tests.Actions.ActionEntryTests.Form_actions_read_their_url_fields_flags_and_character_set`, `Broadside.Tests.Actions.MalformedActionTests.An_action_missing_a_required_entry_is_read_with_a_warning` | Tables 239-240: F (URL file specification, `PdfFileSpecification.IsUrl`), Fields (field dictionaries and names; names unresolved until #74), Flags (bits 1-12 and 14), CharSet (2.0). Flags and CharSet read from the action only ("inheritable" names no parent). Never submitted | +| 12.7.6.3 | Reset-form action | done | `PdfResetFormAction`, `PdfResetFormFlags`, `PdfActionTarget` | `Broadside.Tests.Actions.ActionEntryTests.Form_actions_read_their_url_fields_flags_and_character_set`, `Broadside.Tests.Actions.MalformedActionTests.An_action_missing_a_required_entry_is_read_with_a_warning` | Tables 241-242. Never performed | +| 12.7.6.4 | Import-data action | done | `PdfImportDataAction` | `Broadside.Tests.Actions.ActionEntryTests.Form_actions_read_their_url_fields_flags_and_character_set`, `Broadside.Tests.Actions.MalformedActionTests.An_action_missing_a_required_entry_is_read_with_a_warning` | Table 243: F as `PdfFileSpecification`. Never imported | +| 12.7.7 | Named pages | not started | | | | +| 12.7.8 | Forms data format | not started | | | | +| 12.7.9 | Non-interactive forms | not started | | | | | 12.8 | Digital signatures | not started | | | | | 12.9 | Measurement properties | not started | | | | | 12.10 | Geospatial features | not started | | | | diff --git a/src/Broadside/PdfAction.cs b/src/Broadside/PdfAction.cs index 4d2ba75f..9424e71a 100644 --- a/src/Broadside/PdfAction.cs +++ b/src/Broadside/PdfAction.cs @@ -74,7 +74,7 @@ public IReadOnlyList Next case CosNull: return []; case CosDictionary: - return Create(Document, next, DiagnosticReference) is { } action ? [action] : []; + return Create(Document, next, DiagnosticReference) is { } single ? [single] : []; case CosArray array: var actions = new List(array.Count); foreach (CosObject element in array) @@ -83,9 +83,9 @@ public IReadOnlyList Next { Report(DiagnosticCodes.ActionNextInvalid, $"An element of the {ActionType.Value} action's Next array is not an action dictionary; it is skipped."); } - else if (Create(Document, element, DiagnosticReference) is { } action) + else if (Create(Document, element, DiagnosticReference) is { } following) { - actions.Add(action); + actions.Add(following); } } @@ -251,19 +251,21 @@ private protected void ReportEntry(CosName key, string expected) => } } - /// Reads a file specification entry (§7.11): a string or a dictionary, as stored after resolving; anything else reads as absent with a diagnostic. - private protected CosObject? ReadFileSpecification(CosName key) + /// Reads a file specification entry (§7.11): a string or a dictionary; anything else reads as absent with a diagnostic. + private protected PdfFileSpecification? ReadFileSpecification(CosName key) { - switch (Get(key)) + if (Get(key) is null) { - case null: - return null; - case CosString or CosDictionary and var value: - return value; - default: - ReportEntry(key, "a file specification (a string or a dictionary)"); - return null; + return null; + } + + PdfFileSpecification? file = PdfFileSpecification.Create(Document, Dictionary[key]); + if (file is null) + { + ReportEntry(key, "a file specification (a string or a dictionary)"); } + + return file; } /// Reads a text string or text stream entry (§7.9.2.2, §7.9.3), decoded; anything else reads as absent with a diagnostic. @@ -284,6 +286,10 @@ private protected void ReportEntry(CosName key, string expected) => } } + /// Reads an annotation or field target, or an array of them (Tables 214, 239, 241); when absent. + private protected List? ReadTargets(CosName key, string expected) => + Dictionary.TryGetValue(key, out CosObject? value) ? PdfActionTarget.Read(Document, value, () => ReportEntry(key, expected)) : null; + /// Reads a destination entry (§12.3.2) with the remote flag for go-to actions of other documents. private protected PdfDestination? ReadDestination(CosName key, bool isRemote) => Dictionary.TryGetValue(key, out CosObject? value) ? PdfDestination.Create(Document, value, isRemote, DiagnosticReference) : null; diff --git a/src/Broadside/PdfActionEnums.cs b/src/Broadside/PdfActionEnums.cs new file mode 100644 index 00000000..a32ed0ff --- /dev/null +++ b/src/Broadside/PdfActionEnums.cs @@ -0,0 +1,146 @@ +namespace Broadside; + +/// The relationship of an embedded go-to action's target to the current document (R). +/// ISO 32000-2 §12.6.4.4, Table 205. +public enum PdfEmbeddedTargetRelationship +{ + /// R is missing or names neither P nor C. + Unknown, + + /// P: the target is the parent of the current document. + Parent, + + /// C: the target is a child (an embedded file) of the current document. + Child, +} + +/// The operation of a movie action (Operation). +/// ISO 32000-2 §12.6.4.10, Table 213 (deprecated in PDF 2.0). Default . +public enum PdfMovieOperation +{ + /// Start playing the movie. + Play, + + /// Stop playing the movie. + Stop, + + /// Pause a playing movie. + Pause, + + /// Resume a paused movie. + Resume, +} + +/// The predefined action of a named action (N). +/// ISO 32000-2 §12.6.4.12, Table 215. Other names are allowed but not portable; an unrecognised one "shall take no action". +public enum PdfNamedOperation +{ + /// A name Table 215 does not list (see ), or none. + Other, + + /// NextPage: go to the next page. + NextPage, + + /// PrevPage: go to the previous page. + PreviousPage, + + /// FirstPage: go to the first page. + FirstPage, + + /// LastPage: go to the last page. + LastPage, +} + +/// The flags of a submit-form action (Flags); each member's value is its bit. +/// ISO 32000-2 §12.7.6.2, Table 240. Bit 13 and bits above 14 are reserved. +[Flags] +public enum PdfSubmitFormFlags +{ + /// No flag set: the default. + None = 0, + + /// Bit 1, Include/Exclude: when set, Fields lists the fields to exclude rather than include. + Exclude = 1 << 0, + + /// Bit 2, IncludeNoValueFields: submit fields that have no value too. + IncludeNoValueFields = 1 << 1, + + /// Bit 3, ExportFormat: submit in HTML form format rather than FDF. + ExportFormat = 1 << 2, + + /// Bit 4, GetMethod: submit with an HTTP GET request (HTML format only). + GetMethod = 1 << 3, + + /// Bit 5, SubmitCoordinates: submit the coordinates of the mouse click. + SubmitCoordinates = 1 << 4, + + /// Bit 6, XFDF (PDF 1.4): submit as XFDF. + Xfdf = 1 << 5, + + /// Bit 7, IncludeAppendSaves (PDF 1.4): include the incremental updates in the FDF. + IncludeAppendSaves = 1 << 6, + + /// Bit 8, IncludeAnnotations (PDF 1.4): include markup annotations in the FDF. + IncludeAnnotations = 1 << 7, + + /// Bit 9, SubmitPDF (PDF 1.4): submit the whole document as PDF. + SubmitPdf = 1 << 8, + + /// Bit 10, CanonicalFormat (PDF 1.4): submit dates in the canonical format. + CanonicalFormat = 1 << 9, + + /// Bit 11, ExclNonUserAnnots (PDF 1.4): include only the current user's markup annotations. + ExcludeNonUserAnnotations = 1 << 10, + + /// Bit 12, ExclFKey (PDF 1.4): leave out the FDF's F entry. + ExcludeFKey = 1 << 11, + + /// Bit 14, EmbedForm (PDF 1.5): embed the PDF file in the FDF's F entry. + EmbedForm = 1 << 13, +} + +/// The flags of a reset-form action (Flags); each member's value is its bit. +/// ISO 32000-2 §12.7.6.3, Table 242. +[Flags] +public enum PdfResetFormFlags +{ + /// No flag set: the default. + None = 0, + + /// Bit 1, Include/Exclude: when set, Fields lists the fields to exclude rather than reset. + Exclude = 1 << 0, +} + +/// What a set-OCG-state action does to the groups after a state name (State). +/// ISO 32000-2 §12.6.4.13, Table 217. +public enum PdfOcgStateOperation +{ + /// ON: turn the groups on. + On, + + /// OFF: turn the groups off. + Off, + + /// Toggle: reverse the groups' states. + Toggle, +} + +/// The operation of a rendition action (OP). +/// ISO 32000-2 §12.6.4.14, Table 218. +public enum PdfRenditionOperation +{ + /// 0: play the rendition R in the screen annotation AN, replacing any rendition it plays. + Play = 0, + + /// 1: stop the rendition playing in AN. + Stop = 1, + + /// 2: pause the rendition playing in AN. + Pause = 2, + + /// 3: resume the paused rendition in AN. + Resume = 3, + + /// 4: play R in AN, or resume it when it is paused. + PlayOrResume = 4, +} diff --git a/src/Broadside/PdfActionTarget.cs b/src/Broadside/PdfActionTarget.cs new file mode 100644 index 00000000..46f987ec --- /dev/null +++ b/src/Broadside/PdfActionTarget.cs @@ -0,0 +1,68 @@ +using Broadside.Objects; + +namespace Broadside; + +/// +/// An annotation or form field an action applies to, given either by its dictionary or by the fully qualified name of a field: an element +/// of a hide action's T or of a form action's Fields. +/// +/// +/// ISO 32000-2 §12.6.4.11, Table 214, and §12.7.6.2-12.7.6.3, Tables 239 and 241. Field names are not resolved here: that needs the +/// field tree (§12.7.4.2). +/// +public sealed class PdfActionTarget +{ + internal PdfActionTarget(CosDictionary? dictionary, CosReference? reference, string? fieldName) + { + Dictionary = dictionary; + Reference = reference; + FieldName = fieldName; + } + + /// Gets the annotation or field dictionary, or when the target is given by name. + public CosDictionary? Dictionary { get; } + + /// Gets the indirect reference to , or . + public CosReference? Reference { get; } + + /// Gets the fully qualified field name, or when the target is given by its dictionary. + /// ISO 32000-2 §12.7.4.2. + public string? FieldName { get; } + + /// Reads a single target or an array of them; elements of another type are skipped with a diagnostic through . + internal static List Read(PdfDocument document, CosObject? value, Action invalid) + { + var targets = new List(); + if (document.Resolve(value) is CosArray array) + { + foreach (CosObject element in array) + { + Add(document, element, targets, invalid); + } + } + else if (value is not null) + { + Add(document, value, targets, invalid); + } + + return targets; + } + + private static void Add(PdfDocument document, CosObject element, List targets, Action invalid) + { + switch (document.Resolve(element)) + { + case CosDictionary dictionary: + targets.Add(new PdfActionTarget(dictionary, element as CosReference, fieldName: null)); + break; + case CosString name: + targets.Add(new PdfActionTarget(dictionary: null, reference: null, name.DecodeText())); + break; + case CosNull: + break; + default: + invalid(); + break; + } + } +} diff --git a/src/Broadside/PdfAdditionalActions.cs b/src/Broadside/PdfAdditionalActions.cs new file mode 100644 index 00000000..8ad45348 --- /dev/null +++ b/src/Broadside/PdfAdditionalActions.cs @@ -0,0 +1,209 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// An additional-actions dictionary: the actions triggered by events other than activation. A live view. +/// +/// ISO 32000-2 §12.6.3, Tables 197 to 200. The same key means different events for different owners (C is a page's close but a +/// field's calculate), so the dictionary is typed by its owner: , +/// , and . +/// lists every entry, triggers the table does not define included. Reading never writes to the dictionary. +/// +public abstract class PdfAdditionalActions +{ + private protected PdfAdditionalActions(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosReference? owner) + { + Document = document; + Dictionary = dictionary; + Reference = reference; + Owner = reference ?? owner; + } + + /// Gets the additional-actions dictionary. + /// ISO 32000-2 §12.6.3. + public CosDictionary Dictionary { get; } + + /// Gets the indirect reference to the dictionary, or when it is direct. + public CosReference? Reference { get; } + + /// Gets every trigger and its action, in dictionary order; an entry that is not an action is skipped with a diagnostic. + /// ISO 32000-2 §12.6.3. + public IReadOnlyList> Actions + { + get + { + var actions = new List>(Dictionary.Count); + foreach (KeyValuePair entry in Dictionary) + { + if (PdfAction.Create(Document, entry.Value, Owner) is { } action) + { + actions.Add(new(entry.Key, action)); + } + } + + return actions; + } + } + + private protected PdfDocument Document { get; } + + private protected CosReference? Owner { get; } + + /// Returns the action for , or when there is none. + /// The key, for example O or WC. + /// The action; when absent or, with a diagnostic, not an action dictionary. + /// ISO 32000-2 §12.6.3. + public PdfAction? GetAction(CosName trigger) + { + ArgumentNullException.ThrowIfNull(trigger); + return Dictionary.TryGetValue(trigger, out CosObject? value) ? PdfAction.Create(Document, value, Owner) : null; + } + + /// Reads an AA entry: absent or null reads as none; another type than a dictionary as none with a diagnostic. + internal static T? Create(PdfDocument document, CosObject? value, CosReference? owner, Func create) + where T : PdfAdditionalActions + { + switch (document.Resolve(value)) + { + case CosNull: + return null; + case CosDictionary dictionary: + return create(document, dictionary, value as CosReference, owner); + default: + document.DiagnosticSink.Report( + DiagnosticCodes.AdditionalActionsInvalid, + DiagnosticSeverity.Warning, + "An AA entry shall be an additional-actions dictionary; it is ignored.", + objectReference: value as CosReference ?? owner); + return null; + } + } + + private protected PdfAction? Get(string trigger) => GetAction(new CosName(trigger)); +} + +/// The additional actions of an annotation: cursor, mouse button, focus and page events. +/// ISO 32000-2 §12.6.3, Table 197 (PDF 1.2; PO, PC, PV and PI PDF 1.5). +public sealed class PdfAnnotationAdditionalActions : PdfAdditionalActions +{ + internal PdfAnnotationAdditionalActions(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosReference? owner) + : base(document, dictionary, reference, owner) + { + } + + /// Gets the action when the cursor enters the annotation's active area (E). + /// ISO 32000-2 §12.6.3, Table 197. + public PdfAction? CursorEnter => Get("E"); + + /// Gets the action when the cursor exits the annotation's active area (X). + /// ISO 32000-2 §12.6.3, Table 197. + public PdfAction? CursorExit => Get("X"); + + /// Gets the action when the mouse button is pressed inside the active area (D). + /// ISO 32000-2 §12.6.3, Table 197. + public PdfAction? MouseDown => Get("D"); + + /// Gets the action when the mouse button is released inside the active area (U); the annotation's A takes precedence over it. + /// ISO 32000-2 §12.6.3, Table 197. + public PdfAction? MouseUp => Get("U"); + + /// Gets the action when the annotation receives the input focus (Fo; widget annotations only). + /// ISO 32000-2 §12.6.3, Table 197. + public PdfAction? Focus => Get("Fo"); + + /// Gets the action when the annotation loses the input focus (Bl; widget annotations only). + /// ISO 32000-2 §12.6.3, Table 197. + public PdfAction? Blur => Get("Bl"); + + /// Gets the action when the page holding the annotation is opened (PO, PDF 1.5), after the page's own open action. + /// ISO 32000-2 §12.6.3, Table 197. + public PdfAction? PageOpen => Get("PO"); + + /// Gets the action when the page holding the annotation is closed (PC, PDF 1.5), before the page's own close action. + /// ISO 32000-2 §12.6.3, Table 197. + public PdfAction? PageClose => Get("PC"); + + /// Gets the action when the page holding the annotation becomes visible (PV, PDF 1.5). + /// ISO 32000-2 §12.6.3, Table 197. + public PdfAction? PageVisible => Get("PV"); + + /// Gets the action when the page holding the annotation is no longer visible (PI, PDF 1.5). + /// ISO 32000-2 §12.6.3, Table 197. + public PdfAction? PageInvisible => Get("PI"); +} + +/// The additional actions of a page: opening and closing it. +/// ISO 32000-2 §12.6.3, Table 198 (PDF 1.2). +public sealed class PdfPageAdditionalActions : PdfAdditionalActions +{ + internal PdfPageAdditionalActions(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosReference? owner) + : base(document, dictionary, reference, owner) + { + } + + /// Gets the action when the page is opened (O), after the document's open action. + /// ISO 32000-2 §12.6.3, Table 198. + public PdfAction? Open => Get("O"); + + /// Gets the action when the page is closed (C), before any other page is opened. + /// ISO 32000-2 §12.6.3, Table 198. + public PdfAction? Close => Get("C"); +} + +/// The additional actions of a form field: keystroke, format, validate and calculate scripts. +/// ISO 32000-2 §12.6.3, Table 199 (PDF 1.3). Not defined for button fields. +public sealed class PdfFieldAdditionalActions : PdfAdditionalActions +{ + internal PdfFieldAdditionalActions(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosReference? owner) + : base(document, dictionary, reference, owner) + { + } + + /// Gets the action when the user changes a character or a list selection (K). + /// ISO 32000-2 §12.6.3, Table 199. + public PdfAction? Keystroke => Get("K"); + + /// Gets the action before the field's value is formatted for display (F). + /// ISO 32000-2 §12.6.3, Table 199. + public PdfAction? Format => Get("F"); + + /// Gets the action when the field's value changes, to validate it (V). + /// ISO 32000-2 §12.6.3, Table 199. + public PdfAction? Validate => Get("V"); + + /// Gets the action that recalculates the field's value when another field changes (C), in the order of the form's CO. + /// ISO 32000-2 §12.6.3, Table 199, and §12.7.3, Table 224. + public PdfAction? Calculate => Get("C"); +} + +/// The additional actions of the document: before and after closing, saving and printing. +/// ISO 32000-2 §12.6.3, Table 200 (PDF 1.4). +public sealed class PdfDocumentAdditionalActions : PdfAdditionalActions +{ + internal PdfDocumentAdditionalActions(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosReference? owner) + : base(document, dictionary, reference, owner) + { + } + + /// Gets the action before the document closes (WC). + /// ISO 32000-2 §12.6.3, Table 200. + public PdfAction? WillClose => Get("WC"); + + /// Gets the action before the document is saved (WS). + /// ISO 32000-2 §12.6.3, Table 200. + public PdfAction? WillSave => Get("WS"); + + /// Gets the action after the document is saved (DS). + /// ISO 32000-2 §12.6.3, Table 200. + public PdfAction? DidSave => Get("DS"); + + /// Gets the action before the document is printed (WP). + /// ISO 32000-2 §12.6.3, Table 200. + public PdfAction? WillPrint => Get("WP"); + + /// Gets the action after the document is printed (DP). + /// ISO 32000-2 §12.6.3, Table 200. + public PdfAction? DidPrint => Get("DP"); +} diff --git a/src/Broadside/PdfDocument.Actions.cs b/src/Broadside/PdfDocument.Actions.cs new file mode 100644 index 00000000..6325dfcd --- /dev/null +++ b/src/Broadside/PdfDocument.Actions.cs @@ -0,0 +1,123 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// Actions and trigger events (issue #73): ISO 32000-2 §12.6 and the catalog's OpenAction, AA and URI entries (§7.7.2). +public sealed partial class PdfDocument +{ + private static readonly CosName UriKey = new("URI"); + + /// + /// Gets the action performed when the document is opened (OpenAction as an action dictionary), or + /// when the entry is absent or is a destination (see ). + /// + /// ISO 32000-2 §7.7.2, Table 29 (PDF 1.1), and §12.6. Read from the catalog on every call. + public PdfAction? OpenAction + { + get + { + Catalog.TryGetValue(ActionNames.OpenAction, out CosObject? entry); + return ReadOpenAction(entry) is CosDictionary ? PdfAction.Create(this, entry, CatalogReference) : null; + } + } + + /// + /// Gets the destination shown when the document is opened (OpenAction as a destination array), or + /// when the entry is absent or is an action (see ): the top of the first page. + /// + /// + /// ISO 32000-2 §7.7.2, Table 29, and §12.3.2. The entry shall be an array or a dictionary; a name or string is read as a named + /// destination with an OpenActionInvalid diagnostic, and any other value as absent with the same diagnostic. + /// + public PdfDestination? OpenDestination + { + get + { + Catalog.TryGetValue(ActionNames.OpenAction, out CosObject? entry); + return ReadOpenAction(entry) is CosArray or CosName or CosString ? PdfDestination.Create(this, entry, isRemote: false, CatalogReference) : null; + } + } + + /// Gets the document's additional actions (AA, PDF 1.4): scripts run before and after closing, saving and printing; when absent. + /// ISO 32000-2 §7.7.2, Table 29, and §12.6.3, Table 200. Read from the catalog on every call; reading never creates the entry. + public PdfDocumentAdditionalActions? AdditionalActions => + PdfAdditionalActions.Create(this, Catalog.TryGetValue(ActionNames.AA, out CosObject? aa) ? aa : null, CatalogReference, static (d, a, r, o) => new PdfDocumentAdditionalActions(d, a, r, o)); + + /// + /// Gets the base URI relative URI actions are resolved against (the catalog's URI dictionary's Base, PDF 1.1), or + /// when there is none or it is not an absolute URI (with a diagnostic). + /// + /// ISO 32000-2 §7.7.2, Table 29, and §12.6.4.8, Table 211. See . + public Uri? UriBase + { + get + { + if (Resolve(Catalog.TryGetValue(UriKey, out CosObject? entry) ? entry : null) is not CosDictionary uri || + Resolve(uri.TryGetValue(ActionNames.Base, out CosObject? value) ? value : null) is not { } baseValue || + baseValue is CosNull) + { + return null; + } + + if (baseValue is CosString text && Uri.TryCreate(PdfUriAction.DecodeUri(text.Bytes, out _), UriKind.Absolute, out Uri? result)) + { + return result; + } + + CatalogView.Report(DiagnosticCodes.CatalogEntryInvalid, "The catalog's URI dictionary's Base shall be an absolute URI string; it is ignored."); + return null; + } + } + + /// Reads an action dictionary through the typed view of its type. + /// The action dictionary, or a reference to it, from this document: an A entry, an element of Next, a value of an additional-actions dictionary. + /// The indirect object holding , for diagnostics when the action is direct. + /// + /// The action; when is absent or resolves to null, or, with an ActionInvalid + /// diagnostic, when it is not a dictionary with an S name. + /// + /// + /// ISO 32000-2 §12.6.2 and §12.6.4. The entry point for actions held by objects the document model does not type yet (link, + /// screen and widget annotations, form fields). The action's own deviations are reported now, so strict mode throws here. + /// + public PdfAction? GetAction(CosObject? value, CosReference? ownerReference = null) => PdfAction.Create(this, value, ownerReference); + + /// Reads an annotation's additional-actions dictionary (its AA entry). + /// The AA dictionary, or a reference to it. + /// The annotation, for diagnostics when the dictionary is direct. + /// The view; when absent, or, with an AdditionalActionsInvalid diagnostic, not a dictionary. + /// + /// ISO 32000-2 §12.6.3, Table 197. For a widget merged with its form field the same dictionary also holds Table 199's field triggers: + /// read it with too, since C means calculate there. + /// + public PdfAnnotationAdditionalActions? GetAnnotationAdditionalActions(CosObject? value, CosReference? ownerReference = null) => + PdfAdditionalActions.Create(this, value, ownerReference, static (d, a, r, o) => new PdfAnnotationAdditionalActions(d, a, r, o)); + + /// Reads a form field's additional-actions dictionary (its AA entry, PDF 1.3). + /// The AA dictionary, or a reference to it. + /// The field, for diagnostics when the dictionary is direct. + /// The view; when absent, or, with an AdditionalActionsInvalid diagnostic, not a dictionary. + /// ISO 32000-2 §12.6.3, Table 199. The field's own entry: AA is not inheritable (§12.7.4.1, Table 226). + public PdfFieldAdditionalActions? GetFieldAdditionalActions(CosObject? value, CosReference? ownerReference = null) => + PdfAdditionalActions.Create(this, value, ownerReference, static (d, a, r, o) => new PdfFieldAdditionalActions(d, a, r, o)); + + /// Resolves the catalog's OpenAction, reporting a value of a type Table 29 does not allow. + private CosObject ReadOpenAction(CosObject? entry) + { + CosObject value = Resolve(entry); + if (value is not (CosNull or CosArray or CosDictionary)) + { + _diagnostics.Report( + DiagnosticCodes.OpenActionInvalid, + DiagnosticSeverity.Warning, + value is CosName or CosString + ? "The catalog's OpenAction shall be a destination array or an action dictionary; it is a name or string, read as a named destination." + : "The catalog's OpenAction shall be a destination array or an action dictionary; it is ignored.", + objectReference: entry as CosReference ?? CatalogReference); + } + + return value; + } +} diff --git a/src/Broadside/PdfEmbeddedGoToAction.cs b/src/Broadside/PdfEmbeddedGoToAction.cs new file mode 100644 index 00000000..78835cf1 --- /dev/null +++ b/src/Broadside/PdfEmbeddedGoToAction.cs @@ -0,0 +1,52 @@ +using Broadside.Objects; + +namespace Broadside; + +/// An embedded go-to action: changes the view to a destination in a PDF file embedded in this one, in its parent, or in another file's hierarchy. +/// +/// ISO 32000-2 §12.6.4.4, Table 204 (PDF 1.6). is the path from this document to the target document, one +/// per step; names the target's root document when it is not this one's. The +/// destination is in the target document ( is true). The library never opens the target. +/// +public sealed class PdfEmbeddedGoToAction : PdfAction +{ + internal PdfEmbeddedGoToAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// + public override PdfActionKind Kind => PdfActionKind.GoToE; + + /// Gets the root document of the target relative to this document's root (F), or : the same root. + /// ISO 32000-2 §12.6.4.4, Table 204, and §7.11. + public PdfFileSpecification? File => ReadFileSpecification(NavigationNames.F); + + /// Gets the destination in the target document (D, required), or . + /// ISO 32000-2 §12.6.4.4, Table 204, and §12.3.2. + public PdfDestination? Destination => ReadDestination(NavigationNames.D, isRemote: true); + + /// Gets whether to open the target in a new window (NewWindow); when absent: the processor's preference. + /// ISO 32000-2 §12.6.4.4, Table 204. + public bool? NewWindow => ReadBoolean(ActionNames.NewWindow); + + /// Gets the first step of the path to the target document (T; required when F is absent), or . + /// ISO 32000-2 §12.6.4.4, Tables 204 and 205. + public PdfEmbeddedTarget? Target => ReadDictionary(ActionNames.T) is { } target + ? new PdfEmbeddedTarget(Document, target, DiagnosticReference, [Dictionary]) + : null; + + /// + private protected override void Check() + { + if (!Dictionary.ContainsKey(NavigationNames.D)) + { + Report("An embedded go-to action shall have a D entry; it has none, so it goes nowhere."); + } + + if (!Dictionary.ContainsKey(NavigationNames.F) && !Dictionary.ContainsKey(ActionNames.T)) + { + Report("An embedded go-to action without an F entry shall have a T target dictionary; it has neither."); + } + } +} diff --git a/src/Broadside/PdfEmbeddedTarget.cs b/src/Broadside/PdfEmbeddedTarget.cs new file mode 100644 index 00000000..9ccafcee --- /dev/null +++ b/src/Broadside/PdfEmbeddedTarget.cs @@ -0,0 +1,92 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// One step of an embedded go-to action's path to its target document: to the parent, or to a child embedded file. A live view over a target dictionary. +/// +/// ISO 32000-2 §12.6.4.4, Table 205. A child is found either by its name in the EmbeddedFiles name tree +/// () or through a file attachment annotation ( or , with +/// or ). "It is an error for a target dictionary to have an infinite cycle": +/// refuses a step that leads back to a dictionary already on the path, with an ActionTargetCycle diagnostic. +/// +public sealed class PdfEmbeddedTarget +{ + private const int MaxDepth = 64; + + private static readonly CosName P = new("P"); + private static readonly CosName A = new("A"); + + private readonly PdfDocument _document; + private readonly CosReference? _owner; + private readonly CosDictionary[] _path; + + internal PdfEmbeddedTarget(PdfDocument document, CosDictionary dictionary, CosReference? owner, CosDictionary[] path) + { + _document = document; + _owner = owner; + _path = path; + Dictionary = dictionary; + } + + /// Gets the target dictionary. + /// ISO 32000-2 §12.6.4.4, Table 205. + public CosDictionary Dictionary { get; } + + /// Gets the relationship of the target to the current document (R, required). + /// ISO 32000-2 §12.6.4.4, Table 205: P parent, C child; anything else reads as . + public PdfEmbeddedTargetRelationship Relationship => (Get(ActionNames.R) as CosName)?.Value switch + { + "P" => PdfEmbeddedTargetRelationship.Parent, + "C" => PdfEmbeddedTargetRelationship.Child, + _ => PdfEmbeddedTargetRelationship.Unknown, + }; + + /// Gets the name of the child in the current document's EmbeddedFiles name tree (N), or . + /// ISO 32000-2 §12.6.4.4, Table 205: a byte string. + public CosString? EmbeddedFileName => Get(ActionNames.N) as CosString; + + /// Gets the 0-based page number of the file attachment annotation holding the child (P as an integer), or . + /// ISO 32000-2 §12.6.4.4, Table 205. + public int? PageNumber => Get(P) is CosInteger { Value: >= 0 and <= int.MaxValue } page ? (int)page.Value : null; + + /// Gets the named destination giving the page of the file attachment annotation (P as a string), or . + /// ISO 32000-2 §12.6.4.4, Table 205. + public CosString? PageName => Get(P) as CosString; + + /// Gets the 0-based index of the file attachment annotation in the page's Annots (A as an integer), or . + /// ISO 32000-2 §12.6.4.4, Table 205. + public int? AnnotationIndex => Get(A) is CosInteger { Value: >= 0 and <= int.MaxValue } index ? (int)index.Value : null; + + /// Gets the NM name of the file attachment annotation (A as a text string), or . + /// ISO 32000-2 §12.6.4.4, Table 205. + public string? AnnotationName => (Get(A) as CosString)?.DecodeText(); + + /// Gets the next step of the path (T), or when this step reaches the target document. + /// ISO 32000-2 §12.6.4.4, Table 205. A step leading back to a dictionary on the path is refused with an ActionTargetCycle diagnostic. + public PdfEmbeddedTarget? Target + { + get + { + if (Get(ActionNames.T) is not CosDictionary next) + { + return null; + } + + if (ReferenceEquals(next, Dictionary) || Array.Exists(_path, step => ReferenceEquals(step, next)) || _path.Length >= MaxDepth) + { + _document.DiagnosticSink.Report( + DiagnosticCodes.ActionTargetCycle, + DiagnosticSeverity.Warning, + "An embedded go-to action's target dictionaries form a cycle (or nest too deeply); the action shall not be performed.", + objectReference: _owner); + return null; + } + + return new PdfEmbeddedTarget(_document, next, _owner, [.. _path, Dictionary]); + } + } + + private CosObject? Get(CosName key) => Dictionary.TryGetValue(key, out CosObject? value) ? _document.Resolve(value) : null; +} diff --git a/src/Broadside/PdfFormActions.cs b/src/Broadside/PdfFormActions.cs new file mode 100644 index 00000000..830e9d0d --- /dev/null +++ b/src/Broadside/PdfFormActions.cs @@ -0,0 +1,97 @@ +using Broadside.Objects; + +namespace Broadside; + +/// A submit-form action: sends the values of interactive form fields to a URL. The library never submits anything. +/// +/// ISO 32000-2 §12.7.6.2, Tables 239 and 240 (PDF 1.2). Table 239 marks Flags and CharSet "inheritable" without saying +/// from where; they are read from the action dictionary only. +/// +public sealed class PdfSubmitFormAction : PdfAction +{ + internal PdfSubmitFormAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// + public override PdfActionKind Kind => PdfActionKind.SubmitForm; + + /// Gets the URL to submit to (F, required; a URL file specification, §7.11.5), or . + /// ISO 32000-2 §12.7.6.2, Table 239. The URL is untrusted data from the document. + public PdfFileSpecification? File => ReadFileSpecification(NavigationNames.F); + + /// + /// Gets the fields to include or, with , exclude (Fields): field dictionaries and + /// (PDF 1.3) fully qualified field names; when absent: every field. + /// + /// ISO 32000-2 §12.7.6.2, Table 239. + public IReadOnlyList? Fields => ReadTargets(ActionNames.Fields, "an array of field dictionaries and text strings"); + + /// Gets the flags (Flags); when absent. + /// ISO 32000-2 §12.7.6.2, Tables 239 and 240. Reserved bits are kept as they are. + public PdfSubmitFormFlags Flags => (PdfSubmitFormFlags)(ReadInteger(ActionNames.Flags) ?? 0); + + /// Gets the character set of the submitted data (CharSet, PDF 2.0), such as utf-8, or . + /// ISO 32000-2 §12.7.6.2, Table 239: utf-8, utf-16, Shift-JIS, BigFive, GBK or UHC are supported values. + public string? CharacterSet => ReadString(ActionNames.CharSet) is { } charSet ? System.Text.Encoding.Latin1.GetString(charSet.Bytes) : null; + + /// + private protected override void Check() + { + if (!Dictionary.ContainsKey(NavigationNames.F)) + { + Report("A submit-form action shall have an F entry giving the URL; it has none, so it submits nowhere."); + } + } +} + +/// A reset-form action: resets interactive form fields to their default values. +/// ISO 32000-2 §12.7.6.3, Tables 241 and 242 (PDF 1.2). +public sealed class PdfResetFormAction : PdfAction +{ + internal PdfResetFormAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// + public override PdfActionKind Kind => PdfActionKind.ResetForm; + + /// + /// Gets the fields to reset or, with , not to reset (Fields): field dictionaries and + /// fully qualified field names; when absent: every field. + /// + /// ISO 32000-2 §12.7.6.3, Table 241. + public IReadOnlyList? Fields => ReadTargets(ActionNames.Fields, "an array of field dictionaries and text strings"); + + /// Gets the flags (Flags); when absent. + /// ISO 32000-2 §12.7.6.3, Tables 241 and 242. + public PdfResetFormFlags Flags => (PdfResetFormFlags)(ReadInteger(ActionNames.Flags) ?? 0); +} + +/// An import-data action: imports field values from a file (FDF, XFDF or another format). The library never imports anything. +/// ISO 32000-2 §12.7.6.4, Table 243 (PDF 1.2). +public sealed class PdfImportDataAction : PdfAction +{ + internal PdfImportDataAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// + public override PdfActionKind Kind => PdfActionKind.ImportData; + + /// Gets the file to import from (F, required), or . + /// ISO 32000-2 §12.7.6.4, Table 243, and §7.11. The file name is untrusted data from the document. + public PdfFileSpecification? File => ReadFileSpecification(NavigationNames.F); + + /// + private protected override void Check() + { + if (!Dictionary.ContainsKey(NavigationNames.F)) + { + Report("An import-data action shall have an F entry naming the file; it has none."); + } + } +} diff --git a/src/Broadside/PdfGoTo3DViewAction.cs b/src/Broadside/PdfGoTo3DViewAction.cs new file mode 100644 index 00000000..1c1a6f5b --- /dev/null +++ b/src/Broadside/PdfGoTo3DViewAction.cs @@ -0,0 +1,50 @@ +using Broadside.Objects; + +namespace Broadside; + +/// A go-to-3D-view action: sets the view of a 3D annotation. Kept as data; 3D artwork is out of scope. +/// ISO 32000-2 §12.6.4.16, Table 220 (PDF 1.6), and §13.6 (3D artwork, exposed raw). +public sealed class PdfGoTo3DViewAction : PdfAction +{ + internal PdfGoTo3DViewAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// + public override PdfActionKind Kind => PdfActionKind.GoTo3DView; + + /// Gets the 3D annotation whose view to set (TA, required), or . + /// ISO 32000-2 §12.6.4.16, Table 220. + public CosDictionary? Annotation => ReadDictionary(ActionNames.TA); + + /// Gets the view (V, required) as stored: a 3D view dictionary, an index, a view name or a keyword name; when absent. + /// ISO 32000-2 §12.6.4.16, Table 220. + public CosObject? View => Get(ActionNames.V); + + /// Gets the 3D view dictionary when V is one, else . + /// ISO 32000-2 §12.6.4.16, Table 220, and §13.6.4, Table 315. + public CosDictionary? ViewDictionary => View as CosDictionary; + + /// Gets the index into the 3D stream's VA array when V is an integer, else . + /// ISO 32000-2 §12.6.4.16, Table 220. + public int? ViewIndex => View is CosInteger { Value: >= 0 and <= int.MaxValue } index ? (int)index.Value : null; + + /// Gets the view's internal name (its IN entry) when V is a text string, else . + /// ISO 32000-2 §12.6.4.16, Table 220. + public string? ViewName => (View as CosString)?.DecodeText(); + + /// Gets the keyword when V is a name: F first, L last, N next, P previous or D default; else . + /// ISO 32000-2 §12.6.4.16, Table 220. + public CosName? ViewKeyword => View as CosName; + + /// + private protected override void Check() + { + ReportOutOfScope("3D artwork"); + if (!Dictionary.ContainsKey(ActionNames.TA) || !Dictionary.ContainsKey(ActionNames.V)) + { + Report("A go-to-3D-view action shall have a TA and a V entry; it lacks one, so it does nothing."); + } + } +} diff --git a/src/Broadside/PdfGoToAction.cs b/src/Broadside/PdfGoToAction.cs index bd842b1b..7a720f93 100644 --- a/src/Broadside/PdfGoToAction.cs +++ b/src/Broadside/PdfGoToAction.cs @@ -11,6 +11,9 @@ internal PdfGoToAction(PdfDocument document, CosDictionary dictionary, CosRefere { } + /// + public override PdfActionKind Kind => PdfActionKind.GoTo; + /// Gets the destination to show, the D entry: explicit or named; when absent or invalid. /// ISO 32000-2 §12.6.4.2, Table 202, and §12.3.2. public PdfDestination? Destination => diff --git a/src/Broadside/PdfGoToDocumentPartAction.cs b/src/Broadside/PdfGoToDocumentPartAction.cs new file mode 100644 index 00000000..af467881 --- /dev/null +++ b/src/Broadside/PdfGoToDocumentPartAction.cs @@ -0,0 +1,29 @@ +using Broadside.Objects; + +namespace Broadside; + +/// A go-to-document-part action: changes the view to the start page of a document part (DPart). +/// ISO 32000-2 §12.6.4.5, Table 206 (PDF 2.0), and §14.12 (document parts, exposed raw). +public sealed class PdfGoToDocumentPartAction : PdfAction +{ + internal PdfGoToDocumentPartAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// + public override PdfActionKind Kind => PdfActionKind.GoToDp; + + /// Gets the DPart dictionary to go to (Dp, required, an indirect reference), or . + /// ISO 32000-2 §12.6.4.5, Table 206, and §14.12, Table 409. + public CosDictionary? DocumentPart => ReadDictionary(ActionNames.Dp); + + /// + private protected override void Check() + { + if (!Dictionary.ContainsKey(ActionNames.Dp)) + { + Report("A GoToDp action shall have a Dp entry naming a DPart; it has none, so it goes nowhere."); + } + } +} diff --git a/src/Broadside/PdfHideAction.cs b/src/Broadside/PdfHideAction.cs new file mode 100644 index 00000000..b733adf4 --- /dev/null +++ b/src/Broadside/PdfHideAction.cs @@ -0,0 +1,37 @@ +using Broadside.Objects; + +namespace Broadside; + +/// A hide action: hides or shows annotations by setting or clearing their Hidden flags. +/// ISO 32000-2 §12.6.4.11, Table 214 (PDF 1.2). +public sealed class PdfHideAction : PdfAction +{ + internal PdfHideAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// + public override PdfActionKind Kind => PdfActionKind.Hide; + + /// + /// Gets the annotations to hide or show (T, required): annotation dictionaries, and fully qualified field names whose widget + /// annotations are meant. A single target reads as a list of one; an element of another type is skipped with a diagnostic. + /// + /// ISO 32000-2 §12.6.4.11, Table 214. + public IReadOnlyList Targets => + ReadTargets(ActionNames.T, "an annotation dictionary, a text string or an array of them") ?? []; + + /// Gets whether to hide (, the default) or show () the annotations (H). + /// ISO 32000-2 §12.6.4.11, Table 214. + public bool Hide => ReadBoolean(ActionNames.H) ?? true; + + /// + private protected override void Check() + { + if (!Dictionary.ContainsKey(ActionNames.T)) + { + Report("A hide action shall have a T entry naming the annotations; it has none."); + } + } +} diff --git a/src/Broadside/PdfJavaScriptAction.cs b/src/Broadside/PdfJavaScriptAction.cs new file mode 100644 index 00000000..acccd651 --- /dev/null +++ b/src/Broadside/PdfJavaScriptAction.cs @@ -0,0 +1,41 @@ +using Broadside.Objects; + +namespace Broadside; + +/// An ECMAScript (JavaScript) action: a script to run. Kept as data; the library never runs scripts and has no script engine. +/// +/// ISO 32000-2 §12.6.4.17, Table 221 (PDF 1.3). The type is named JavaScript in files although the specification calls the +/// language ECMAScript; a name written with an escape such as /Java#53cript is the same name (§7.3.5). Document-level scripts +/// are in the name dictionary's JavaScript tree (). +/// +public sealed class PdfJavaScriptAction : PdfAction +{ + internal PdfJavaScriptAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// + public override PdfActionKind Kind => PdfActionKind.JavaScript; + + /// Gets the script (JS, required), decoded from its text string or text stream, or . Never run. + /// + /// ISO 32000-2 §12.6.4.17, Table 221, and §7.9.2.2: a byte order mark selects UTF-16BE or UTF-8, else PDFDocEncoding. A stream is + /// decoded through its filters into new memory; the stream is not changed. The raw value is . + /// + public string? Script => ReadScript(ActionNames.JS); + + /// Gets the JS entry as stored (resolved): a string or a stream; when absent. + /// ISO 32000-2 §12.6.4.17, Table 221. + public CosObject? ScriptObject => Get(ActionNames.JS); + + /// + private protected override void Check() + { + ReportOutOfScope("ECMAScript"); + if (!Dictionary.ContainsKey(ActionNames.JS)) + { + Report("An ECMAScript action shall have a JS entry; it has none."); + } + } +} diff --git a/src/Broadside/PdfLaunchAction.cs b/src/Broadside/PdfLaunchAction.cs new file mode 100644 index 00000000..912e272f --- /dev/null +++ b/src/Broadside/PdfLaunchAction.cs @@ -0,0 +1,86 @@ +using Broadside.Objects; + +namespace Broadside; + +/// A launch action: launches an application or opens or prints a document. The library never launches anything. +/// +/// ISO 32000-2 §12.6.4.6, Table 207 (PDF 1.1). The file names are untrusted data from the document. The platform entries +/// Win, Mac and Unix are deprecated in PDF 2.0; reading them is not a deviation. +/// +public sealed class PdfLaunchAction : PdfAction +{ + internal PdfLaunchAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// + public override PdfActionKind Kind => PdfActionKind.Launch; + + /// Gets the application to launch or the document to open or print (F; required unless Win, Mac or Unix is present). + /// ISO 32000-2 §12.6.4.6, Table 207, and §7.11. + public PdfFileSpecification? File => ReadFileSpecification(NavigationNames.F); + + /// Gets the Microsoft Windows launch parameters (Win; deprecated in PDF 2.0), or . + /// ISO 32000-2 §12.6.4.6, Tables 207 and 208. + public PdfWindowsLaunchParameters? Windows => ReadDictionary(ActionNames.Win) is { } win ? new PdfWindowsLaunchParameters(Document, win) : null; + + /// Gets the Mac OS launch parameters (Mac; deprecated in PDF 2.0, never defined), as stored, or . + /// ISO 32000-2 §12.6.4.6, Table 207. + public CosObject? Mac => Get(ActionNames.Mac); + + /// Gets the UNIX launch parameters (Unix; deprecated in PDF 2.0, never defined), as stored, or . + /// ISO 32000-2 §12.6.4.6, Table 207. + public CosObject? Unix => Get(ActionNames.Unix); + + /// Gets whether to open a PDF document in a new window (NewWindow, PDF 1.2); when absent: the processor's preference. + /// ISO 32000-2 §12.6.4.6, Table 207. + public bool? NewWindow => ReadBoolean(ActionNames.NewWindow); + + /// + private protected override void Check() + { + if (!Dictionary.ContainsKey(NavigationNames.F) && !Dictionary.ContainsKey(ActionNames.Win) && + !Dictionary.ContainsKey(ActionNames.Mac) && !Dictionary.ContainsKey(ActionNames.Unix)) + { + Report("A launch action shall have an F entry when it has no Win, Mac or Unix entry; it has none of them, so it does nothing."); + } + } +} + +/// The Microsoft Windows parameters of a launch action (Win, deprecated in PDF 2.0). A live view. +/// ISO 32000-2 §12.6.4.6, Table 208. Every value is untrusted data from the document. +public sealed class PdfWindowsLaunchParameters +{ + private static readonly CosName P = new("P"); + + private readonly PdfDocument _document; + + internal PdfWindowsLaunchParameters(PdfDocument document, CosDictionary dictionary) + { + _document = document; + Dictionary = dictionary; + } + + /// Gets the parameter dictionary. + /// ISO 32000-2 §12.6.4.6, Table 208. + public CosDictionary Dictionary { get; } + + /// Gets the file name of the application or document (F, required; a byte string, not a file specification), or . + /// ISO 32000-2 §12.6.4.6, Table 208. + public CosString? FileName => Get(NavigationNames.F) as CosString; + + /// Gets the default directory (D), or . + /// ISO 32000-2 §12.6.4.6, Table 208. + public CosString? DefaultDirectory => Get(NavigationNames.D) as CosString; + + /// Gets the operation (O): open or print; open when absent. + /// ISO 32000-2 §12.6.4.6, Table 208: an ASCII string, default open. + public string Operation => Get(ActionNames.O) is CosString operation ? System.Text.Encoding.Latin1.GetString(operation.Bytes) : "open"; + + /// Gets the parameters passed to the application (P), or . + /// ISO 32000-2 §12.6.4.6, Table 208. + public CosString? Parameters => Get(P) as CosString; + + private CosObject? Get(CosName key) => Dictionary.TryGetValue(key, out CosObject? value) ? _document.Resolve(value) : null; +} diff --git a/src/Broadside/PdfMovieAction.cs b/src/Broadside/PdfMovieAction.cs new file mode 100644 index 00000000..01d783d9 --- /dev/null +++ b/src/Broadside/PdfMovieAction.cs @@ -0,0 +1,63 @@ +using Broadside.Objects; + +namespace Broadside; + +/// A movie action: plays, stops, pauses or resumes a movie. Kept as data; the library never plays anything. +/// +/// ISO 32000-2 §12.6.4.10, Table 213 (PDF 1.2; deprecated in PDF 2.0). The dictionary may also hold the entries of a movie activation +/// dictionary (Table 307: Start, Duration, Rate, Volume, ShowControls, Mode, Synchronous, FWScale, FWPosition), which override those of +/// the movie annotation; they are reachable through . +/// +public sealed class PdfMovieAction : PdfAction +{ + internal PdfMovieAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// + public override PdfActionKind Kind => PdfActionKind.Movie; + + /// Gets the movie annotation whose movie to play (Annotation, an indirect reference), or . + /// ISO 32000-2 §12.6.4.10, Table 213. Either this or identifies the movie, not both. + public CosDictionary? Annotation => ReadDictionary(ActionNames.Annotation); + + /// Gets the title of the movie annotation whose movie to play (T), or . + /// ISO 32000-2 §12.6.4.10, Table 213. + public string? Title => ReadText(ActionNames.T); + + /// Gets the operation (Operation); when absent or unknown (an unknown name with a diagnostic). + /// ISO 32000-2 §12.6.4.10, Table 213. + public PdfMovieOperation Operation + { + get + { + switch (ReadName(ActionNames.Operation)?.Value) + { + case null or "Play": + return PdfMovieOperation.Play; + case "Stop": + return PdfMovieOperation.Stop; + case "Pause": + return PdfMovieOperation.Pause; + case "Resume": + return PdfMovieOperation.Resume; + default: + ReportEntry(ActionNames.Operation, "Play, Stop, Pause or Resume"); + return PdfMovieOperation.Play; + } + } + } + + /// + private protected override void Check() + { + ReportOutOfScope("movie playback"); + bool annotation = Dictionary.ContainsKey(ActionNames.Annotation); + bool title = Dictionary.ContainsKey(ActionNames.T); + if (annotation == title) + { + Report("A movie action shall have either an Annotation or a T entry, but not both."); + } + } +} diff --git a/src/Broadside/PdfNameDictionary.cs b/src/Broadside/PdfNameDictionary.cs index 09e56d28..41e2249b 100644 --- a/src/Broadside/PdfNameDictionary.cs +++ b/src/Broadside/PdfNameDictionary.cs @@ -1,4 +1,6 @@ +using Broadside.Diagnostics; using Broadside.Objects; +using Broadside.Parsing; namespace Broadside; @@ -34,6 +36,46 @@ internal PdfNameDictionary(PdfDocument document, CosDictionary dictionary) /// ISO 32000-2 §7.7.4, Table 32 (PDF 1.4), and §7.11.4. lists it typed. public PdfNameTree? EmbeddedFiles => GetTree(FileAndLayerNames.EmbeddedFiles); + /// Gets the tree of document-level ECMAScript actions (JavaScript, PDF 1.3), or when there is none. + /// ISO 32000-2 §7.7.4, Table 32, and §12.6.4.17: the actions a processor runs when the document opens; the names are arbitrary. See . + public PdfNameTree? JavaScript => GetTree(ActionNames.JavaScript); + + /// + /// Gets the document-level ECMAScript actions of the JavaScript tree, in key order. Never run. A value that is not an + /// ECMAScript action is skipped with a diagnostic. + /// + /// ISO 32000-2 §7.7.4, Table 32, and §12.6.4.17. A fresh walk of the tree on every call. + public IReadOnlyList> JavaScriptActions + { + get + { + var actions = new List>(); + if (JavaScript is not { } tree) + { + return actions; + } + + foreach (KeyValuePair entry in tree) + { + switch (PdfAction.Create(_document, entry.Value, tree.RootReference)) + { + case PdfJavaScriptAction script: + actions.Add(new(entry.Key, script)); + break; + case { } other: + _document.DiagnosticSink.Report( + DiagnosticCodes.ActionEntryInvalid, + DiagnosticSeverity.Warning, + $"A value of the name dictionary's JavaScript tree shall be an ECMAScript action; it is a {other.ActionType.Value} action, skipped.", + objectReference: other.Reference ?? tree.RootReference); + break; + } + } + + return actions; + } + } + /// Gets the name tree under , or when the entry is absent. /// The entry, for example EmbeddedFiles or JavaScript. /// The tree, read lazily; when the entry is absent or is not a dictionary (with a diagnostic). diff --git a/src/Broadside/PdfNamedAction.cs b/src/Broadside/PdfNamedAction.cs new file mode 100644 index 00000000..bd9b781e --- /dev/null +++ b/src/Broadside/PdfNamedAction.cs @@ -0,0 +1,43 @@ +using Broadside.Objects; + +namespace Broadside; + +/// A named action: one of the predefined actions such as going to the next page. +/// +/// ISO 32000-2 §12.6.4.12, Tables 215 and 216 (PDF 1.2). Names Table 215 does not list are allowed (not portable): they read as +/// without a diagnostic, and a processor that does not recognise one "shall take no action". +/// +public sealed class PdfNamedAction : PdfAction +{ + internal PdfNamedAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// + public override PdfActionKind Kind => PdfActionKind.Named; + + /// Gets the name of the action (N, required), or . + /// ISO 32000-2 §12.6.4.12, Table 216. + public CosName? Name => ReadName(ActionNames.N); + + /// Gets the predefined action names, or . + /// ISO 32000-2 §12.6.4.12, Table 215. + public PdfNamedOperation Operation => Name?.Value switch + { + "NextPage" => PdfNamedOperation.NextPage, + "PrevPage" => PdfNamedOperation.PreviousPage, + "FirstPage" => PdfNamedOperation.FirstPage, + "LastPage" => PdfNamedOperation.LastPage, + _ => PdfNamedOperation.Other, + }; + + /// + private protected override void Check() + { + if (!Dictionary.ContainsKey(ActionNames.N)) + { + Report("A named action shall have an N entry; it has none, so it does nothing."); + } + } +} diff --git a/src/Broadside/PdfPage.cs b/src/Broadside/PdfPage.cs index cfa3044e..fc5f3726 100644 --- a/src/Broadside/PdfPage.cs +++ b/src/Broadside/PdfPage.cs @@ -41,6 +41,11 @@ internal PdfPage(PdfDocument document, CosDictionary dictionary, CosReference? r /// Gets the indirect reference to the page object, or when the page tree holds it directly. public CosReference? Reference { get; } + /// Gets the page's additional actions (AA, PDF 1.2): actions when the page opens and closes; when absent. + /// ISO 32000-2 §7.7.3.3, Table 31, and §12.6.3, Table 198. Not inheritable; read on every call, never created by reading. + public PdfPageAdditionalActions? AdditionalActions => + PdfAdditionalActions.Create(_document, Dictionary.TryGetValue(ActionNames.AA, out CosObject? aa) ? aa : null, Reference, static (d, a, r, o) => new PdfPageAdditionalActions(d, a, r, o)); + /// Gets the media box: the boundaries of the physical medium the page is displayed or printed on. Inheritable. /// ISO 32000-2 §7.7.3.3, Table 31, and §14.11.2. Required; when missing or malformed, US Letter [0 0 612 792]. public PdfRectangle MediaBox => ReadBox(KnownNames.MediaBox, inheritable: true, out PdfRectangle box) == PageAttributeState.Valid ? box : DefaultMediaBox; diff --git a/src/Broadside/PdfRemoteGoToAction.cs b/src/Broadside/PdfRemoteGoToAction.cs new file mode 100644 index 00000000..d7588c07 --- /dev/null +++ b/src/Broadside/PdfRemoteGoToAction.cs @@ -0,0 +1,50 @@ +using Broadside.Objects; + +namespace Broadside; + +/// A remote go-to action: changes the view to a destination in another PDF file. +/// +/// ISO 32000-2 §12.6.4.3, Table 203 (PDF 1.1). The destination belongs to the other file: an explicit destination names a 0-based +/// page number there, and a named destination is looked up there, so is true and nothing is +/// resolved against this document. The library never opens the other file. +/// +public sealed class PdfRemoteGoToAction : PdfAction +{ + internal PdfRemoteGoToAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// + public override PdfActionKind Kind => PdfActionKind.GoToR; + + /// Gets the file holding the destination (F, required), or when absent or invalid. + /// ISO 32000-2 §12.6.4.3, Table 203, and §7.11. The file name is untrusted data from the document. + public PdfFileSpecification? File => ReadFileSpecification(NavigationNames.F); + + /// Gets the destination in the other file (D, required), or ; an explicit one names a 0-based page number. + /// ISO 32000-2 §12.6.4.3, Table 203, and §12.3.2. + public PdfDestination? Destination => ReadDestination(NavigationNames.D, isRemote: true); + + /// Gets the structure destination in the other file (SD, PDF 2.0), whose first element is a structure element ID; it should take precedence over . + /// ISO 32000-2 §12.6.4.3, Table 203, and §12.3.2.3. + public PdfExplicitDestination? StructureDestination => ReadDestination(NavigationNames.SD, isRemote: true) as PdfExplicitDestination; + + /// Gets whether to open the other file in a new window (NewWindow, PDF 1.2); when absent: the processor's preference. + /// ISO 32000-2 §12.6.4.3, Table 203. + public bool? NewWindow => ReadBoolean(ActionNames.NewWindow); + + /// + private protected override void Check() + { + if (!Dictionary.ContainsKey(NavigationNames.F)) + { + Report("A remote go-to action shall have an F entry naming the file; it has none."); + } + + if (!Dictionary.ContainsKey(NavigationNames.D)) + { + Report("A remote go-to action shall have a D entry; it has none, so it goes nowhere."); + } + } +} diff --git a/src/Broadside/PdfRenditionAction.cs b/src/Broadside/PdfRenditionAction.cs new file mode 100644 index 00000000..9f5714d0 --- /dev/null +++ b/src/Broadside/PdfRenditionAction.cs @@ -0,0 +1,68 @@ +using Broadside.Objects; + +namespace Broadside; + +/// A rendition action: plays, stops, pauses or resumes multimedia content, or runs a script. Kept as data; the library never plays or runs anything. +/// +/// ISO 32000-2 §12.6.4.14, Table 218 (PDF 1.5), and §13.2.3 (renditions, exposed raw). Either JS or OP shall be present; +/// when both are, OP is the fallback for a processor that cannot run scripts. An unrecognised OP without JS makes +/// the action invalid. +/// +public sealed class PdfRenditionAction : PdfAction +{ + internal PdfRenditionAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// + public override PdfActionKind Kind => PdfActionKind.Rendition; + + /// Gets the rendition object (R; required when OP is 0 or 4), or . + /// ISO 32000-2 §12.6.4.14, Table 218, and §13.2.3. + public CosDictionary? Rendition => ReadDictionary(ActionNames.R); + + /// Gets the screen annotation (AN; required when OP is present), or . + /// ISO 32000-2 §12.6.4.14, Table 218, and §12.5.6.18. + public CosDictionary? ScreenAnnotation => ReadDictionary(ActionNames.AN); + + /// Gets the operation (OP) as stored, or when absent. + /// ISO 32000-2 §12.6.4.14, Table 218. + public int? OperationValue => ReadInteger(ActionNames.OP); + + /// Gets the operation (OP), or when absent or not one of 0 to 4. + /// ISO 32000-2 §12.6.4.14, Table 218. + public PdfRenditionOperation? Operation => OperationValue is >= 0 and <= 4 and int value ? (PdfRenditionOperation)value : null; + + /// Gets the script (JS), decoded from its text string or text stream, or . Never run. + /// ISO 32000-2 §12.6.4.14, Table 218, and §12.6.4.17. The raw value is . + public string? Script => ReadScript(ActionNames.JS); + + /// Gets the JS entry as stored (resolved): a string or a stream; when absent. + /// ISO 32000-2 §12.6.4.14, Table 218. + public CosObject? ScriptObject => Get(ActionNames.JS); + + /// + private protected override void Check() + { + ReportOutOfScope("multimedia playback and scripts"); + bool script = Dictionary.ContainsKey(ActionNames.JS); + int? operation = OperationValue; + if (!script && !Dictionary.ContainsKey(ActionNames.OP)) + { + Report("A rendition action shall have a JS or an OP entry; it has neither."); + } + else if (!script && operation is not (>= 0 and <= 4)) + { + Report("A rendition action's OP is not one of 0 to 4 and it has no JS entry, so the action is invalid."); + } + else if (operation is >= 0 and <= 4 && !Dictionary.ContainsKey(ActionNames.AN)) + { + Report("A rendition action with an OP entry shall have an AN entry naming a screen annotation; it has none."); + } + else if (operation is 0 or 4 && !Dictionary.ContainsKey(ActionNames.R)) + { + Report("A rendition action whose OP is 0 or 4 shall have an R entry naming a rendition; it has none."); + } + } +} diff --git a/src/Broadside/PdfRichMediaExecuteAction.cs b/src/Broadside/PdfRichMediaExecuteAction.cs new file mode 100644 index 00000000..9fc8f6a6 --- /dev/null +++ b/src/Broadside/PdfRichMediaExecuteAction.cs @@ -0,0 +1,74 @@ +using Broadside.Objects; + +namespace Broadside; + +/// A rich-media-execute action: sends a command to a rich media annotation's handler. Kept as data; rich media is out of scope. +/// ISO 32000-2 §12.6.4.18, Tables 222 and 223 (PDF 2.0), and §13.7 (rich media, exposed raw). +public sealed class PdfRichMediaExecuteAction : PdfAction +{ + internal PdfRichMediaExecuteAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// + public override PdfActionKind Kind => PdfActionKind.RichMediaExecute; + + /// Gets the rich media annotation to send the command to (TA, required), or . + /// ISO 32000-2 §12.6.4.18, Table 222. + public CosDictionary? Annotation => ReadDictionary(ActionNames.TA); + + /// Gets the RichMediaInstance dictionary the command targets (TI), or . + /// ISO 32000-2 §12.6.4.18, Table 222. + public CosDictionary? Instance => ReadDictionary(ActionNames.TI); + + /// Gets the command (CMD, required), or . + /// ISO 32000-2 §12.6.4.18, Tables 222 and 223. + public PdfRichMediaCommand? Command => ReadDictionary(ActionNames.CMD) is { } command ? new PdfRichMediaCommand(Document, command) : null; + + /// + private protected override void Check() + { + ReportOutOfScope("rich media"); + if (!Dictionary.ContainsKey(ActionNames.TA) || !Dictionary.ContainsKey(ActionNames.CMD)) + { + Report("A rich-media-execute action shall have a TA and a CMD entry; it lacks one, so it does nothing."); + } + } +} + +/// The command of a rich-media-execute action: a function name and its arguments. A live view. +/// ISO 32000-2 §12.6.4.18, Table 223 (PDF 2.0). +public sealed class PdfRichMediaCommand +{ + private static readonly CosName C = new("C"); + private static readonly CosName A = new("A"); + + private readonly PdfDocument _document; + + internal PdfRichMediaCommand(PdfDocument document, CosDictionary dictionary) + { + _document = document; + Dictionary = dictionary; + } + + /// Gets the RichMediaCommand dictionary. + /// ISO 32000-2 §12.6.4.18, Table 223. + public CosDictionary Dictionary { get; } + + /// Gets the script command, an ECMAScript function name (C, required), or . + /// ISO 32000-2 §12.6.4.18, Table 223. + public string? Name => Get(C) is CosString name ? name.DecodeText() : null; + + /// Gets the arguments (A), resolved: one value, or each element of an array; empty when absent. + /// ISO 32000-2 §12.6.4.18, Table 223: text strings, integers, numbers or booleans. + public IReadOnlyList Arguments => Get(A) switch + { + null => [], + CosArray array => [.. array.Select(_document.Resolve)], + var value => [value], + }; + + private CosObject? Get(CosName key) => + Dictionary.TryGetValue(key, out CosObject? value) && _document.Resolve(value) is not CosNull and var resolved ? resolved : null; +} diff --git a/src/Broadside/PdfSetOcgStateAction.cs b/src/Broadside/PdfSetOcgStateAction.cs new file mode 100644 index 00000000..7762c3c8 --- /dev/null +++ b/src/Broadside/PdfSetOcgStateAction.cs @@ -0,0 +1,135 @@ +using Broadside.Objects; + +namespace Broadside; + +/// A set-OCG-state action: turns optional content groups on or off, or toggles them. +/// +/// ISO 32000-2 §12.6.4.13, Table 217 (PDF 1.5). lists the State array's changes in order; +/// computes the states the action would leave, without changing the document. +/// +public sealed class PdfSetOcgStateAction : PdfAction +{ + internal PdfSetOcgStateAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// + public override PdfActionKind Kind => PdfActionKind.SetOcgState; + + /// Gets the State array (required) as stored, or . + /// ISO 32000-2 §12.6.4.13, Table 217. + public CosArray? State => Read(ActionNames.State); + + /// + /// Gets the changes of the State array, left to right: each group with the state name before it. A group before any state + /// name, an unknown name and its groups, and an element that is neither a name nor a dictionary are skipped with a diagnostic. + /// + /// ISO 32000-2 §12.6.4.13, Table 217. A group may appear more than once; each change applies in order. + public IReadOnlyList Changes + { + get + { + var changes = new List(); + if (State is not { } state) + { + return changes; + } + + PdfOcgStateOperation? operation = null; + bool reported = false; + foreach (CosObject element in state) + { + switch (Document.Resolve(element)) + { + case CosName name: + operation = name.Value switch + { + "ON" => PdfOcgStateOperation.On, + "OFF" => PdfOcgStateOperation.Off, + "Toggle" => PdfOcgStateOperation.Toggle, + _ => null, + }; + reported |= operation is null && Invalid(); + break; + case CosDictionary group when operation is { } current: + changes.Add(new PdfOcgStateChange(current, group, element as CosReference)); + break; + default: + reported |= Invalid(); + break; + } + } + + return changes; + + bool Invalid() + { + if (!reported) + { + ReportEntry(ActionNames.State, "an array of ON, OFF or Toggle names each followed by optional content group dictionaries"); + } + + return true; + } + } + } + + /// Gets whether radio-button relationships between groups are preserved (PreserveRB); when absent. + /// ISO 32000-2 §12.6.4.13, Table 217, and §8.11.4.3, Table 99 (RBGroups). + public bool PreserveRadioButtons => ReadBoolean(ActionNames.PreserveRB) ?? true; + + /// Returns the states becomes when this action's changes are applied to it. The document is not changed. + /// The current states of the document's optional content groups. + /// The new states; itself when the action has no State array. + /// ISO 32000-2 §12.6.4.13, Table 217, through . + public PdfOptionalContentState ApplyTo(PdfOptionalContentState state) + { + ArgumentNullException.ThrowIfNull(state); + return State is { } array ? state.Apply(array, PreserveRadioButtons) : state; + } + + /// + private protected override void Check() + { + if (!Dictionary.ContainsKey(ActionNames.State)) + { + Report("A set-OCG-state action shall have a State array; it has none, so it does nothing."); + } + } + + private CosArray? Read(CosName key) + { + switch (Get(key)) + { + case null: + return null; + case CosArray array: + return array; + default: + ReportEntry(key, "an array"); + return null; + } + } +} + +/// One change of a set-OCG-state action: a group and what happens to it. +/// ISO 32000-2 §12.6.4.13, Table 217. +public sealed class PdfOcgStateChange +{ + internal PdfOcgStateChange(PdfOcgStateOperation operation, CosDictionary group, CosReference? groupReference) + { + Operation = operation; + Group = group; + GroupReference = groupReference; + } + + /// Gets what happens to the group: on, off or toggled. + public PdfOcgStateOperation Operation { get; } + + /// Gets the optional content group dictionary (§8.11.2.1). + public CosDictionary Group { get; } + + /// Gets the indirect reference to , or . + public CosReference? GroupReference { get; } +} diff --git a/src/Broadside/PdfSoundAction.cs b/src/Broadside/PdfSoundAction.cs new file mode 100644 index 00000000..fc6f2a16 --- /dev/null +++ b/src/Broadside/PdfSoundAction.cs @@ -0,0 +1,59 @@ +using Broadside.Objects; + +namespace Broadside; + +/// A sound action: plays a sound. Kept as data; the library never plays anything. +/// ISO 32000-2 §12.6.4.9, Table 212 (PDF 1.2; deprecated in PDF 2.0), and §13.3 (sound objects, exposed raw). +public sealed class PdfSoundAction : PdfAction +{ + internal PdfSoundAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// + public override PdfActionKind Kind => PdfActionKind.Sound; + + /// Gets the sound object (Sound, required), or . + /// ISO 32000-2 §12.6.4.9, Table 212, and §13.3, Table 302. + public CosStream? Sound => ReadStream(ActionNames.Sound); + + /// Gets the volume (Volume), -1.0 to 1.0; 1.0 when absent. A value outside the range is clamped into it, with a diagnostic. + /// ISO 32000-2 §12.6.4.9, Table 212. + public double Volume + { + get + { + double volume = ReadNumber(ActionNames.Volume) ?? 1.0; + if (volume is >= -1.0 and <= 1.0) + { + return volume; + } + + ReportEntry(ActionNames.Volume, "a number from -1.0 to 1.0"); + return Math.Clamp(volume, -1.0, 1.0); + } + } + + /// Gets whether the sound plays synchronously (Synchronous); when absent. Ignored when Repeat is present. + /// ISO 32000-2 §12.6.4.9, Table 212. + public bool IsSynchronous => ReadBoolean(ActionNames.Synchronous) ?? false; + + /// Gets whether the sound repeats indefinitely (Repeat); when absent. + /// ISO 32000-2 §12.6.4.9, Table 212. + public bool Repeats => ReadBoolean(ActionNames.Repeat) ?? false; + + /// Gets whether the sound mixes with any sound already playing (Mix); when absent. + /// ISO 32000-2 §12.6.4.9, Table 212. + public bool Mixes => ReadBoolean(ActionNames.Mix) ?? false; + + /// + private protected override void Check() + { + ReportOutOfScope("sound playback"); + if (!Dictionary.ContainsKey(ActionNames.Sound)) + { + Report("A sound action shall have a Sound entry; it has none."); + } + } +} diff --git a/src/Broadside/PdfThreadAction.cs b/src/Broadside/PdfThreadAction.cs new file mode 100644 index 00000000..9680cacb --- /dev/null +++ b/src/Broadside/PdfThreadAction.cs @@ -0,0 +1,73 @@ +using Broadside.Objects; + +namespace Broadside; + +/// A thread action: jumps to an article thread (bead) in this or another document. +/// +/// ISO 32000-2 §12.6.4.7, Table 209 (PDF 1.1), and §12.4.3 (articles, exposed raw). The thread is given by its dictionary +/// (), by its index in the catalog's Threads array () or by its title +/// (); the bead likewise by dictionary or index. When is present they belong to that file. +/// +public sealed class PdfThreadAction : PdfAction +{ + internal PdfThreadAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// + public override PdfActionKind Kind => PdfActionKind.Thread; + + /// Gets the file holding the thread (F), or : this document. + /// ISO 32000-2 §12.6.4.7, Table 209, and §7.11. + public PdfFileSpecification? File => ReadFileSpecification(NavigationNames.F); + + /// Gets the thread (D, required) as stored: a thread dictionary, an index or a title; when absent. + /// ISO 32000-2 §12.6.4.7, Table 209. + public CosObject? Thread => Get(NavigationNames.D); + + /// Gets the thread dictionary when D is one, else . + /// ISO 32000-2 §12.6.4.7, Table 209, and §12.4.3, Table 162. + public CosDictionary? ThreadDictionary => Thread as CosDictionary; + + /// Gets the 0-based index of the thread in the catalog's Threads array when D is an integer, else . + /// ISO 32000-2 §12.6.4.7, Table 209. + public int? ThreadIndex => Thread is CosInteger { Value: >= 0 and <= int.MaxValue } index ? (int)index.Value : null; + + /// Gets the title of the thread when D is a text string, else ; the first thread with that title is meant. + /// ISO 32000-2 §12.6.4.7, Table 209. + public string? ThreadTitle => (Thread as CosString)?.DecodeText(); + + /// Gets the bead (B) as stored: a bead dictionary or an index into the thread's beads; : the first bead. + /// ISO 32000-2 §12.6.4.7, Table 209. + public CosObject? Bead => Get(ActionNames.B); + + /// Gets the bead dictionary when B is one, else . + /// ISO 32000-2 §12.6.4.7, Table 209, and §12.4.3, Table 163. + public CosDictionary? BeadDictionary => Bead as CosDictionary; + + /// Gets the 0-based index of the bead in the thread when B is an integer, else . + /// ISO 32000-2 §12.6.4.7, Table 209. + public int? BeadIndex => Bead is CosInteger { Value: >= 0 and <= int.MaxValue } index ? (int)index.Value : null; + + /// + private protected override void Check() + { + switch (Thread) + { + case null: + Report("A thread action shall have a D entry naming the thread; it has none, so it goes nowhere."); + break; + case CosDictionary or CosInteger or CosString: + break; + default: + ReportEntry(NavigationNames.D, "a thread dictionary, an integer or a text string"); + break; + } + + if (Bead is not (null or CosDictionary or CosInteger)) + { + ReportEntry(ActionNames.B, "a bead dictionary or an integer"); + } + } +} diff --git a/src/Broadside/PdfTransitionAction.cs b/src/Broadside/PdfTransitionAction.cs new file mode 100644 index 00000000..9da14cae --- /dev/null +++ b/src/Broadside/PdfTransitionAction.cs @@ -0,0 +1,29 @@ +using Broadside.Objects; + +namespace Broadside; + +/// A transition action: shows the result of the previous actions of a sequence with a transition effect. +/// ISO 32000-2 §12.6.4.15, Table 219 (PDF 1.5), and §12.4.4.2 (transition dictionaries, exposed raw). +public sealed class PdfTransitionAction : PdfAction +{ + internal PdfTransitionAction(PdfDocument document, CosDictionary dictionary, CosReference? reference, CosName actionType) + : base(document, dictionary, reference, actionType) + { + } + + /// + public override PdfActionKind Kind => PdfActionKind.Transition; + + /// Gets the transition dictionary (Trans, required), or . + /// ISO 32000-2 §12.6.4.15, Table 219, and §12.4.4.2, Table 164. + public CosDictionary? Transition => ReadDictionary(ActionNames.Trans); + + /// + private protected override void Check() + { + if (!Dictionary.ContainsKey(ActionNames.Trans)) + { + Report("A transition action shall have a Trans entry; it has none."); + } + } +} diff --git a/src/Broadside/PdfUnknownAction.cs b/src/Broadside/PdfUnknownAction.cs index 17550074..d4e2a115 100644 --- a/src/Broadside/PdfUnknownAction.cs +++ b/src/Broadside/PdfUnknownAction.cs @@ -13,4 +13,7 @@ internal PdfUnknownAction(PdfDocument document, CosDictionary dictionary, CosRef : base(document, dictionary, reference, actionType) { } + + /// + public override PdfActionKind Kind => PdfActionKind.Unknown; } diff --git a/src/Broadside/PdfUriAction.cs b/src/Broadside/PdfUriAction.cs index a3ff0184..59b90470 100644 --- a/src/Broadside/PdfUriAction.cs +++ b/src/Broadside/PdfUriAction.cs @@ -1,13 +1,15 @@ using System.Diagnostics.CodeAnalysis; using System.Text; using Broadside.Objects; +using Broadside.Parsing; namespace Broadside; /// A URI action: resolves a uniform resource identifier, typically a hypertext link. /// -/// ISO 32000-2 §12.6.4.8, Table 210 (PDF 1.1). The URI is untrusted data from the file: the library never resolves it. A relative URI -/// is relative to the catalog's URI dictionary's Base (Table 211), which this view does not apply. +/// ISO 32000-2 §12.6.4.8, Table 210 (PDF 1.1). The URI is untrusted data from the file: the library never resolves it, and any scheme +/// (javascript: included) is returned as written. A relative URI is relative to the catalog's URI dictionary's Base +/// (Table 211, ); combines the two without fetching anything. /// public sealed class PdfUriAction : PdfAction { @@ -16,16 +18,83 @@ internal PdfUriAction(PdfDocument document, CosDictionary dictionary, CosReferen { } - /// Gets the URI, the URI string decoded as UTF-8, or when it is absent or not a string. - /// ISO 32000-2 §12.6.4.8, Table 210: an ASCII string "encoded in UTF-8". + /// + public override PdfActionKind Kind => PdfActionKind.Uri; + + /// Gets the URI, decoded as UTF-8, or when it is absent or not a string. + /// + /// ISO 32000-2 §12.6.4.8, Table 210: an ASCII string "encoded in UTF-8". Bytes that are not UTF-8 are read through PDFDocEncoding and + /// a UTF-16 byte order mark as UTF-16, each with a UriInvalid diagnostic; a URI written as a name is read as its bytes, with + /// the same diagnostic. The value as stored is . + /// [SuppressMessage("Design", "CA1056:URI-like properties should not be strings", Justification = "The file may hold a relative or malformed URI (relative to the catalog URI Base); the text is returned as stored.")] - public string? Uri => Dictionary.TryGetValue(NavigationNames.Uri, out CosObject? uri) && Document.Resolve(uri) is CosString text - ? Encoding.UTF8.GetString(text.Bytes) - : null; + public string? Uri + { + get + { + switch (Get(NavigationNames.Uri)) + { + case CosString text: + string uri = DecodeUri(text.Bytes, out bool repaired); + if (repaired) + { + Report(DiagnosticCodes.UriInvalid, "A URI action's URI is not UTF-8; it is read as UTF-16 or PDFDocEncoding."); + } + + return uri; + case CosName name: + Report(DiagnosticCodes.UriInvalid, "A URI action's URI shall be a string; it is a name, read as its bytes."); + return DecodeUri(name.Bytes, out _); + case null: + return null; + default: + ReportEntry(NavigationNames.Uri, "an ASCII string"); + return null; + } + } + } + + /// Gets the URI entry as stored (resolved): normally a string; when absent. + /// ISO 32000-2 §12.6.4.8, Table 210. + public CosObject? UriObject => Get(NavigationNames.Uri); /// Gets a value indicating whether the mouse position is appended to the URI when a link is clicked. Default . /// ISO 32000-2 §12.6.4.8, Table 210; ignored for outline items and the document's open action. - public bool IsMap => Dictionary.TryGetValue(NavigationNames.IsMap, out CosObject? isMap) && Document.Resolve(isMap) is CosBoolean { Value: true }; + public bool IsMap => ReadBoolean(NavigationNames.IsMap) ?? false; + + /// + /// Returns the URI as an absolute : itself when it is absolute, else resolved against the + /// document's . Nothing is fetched. + /// + /// The absolute URI; when there is no URI, or it is relative and the document has no base URI, or it is not a URI at all. + /// ISO 32000-2 §12.6.4.8, Tables 210 and 211 (RFC 3986 reference resolution). The result is untrusted data from the document. + public System.Uri? ResolveUri() + { + if (Uri is not { } text) + { + return null; + } + + if (System.Uri.TryCreate(text, UriKind.Absolute, out System.Uri? absolute)) + { + return absolute; + } + + return Document.UriBase is { } baseUri && System.Uri.TryCreate(baseUri, text, out System.Uri? resolved) ? resolved : null; + } + + /// Decodes URI bytes: UTF-8 when valid, else UTF-16 after a byte order mark, else PDFDocEncoding ( set). + internal static string DecodeUri(ReadOnlySpan bytes, out bool repaired) + { + repaired = false; + if (!bytes.StartsWith("\uFEFF"u8) && !bytes.StartsWith((ReadOnlySpan)[0xFE, 0xFF]) && System.Text.Unicode.Utf8.IsValid(bytes)) + { + return Encoding.UTF8.GetString(bytes); + } + + repaired = !bytes.StartsWith(""u8); + return bytes.StartsWith(""u8) ? Encoding.UTF8.GetString(bytes[3..]) : TextStringDecoder.Decode(bytes); + } /// private protected override void Check() diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index 853234a6..4187d652 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -1,5 +1,6 @@ #nullable enable abstract Broadside.Objects.CosNumber.ToDouble() -> double +abstract Broadside.PdfAction.Kind.get -> Broadside.PdfActionKind Broadside.Content.ClipEvent Broadside.Content.ClipEvent.ClipEvent() -> void Broadside.Content.ClipEvent.Ctm.get -> Broadside.Graphics.Matrix @@ -437,8 +438,225 @@ Broadside.Objects.CosString.CosString(System.ReadOnlySpan bytes, bool hexa Broadside.Objects.CosString.DecodeText() -> string! Broadside.Objects.CosString.Equals(Broadside.Objects.CosString? other) -> bool Broadside.Objects.CosString.IsHexadecimal.get -> bool +Broadside.PdfAction.EnumerateActionTree(int maxDepth = 64) -> System.Collections.Generic.IEnumerable! +Broadside.PdfAction.Next.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfActionKind +Broadside.PdfActionKind.GoTo = 1 -> Broadside.PdfActionKind +Broadside.PdfActionKind.GoTo3DView = 18 -> Broadside.PdfActionKind +Broadside.PdfActionKind.GoToDp = 4 -> Broadside.PdfActionKind +Broadside.PdfActionKind.GoToE = 3 -> Broadside.PdfActionKind +Broadside.PdfActionKind.GoToR = 2 -> Broadside.PdfActionKind +Broadside.PdfActionKind.Hide = 10 -> Broadside.PdfActionKind +Broadside.PdfActionKind.ImportData = 14 -> Broadside.PdfActionKind +Broadside.PdfActionKind.JavaScript = 19 -> Broadside.PdfActionKind +Broadside.PdfActionKind.Launch = 5 -> Broadside.PdfActionKind +Broadside.PdfActionKind.Movie = 9 -> Broadside.PdfActionKind +Broadside.PdfActionKind.Named = 11 -> Broadside.PdfActionKind +Broadside.PdfActionKind.Rendition = 16 -> Broadside.PdfActionKind +Broadside.PdfActionKind.ResetForm = 13 -> Broadside.PdfActionKind +Broadside.PdfActionKind.RichMediaExecute = 20 -> Broadside.PdfActionKind +Broadside.PdfActionKind.SetOcgState = 15 -> Broadside.PdfActionKind +Broadside.PdfActionKind.Sound = 8 -> Broadside.PdfActionKind +Broadside.PdfActionKind.SubmitForm = 12 -> Broadside.PdfActionKind +Broadside.PdfActionKind.Thread = 6 -> Broadside.PdfActionKind +Broadside.PdfActionKind.Transition = 17 -> Broadside.PdfActionKind +Broadside.PdfActionKind.Unknown = 0 -> Broadside.PdfActionKind +Broadside.PdfActionKind.Uri = 7 -> Broadside.PdfActionKind +Broadside.PdfActionTarget +Broadside.PdfActionTarget.Dictionary.get -> Broadside.Objects.CosDictionary? +Broadside.PdfActionTarget.FieldName.get -> string? +Broadside.PdfActionTarget.Reference.get -> Broadside.Objects.CosReference? +Broadside.PdfAdditionalActions +Broadside.PdfAdditionalActions.Actions.get -> System.Collections.Generic.IReadOnlyList>! +Broadside.PdfAdditionalActions.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfAdditionalActions.GetAction(Broadside.Objects.CosName! trigger) -> Broadside.PdfAction? +Broadside.PdfAdditionalActions.Reference.get -> Broadside.Objects.CosReference? +Broadside.PdfAnnotationAdditionalActions +Broadside.PdfAnnotationAdditionalActions.Blur.get -> Broadside.PdfAction? +Broadside.PdfAnnotationAdditionalActions.CursorEnter.get -> Broadside.PdfAction? +Broadside.PdfAnnotationAdditionalActions.CursorExit.get -> Broadside.PdfAction? +Broadside.PdfAnnotationAdditionalActions.Focus.get -> Broadside.PdfAction? +Broadside.PdfAnnotationAdditionalActions.MouseDown.get -> Broadside.PdfAction? +Broadside.PdfAnnotationAdditionalActions.MouseUp.get -> Broadside.PdfAction? +Broadside.PdfAnnotationAdditionalActions.PageClose.get -> Broadside.PdfAction? +Broadside.PdfAnnotationAdditionalActions.PageInvisible.get -> Broadside.PdfAction? +Broadside.PdfAnnotationAdditionalActions.PageOpen.get -> Broadside.PdfAction? +Broadside.PdfAnnotationAdditionalActions.PageVisible.get -> Broadside.PdfAction? +Broadside.PdfDocument.AdditionalActions.get -> Broadside.PdfDocumentAdditionalActions? +Broadside.PdfDocument.GetAction(Broadside.Objects.CosObject? value, Broadside.Objects.CosReference? ownerReference = null) -> Broadside.PdfAction? +Broadside.PdfDocument.GetAnnotationAdditionalActions(Broadside.Objects.CosObject? value, Broadside.Objects.CosReference? ownerReference = null) -> Broadside.PdfAnnotationAdditionalActions? +Broadside.PdfDocument.GetFieldAdditionalActions(Broadside.Objects.CosObject? value, Broadside.Objects.CosReference? ownerReference = null) -> Broadside.PdfFieldAdditionalActions? +Broadside.PdfDocument.OpenAction.get -> Broadside.PdfAction? +Broadside.PdfDocument.OpenDestination.get -> Broadside.PdfDestination? +Broadside.PdfDocument.UriBase.get -> System.Uri? +Broadside.PdfDocumentAdditionalActions +Broadside.PdfDocumentAdditionalActions.DidPrint.get -> Broadside.PdfAction? +Broadside.PdfDocumentAdditionalActions.DidSave.get -> Broadside.PdfAction? +Broadside.PdfDocumentAdditionalActions.WillClose.get -> Broadside.PdfAction? +Broadside.PdfDocumentAdditionalActions.WillPrint.get -> Broadside.PdfAction? +Broadside.PdfDocumentAdditionalActions.WillSave.get -> Broadside.PdfAction? +Broadside.PdfEmbeddedGoToAction +Broadside.PdfEmbeddedGoToAction.Destination.get -> Broadside.PdfDestination? +Broadside.PdfEmbeddedGoToAction.File.get -> Broadside.PdfFileSpecification? +Broadside.PdfEmbeddedGoToAction.NewWindow.get -> bool? +Broadside.PdfEmbeddedGoToAction.Target.get -> Broadside.PdfEmbeddedTarget? +Broadside.PdfEmbeddedTarget +Broadside.PdfEmbeddedTarget.AnnotationIndex.get -> int? +Broadside.PdfEmbeddedTarget.AnnotationName.get -> string? +Broadside.PdfEmbeddedTarget.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfEmbeddedTarget.EmbeddedFileName.get -> Broadside.Objects.CosString? +Broadside.PdfEmbeddedTarget.PageName.get -> Broadside.Objects.CosString? +Broadside.PdfEmbeddedTarget.PageNumber.get -> int? +Broadside.PdfEmbeddedTarget.Relationship.get -> Broadside.PdfEmbeddedTargetRelationship +Broadside.PdfEmbeddedTarget.Target.get -> Broadside.PdfEmbeddedTarget? +Broadside.PdfEmbeddedTargetRelationship +Broadside.PdfEmbeddedTargetRelationship.Child = 2 -> Broadside.PdfEmbeddedTargetRelationship +Broadside.PdfEmbeddedTargetRelationship.Parent = 1 -> Broadside.PdfEmbeddedTargetRelationship +Broadside.PdfEmbeddedTargetRelationship.Unknown = 0 -> Broadside.PdfEmbeddedTargetRelationship +Broadside.PdfFieldAdditionalActions +Broadside.PdfFieldAdditionalActions.Calculate.get -> Broadside.PdfAction? +Broadside.PdfFieldAdditionalActions.Format.get -> Broadside.PdfAction? +Broadside.PdfFieldAdditionalActions.Keystroke.get -> Broadside.PdfAction? +Broadside.PdfFieldAdditionalActions.Validate.get -> Broadside.PdfAction? +Broadside.PdfGoTo3DViewAction +Broadside.PdfGoTo3DViewAction.Annotation.get -> Broadside.Objects.CosDictionary? +Broadside.PdfGoTo3DViewAction.View.get -> Broadside.Objects.CosObject? +Broadside.PdfGoTo3DViewAction.ViewDictionary.get -> Broadside.Objects.CosDictionary? +Broadside.PdfGoTo3DViewAction.ViewIndex.get -> int? +Broadside.PdfGoTo3DViewAction.ViewKeyword.get -> Broadside.Objects.CosName? +Broadside.PdfGoTo3DViewAction.ViewName.get -> string? +Broadside.PdfGoToDocumentPartAction +Broadside.PdfGoToDocumentPartAction.DocumentPart.get -> Broadside.Objects.CosDictionary? +Broadside.PdfHideAction +Broadside.PdfHideAction.Hide.get -> bool +Broadside.PdfHideAction.Targets.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfImportDataAction +Broadside.PdfImportDataAction.File.get -> Broadside.PdfFileSpecification? +Broadside.PdfJavaScriptAction +Broadside.PdfJavaScriptAction.Script.get -> string? +Broadside.PdfJavaScriptAction.ScriptObject.get -> Broadside.Objects.CosObject? +Broadside.PdfLaunchAction +Broadside.PdfLaunchAction.File.get -> Broadside.PdfFileSpecification? +Broadside.PdfLaunchAction.Mac.get -> Broadside.Objects.CosObject? +Broadside.PdfLaunchAction.NewWindow.get -> bool? +Broadside.PdfLaunchAction.Unix.get -> Broadside.Objects.CosObject? +Broadside.PdfLaunchAction.Windows.get -> Broadside.PdfWindowsLaunchParameters? +Broadside.PdfMovieAction +Broadside.PdfMovieAction.Annotation.get -> Broadside.Objects.CosDictionary? +Broadside.PdfMovieAction.Operation.get -> Broadside.PdfMovieOperation +Broadside.PdfMovieAction.Title.get -> string? +Broadside.PdfMovieOperation +Broadside.PdfMovieOperation.Pause = 2 -> Broadside.PdfMovieOperation +Broadside.PdfMovieOperation.Play = 0 -> Broadside.PdfMovieOperation +Broadside.PdfMovieOperation.Resume = 3 -> Broadside.PdfMovieOperation +Broadside.PdfMovieOperation.Stop = 1 -> Broadside.PdfMovieOperation +Broadside.PdfNamedAction +Broadside.PdfNamedAction.Name.get -> Broadside.Objects.CosName? +Broadside.PdfNamedAction.Operation.get -> Broadside.PdfNamedOperation +Broadside.PdfNameDictionary.JavaScript.get -> Broadside.PdfNameTree? +Broadside.PdfNameDictionary.JavaScriptActions.get -> System.Collections.Generic.IReadOnlyList>! +Broadside.PdfNamedOperation +Broadside.PdfNamedOperation.FirstPage = 3 -> Broadside.PdfNamedOperation +Broadside.PdfNamedOperation.LastPage = 4 -> Broadside.PdfNamedOperation +Broadside.PdfNamedOperation.NextPage = 1 -> Broadside.PdfNamedOperation +Broadside.PdfNamedOperation.Other = 0 -> Broadside.PdfNamedOperation +Broadside.PdfNamedOperation.PreviousPage = 2 -> Broadside.PdfNamedOperation +Broadside.PdfOcgStateChange +Broadside.PdfOcgStateChange.Group.get -> Broadside.Objects.CosDictionary! +Broadside.PdfOcgStateChange.GroupReference.get -> Broadside.Objects.CosReference? +Broadside.PdfOcgStateChange.Operation.get -> Broadside.PdfOcgStateOperation +Broadside.PdfOcgStateOperation +Broadside.PdfOcgStateOperation.Off = 1 -> Broadside.PdfOcgStateOperation +Broadside.PdfOcgStateOperation.On = 0 -> Broadside.PdfOcgStateOperation +Broadside.PdfOcgStateOperation.Toggle = 2 -> Broadside.PdfOcgStateOperation +Broadside.PdfPage.AdditionalActions.get -> Broadside.PdfPageAdditionalActions? Broadside.PdfPage.ProcessContent(Broadside.Content.ContentProcessor! processor) -> void Broadside.PdfPage.ProcessContent(Broadside.Content.ContentProcessor! processor, Broadside.Content.ContentOptions! options) -> void +Broadside.PdfPageAdditionalActions +Broadside.PdfPageAdditionalActions.Close.get -> Broadside.PdfAction? +Broadside.PdfPageAdditionalActions.Open.get -> Broadside.PdfAction? +Broadside.PdfRemoteGoToAction +Broadside.PdfRemoteGoToAction.Destination.get -> Broadside.PdfDestination? +Broadside.PdfRemoteGoToAction.File.get -> Broadside.PdfFileSpecification? +Broadside.PdfRemoteGoToAction.NewWindow.get -> bool? +Broadside.PdfRemoteGoToAction.StructureDestination.get -> Broadside.PdfExplicitDestination? +Broadside.PdfRenditionAction +Broadside.PdfRenditionAction.Operation.get -> Broadside.PdfRenditionOperation? +Broadside.PdfRenditionAction.OperationValue.get -> int? +Broadside.PdfRenditionAction.Rendition.get -> Broadside.Objects.CosDictionary? +Broadside.PdfRenditionAction.ScreenAnnotation.get -> Broadside.Objects.CosDictionary? +Broadside.PdfRenditionAction.Script.get -> string? +Broadside.PdfRenditionAction.ScriptObject.get -> Broadside.Objects.CosObject? +Broadside.PdfRenditionOperation +Broadside.PdfRenditionOperation.Pause = 2 -> Broadside.PdfRenditionOperation +Broadside.PdfRenditionOperation.Play = 0 -> Broadside.PdfRenditionOperation +Broadside.PdfRenditionOperation.PlayOrResume = 4 -> Broadside.PdfRenditionOperation +Broadside.PdfRenditionOperation.Resume = 3 -> Broadside.PdfRenditionOperation +Broadside.PdfRenditionOperation.Stop = 1 -> Broadside.PdfRenditionOperation +Broadside.PdfResetFormAction +Broadside.PdfResetFormAction.Fields.get -> System.Collections.Generic.IReadOnlyList? +Broadside.PdfResetFormAction.Flags.get -> Broadside.PdfResetFormFlags +Broadside.PdfResetFormFlags +Broadside.PdfResetFormFlags.Exclude = 1 -> Broadside.PdfResetFormFlags +Broadside.PdfResetFormFlags.None = 0 -> Broadside.PdfResetFormFlags +Broadside.PdfRichMediaCommand +Broadside.PdfRichMediaCommand.Arguments.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfRichMediaCommand.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfRichMediaCommand.Name.get -> string? +Broadside.PdfRichMediaExecuteAction +Broadside.PdfRichMediaExecuteAction.Annotation.get -> Broadside.Objects.CosDictionary? +Broadside.PdfRichMediaExecuteAction.Command.get -> Broadside.PdfRichMediaCommand? +Broadside.PdfRichMediaExecuteAction.Instance.get -> Broadside.Objects.CosDictionary? +Broadside.PdfSetOcgStateAction +Broadside.PdfSetOcgStateAction.ApplyTo(Broadside.PdfOptionalContentState! state) -> Broadside.PdfOptionalContentState! +Broadside.PdfSetOcgStateAction.Changes.get -> System.Collections.Generic.IReadOnlyList! +Broadside.PdfSetOcgStateAction.PreserveRadioButtons.get -> bool +Broadside.PdfSetOcgStateAction.State.get -> Broadside.Objects.CosArray? +Broadside.PdfSoundAction +Broadside.PdfSoundAction.IsSynchronous.get -> bool +Broadside.PdfSoundAction.Mixes.get -> bool +Broadside.PdfSoundAction.Repeats.get -> bool +Broadside.PdfSoundAction.Sound.get -> Broadside.Objects.CosStream? +Broadside.PdfSoundAction.Volume.get -> double +Broadside.PdfSubmitFormAction +Broadside.PdfSubmitFormAction.CharacterSet.get -> string? +Broadside.PdfSubmitFormAction.Fields.get -> System.Collections.Generic.IReadOnlyList? +Broadside.PdfSubmitFormAction.File.get -> Broadside.PdfFileSpecification? +Broadside.PdfSubmitFormAction.Flags.get -> Broadside.PdfSubmitFormFlags +Broadside.PdfSubmitFormFlags +Broadside.PdfSubmitFormFlags.CanonicalFormat = 512 -> Broadside.PdfSubmitFormFlags +Broadside.PdfSubmitFormFlags.EmbedForm = 8192 -> Broadside.PdfSubmitFormFlags +Broadside.PdfSubmitFormFlags.Exclude = 1 -> Broadside.PdfSubmitFormFlags +Broadside.PdfSubmitFormFlags.ExcludeFKey = 2048 -> Broadside.PdfSubmitFormFlags +Broadside.PdfSubmitFormFlags.ExcludeNonUserAnnotations = 1024 -> Broadside.PdfSubmitFormFlags +Broadside.PdfSubmitFormFlags.ExportFormat = 4 -> Broadside.PdfSubmitFormFlags +Broadside.PdfSubmitFormFlags.GetMethod = 8 -> Broadside.PdfSubmitFormFlags +Broadside.PdfSubmitFormFlags.IncludeAnnotations = 128 -> Broadside.PdfSubmitFormFlags +Broadside.PdfSubmitFormFlags.IncludeAppendSaves = 64 -> Broadside.PdfSubmitFormFlags +Broadside.PdfSubmitFormFlags.IncludeNoValueFields = 2 -> Broadside.PdfSubmitFormFlags +Broadside.PdfSubmitFormFlags.None = 0 -> Broadside.PdfSubmitFormFlags +Broadside.PdfSubmitFormFlags.SubmitCoordinates = 16 -> Broadside.PdfSubmitFormFlags +Broadside.PdfSubmitFormFlags.SubmitPdf = 256 -> Broadside.PdfSubmitFormFlags +Broadside.PdfSubmitFormFlags.Xfdf = 32 -> Broadside.PdfSubmitFormFlags +Broadside.PdfThreadAction +Broadside.PdfThreadAction.Bead.get -> Broadside.Objects.CosObject? +Broadside.PdfThreadAction.BeadDictionary.get -> Broadside.Objects.CosDictionary? +Broadside.PdfThreadAction.BeadIndex.get -> int? +Broadside.PdfThreadAction.File.get -> Broadside.PdfFileSpecification? +Broadside.PdfThreadAction.Thread.get -> Broadside.Objects.CosObject? +Broadside.PdfThreadAction.ThreadDictionary.get -> Broadside.Objects.CosDictionary? +Broadside.PdfThreadAction.ThreadIndex.get -> int? +Broadside.PdfThreadAction.ThreadTitle.get -> string? +Broadside.PdfTransitionAction +Broadside.PdfTransitionAction.Transition.get -> Broadside.Objects.CosDictionary? +Broadside.PdfUriAction.ResolveUri() -> System.Uri? +Broadside.PdfUriAction.UriObject.get -> Broadside.Objects.CosObject? +Broadside.PdfWindowsLaunchParameters +Broadside.PdfWindowsLaunchParameters.DefaultDirectory.get -> Broadside.Objects.CosString? +Broadside.PdfWindowsLaunchParameters.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.PdfWindowsLaunchParameters.FileName.get -> Broadside.Objects.CosString? +Broadside.PdfWindowsLaunchParameters.Operation.get -> string! +Broadside.PdfWindowsLaunchParameters.Parameters.get -> Broadside.Objects.CosString? const Broadside.Content.ContentOptions.DefaultMaxNestingDepth = 50 -> int const Broadside.Content.ContentOptions.DefaultMaxOperands = 65536 -> int const Broadside.Content.ContentOptions.DefaultMaxSaveDepth = 4096 -> int @@ -769,6 +987,7 @@ Broadside.PdfVisibilityPolicy.AllOn = 0 -> Broadside.PdfVisibilityPolicy Broadside.PdfVisibilityPolicy.AnyOff = 2 -> Broadside.PdfVisibilityPolicy Broadside.PdfVisibilityPolicy.AnyOn = 1 -> Broadside.PdfVisibilityPolicy const Broadside.Objects.CosReference.MaxGeneration = 65535 -> int +const Broadside.PdfAction.DefaultMaxTreeDepth = 64 -> int override Broadside.Content.CompositeContentProcessor.BeginForm(in Broadside.Content.FormEvent form, Broadside.Content.ContentContext! context) -> Broadside.Content.ContentVisit override Broadside.Content.CompositeContentProcessor.BeginMarkedContent(in Broadside.Content.MarkedContentEvent mc, Broadside.Content.ContentContext! context) -> void override Broadside.Content.CompositeContentProcessor.BeginRun(Broadside.Content.ContentContext! context) -> void @@ -811,6 +1030,27 @@ override Broadside.Objects.CosReference.GetHashCode() -> int override Broadside.Objects.CosStream.IsDirty.get -> bool override Broadside.Objects.CosString.Equals(object? obj) -> bool override Broadside.Objects.CosString.GetHashCode() -> int +override Broadside.PdfEmbeddedGoToAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfGoTo3DViewAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfGoToAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfGoToDocumentPartAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfHideAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfImportDataAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfJavaScriptAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfLaunchAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfMovieAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfNamedAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfRemoteGoToAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfRenditionAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfResetFormAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfRichMediaExecuteAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfSetOcgStateAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfSoundAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfSubmitFormAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfThreadAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfTransitionAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfUnknownAction.Kind.get -> Broadside.PdfActionKind +override Broadside.PdfUriAction.Kind.get -> Broadside.PdfActionKind static Broadside.Graphics.Matrix.CreateScale(double sx, double sy) -> Broadside.Graphics.Matrix static Broadside.Graphics.Matrix.CreateTranslation(double tx, double ty) -> Broadside.Graphics.Matrix static Broadside.Graphics.Matrix.Identity.get -> Broadside.Graphics.Matrix diff --git a/tests/Broadside.Fuzz/Broadside.Fuzz.csproj b/tests/Broadside.Fuzz/Broadside.Fuzz.csproj index 06860c0b..ac034c5d 100644 --- a/tests/Broadside.Fuzz/Broadside.Fuzz.csproj +++ b/tests/Broadside.Fuzz/Broadside.Fuzz.csproj @@ -19,6 +19,7 @@ + diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 0608bccc..faa9c1a5 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -8,6 +8,7 @@ using Broadside.Objects; using Broadside.Parsing; using Broadside.Security; +using Broadside.TestSupport; using SharpFuzz; namespace Broadside.Fuzz; @@ -115,6 +116,7 @@ private static void Document(ReadOnlySpan data) } Navigation(document); + _ = ActionWalker.Walk(document); } /// diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index 61ddd953..39ce2206 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters, and reads every font of each page's resources through the font model (each simple font's 256 glyph names and widths, which must be non-empty and finite, and its descriptor); a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. `xmp` reads the input as an XMP packet (ISO 16684-1) through the reader the document uses, and again from its first `> /RoleMap << /A /B /B /A >>` followed by `<< /S /A /P 4 0 R /Pg 3 0 R /K [0 5 0 R] /A [1 << /O /Layout >> 2] >>`. `content-lexer` reads the input as decoded content stream bytes with the content reader (ISO 32000-2 §7.8.2, #55): every operator must lie inside the input, after the previous one, with a keyword of at least one byte, and every operand, nested arrays and dictionaries included, must be readable; `content-interpreter` runs the input as a page's content through the interpreter with a processor that asks for every event and checks that path verbs and points agree, that clip handles chain back to the initial clip and that the state stack is balanced at the end; `document` now also interprets every page with that processor. Whole files are weak seeds for the two content targets; for libFuzzer and AFL seed them with decoded content streams (`qpdf --show-object=4 --filtered-stream-data tests/Corpus/filter-chain.pdf`) and with `ContentSamples.PathHeavy` output. `function-type4` compiles the input after its first byte as a Type 4 (PostScript calculator) program (byte 0 picks 1 to 4 inputs and 1 to 4 outputs) and `function-sampled` builds a Type 0 (sampled) function whose Size, BitsPerSample, Order and Encode come from bytes 0 to 4 and whose samples are the rest (ISO 32000-2 §7.10); both evaluate at fixed points inside and outside the domain, require every output inside the range, and require warm evaluations to allocate nothing. `optional-content` (#76) opens an input that starts with `%PDF-` as a whole file and otherwise uses the bytes as choices for a generated file with optional content properties, groups, membership dictionaries and visibility expressions that may be cyclic, deep or mistyped; it computes default and alternate states, auto and usage states, every object's visibility (which must be the same twice) and a marked-content tracker over every object (whose nesting must return to zero); any input is a valid seed, and `optional-content.pdf` is the whole-file seed. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters, and reads every font of each page's resources through the font model (each simple font's 256 glyph names and widths, which must be non-empty and finite, and its descriptor); a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. `xmp` reads the input as an XMP packet (ISO 16684-1) through the reader the document uses, and again from its first `> /RoleMap << /A /B /B /A >>` followed by `<< /S /A /P 4 0 R /Pg 3 0 R /K [0 5 0 R] /A [1 << /O /Layout >> 2] >>`. `content-lexer` reads the input as decoded content stream bytes with the content reader (ISO 32000-2 §7.8.2, #55): every operator must lie inside the input, after the previous one, with a keyword of at least one byte, and every operand, nested arrays and dictionaries included, must be readable; `content-interpreter` runs the input as a page's content through the interpreter with a processor that asks for every event and checks that path verbs and points agree, that clip handles chain back to the initial clip and that the state stack is balanced at the end; `document` now also interprets every page with that processor. Whole files are weak seeds for the two content targets; for libFuzzer and AFL seed them with decoded content streams (`qpdf --show-object=4 --filtered-stream-data tests/Corpus/filter-chain.pdf`) and with `ContentSamples.PathHeavy` output. `function-type4` compiles the input after its first byte as a Type 4 (PostScript calculator) program (byte 0 picks 1 to 4 inputs and 1 to 4 outputs) and `function-sampled` builds a Type 0 (sampled) function whose Size, BitsPerSample, Order and Encode come from bytes 0 to 4 and whose samples are the rest (ISO 32000-2 §7.10); both evaluate at fixed points inside and outside the domain, require every output inside the range, and require warm evaluations to allocate nothing. `optional-content` (#76) opens an input that starts with `%PDF-` as a whole file and otherwise uses the bytes as choices for a generated file with optional content properties, groups, membership dictionaries and visibility expressions that may be cyclic, deep or mistyped; it computes default and alternate states, auto and usage states, every object's visibility (which must be the same twice) and a marked-content tracker over every object (whose nesting must return to zero); any input is a valid seed, and `optional-content.pdf` is the whole-file seed. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. diff --git a/tests/Broadside.TestSupport/ActionWalker.cs b/tests/Broadside.TestSupport/ActionWalker.cs new file mode 100644 index 00000000..afbce3b3 --- /dev/null +++ b/tests/Broadside.TestSupport/ActionWalker.cs @@ -0,0 +1,172 @@ +using Broadside.Objects; + +namespace Broadside.TestSupport; + +/// +/// Reads every action the document model reaches (issue #73): the catalog's OpenAction and AA, every page's AA, every annotation's A +/// and AA, every outline item's action and every document-level script, each through its whole Next tree and every typed property. +/// Public API only; shared by and the document fuzz target (linked as source there). +/// +/// ISO 32000-2 §12.6, §12.7.6, §7.7.2, §7.7.4. +public static class ActionWalker +{ + private static readonly CosName AnnotsKey = new("Annots"); + private static readonly CosName AKey = new("A"); + private static readonly CosName AAKey = new("AA"); + + /// Walks every action of ; throws when a tree yields an action twice. + /// An open document. + /// How many actions were read. + public static int Walk(PdfDocument document) + { + ArgumentNullException.ThrowIfNull(document); + int count = 0; + _ = document.OpenDestination; + _ = document.UriBase; + count += Read(document.OpenAction); + count += Read(document.AdditionalActions); + foreach (PdfPage page in document.Pages) + { + count += Read(page.AdditionalActions); + if (document.Resolve(page.Dictionary.TryGetValue(AnnotsKey, out CosObject? annots) ? annots : null) is not CosArray array) + { + continue; + } + + foreach (CosObject element in array) + { + if (document.Resolve(element) is CosDictionary annotation) + { + var owner = element as CosReference; + count += Read(document.GetAction(annotation.TryGetValue(AKey, out CosObject? a) ? a : null, owner)); + CosObject? aa = annotation.TryGetValue(AAKey, out CosObject? value) ? value : null; + count += Read(document.GetAnnotationAdditionalActions(aa, owner)); + count += Read(document.GetFieldAdditionalActions(aa, owner)); + } + } + } + + var outline = new Stack(document.Outline?.Items ?? []); + while (outline.TryPop(out PdfOutlineItem? item)) + { + count += Read(item.Action); + foreach (PdfOutlineItem child in item.Children) + { + outline.Push(child); + } + } + + foreach (KeyValuePair script in document.Names?.JavaScriptActions ?? []) + { + count += Read(script.Value); + } + + return count; + } + + private static int Read(PdfAdditionalActions? actions) + { + int count = 0; + foreach (KeyValuePair entry in actions?.Actions ?? []) + { + count += Read(entry.Value); + } + + return count; + } + + private static int Read(PdfAction? root) + { + if (root is null) + { + return 0; + } + + var seen = new HashSet(ReferenceEqualityComparer.Instance); + foreach (PdfAction action in root.EnumerateActionTree()) + { + if (!seen.Add(action.Dictionary)) + { + throw new InvalidOperationException("An action tree yielded the same action twice."); + } + + ReadProperties(action); + } + + return seen.Count; + } + + private static void ReadProperties(PdfAction action) + { + _ = (action.Kind, action.ActionType, action.Reference); + switch (action) + { + case PdfGoToAction goTo: + _ = (goTo.Destination, goTo.StructureDestination); + break; + case PdfRemoteGoToAction remote: + _ = (remote.File?.FileName, remote.Destination, remote.StructureDestination, remote.NewWindow); + break; + case PdfEmbeddedGoToAction embedded: + _ = (embedded.File?.FileName, embedded.Destination, embedded.NewWindow); + for (PdfEmbeddedTarget? target = embedded.Target; target is not null; target = target.Target) + { + _ = (target.Relationship, target.EmbeddedFileName, target.PageNumber, target.PageName, target.AnnotationIndex, target.AnnotationName); + } + + break; + case PdfGoToDocumentPartAction part: + _ = part.DocumentPart; + break; + case PdfLaunchAction launch: + _ = (launch.File?.FileName, launch.Mac, launch.Unix, launch.NewWindow); + _ = (launch.Windows?.FileName, launch.Windows?.DefaultDirectory, launch.Windows?.Operation, launch.Windows?.Parameters); + break; + case PdfThreadAction thread: + _ = (thread.File?.FileName, thread.ThreadDictionary, thread.ThreadIndex, thread.ThreadTitle, thread.BeadDictionary, thread.BeadIndex); + break; + case PdfUriAction uri: + _ = (uri.Uri, uri.UriObject, uri.IsMap, uri.ResolveUri()); + break; + case PdfSoundAction sound: + _ = (sound.Sound, sound.Volume, sound.IsSynchronous, sound.Repeats, sound.Mixes); + break; + case PdfMovieAction movie: + _ = (movie.Annotation, movie.Title, movie.Operation); + break; + case PdfHideAction hide: + _ = (hide.Targets.Select(target => (target.Dictionary, target.FieldName)).ToList(), hide.Hide); + break; + case PdfNamedAction named: + _ = (named.Name, named.Operation); + break; + case PdfSubmitFormAction submit: + _ = (submit.File?.IsUrl, submit.Fields?.Count, submit.Flags, submit.CharacterSet); + break; + case PdfResetFormAction reset: + _ = (reset.Fields?.Count, reset.Flags); + break; + case PdfImportDataAction import: + _ = import.File?.FileName; + break; + case PdfSetOcgStateAction state: + _ = (state.Changes.Count, state.PreserveRadioButtons); + break; + case PdfRenditionAction rendition: + _ = (rendition.Rendition, rendition.ScreenAnnotation, rendition.Operation, rendition.Script); + break; + case PdfTransitionAction transition: + _ = transition.Transition; + break; + case PdfGoTo3DViewAction view: + _ = (view.Annotation, view.ViewDictionary, view.ViewIndex, view.ViewName, view.ViewKeyword); + break; + case PdfJavaScriptAction script: + _ = script.Script; + break; + case PdfRichMediaExecuteAction richMedia: + _ = (richMedia.Annotation, richMedia.Instance, richMedia.Command?.Name, richMedia.Command?.Arguments.Count); + break; + } + } +} diff --git a/tests/Broadside.TestSupport/DocumentWalker.cs b/tests/Broadside.TestSupport/DocumentWalker.cs index 4c198c04..ef6b2b63 100644 --- a/tests/Broadside.TestSupport/DocumentWalker.cs +++ b/tests/Broadside.TestSupport/DocumentWalker.cs @@ -13,7 +13,7 @@ public sealed record DocumentWalkResult(int Pages, int Objects, int Streams, lon /// /// Reads everything the document model exposes, so that "the file opens" means more than "the trailer parsed" (objects load /// lazily, issue #45): version, trailer, revisions, linearization and hint tables, security, every page's boxes, rotation, user unit -/// and resources, the outline and every named destination (issue #70), every indirect object reachable from the trailer and every object number below the trailer's Size, and +/// and resources, the outline and every named destination (issue #70), every action through (issue #73), every indirect object reachable from the trailer and every object number below the trailer's Size, and /// every stream decoded through the filter pipeline (image filters that are not implemented yet end in a diagnostic, not an /// exception). Used by the real-world corpus gate (issue #47) and meant to be shared with the open-and-walk fuzz target and /// benchmark (issue #48): link this file as source there, as is. Public API only. @@ -60,6 +60,7 @@ public static DocumentWalkResult Walk(PdfDocument document) ReadCatalogEssentials(document); WalkNavigation(document); + _ = ActionWalker.Walk(document); var walk = new GraphWalk(document); walk.Visit(document.Trailer); diff --git a/tests/Broadside.Tests/Actions/ActionEntryTests.cs b/tests/Broadside.Tests/Actions/ActionEntryTests.cs new file mode 100644 index 00000000..b71b8311 --- /dev/null +++ b/tests/Broadside.Tests/Actions/ActionEntryTests.cs @@ -0,0 +1,216 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Actions; + +/// The entries of each action type (ISO 32000-2 §12.6.4.2 to §12.6.4.18, §12.7.6.2 to §12.7.6.4), read from actions-all.pdf. +public class ActionEntryTests +{ + [Fact] + public void Go_to_actions_read_their_local_remote_and_embedded_destinations() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("actions-all.pdf")); + IReadOnlyList actions = ActionTypeTests.LinkActions(document); + + var goTo = (PdfGoToAction)actions[0]; + Assert.Equal(0, Assert.IsType(goTo.Destination).PageIndex); + Assert.Equal(PdfDestinationTarget.StructureElement, goTo.StructureDestination!.TargetKind); + + var remote = (PdfRemoteGoToAction)actions[1]; + Assert.Equal("other.pdf", remote.File!.FileName); + PdfExplicitDestination remoteDestination = Assert.IsType(remote.Destination); + Assert.True(remoteDestination.IsRemote); + Assert.Equal((0, (int?)null, PdfDestinationView.Fit), (remoteDestination.PageNumber, remoteDestination.PageIndex, remoteDestination.View)); + Assert.True(remote.NewWindow); + Assert.Null(remote.StructureDestination); + + var embedded = (PdfEmbeddedGoToAction)actions[2]; + Assert.Null(embedded.File); + Assert.False(embedded.NewWindow); + PdfNamedDestination chapter = Assert.IsType(embedded.Destination); + Assert.Equal(("Chapter 1", true), (chapter.Text, chapter.IsRemote)); + PdfEmbeddedTarget parent = embedded.Target!; + Assert.Equal(PdfEmbeddedTargetRelationship.Parent, parent.Relationship); + PdfEmbeddedTarget child = parent.Target!; + Assert.Equal((PdfEmbeddedTargetRelationship.Child, "embedded.pdf"), (child.Relationship, child.EmbeddedFileName!.DecodeText())); + PdfEmbeddedTarget attachment = child.Target!; + Assert.Equal((0, (int?)null, "attached"), (attachment.PageNumber, attachment.AnnotationIndex, attachment.AnnotationName)); + Assert.Null(attachment.PageName); + Assert.Null(attachment.Target); + + var part = (PdfGoToDocumentPartAction)actions[3]; + Assert.Same(document.Resolve(new CosReference(82, 0)), part.DocumentPart); + Assert.Empty(Warnings(document)); + } + + [Fact] + public void Launch_and_thread_actions_read_their_files_platform_parameters_and_article_indexes() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("actions-all.pdf")); + IReadOnlyList actions = ActionTypeTests.LinkActions(document); + + var launch = (PdfLaunchAction)actions[4]; + Assert.Equal("readme.txt", launch.File!.FileName); + Assert.True(launch.NewWindow); + PdfWindowsLaunchParameters windows = launch.Windows!; + Assert.Equal(("notepad.exe", @"C:\Temp", "print", "readme.txt"), + (windows.FileName!.DecodeText(), windows.DefaultDirectory!.DecodeText(), windows.Operation, windows.Parameters!.DecodeText())); + Assert.Null(launch.Mac); + Assert.Null(launch.Unix); + + var thread = (PdfThreadAction)actions[5]; + Assert.Equal((0, 0), (thread.ThreadIndex, thread.BeadIndex)); + Assert.Null(thread.ThreadDictionary); + Assert.Null(thread.ThreadTitle); + Assert.Null(thread.File); + Assert.Empty(Warnings(document)); + } + + [Fact] + public void A_relative_uri_is_resolved_against_the_catalog_base_without_being_fetched() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("actions-all.pdf")); + var uri = (PdfUriAction)ActionTypeTests.LinkActions(document)[6]; + + Assert.Equal("docs/index.html", uri.Uri); + Assert.True(uri.IsMap); + Assert.Equal(new Uri("https://example.com/"), document.UriBase); + Assert.Equal(new Uri("https://example.com/docs/index.html"), uri.ResolveUri()); + Assert.Empty(Warnings(document)); + } + + [Fact] + public void Multimedia_actions_are_exposed_as_data_with_their_defaults() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("actions-all.pdf")); + IReadOnlyList actions = ActionTypeTests.LinkActions(document); + + var sound = (PdfSoundAction)actions[7]; + Assert.Equal(4, sound.Sound!.EncodedData.Length); + Assert.Equal((0.25, true, false, true), (sound.Volume, sound.IsSynchronous, sound.Repeats, sound.Mixes)); + + var movie = (PdfMovieAction)actions[8]; + Assert.Same(document.Resolve(new CosReference(68, 0)), movie.Annotation); + Assert.Null(movie.Title); + Assert.Equal(PdfMovieOperation.Pause, movie.Operation); + + var rendition = (PdfRenditionAction)actions[15]; + Assert.Equal((PdfRenditionOperation.Play, 0, "play();"), (rendition.Operation, rendition.OperationValue, rendition.Script)); + Assert.Same(document.Resolve(new CosReference(72, 0)), rendition.ScreenAnnotation); + Assert.Same(document.Resolve(new CosReference(73, 0)), rendition.Rendition); + Assert.IsType(rendition.ScriptObject); + + var view = (PdfGoTo3DViewAction)actions[17]; + Assert.Same(document.Resolve(new CosReference(74, 0)), view.Annotation); + Assert.Equal(new CosName("F"), view.ViewKeyword); + Assert.Null(view.ViewIndex); + Assert.Null(view.ViewName); + Assert.Null(view.ViewDictionary); + + var richMedia = (PdfRichMediaExecuteAction)actions[19]; + Assert.Same(document.Resolve(new CosReference(77, 0)), richMedia.Annotation); + Assert.Same(document.Resolve(new CosReference(78, 0)), richMedia.Instance); + PdfRichMediaCommand command = richMedia.Command!; + Assert.Equal("play", command.Name); + Assert.Equal([new CosString("intro"u8), new CosInteger(2), CosBoolean.True], command.Arguments); + Assert.Empty(Warnings(document)); + } + + [Fact] + public void Scripts_and_multimedia_are_recorded_as_out_of_scope_information_and_never_as_warnings() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("actions-all.pdf")); + + _ = ActionTypeTests.LinkActions(document); + + Assert.Equal( + ["ActionOutOfScope 47", "ActionOutOfScope 48", "ActionOutOfScope 55", "ActionOutOfScope 57", "ActionOutOfScope 58", "ActionOutOfScope 59"], + document.Diagnostics.Select(diagnostic => $"{diagnostic.Code} {diagnostic.ObjectReference?.ObjectNumber}")); + Assert.All(document.Diagnostics, diagnostic => Assert.Equal(DiagnosticSeverity.Information, diagnostic.Severity)); + } + + [Fact] + public void Hide_named_and_transition_actions_read_their_targets_names_and_transitions() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("actions-all.pdf")); + IReadOnlyList actions = ActionTypeTests.LinkActions(document); + + var hide = (PdfHideAction)actions[9]; + Assert.False(hide.Hide); + Assert.Equal(2, hide.Targets.Count); + Assert.Equal((new CosReference(40, 0), (string?)null), (hide.Targets[0].Reference, hide.Targets[0].FieldName)); + Assert.Same(document.Resolve(new CosReference(40, 0)), hide.Targets[0].Dictionary); + Assert.Equal(("email", (CosDictionary?)null), (hide.Targets[1].FieldName, hide.Targets[1].Dictionary)); + + var named = (PdfNamedAction)actions[10]; + Assert.Equal((PdfNamedOperation.NextPage, new CosName("NextPage")), (named.Operation, named.Name)); + var print = (PdfNamedAction)Assert.Single(named.Next); + Assert.Equal((PdfNamedOperation.Other, new CosName("Print")), (print.Operation, print.Name)); + + var transition = (PdfTransitionAction)actions[16]; + Assert.Equal(new CosName("Dissolve"), transition.Transition![new CosName("S")]); + Assert.Empty(Warnings(document)); + } + + [Fact] + public void Form_actions_read_their_url_fields_flags_and_character_set() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("actions-all.pdf")); + IReadOnlyList actions = ActionTypeTests.LinkActions(document); + + var submit = (PdfSubmitFormAction)actions[11]; + Assert.True(submit.File!.IsUrl); + Assert.Equal("https://example.com/submit", submit.File.FileName); + Assert.Equal(PdfSubmitFormFlags.Exclude | PdfSubmitFormFlags.ExportFormat | PdfSubmitFormFlags.GetMethod, submit.Flags); + Assert.Equal("utf-8", submit.CharacterSet); + Assert.Equal([new CosReference(69, 0), null], submit.Fields!.Select(field => field.Reference)); + Assert.Equal([null, "name.first"], submit.Fields!.Select(field => field.FieldName)); + + var reset = (PdfResetFormAction)actions[12]; + Assert.Equal(PdfResetFormFlags.Exclude, reset.Flags); + Assert.Equal("email", Assert.Single(reset.Fields!).FieldName); + + var import = (PdfImportDataAction)actions[13]; + Assert.Equal("data.fdf", import.File!.FileName); + Assert.False(import.File.IsUrl); + Assert.Empty(Warnings(document)); + } + + [Fact] + public void A_set_ocg_state_action_lists_its_changes_and_applies_them_to_a_state_snapshot() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("actions-all.pdf")); + var action = (PdfSetOcgStateAction)ActionTypeTests.LinkActions(document)[14]; + PdfOptionalContentProperties properties = document.OptionalContent!; + PdfOptionalContentGroup one = properties.Groups[0]; + PdfOptionalContentGroup two = properties.Groups[1]; + PdfOptionalContentState before = properties.GetDefaultStates(); + + PdfOptionalContentState after = action.ApplyTo(before); + + Assert.False(action.PreserveRadioButtons); + Assert.Equal( + ["Off 70", "Toggle 71", "Toggle 70"], + action.Changes.Select(change => $"{change.Operation} {change.GroupReference?.ObjectNumber}")); + Assert.Same(document.Resolve(new CosReference(70, 0)), action.Changes[0].Group); + Assert.True(before.IsOn(one) && before.IsOn(two)); + Assert.True(after.IsOn(one)); + Assert.False(after.IsOn(two)); + Assert.Empty(Warnings(document)); + } + + [Fact] + public void A_javascript_action_reads_its_script_from_a_stream_and_is_never_run() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("actions-all.pdf")); + var script = (PdfJavaScriptAction)ActionTypeTests.LinkActions(document)[18]; + + Assert.Equal("app.alert(\"stream\");", script.Script); + Assert.Same(document.Resolve(new CosReference(76, 0)), script.ScriptObject); + Assert.Equal(new CosName("JavaScript"), script.ActionType); + } + + internal static IEnumerable Warnings(PdfDocument document) => + document.Diagnostics.Where(diagnostic => diagnostic.Severity > DiagnosticSeverity.Information); +} diff --git a/tests/Broadside.Tests/Actions/ActionTypeTests.cs b/tests/Broadside.Tests/Actions/ActionTypeTests.cs index 6e4867f5..ef0d094b 100644 --- a/tests/Broadside.Tests/Actions/ActionTypeTests.cs +++ b/tests/Broadside.Tests/Actions/ActionTypeTests.cs @@ -52,5 +52,5 @@ public void An_action_type_the_table_does_not_list_is_kept_as_an_unknown_action( /// The actions of the link annotations 40 to 59, in page order. internal static IReadOnlyList LinkActions(PdfDocument document) => - [.. Enumerable.Range(40, 20).Select(number => document.GetAction(((CosDictionary)document.Resolve(new CosReference(number, 0)))[A])!)]; + [.. Enumerable.Range(40, 20).Select(number => document.GetAction(((CosDictionary)document.Resolve(new CosReference(number, 0)))[A], new CosReference(number, 0))!)]; } diff --git a/tests/Broadside.Tests/Actions/MalformedActionTests.cs b/tests/Broadside.Tests/Actions/MalformedActionTests.cs new file mode 100644 index 00000000..78a8b460 --- /dev/null +++ b/tests/Broadside.Tests/Actions/MalformedActionTests.cs @@ -0,0 +1,150 @@ +using System.Text; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Actions; + +/// Actions that break a "shall" of ISO 32000-2 §12.6 read leniently with a diagnostic, and throw in strict mode only when read. +public class MalformedActionTests +{ + private static readonly CosReference Owner = new(3, 0); + + public static TheoryData MissingRequiredEntries => new() + { + { "/S /GoToR /D [0 /Fit]", "ActionInvalid" }, + { "/S /GoToE /D (x)", "ActionInvalid" }, + { "/S /GoToDp", "ActionInvalid" }, + { "/S /Launch", "ActionInvalid" }, + { "/S /Thread", "ActionInvalid" }, + { "/S /Movie", "ActionInvalid" }, + { "/S /Movie /T (a) /Annotation << >>", "ActionInvalid" }, + { "/S /Hide", "ActionInvalid" }, + { "/S /Named", "ActionInvalid" }, + { "/S /SubmitForm", "ActionInvalid" }, + { "/S /ImportData", "ActionInvalid" }, + { "/S /SetOCGState", "ActionInvalid" }, + { "/S /Rendition", "ActionInvalid" }, + { "/S /Rendition /OP 7", "ActionInvalid" }, + { "/S /Rendition /OP 1", "ActionInvalid" }, + { "/S /Rendition /OP 0 /AN << >>", "ActionInvalid" }, + { "/S /Trans", "ActionInvalid" }, + { "/S /GoTo3DView /TA << >>", "ActionInvalid" }, + { "/S /JavaScript", "ActionInvalid" }, + { "/S /RichMediaExecute /TA << >>", "ActionInvalid" }, + { "/S /Thread /D true", "ActionEntryInvalid" }, + }; + + [Theory] + [MemberData(nameof(MissingRequiredEntries))] + public void An_action_missing_a_required_entry_is_read_with_a_warning(string entries, string code) + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + + Assert.NotNull(document.GetAction(Parse(entries), Owner)); + + Assert.Equal([code], Warnings(document).Select(diagnostic => diagnostic.Code)); + } + + [Fact] + public void A_rendition_with_a_script_and_an_unknown_operation_is_valid() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + + var rendition = (PdfRenditionAction)document.GetAction(Parse("/S /Rendition /OP 9 /JS (x\\(\\);)"), Owner)!; + + Assert.Equal((9, (PdfRenditionOperation?)null, "x();"), (rendition.OperationValue, rendition.Operation, rendition.Script)); + Assert.Empty(Warnings(document)); + } + + [Fact] + public void Entries_of_the_wrong_type_read_as_absent_or_default_with_a_warning() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + + var sound = (PdfSoundAction)document.GetAction(Parse("/S /Sound /Sound 5 /Volume 3 /Mix 1"), Owner)!; + Assert.Null(sound.Sound); + Assert.Equal(1.0, sound.Volume); + Assert.False(sound.Mixes); + + var movie = (PdfMovieAction)document.GetAction(Parse("/S /Movie /T (clip) /Operation /Rewind"), new CosReference(4, 0))!; + Assert.Equal(PdfMovieOperation.Play, movie.Operation); + + var script = (PdfJavaScriptAction)document.GetAction(Parse("/S /JavaScript /JS 12"), new CosReference(5, 0))!; + Assert.Null(script.Script); + + var remote = (PdfRemoteGoToAction)document.GetAction(Parse("/S /GoToR /F 1 /D [0 /Fit]"), new CosReference(6, 0))!; + Assert.Null(remote.File); + + var state = (PdfSetOcgStateAction)document.GetAction(Parse("/S /SetOCGState /State [<< >> /Dim << >> 3 /ON << >>]"), new CosReference(7, 0))!; + Assert.Equal([PdfOcgStateOperation.On], state.Changes.Select(change => change.Operation)); + + Assert.Equal( + ["ActionEntryInvalid 3", "ActionEntryInvalid 4", "ActionEntryInvalid 5", "ActionEntryInvalid 6", "ActionEntryInvalid 7"], + Warnings(document).Select(diagnostic => $"{diagnostic.Code} {diagnostic.ObjectReference?.ObjectNumber}")); + } + + [Fact] + public void A_uri_that_is_not_utf8_or_not_a_string_is_read_with_a_warning() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + + var utf8 = (PdfUriAction)document.GetAction(Parse("/S /URI /URI (https://example.com/\xC3\xA9t\xC3\xA9)"), new CosReference(3, 0))!; + var latin1 = (PdfUriAction)document.GetAction(Parse("/S /URI /URI (https://example.com/caf\xE9)"), new CosReference(4, 0))!; + var utf16 = (PdfUriAction)document.GetAction(Parse("/S /URI /URI "), new CosReference(5, 0))!; + var name = (PdfUriAction)document.GetAction(Parse("/S /URI /URI /relative"), new CosReference(6, 0))!; + + Assert.Equal("https://example.com/été", utf8.Uri); + Assert.Equal("https://example.com/café", latin1.Uri); + Assert.Equal("a/b", utf16.Uri); + Assert.Equal("relative", name.Uri); + Assert.Null(name.ResolveUri()); + Assert.Equal(new Uri("https://example.com/%C3%A9t%C3%A9"), utf8.ResolveUri()); + Assert.Equal( + ["UriInvalid 4", "UriInvalid 5", "UriInvalid 6"], + Warnings(document).Select(diagnostic => $"{diagnostic.Code} {diagnostic.ObjectReference?.ObjectNumber}")); + } + + [Fact] + public void A_cycle_of_embedded_target_dictionaries_is_refused_with_a_warning() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + CosDictionary action = Parse("/S /GoToE /D (x) /T << /R /C /N (a) >>"); + var target = (CosDictionary)action[new CosName("T")]; + target[new CosName("T")] = target; + + var goTo = (PdfEmbeddedGoToAction)document.GetAction(action, Owner)!; + + Assert.Null(goTo.Target!.Target); + Assert.Equal("ActionTargetCycle", Assert.Single(Warnings(document)).Code); + } + + [Fact] + public void Strict_mode_throws_when_an_invalid_action_is_read_not_when_the_document_opens() + { + byte[] file = TestPdfWithOpenAction("<< /S /GoTo >>"); + using PdfDocument document = PdfDocument.Open(file, new PdfOptions().UseStrict()); + + DiagnosticException error = Assert.Throws(() => document.OpenAction); + + Assert.Equal("ActionInvalid", error.Diagnostic.Code); + } + + [Fact] + public void Strict_mode_records_out_of_scope_scripts_without_throwing() + { + byte[] file = TestPdfWithOpenAction("<< /S /JavaScript /JS (x\\(\\);) >>"); + using PdfDocument document = PdfDocument.Open(file, new PdfOptions().UseStrict()); + + Assert.Equal("x();", Assert.IsType(document.OpenAction).Script); + Assert.Equal(DiagnosticSeverity.Information, Assert.Single(document.Diagnostics).Severity); + } + + private static CosDictionary Parse(string entries) => + (CosDictionary)CosObject.Parse(Encoding.Latin1.GetBytes("<< " + entries + " >>")); + + private static IEnumerable Warnings(PdfDocument document) => ActionEntryTests.Warnings(document); + + private static byte[] TestPdfWithOpenAction(string action) => + Document.TestPdf.OnePage(pageEntries: "", catalogEntries: " /OpenAction " + action); +} diff --git a/tests/Broadside.Tests/Actions/PreservedActionTests.cs b/tests/Broadside.Tests/Actions/PreservedActionTests.cs new file mode 100644 index 00000000..4152b779 --- /dev/null +++ b/tests/Broadside.Tests/Actions/PreservedActionTests.cs @@ -0,0 +1,114 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Tests.Writing; +using Broadside.TestSupport; + +namespace Broadside.Tests.Actions; + +/// +/// Actions the library keeps as data (ISO 32000-2 §12.6.4.9, §12.6.4.10, §12.6.4.14, §12.6.4.17, §12.6.4.18): reading them through +/// every typed view changes nothing, and saving the document copies them byte for byte (actions-preserved.pdf). +/// +public class PreservedActionTests +{ + private static readonly CosName A = new("A"); + + private static readonly int[] ActionObjects = [10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 23, 24, 27]; + + private static readonly int[] OwnerObjects = [1, 3, 19, 21, 22, 30, 31, 32, 33, 34, 35, 36, 37]; + + [Fact] + public void Scripts_sounds_movies_renditions_and_rich_media_read_as_data_in_their_stored_forms() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("actions-preserved.pdf")); + + Assert.Equal(Expected, Read(document)); + Assert.DoesNotContain(document.Diagnostics, diagnostic => diagnostic.Severity > DiagnosticSeverity.Information); + Assert.Contains(document.Diagnostics, diagnostic => diagnostic is { Code: "ActionCycle", Severity: DiagnosticSeverity.Information }); + } + + [Fact] + public void Reading_every_action_changes_no_object() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("actions-preserved.pdf")); + + _ = Read(document); + + Assert.All(ActionObjects.Concat(OwnerObjects), number => Assert.False(document.Resolve(new CosReference(number, 0)).IsDirty, $"object {number}")); + } + + [Fact] + public void Saving_after_reading_every_action_keeps_their_bytes_and_their_values() + { + byte[] source = Corpus.Bytes("actions-preserved.pdf"); + using var saved = new MemoryStream(); + using (PdfDocument document = PdfDocument.Open(source)) + { + _ = Read(document); + document.Save(saved); + } + + Dictionary<(int Number, int Generation), byte[]> before = ObjectBodies.Read(source); + Dictionary<(int Number, int Generation), byte[]> after = ObjectBodies.Read(saved.ToArray()); + Assert.All(ActionObjects.Concat(OwnerObjects), number => Assert.Equal(before[(number, 0)], after[(number, 0)])); + Assert.True(after[(10, 0)].AsSpan().IndexOf("\\053\\r\\n// one \\\nline"u8) >= 0); + Assert.True(after[(13, 0)].AsSpan().IndexOf("/Java#53cript"u8) >= 0); + Assert.True(after[(14, 0)].AsSpan().IndexOf("/Volume .50"u8) >= 0); + + using PdfDocument reopened = PdfDocument.Open(saved.ToArray()); + Assert.Empty(reopened.Diagnostics); + Assert.Equal(Expected, Read(reopened)); + Assert.Equal( + ["ActionCycle"], + reopened.Diagnostics.Where(diagnostic => diagnostic.Code != "ActionOutOfScope").Select(diagnostic => diagnostic.Code)); + } + + private static IReadOnlyList Expected => + [ + "open JavaScript app.alert('flate');", + "page-open JavaScript app.alert('hex') ", + "doc JavaScript var x = 1;", + "30 JavaScript app.alert(\"hi\");+\r\n// one line", + "31 JavaScript app.alert('hex') ", + "32 JavaScript var x = 1;", + "33 Sound 0.5 False False True 4", + "34 Rendition PlayOrResume play(); MR 21", + "35 Movie Play 19", + "36 RichMediaExecute rewind 0 22 26", + "37 GoTo,GoTo", + ]; + + /// Reads every preserved action through the public model and describes what it read. + private static List Read(PdfDocument document) + { + var read = new List + { + $"open {Describe(document.OpenAction!)}", + $"page-open {Describe(document.Pages[0].AdditionalActions!.Open!)}", + $"doc {Describe(document.Names!.JavaScriptActions.Single().Value)}", + }; + for (int number = 30; number <= 37; number++) + { + var link = (CosDictionary)document.Resolve(new CosReference(number, 0)); + PdfAction action = document.GetAction(link[A], new CosReference(number, 0))!; + read.Add($"{number} {(action is PdfGoToAction ? string.Join(",", action.EnumerateActionTree().Select(next => next.Kind)) : Describe(action))}"); + } + + return read; + } + + private static string Describe(PdfAction action) => action switch + { + PdfJavaScriptAction script => $"JavaScript {script.Script}", + PdfSoundAction sound => $"Sound {sound.Volume} {sound.IsSynchronous} {sound.Repeats} {sound.Mixes} {sound.Sound!.EncodedData.Length}", + PdfRenditionAction rendition => + $"Rendition {rendition.Operation} {rendition.Script} {((CosName)rendition.Rendition![new CosName("S")]).Value} {Number(rendition.Dictionary, "AN")}", + PdfMovieAction movie => $"Movie {movie.Operation} {Number(movie.Dictionary, "Annotation")}", + PdfRichMediaExecuteAction richMedia => + $"RichMediaExecute {richMedia.Command!.Name} {string.Join(" ", richMedia.Command.Arguments.Select(argument => ((CosNumber)argument).ToDouble()))} {Number(richMedia.Dictionary, "TA")} {Number(richMedia.Dictionary, "TI")}", + _ => action.Kind.ToString(), + }; + + private static int Number(CosDictionary dictionary, string key) => ((CosReference)dictionary[new CosName(key)]).ObjectNumber; + +} diff --git a/tests/Broadside.Tests/Actions/TriggerEventTests.cs b/tests/Broadside.Tests/Actions/TriggerEventTests.cs new file mode 100644 index 00000000..976df220 --- /dev/null +++ b/tests/Broadside.Tests/Actions/TriggerEventTests.cs @@ -0,0 +1,174 @@ +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Actions; + +/// Trigger events (ISO 32000-2 §12.6.3, Tables 197-200), the catalog's OpenAction and the document-level scripts (§7.7.2, §7.7.4), and Next chains (§12.6.2). +public class TriggerEventTests +{ + private static readonly CosName AA = new("AA"); + + [Fact] + public void The_open_action_is_a_go_to_action_and_the_document_has_no_open_destination() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("actions-all.pdf")); + + PdfGoToAction open = Assert.IsType(document.OpenAction); + + Assert.Equal(PdfDestinationView.Fit, Assert.IsType(open.Destination).View); + Assert.Null(document.OpenDestination); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void An_open_action_array_is_the_open_destination() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("outline.pdf")); + document.Catalog[new CosName("OpenAction")] = new CosArray([new CosReference(3, 0), new CosName("FitH"), new CosInteger(700)]); + + PdfExplicitDestination destination = Assert.IsType(document.OpenDestination); + + Assert.Equal((0, PdfDestinationView.FitH, (double?)700), (destination.PageIndex, destination.View, destination.Top)); + Assert.Null(document.OpenAction); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void An_open_action_that_is_a_name_is_read_as_a_named_destination_with_a_warning() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + document.Catalog[new CosName("OpenAction")] = new CosName("Start"); + + Assert.Equal("Start", Assert.IsType(document.OpenDestination).Text); + Assert.Null(document.OpenAction); + Assert.Equal("OpenActionInvalid", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void Documents_without_actions_have_no_open_action_and_no_additional_actions() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + + Assert.Null(document.OpenAction); + Assert.Null(document.OpenDestination); + Assert.Null(document.AdditionalActions); + Assert.Null(document.Pages[0].AdditionalActions); + Assert.Null(document.UriBase); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void The_catalog_page_annotation_and_field_triggers_are_typed_by_their_owner() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("actions-all.pdf")); + + PdfDocumentAdditionalActions catalog = document.AdditionalActions!; + Assert.Equal( + ["WC();", "WS();", "DS();", "WP();", "DP();"], + new[] { catalog.WillClose, catalog.WillSave, catalog.DidSave, catalog.WillPrint, catalog.DidPrint }.Select(Script)); + + PdfPageAdditionalActions page = document.Pages[0].AdditionalActions!; + Assert.Equal(PdfNamedOperation.FirstPage, Assert.IsType(page.Open).Operation); + Assert.Equal("pageClosed();", Script(page.Close)); + + var link = (CosDictionary)document.Resolve(new CosReference(60, 0)); + PdfAnnotationAdditionalActions annotation = document.GetAnnotationAdditionalActions(link[AA], new CosReference(60, 0))!; + Assert.Equal( + ["E();", "X();", "D();", "U();", "PO();", "PC();", "PV();", "PI();"], + new[] + { + annotation.CursorEnter, annotation.CursorExit, annotation.MouseDown, annotation.MouseUp, + annotation.PageOpen, annotation.PageClose, annotation.PageVisible, annotation.PageInvisible, + }.Select(Script)); + Assert.Null(annotation.Focus); + + // A widget merged with its field: one AA holds both sets, and C means calculate for the field. + var widget = (CosDictionary)document.Resolve(new CosReference(69, 0)); + PdfFieldAdditionalActions field = document.GetFieldAdditionalActions(widget[AA], new CosReference(69, 0))!; + Assert.Equal(["K();", "F();", "V();", "C();"], new[] { field.Keystroke, field.Format, field.Validate, field.Calculate }.Select(Script)); + PdfAnnotationAdditionalActions widgetAnnotation = document.GetAnnotationAdditionalActions(widget[AA], new CosReference(69, 0))!; + Assert.Equal(["Fo();", "Bl();"], new[] { widgetAnnotation.Focus, widgetAnnotation.Blur }.Select(Script)); + Assert.Equal(["K", "F", "V", "C", "Fo", "Bl"], widgetAnnotation.Actions.Select(entry => entry.Key.Value)); + Assert.Empty(ActionEntryTests.Warnings(document)); + } + + [Fact] + public void An_additional_actions_entry_that_is_not_a_dictionary_reads_as_none_with_a_warning() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + document.Pages[0].Dictionary[AA] = new CosInteger(1); + + Assert.Null(document.Pages[0].AdditionalActions); + Assert.Equal("AdditionalActionsInvalid 3", Describe(Assert.Single(document.Diagnostics))); + } + + [Fact] + public void The_name_dictionary_holds_one_document_level_script() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("actions-all.pdf")); + + KeyValuePair script = Assert.Single(document.Names!.JavaScriptActions); + + Assert.Equal("init", script.Key.DecodeText()); + Assert.Equal("var initialised = true;", script.Value.Script); + Assert.NotNull(document.Names.JavaScript); + } + + [Fact] + public void The_action_tree_is_walked_depth_first_in_execution_order() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("actions-all.pdf")); + PdfAction goTo = ActionTypeTests.LinkActions(document)[0]; + + Assert.Equal([PdfActionKind.Named, PdfActionKind.Uri], goTo.Next.Select(action => action.Kind)); + Assert.Equal( + [PdfActionKind.GoTo, PdfActionKind.Named, PdfActionKind.JavaScript, PdfActionKind.Uri], + goTo.EnumerateActionTree().Select(action => action.Kind)); + Assert.Equal([PdfActionKind.GoTo], goTo.EnumerateActionTree(maxDepth: 0).Select(action => action.Kind)); + Assert.Equal("ActionTreeTooDeep 40", Describe(Assert.Single(ActionEntryTests.Warnings(document)))); + } + + [Fact] + public void A_cycle_of_next_actions_is_cut_with_information_and_a_shared_action_is_yielded_once() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + var shared = new CosDictionary { [new CosName("S")] = new CosName("Named"), [new CosName("N")] = new CosName("LastPage") }; + var first = new CosDictionary { [new CosName("S")] = new CosName("Named"), [new CosName("N")] = new CosName("NextPage") }; + var root = new CosDictionary + { + [new CosName("S")] = new CosName("Named"), + [new CosName("N")] = new CosName("FirstPage"), + [new CosName("Next")] = new CosArray([first, shared, shared]), + }; + first[new CosName("Next")] = new CosArray([shared, root]); + + PdfAction action = document.GetAction(root)!; + + Assert.Equal( + [PdfNamedOperation.FirstPage, PdfNamedOperation.NextPage, PdfNamedOperation.LastPage], + action.EnumerateActionTree().Select(next => ((PdfNamedAction)next).Operation)); + Diagnostics.Diagnostic cycle = Assert.Single(document.Diagnostics); + Assert.Equal(("ActionCycle", Diagnostics.DiagnosticSeverity.Information), (cycle.Code, cycle.Severity)); + } + + [Fact] + public void A_next_entry_with_elements_that_are_not_actions_skips_them_with_a_warning() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + var root = new CosDictionary + { + [new CosName("S")] = new CosName("Named"), + [new CosName("N")] = new CosName("FirstPage"), + [new CosName("Next")] = new CosArray([new CosInteger(1), new CosDictionary { [new CosName("S")] = new CosName("Trans"), [new CosName("Trans")] = new CosDictionary() }]), + }; + + PdfAction action = document.GetAction(root, new CosReference(3, 0))!; + + Assert.Equal(PdfActionKind.Transition, Assert.Single(action.Next).Kind); + Assert.Equal("ActionNextInvalid 3", Describe(Assert.Single(document.Diagnostics))); + } + + private static string? Script(PdfAction? action) => Assert.IsType(action).Script; + + private static string Describe(Diagnostics.Diagnostic diagnostic) => $"{diagnostic.Code} {diagnostic.ObjectReference?.ObjectNumber}"; +} diff --git a/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt b/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt index ff652729..42e34c04 100644 --- a/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt +++ b/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt @@ -1,6 +1,6 @@ pdfjs: 989 files - Clean: 670 - Diagnostics: 305 + Clean: 666 + Diagnostics: 309 PasswordRequired: 12 CertificateRequired: 0 EncryptionUnsupported: 0 @@ -21,6 +21,7 @@ UnexpectedToken: 8 XrefEntryFormatInvalid: 8 StartxrefMissing: 7 + DestinationInvalid: 6 FilterDataInvalid: 6 FilterDataTruncated: 6 DictionaryKeyNotName: 5 @@ -30,9 +31,9 @@ DictionaryDuplicateKey: 4 PageMediaBoxMissing: 4 DateInvalid: 3 - DestinationInvalid: 3 DictionaryUnterminated: 3 FileIdentifierInvalid: 3 + NameTreeNodeInvalid: 3 PageTreeNodeTypeInvalid: 3 PagesMissing: 3 ArrayUnterminated: 2 @@ -189,8 +190,8 @@ qpdf: 639 files XrefStreamWidthsInvalid: 1 XrefSubsectionHeaderInvalid: 1 pdfium-tests: 840 files - Clean: 281 - Diagnostics: 552 + Clean: 269 + Diagnostics: 564 PasswordRequired: 2 CertificateRequired: 4 EncryptionUnsupported: 0 @@ -216,7 +217,9 @@ pdfium-tests: 840 files MissingEndobj: 12 OutlineCountInvalid: 12 OutlineItemInvalid: 12 + DestinationInvalid: 11 UnexpectedToken: 10 + ActionInvalid: 7 CatalogTypeInvalid: 5 DictionaryDuplicateKey: 5 FileIdentifierInvalid: 5 @@ -224,7 +227,6 @@ pdfium-tests: 840 files PageResourcesMissing: 5 PageTreeNodeTypeInvalid: 5 PageTreeParentMismatch: 5 - DestinationInvalid: 4 DictionaryUnterminated: 4 StartxrefMissing: 4 XrefEntryFormatInvalid: 4 @@ -232,6 +234,7 @@ pdfium-tests: 840 files MetadataNotEncrypted: 3 NameTreeLimitsInvalid: 3 StringUnterminated: 3 + ActionEntryInvalid: 2 ArrayUnterminated: 2 EncryptionRevisionInvalid: 2 EndOfFileMarkerNotLast: 2 @@ -239,7 +242,6 @@ pdfium-tests: 840 files TrailerMissing: 2 ViewerPreferenceInvalid: 2 XrefSubsectionHeaderInvalid: 2 - ActionInvalid: 1 DictionaryValueMissing: 1 EncryptDictionaryInvalid: 1 EndOfFileMarkerMissing: 1 diff --git a/tests/Broadside.Tests/LogicalStructure/StructureCorpusTests.cs b/tests/Broadside.Tests/LogicalStructure/StructureCorpusTests.cs index 4e752b7f..04af252d 100644 --- a/tests/Broadside.Tests/LogicalStructure/StructureCorpusTests.cs +++ b/tests/Broadside.Tests/LogicalStructure/StructureCorpusTests.cs @@ -41,6 +41,7 @@ public void A_well_formed_file_reads_its_structure_tree_with_no_diagnostics(stri "tagged-structure.pdf" => 18, "associated-files.pdf" => 1, // the structure element that carries an AF entry (§14.13.6) "outline-full.pdf" => 1, // the H1 an outline item's /SE points to (§12.3.3) + "actions-all.pdf" => 1, // the P a go-to action's SD points to (§12.6.4.2) _ => -1, }; Assert.Equal(expected, elements); diff --git a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt index 93f07fb1..d6a82683 100644 --- a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt +++ b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt @@ -1,4 +1,6 @@ [ + actions-all.pdf, + actions-preserved.pdf, annotations-link.pdf, ascii85-stream.pdf, asciihex-stream.pdf, diff --git a/tests/Corpus/actions-all.pdf b/tests/Corpus/actions-all.pdf index ee45a03e30c18ebcbb1bf31480c291266a9a359c..82022d28e4eca3b8850585bd18d50e128959b3dc 100644 GIT binary patch delta 565 zcmZXRI}XAy5JYPtB2iJhNx!!DW0xR73n!uA0;b^vY3R8Ch_lf{oF>V*T8*ClG~V0( zyL&y_&$E4RijR(l<1VhL14UKLk`KV;Xv>UA6tW=5sYvC@M9fARE}MX#%lWL@os=Cs_+G#YzfatsWa|pagd#<9kfA#^aLz3$H_e WcIz$fQQ5e^y89|h({+c_vH1Z;z;3Dl delta 547 zcmZXRJqp4=5QR%I5U{e|CN>uCZ02uE1ue}f#Lg?k#uLQCV+i8W>?N^@d0Q=yZ}#KO zezw=$^HI*ira1dWo_SC$Y?5-ltCgY$Y}<#7$fHl bytes: b" /Fields [69 0 R (name.first)] /Flags 13 /CharSet (utf-8) >>")), (52, link(b"<< /S /ResetForm /Fields [(email)] /Flags 1 >>")), (53, link(b"<< /S /ImportData /F (data.fdf) >>")), - (54, link(b"<< /S /SetOCGState /State [/OFF 70 0 R /Toggle 71 0 R 70 0 R /ON 71 0 R] /PreserveRB false >>")), + (54, link(b"<< /S /SetOCGState /State [/OFF 70 0 R /Toggle 71 0 R 70 0 R] /PreserveRB false >>")), (55, link(b"<< /S /Rendition /OP 0 /AN 72 0 R /R 73 0 R /JS (play\\(\\);) >>")), (56, link(b"<< /S /Trans /Trans << /Type /Trans /S /Dissolve /D 0.5 >> >>")), (57, link(b"<< /S /GoTo3DView /TA 74 0 R /V /F >>")), From 57e0011b4bfec26aaef5118f0a7a99dfd711ca7c Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:31:47 -0500 Subject: [PATCH 043/152] feat(annotations): every annotation subtype with appearances (#71) Typed views for the 28 subtypes of ISO 32000-2 Table 171 plus an unknown subtype, common, markup and subtype entries, flags, borders, colours, quadrilaterals, popup/parent and reply relations, appearance dictionaries and states, a minimal form XObject view and the 12.5.5 appearance matrix. Lenient diagnostics for real-world deviations; corpus files annotations-subtypes, annotations-appearance and annotations-malformed. Co-Authored-By: Claude Opus 5.5 --- docs/conformance/iso-32000-2.md | 31 +- src/Broadside/Annotations/AnnotationIndex.cs | 181 +++ src/Broadside/Annotations/AnnotationNames.cs | 123 ++ src/Broadside/Annotations/AnnotationValues.cs | 104 ++ src/Broadside/Annotations/Pdf3DAnnotation.cs | 53 + src/Broadside/Annotations/PdfAnnotation.cs | 1042 +++++++++++++++++ .../Annotations/PdfAnnotationBorder.cs | 48 + .../Annotations/PdfAnnotationFlags.cs | 43 + .../Annotations/PdfAnnotationKind.cs | 93 ++ .../PdfAppearanceCharacteristics.cs | 144 +++ .../Annotations/PdfAppearanceDictionary.cs | 70 ++ .../Annotations/PdfAppearanceEntry.cs | 89 ++ .../Annotations/PdfAppearanceMode.cs | 15 + src/Broadside/Annotations/PdfBorderEffect.cs | 20 + .../Annotations/PdfBorderEffectStyle.cs | 12 + src/Broadside/Annotations/PdfBorderSource.cs | 15 + src/Broadside/Annotations/PdfBorderStyle.cs | 24 + .../Annotations/PdfCaretAnnotation.cs | 21 + src/Broadside/Annotations/PdfCaretSymbol.cs | 12 + .../Annotations/PdfCircleAnnotation.cs | 25 + src/Broadside/Annotations/PdfDeviceColor.cs | 64 + .../Annotations/PdfDeviceColorSpace.cs | 18 + .../PdfFileAttachmentAnnotation.cs | 33 + src/Broadside/Annotations/PdfFixedPrint.cs | 87 ++ .../Annotations/PdfFreeTextAnnotation.cs | 58 + .../Annotations/PdfHighlightAnnotation.cs | 13 + src/Broadside/Annotations/PdfHighlightMode.cs | 21 + src/Broadside/Annotations/PdfInkAnnotation.cs | 22 + .../Annotations/PdfLineAnnotation.cs | 85 ++ .../Annotations/PdfLineCaptionPosition.cs | 12 + src/Broadside/Annotations/PdfLineEnding.cs | 36 + .../Annotations/PdfLinkAnnotation.cs | 77 ++ .../Annotations/PdfMarkupAnnotation.cs | 118 ++ .../Annotations/PdfMovieAnnotation.cs | 36 + .../Annotations/PdfPolyLineAnnotation.cs | 38 + .../Annotations/PdfPolygonAnnotation.cs | 34 + .../Annotations/PdfPopupAnnotation.cs | 65 + .../Annotations/PdfPrinterMarkAnnotation.cs | 17 + .../Annotations/PdfProjectionAnnotation.cs | 13 + src/Broadside/Annotations/PdfQuadrilateral.cs | 73 ++ .../Annotations/PdfRectangleDifferences.cs | 12 + .../Annotations/PdfRedactAnnotation.cs | 58 + src/Broadside/Annotations/PdfReplyType.cs | 12 + .../Annotations/PdfRichMediaAnnotation.cs | 32 + .../Annotations/PdfScreenAnnotation.cs | 25 + .../Annotations/PdfSoundAnnotation.cs | 32 + .../Annotations/PdfSquareAnnotation.cs | 25 + .../Annotations/PdfSquigglyAnnotation.cs | 13 + .../Annotations/PdfStampAnnotation.cs | 29 + .../Annotations/PdfStrikeOutAnnotation.cs | 13 + .../Annotations/PdfTextAnnotation.cs | 41 + .../Annotations/PdfTextJustification.cs | 15 + .../Annotations/PdfTextMarkupAnnotation.cs | 17 + .../Annotations/PdfTrapNetAnnotation.cs | 40 + .../Annotations/PdfUnderlineAnnotation.cs | 13 + .../Annotations/PdfUnknownAnnotation.cs | 13 + .../Annotations/PdfWatermarkAnnotation.cs | 17 + .../Annotations/PdfWidgetAnnotation.cs | 29 + src/Broadside/Graphics/PdfFormXObject.cs | 80 ++ .../Parsing/DiagnosticCodes.Annotations.cs | 44 + src/Broadside/PdfDocument.cs | 12 + src/Broadside/PdfPage.cs | 54 + src/Broadside/PublicAPI.Unshipped.txt | 344 ++++++ tests/Broadside.Fuzz/Broadside.Fuzz.csproj | 2 + tests/Broadside.Fuzz/FuzzTargets.cs | 24 + .../Broadside.TestSupport/AnnotationWalker.cs | 106 ++ tests/Broadside.TestSupport/Corpus.cs | 3 + tests/Broadside.TestSupport/DocumentWalker.cs | 3 +- .../Annotations/AnnotationSubtypeTests.cs | 248 ++++ .../Annotations/AppearanceTests.cs | 95 ++ .../Annotations/LinkAnnotationTests.cs | 32 + .../Annotations/MalformedAnnotationTests.cs | 203 ++++ ...histograms_match_the_snapshot.verified.txt | 45 +- ...pus_file_names_match_snapshot.verified.txt | 3 + tests/Broadside.Tests/Writing/SaveTests.cs | 2 +- tests/Corpus/README.md | 3 + tests/Corpus/annotations-appearance.pdf | Bin 0 -> 1511 bytes tests/Corpus/annotations-malformed.pdf | Bin 0 -> 2181 bytes tests/Corpus/annotations-subtypes.pdf | Bin 0 -> 6851 bytes tests/Corpus/generate.py | 133 +++ 80 files changed, 4946 insertions(+), 11 deletions(-) create mode 100644 src/Broadside/Annotations/AnnotationIndex.cs create mode 100644 src/Broadside/Annotations/AnnotationNames.cs create mode 100644 src/Broadside/Annotations/AnnotationValues.cs create mode 100644 src/Broadside/Annotations/Pdf3DAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfAnnotationBorder.cs create mode 100644 src/Broadside/Annotations/PdfAnnotationFlags.cs create mode 100644 src/Broadside/Annotations/PdfAnnotationKind.cs create mode 100644 src/Broadside/Annotations/PdfAppearanceCharacteristics.cs create mode 100644 src/Broadside/Annotations/PdfAppearanceDictionary.cs create mode 100644 src/Broadside/Annotations/PdfAppearanceEntry.cs create mode 100644 src/Broadside/Annotations/PdfAppearanceMode.cs create mode 100644 src/Broadside/Annotations/PdfBorderEffect.cs create mode 100644 src/Broadside/Annotations/PdfBorderEffectStyle.cs create mode 100644 src/Broadside/Annotations/PdfBorderSource.cs create mode 100644 src/Broadside/Annotations/PdfBorderStyle.cs create mode 100644 src/Broadside/Annotations/PdfCaretAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfCaretSymbol.cs create mode 100644 src/Broadside/Annotations/PdfCircleAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfDeviceColor.cs create mode 100644 src/Broadside/Annotations/PdfDeviceColorSpace.cs create mode 100644 src/Broadside/Annotations/PdfFileAttachmentAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfFixedPrint.cs create mode 100644 src/Broadside/Annotations/PdfFreeTextAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfHighlightAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfHighlightMode.cs create mode 100644 src/Broadside/Annotations/PdfInkAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfLineAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfLineCaptionPosition.cs create mode 100644 src/Broadside/Annotations/PdfLineEnding.cs create mode 100644 src/Broadside/Annotations/PdfLinkAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfMarkupAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfMovieAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfPolyLineAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfPolygonAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfPopupAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfPrinterMarkAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfProjectionAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfQuadrilateral.cs create mode 100644 src/Broadside/Annotations/PdfRectangleDifferences.cs create mode 100644 src/Broadside/Annotations/PdfRedactAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfReplyType.cs create mode 100644 src/Broadside/Annotations/PdfRichMediaAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfScreenAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfSoundAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfSquareAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfSquigglyAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfStampAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfStrikeOutAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfTextAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfTextJustification.cs create mode 100644 src/Broadside/Annotations/PdfTextMarkupAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfTrapNetAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfUnderlineAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfUnknownAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfWatermarkAnnotation.cs create mode 100644 src/Broadside/Annotations/PdfWidgetAnnotation.cs create mode 100644 src/Broadside/Graphics/PdfFormXObject.cs create mode 100644 src/Broadside/Parsing/DiagnosticCodes.Annotations.cs create mode 100644 tests/Broadside.TestSupport/AnnotationWalker.cs create mode 100644 tests/Broadside.Tests/Annotations/AnnotationSubtypeTests.cs create mode 100644 tests/Broadside.Tests/Annotations/AppearanceTests.cs create mode 100644 tests/Broadside.Tests/Annotations/LinkAnnotationTests.cs create mode 100644 tests/Broadside.Tests/Annotations/MalformedAnnotationTests.cs create mode 100644 tests/Corpus/annotations-appearance.pdf create mode 100644 tests/Corpus/annotations-malformed.pdf create mode 100644 tests/Corpus/annotations-subtypes.pdf diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index c2771b78..c4b7f969 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -152,7 +152,36 @@ Clause numbers at the second level; split rows to the third level as clauses are | 12.4.2 | Page labels | done | `PdfPageLabels`, `PdfPageLabelRange`, `PdfPageLabelStyle` | `Broadside.Tests.Document.PageLabelTests.Page_labels_pdf_labels_every_page_in_every_style`, `Broadside.Tests.Document.PageLabelTests.Page_labels_pdf_lists_its_ranges_in_page_order`, `Broadside.Tests.Document.PageLabelTests.Number_tree_deep_pdf_finds_each_page_s_range_through_kids_and_limits`, `Broadside.Tests.Document.PageLabelTests.Letters_repeat_rather_than_carry`, `Broadside.Tests.Document.PageLabelTests.Roman_numerals_follow_the_subtractive_form_and_add_an_m_per_thousand_beyond_3999`, `Broadside.Tests.Document.PageLabelTests.Every_roman_numeral_from_1_to_3999_is_canonical_and_reads_back_as_its_number`, `Broadside.Tests.Document.PageLabelTests.A_malformed_page_label_is_repaired_with_a_warning`, `Broadside.Tests.Document.PageLabelTests.Pages_before_the_first_range_are_numbered_in_decimal_with_a_warning`, `Broadside.Tests.Document.PageLabelTests.A_range_whose_value_is_not_a_dictionary_is_skipped_and_the_previous_range_continues` | Floor lookup through #70's `NumberTreeReader`; no key 0 numbers earlier pages in decimal (PDFBox/Acrobat); unknown style decimal; letters and roman capped at 64 characters (decimal beyond); `page-labels.pdf`, `number-tree-deep.pdf` | | 12.4.3 | Articles | not started | | | | | 12.4.4 | Presentations | not started | | | | -| 12.5 | Annotations | not started | | | | +| 12.5.1 | General | partial | `PdfPage`, `PdfAnnotation` | `Broadside.Tests.Annotations.LinkAnnotationTests.Annotations_link_pdf_yields_one_link_whose_action_is_a_uri_action`, `Broadside.Tests.Annotations.AnnotationSubtypeTests.Annotations_subtypes_pdf_maps_each_standard_subtype_to_its_class_and_an_unknown_one_to_the_generic_class`, `Broadside.Tests.Annotations.MalformedAnnotationTests.Annots_on_a_page_tree_node_is_used_with_a_diagnostic` | `PdfPage.Annotations` reads the page's `Annots` (Table 31) in order, typed by subtype; an `Annots` on a page tree node is used with `AnnotsInherited` (pdf.js parity). The page's `Tabs` order (R/C/S/A/W) is not exposed yet | +| 12.5.2 | Annotation dictionaries | done | `PdfAnnotation`, `PdfDeviceColor`, `PdfDeviceColorSpace`, `AnnotationIndex` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Annotations_subtypes_pdf_maps_each_standard_subtype_to_its_class_and_an_unknown_one_to_the_generic_class`, `Broadside.Tests.Annotations.AnnotationSubtypeTests.Reading_every_entry_of_every_annotation_records_nothing_and_changes_nothing`, `Broadside.Tests.Annotations.AnnotationSubtypeTests.Flags_colours_borders_and_markup_entries_are_exposed`, `Broadside.Tests.Annotations.MalformedAnnotationTests.Annotations_malformed_pdf_reads_what_it_can_with_exactly_the_documented_diagnostics`, `Broadside.Tests.Annotations.MalformedAnnotationTests.Strict_mode_throws_from_the_annotation_list_not_from_open`, `Broadside.Tests.Annotations.MalformedAnnotationTests.Strict_mode_throws_from_the_property_that_reads_a_malformed_entry`, `Broadside.Tests.Annotations.MalformedAnnotationTests.A_deviation_in_the_annots_array_or_the_type_entries_is_recorded_once`, `Broadside.Tests.Annotations.MalformedAnnotationTests.An_appearance_is_required_only_in_a_pdf_2_0_file`, `Broadside.Tests.Annotations.MalformedAnnotationTests.A_mutation_that_changes_the_annots_array_or_the_subtype_is_seen_on_the_next_read` | Every Table 166 entry; `M` kept as text with `Modified` parsed when it is a date; `OC` through `IsVisible(PdfOptionalContentState)` (#76), `AF` through `ReadAssociatedFiles` (#76); one view per dictionary (document identity map), owning page = the page whose `Annots` lists it (`P` advisory). `AppearanceMissing` only in PDF 2.0 files (exempt Popup, Link, Projection, zero-size Rect). Diagnostics: AnnotsInvalid, AnnotationEntryInvalid, AnnotationNotIndirect, AnnotationDuplicate, AnnotationSharedAcrossPages, AnnotationPageMismatch, AnnotationTypeInvalid, AnnotationSubtypeMissing, AnnotationSubtypeNotName, AnnotationRectInvalid, AnnotationValueInvalid, AnnotationRequiredEntryMissing, ColorArrayInvalid. `annotations-subtypes.pdf`, `annotations-malformed.pdf` | +| 12.5.3 | Annotation flags | done | `PdfAnnotationFlags`, `PdfAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Flags_colours_borders_and_markup_entries_are_exposed`, `Broadside.Tests.Annotations.MalformedAnnotationTests.Annotations_malformed_pdf_reads_what_it_can_with_exactly_the_documented_diagnostics` | All ten Table 167 bits; undefined bits and real values kept with `AnnotationFlagsInvalid`. Applying Hidden/NoView/NoZoom/NoRotate (and Text's implicit NoZoom/NoRotate) is the renderer's (Phase 3) | +| 12.5.4 | Border styles | done | `PdfAnnotationBorder`, `PdfBorderStyle`, `PdfBorderSource`, `PdfBorderEffect`, `PdfBorderEffectStyle` | `Broadside.Tests.Annotations.LinkAnnotationTests.Annotations_link_pdf_yields_one_link_whose_action_is_a_uri_action`, `Broadside.Tests.Annotations.AnnotationSubtypeTests.Flags_colours_borders_and_markup_entries_are_exposed`, `Broadside.Tests.Annotations.MalformedAnnotationTests.Annotations_malformed_pdf_reads_what_it_can_with_exactly_the_documented_diagnostics` | BS (Table 168) wins over Border; Border with a dash array is dashed; default solid 1 pt; BE (Table 169) on Square, Circle, Polygon, FreeText; short Border padded with 0 (`BorderArrayInvalid`), BS Type not Border used (`BorderStyleTypeInvalid`), unknown style read as solid | +| 12.5.5 | Appearance streams | done | `PdfAppearanceDictionary`, `PdfAppearanceEntry`, `PdfAppearanceMode`, `PdfFormXObject`, `PdfAnnotation` | `Broadside.Tests.Annotations.AppearanceTests.The_appearance_matrix_maps_the_transformed_bounding_box_onto_the_rectangle`, `Broadside.Tests.Annotations.AppearanceTests.A_form_point_lands_where_the_algorithm_puts_it`, `Broadside.Tests.Annotations.AppearanceTests.Annotations_appearance_pdf_places_each_appearance_on_its_rectangle`, `Broadside.Tests.Annotations.AppearanceTests.States_select_the_appearance_and_missing_entries_fall_back_to_the_normal_one`, `Broadside.Tests.Annotations.MalformedAnnotationTests.Annotations_malformed_pdf_reads_what_it_can_with_exactly_the_documented_diagnostics` | Table 170 N/R/D with state subdictionaries and AS; R/D default to N, a rollover/down subdictionary without the state falls back to N's stream for it; Algorithm "Appearance streams" as `PdfAnnotation.ComputeAppearanceMatrix` (AA = Matrix x A, null when degenerate; a missing BBox uses [0 0 w h] of Rect, pdf.js). Diagnostics AppearanceStateMissing, AppearanceEntryInvalid, AppearanceBBoxMissing, AppearanceNotForm. Rendering (Phase 3) must decide between p.485 (ignore BM/CA/ca with an appearance) and p.490 (group composited with the annotation's BM/ca/CA), and apply NoZoom/NoRotate and FixedPrint. `annotations-appearance.pdf` | +| 12.5.6.1 | General | done | `PdfAnnotationKind`, `PdfUnknownAnnotation`, `PdfAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Annotations_subtypes_pdf_maps_each_standard_subtype_to_its_class_and_an_unknown_one_to_the_generic_class`, `Broadside.Tests.Annotations.AnnotationSubtypeTests.Reading_every_entry_of_every_annotation_records_nothing_and_changes_nothing` | Table 171: 28 subtypes map 1:1 to classes; any other subtype, or none, is `PdfUnknownAnnotation` (an unknown subtype is legal, no diagnostic) | +| 12.5.6.2 | Markup annotations | done | `PdfMarkupAnnotation`, `PdfReplyType` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Flags_colours_borders_and_markup_entries_are_exposed`, `Broadside.Tests.Annotations.AnnotationSubtypeTests.Popup_and_parent_refer_to_each_other_and_replies_carry_their_state`, `Broadside.Tests.Annotations.MalformedAnnotationTests.Annotations_malformed_pdf_reads_what_it_can_with_exactly_the_documented_diagnostics` | Table 172 (T, Popup, RC as text, CreationDate, IRT, Subj, RT, IT, ExData raw); Table 173 ExData exposed as stored. PopupLinkMismatch, InReplyToInvalid, InReplyToOtherPage, ReplyTypeWithoutInReplyTo | +| 12.5.6.3 | Annotation states | done | `PdfTextAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Popup_and_parent_refer_to_each_other_and_replies_carry_their_state`, `Broadside.Tests.Annotations.MalformedAnnotationTests.Annotations_malformed_pdf_reads_what_it_can_with_exactly_the_documented_diagnostics` | Table 174 State/StateModel on reply text annotations; `StateModelMissing` | +| 12.5.6.4 | Text annotations | done | `PdfTextAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Flags_colours_borders_and_markup_entries_are_exposed`, `Broadside.Tests.Annotations.AnnotationSubtypeTests.Popup_and_parent_refer_to_each_other_and_replies_carry_their_state` | Table 175 | +| 12.5.6.5 | Link annotations | done | `PdfLinkAnnotation`, `PdfHighlightMode`, `PdfQuadrilateral` | `Broadside.Tests.Annotations.LinkAnnotationTests.Annotations_link_pdf_yields_one_link_whose_action_is_a_uri_action`, `Broadside.Tests.Annotations.AnnotationSubtypeTests.Flags_colours_borders_and_markup_entries_are_exposed`, `Broadside.Tests.Annotations.MalformedAnnotationTests.Annotations_malformed_pdf_reads_what_it_can_with_exactly_the_documented_diagnostics` | Table 176: A and PA through `PdfAction` (#70/#73), Dest through `PdfDestination` (#70), `ActivationRegion` falls back to Rect; `LinkActionAndDest` when both | +| 12.5.6.6 | Free text annotations | done | `PdfFreeTextAnnotation`, `PdfTextJustification`, `PdfLineEnding`, `PdfRectangleDifferences` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Table 177; DA and DS exposed as strings, not parsed | +| 12.5.6.7 | Line annotations | done | `PdfLineAnnotation`, `PdfLineEnding`, `PdfLineCaptionPosition` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Tables 178 and 179; Measure as stored | +| 12.5.6.8 | Square and circle annotations | done | `PdfSquareAnnotation`, `PdfCircleAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Flags_colours_borders_and_markup_entries_are_exposed` | Table 180 | +| 12.5.6.9 | Polygon and polyline annotations | done | `PdfPolygonAnnotation`, `PdfPolyLineAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Table 181 incl. PDF 2.0 Path | +| 12.5.6.10 | Text markup annotations | done | `PdfTextMarkupAnnotation`, `PdfHighlightAnnotation`, `PdfUnderlineAnnotation`, `PdfSquigglyAnnotation`, `PdfStrikeOutAnnotation`, `PdfQuadrilateral` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Flags_colours_borders_and_markup_entries_are_exposed`, `Broadside.Tests.Annotations.MalformedAnnotationTests.Annotations_malformed_pdf_reads_what_it_can_with_exactly_the_documented_diagnostics` | Table 182; quadrilaterals verbatim (never reordered), incomplete ones dropped with `QuadPointsInvalid` | +| 12.5.6.11 | Caret annotations | done | `PdfCaretAnnotation`, `PdfCaretSymbol` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Table 183 | +| 12.5.6.12 | Rubber stamp annotations | done | `PdfStampAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Table 184 incl. PDF 2.0 IT (no default Name for StampImage/StampSnapshot) | +| 12.5.6.13 | Ink annotations | done | `PdfInkAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Table 185 incl. PDF 2.0 Path | +| 12.5.6.14 | Popup annotations | done | `PdfPopupAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Popup_and_parent_refer_to_each_other_and_replies_carry_their_state`, `Broadside.Tests.Annotations.MalformedAnnotationTests.Annotations_malformed_pdf_reads_what_it_can_with_exactly_the_documented_diagnostics` | Table 186; Parent derived from the same page's markup when absent; `PopupParentInvalid` | +| 12.5.6.15 | File attachment annotations | done | `PdfFileAttachmentAnnotation`, `PdfFileSpecification` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Table 187; FS through #76's `PdfFileSpecification` | +| 12.5.6.16 | Sound annotations | done | `PdfSoundAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Deprecated in PDF 2.0: Table 188 exposed as data, never played | +| 12.5.6.17 | Movie annotations | done | `PdfMovieAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Deprecated in PDF 2.0: Table 189 exposed as data; A is the activation (bool or dict), not an action | +| 12.5.6.18 | Screen annotations | partial | `PdfScreenAnnotation`, `PdfAppearanceCharacteristics` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Table 190 T, MK, A; AA (Table 197) is typed by #73's additional-actions views | +| 12.5.6.19 | Widget annotations | partial | `PdfWidgetAnnotation`, `PdfAppearanceCharacteristics`, `PdfHighlightMode` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Tables 191 and 192 (H with T read as P, MK, A, Parent raw); AA is #73's, field entries and widget/field linking #74's | +| 12.5.6.20 | Printer's mark annotations | done | `PdfPrinterMarkAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | MN (§14.11.3, Table 398) | +| 12.5.6.21 | Trap network annotations | done | `PdfTrapNetAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed`, `Broadside.Tests.Annotations.MalformedAnnotationTests.A_trap_network_that_is_not_the_last_annotation_is_recorded` | Deprecated in PDF 2.0: Table 403 exposed as data; `TrapNetPlacementInvalid` | +| 12.5.6.22 | Watermark annotations | done | `PdfWatermarkAnnotation`, `PdfFixedPrint` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Tables 193 and 194; applying FixedPrint is the renderer's | +| 12.5.6.23 | Redaction annotations | done | `PdfRedactAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Table 195; reading never applies the redaction | +| 12.5.6.24 | Projection annotations | done | `PdfProjectionAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Annotations_subtypes_pdf_maps_each_standard_subtype_to_its_class_and_an_unknown_one_to_the_generic_class`, `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Tables 166 and 172 only | +| 12.5.6.25 | 3D and RichMedia annotations | partial | `Pdf3DAnnotation`, `PdfRichMediaAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | parse-and-preserve, CLAUDE.md out of scope: Table 309 and Table 333 entries exposed as stored, never rendered or played | | 12.6 | Actions | partial | `PdfAction`, `PdfGoToAction`, `PdfUriAction`, `PdfUnknownAction` | `Broadside.Tests.Navigation.OutlineTests.Outline_full_pdf_yields_three_levels_with_open_and_closed_items_styles_and_actions`, `Broadside.Tests.Navigation.OutlineTests.Malformed_item_entries_read_as_their_defaults_with_a_diagnostic` | Minimal base (#70): Table 196 S, go-to (Table 202: D, SD) and URI (Table 210: URI as UTF-8, IsMap) actions; every other type is `PdfUnknownAction`, preserved; `ActionInvalid` for a missing S, D or URI. #73 adds the other types, Next chains and trigger events | | 12.7 | Forms | not started | | | | | 12.8 | Digital signatures | not started | | | | diff --git a/src/Broadside/Annotations/AnnotationIndex.cs b/src/Broadside/Annotations/AnnotationIndex.cs new file mode 100644 index 00000000..87feba0a --- /dev/null +++ b/src/Broadside/Annotations/AnnotationIndex.cs @@ -0,0 +1,181 @@ +using System.Runtime.CompilerServices; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Annotations; + +/// +/// The document's annotation views: one view per annotation dictionary (so a pop-up reached from its parent is the instance the page +/// lists), the per-page lists, and a lazily built map from annotation dictionary to the page that holds it. +/// +/// +/// ISO 32000-2 §12.5.2 and §7.7.3.3. Thread-safe: views are created and published with first-publisher-wins semantics; the page map +/// is computed at most once per document (a snapshot of the page tree and the Annots arrays at that time). +/// +internal sealed class AnnotationIndex +{ + private readonly PdfDocument _document; + private readonly ConditionalWeakTable _views = []; + private readonly Lazy> _owners; + + public AnnotationIndex(PdfDocument document) + { + _document = document; + _owners = new Lazy>(IndexOwners, LazyThreadSafetyMode.PublicationOnly); + } + + /// Reads the annotations of from its Annots array, recording what the array gets wrong. + public IReadOnlyList Read(PdfPage page, CosObject? annots, bool inherited) + { + CosReference? pageReference = page.Reference; + if (inherited) + { + Report(DiagnosticCodes.AnnotsInherited, "The page has no Annots entry but a page tree node above it has one, which is not inheritable (Table 31); it is used, as viewers do.", pageReference); + } + + switch (_document.Resolve(annots)) + { + case CosNull: + return []; + case CosArray array: + return ReadArray(page, array, inherited); + default: + Report(DiagnosticCodes.AnnotsInvalid, "The page's Annots entry is not an array; the page has no annotations.", pageReference); + return []; + } + } + + /// Returns the view over , creating it for when there is none or its subtype changed. + public PdfAnnotation GetOrCreate(CosDictionary dictionary, CosReference? reference, PdfPage? page) + { + CosName? subtype = PdfAnnotation.ReadSubtype(_document, dictionary, out _); + if (_views.TryGetValue(dictionary, out PdfAnnotation? existing) && Equals(existing.CreatedSubtype, subtype)) + { + return existing; + } + + PdfAnnotation created = PdfAnnotation.Create(_document, dictionary, reference, page); + if (existing is not null) + { + _views.AddOrUpdate(dictionary, created); + return created; + } + + return _views.TryAdd(dictionary, created) || !_views.TryGetValue(dictionary, out PdfAnnotation? winner) ? created : winner; + } + + /// + /// Returns the annotation names, as the page that holds it lists it: the page of + /// first, then any page; an annotation no page holds gets a view without a page. when the value is not a dictionary. + /// + public PdfAnnotation? Find(CosObject? value, PdfAnnotation from) + { + if (_document.Resolve(value) is not CosDictionary dictionary) + { + return null; + } + + if (TryGetCurrent(dictionary) is { } known) + { + return known; + } + + if (from.Page is { } page) + { + _ = page.Annotations; + if (TryGetCurrent(dictionary) is { } onPage) + { + return onPage; + } + } + + if (_owners.Value.TryGetValue(dictionary, out PdfPage? owner)) + { + _ = owner.Annotations; + if (TryGetCurrent(dictionary) is { } onOwner) + { + return onOwner; + } + } + + return GetOrCreate(dictionary, value as CosReference, page: null); + } + + private PdfAnnotation? TryGetCurrent(CosDictionary dictionary) => + _views.TryGetValue(dictionary, out PdfAnnotation? view) && Equals(view.CreatedSubtype, PdfAnnotation.ReadSubtype(_document, dictionary, out _)) + ? view + : null; + + private PdfAnnotation[] ReadArray(PdfPage page, CosArray array, bool inherited) + { + CosReference? pageReference = page.Reference; + var annotations = new List(array.Count); + var seen = new HashSet(ReferenceEqualityComparer.Instance); + int trapNets = 0; + for (int index = 0; index < array.Count; index++) + { + CosObject element = array[index]; + var reference = element as CosReference; + if (_document.Resolve(element) is not CosDictionary dictionary) + { + Report(DiagnosticCodes.AnnotationEntryInvalid, $"Element {index} of the page's Annots array is not an annotation dictionary; it is skipped.", reference ?? pageReference); + continue; + } + + if (reference is null) + { + Report(DiagnosticCodes.AnnotationNotIndirect, $"Element {index} of the page's Annots array is a direct dictionary; Table 31 requires indirect references. It is read anyway.", pageReference); + } + + if (!seen.Add(dictionary)) + { + Report(DiagnosticCodes.AnnotationDuplicate, $"The page's Annots array lists the same annotation more than once (again at element {index}); each listing is kept.", reference ?? pageReference); + } + + PdfAnnotation annotation = GetOrCreate(dictionary, reference, page); + if (!inherited) + { + if (annotation.Page is not null && !ReferenceEquals(annotation.Page, page)) + { + Report(DiagnosticCodes.AnnotationSharedAcrossPages, "The annotation is listed by the Annots arrays of more than one page; §12.5.2 allows only one. Its page is the first that lists it.", reference ?? pageReference); + } + + if (dictionary.TryGetValue(AnnotationNames.P, out CosObject? p) && !ReferenceEquals(_document.Resolve(p), page.Dictionary)) + { + Report(DiagnosticCodes.AnnotationPageMismatch, "The annotation's P entry does not name the page whose Annots array holds it; that page is used.", reference ?? pageReference); + } + } + + if (annotation.Kind == PdfAnnotationKind.TrapNet) + { + trapNets++; + if (trapNets > 1 || index != array.Count - 1) + { + Report(DiagnosticCodes.TrapNetPlacementInvalid, "A page shall have at most one trap network annotation, the last element of its Annots array (§12.5.6.21).", reference ?? pageReference); + } + } + + annotations.Add(annotation); + } + + return [.. annotations]; + } + + private Dictionary IndexOwners() + { + var owners = new Dictionary(ReferenceEqualityComparer.Instance); + foreach (PdfPage page in _document.Pages) + { + foreach (PdfAnnotation annotation in page.Annotations) + { + owners.TryAdd(annotation.Dictionary, page); + } + } + + return owners; + } + + private void Report(string code, string message, CosReference? reference) => + _document.DiagnosticSink.Report(code, DiagnosticSeverity.Warning, message, objectReference: reference); +} diff --git a/src/Broadside/Annotations/AnnotationNames.cs b/src/Broadside/Annotations/AnnotationNames.cs new file mode 100644 index 00000000..e63fca13 --- /dev/null +++ b/src/Broadside/Annotations/AnnotationNames.cs @@ -0,0 +1,123 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// Names looked up by annotation views (issue #71); kept apart from so parallel tickets do not collide. +internal static class AnnotationNames +{ + // Page and common entries (§7.7.3.3 Table 31; §12.5.2 Table 166). + public static readonly CosName Annots = new("Annots"); + public static readonly CosName Type = new("Type"); + public static readonly CosName Annot = new("Annot"); + public static readonly CosName Subtype = new("Subtype"); + public static readonly CosName Rect = new("Rect"); + public static readonly CosName Contents = new("Contents"); + public static readonly CosName P = new("P"); + public static readonly CosName NM = new("NM"); + public static readonly CosName M = new("M"); + public static readonly CosName F = new("F"); + public static readonly CosName AP = new("AP"); + public static readonly CosName AS = new("AS"); + public static readonly CosName Border = new("Border"); + public static readonly CosName C = new("C"); + public static readonly CosName StructParent = new("StructParent"); + public static readonly CosName OC = new("OC"); + public static readonly CosName AF = new("AF"); + public static readonly CosName NonStrokingOpacity = new("ca"); + public static readonly CosName StrokingOpacity = new("CA"); + public static readonly CosName BM = new("BM"); + public static readonly CosName Lang = new("Lang"); + + // Border style and effect (§12.5.4 Tables 168 and 169). + public static readonly CosName BS = new("BS"); + public static readonly CosName BE = new("BE"); + public static readonly CosName W = new("W"); + public static readonly CosName S = new("S"); + public static readonly CosName D = new("D"); + public static readonly CosName I = new("I"); + + // Appearance dictionaries (§12.5.5 Table 170) and form XObjects (§8.10.1 Table 93). + public static readonly CosName N = new("N"); + public static readonly CosName R = new("R"); + public static readonly CosName Form = new("Form"); + public static readonly CosName BBox = new("BBox"); + public static readonly CosName Matrix = new("Matrix"); + public static readonly CosName Resources = new("Resources"); + public static readonly CosName Group = new("Group"); + public static readonly CosName StructParents = new("StructParents"); + + // Markup annotations (§12.5.6.2 Tables 172 and 173). + public static readonly CosName T = new("T"); + public static readonly CosName Popup = new("Popup"); + public static readonly CosName RC = new("RC"); + public static readonly CosName CreationDate = new("CreationDate"); + public static readonly CosName IRT = new("IRT"); + public static readonly CosName Subj = new("Subj"); + public static readonly CosName RT = new("RT"); + public static readonly CosName IT = new("IT"); + public static readonly CosName ExData = new("ExData"); + + // Subtype entries (§12.5.6.4 to §12.5.6.25, Tables 175 to 195, 309, 333, 398, 403). + public static readonly CosName Open = new("Open"); + public static readonly CosName Name = new("Name"); + public static readonly CosName State = new("State"); + public static readonly CosName StateModel = new("StateModel"); + public static readonly CosName A = new("A"); + public static readonly CosName Dest = new("Dest"); + public static readonly CosName H = new("H"); + public static readonly CosName PA = new("PA"); + public static readonly CosName QuadPoints = new("QuadPoints"); + public static readonly CosName DA = new("DA"); + public static readonly CosName Q = new("Q"); + public static readonly CosName DS = new("DS"); + public static readonly CosName CL = new("CL"); + public static readonly CosName RD = new("RD"); + public static readonly CosName LE = new("LE"); + public static readonly CosName L = new("L"); + public static readonly CosName IC = new("IC"); + public static readonly CosName LL = new("LL"); + public static readonly CosName LLE = new("LLE"); + public static readonly CosName Cap = new("Cap"); + public static readonly CosName LLO = new("LLO"); + public static readonly CosName CP = new("CP"); + public static readonly CosName Measure = new("Measure"); + public static readonly CosName CO = new("CO"); + public static readonly CosName Vertices = new("Vertices"); + public static readonly CosName Path = new("Path"); + public static readonly CosName Sy = new("Sy"); + public static readonly CosName InkList = new("InkList"); + public static readonly CosName Parent = new("Parent"); + public static readonly CosName FS = new("FS"); + public static readonly CosName Sound = new("Sound"); + public static readonly CosName Movie = new("Movie"); + public static readonly CosName MK = new("MK"); + public static readonly CosName AA = new("AA"); + public static readonly CosName MN = new("MN"); + public static readonly CosName LastModified = new("LastModified"); + public static readonly CosName Version = new("Version"); + public static readonly CosName AnnotStates = new("AnnotStates"); + public static readonly CosName FontFauxing = new("FontFauxing"); + public static readonly CosName FixedPrint = new("FixedPrint"); + public static readonly CosName V = new("V"); + public static readonly CosName RO = new("RO"); + public static readonly CosName OverlayText = new("OverlayText"); + public static readonly CosName Repeat = new("Repeat"); + public static readonly CosName ThreeDD = new("3DD"); + public static readonly CosName ThreeDV = new("3DV"); + public static readonly CosName ThreeDA = new("3DA"); + public static readonly CosName ThreeDI = new("3DI"); + public static readonly CosName ThreeDB = new("3DB"); + public static readonly CosName ThreeDU = new("3DU"); + public static readonly CosName GEO = new("GEO"); + public static readonly CosName RichMediaContent = new("RichMediaContent"); + public static readonly CosName RichMediaSettings = new("RichMediaSettings"); + + // Appearance characteristics (§12.5.6.19 Table 192). + public static readonly CosName BC = new("BC"); + public static readonly CosName BG = new("BG"); + public static readonly CosName AC = new("AC"); + public static readonly CosName RI = new("RI"); + public static readonly CosName IX = new("IX"); + public static readonly CosName IF = new("IF"); + public static readonly CosName TP = new("TP"); +} diff --git a/src/Broadside/Annotations/AnnotationValues.cs b/src/Broadside/Annotations/AnnotationValues.cs new file mode 100644 index 00000000..d3b26d8a --- /dev/null +++ b/src/Broadside/Annotations/AnnotationValues.cs @@ -0,0 +1,104 @@ +using Broadside.Graphics; +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// Lenient readers for the value types annotations and form XObjects use; they never report, the caller decides. +internal static class AnnotationValues +{ + /// Reads a rectangle (§7.9.5): an array of four finite numbers, normalized; otherwise. + public static PdfRectangle? ReadRectangle(PdfDocument document, CosObject? value) + { + Span corners = stackalloc double[4]; + return document.Resolve(value) is CosArray { Count: 4 } array && TryReadNumbers(document, array, corners) + ? new PdfRectangle(corners[0], corners[1], corners[2], corners[3]) + : null; + } + + /// Reads a matrix (§8.3.4): an array of six finite numbers; otherwise. + public static Matrix? ReadMatrix(PdfDocument document, CosObject? value) + { + Span elements = stackalloc double[6]; + return document.Resolve(value) is CosArray { Count: 6 } array && TryReadNumbers(document, array, elements) + ? new Matrix(elements[0], elements[1], elements[2], elements[3], elements[4], elements[5]) + : null; + } + + /// Reads an integer in the 32-bit range; otherwise. + public static int? ReadInteger(PdfDocument document, CosObject? value) => + document.Resolve(value) is CosInteger { Value: >= int.MinValue and <= int.MaxValue } integer ? (int)integer.Value : null; + + /// Reads a finite number; otherwise. + public static double? ReadNumber(PdfDocument document, CosObject? value) => + document.Resolve(value) is CosNumber number && double.IsFinite(number.ToDouble()) ? number.ToDouble() : null; + + /// Reads the first values.Length elements of as finite numbers. + public static bool TryReadNumbers(PdfDocument document, CosArray array, Span values) + { + for (int index = 0; index < values.Length; index++) + { + if (ReadNumber(document, array[index]) is not { } number) + { + return false; + } + + values[index] = number; + } + + return true; + } + + /// + /// Reads every element of an array as a number; is false when an element is not one (it is skipped). + /// when is not an array. + /// + public static List? ReadNumbers(PdfDocument document, CosObject? value, out bool complete) + { + complete = true; + if (document.Resolve(value) is not CosArray array) + { + return null; + } + + var numbers = new List(array.Count); + foreach (CosObject element in array) + { + if (ReadNumber(document, element) is { } number) + { + numbers.Add(number); + } + else + { + complete = false; + } + } + + return numbers; + } + + /// Reads a colour array of 0, 1, 3 or 4 numbers (Table 166 C); is false for anything else. + public static PdfDeviceColor? ReadColor(PdfDocument document, CosObject? value, out bool valid) + { + valid = true; + CosObject resolved = document.Resolve(value); + if (resolved is CosNull) + { + return null; + } + + if (resolved is not CosArray { Count: 0 or 1 or 3 or 4 } array) + { + valid = false; + return null; + } + + Span components = stackalloc double[array.Count]; + if (!TryReadNumbers(document, array, components)) + { + valid = false; + return null; + } + + return new PdfDeviceColor(components); + } +} diff --git a/src/Broadside/Annotations/Pdf3DAnnotation.cs b/src/Broadside/Annotations/Pdf3DAnnotation.cs new file mode 100644 index 00000000..095fb7bc --- /dev/null +++ b/src/Broadside/Annotations/Pdf3DAnnotation.cs @@ -0,0 +1,53 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A 3D annotation: 3D artwork on the page. +/// ISO 32000-2 §12.5.6.25 and §13.6.2, Table 309 (PDF 1.6). Parse-and-preserve (3D is out of scope): the entries are exposed as data, never rendered. +public sealed class Pdf3DAnnotation : PdfAnnotation +{ + internal Pdf3DAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.ThreeD) + { + } + + /// Gets the 3D stream or 3D reference dictionary (3DD, required), as stored, or . + /// ISO 32000-2 §13.6.2, Table 309. + public CosObject? Artwork + { + get + { + CosObject? value = Get(AnnotationNames.ThreeDD); + if (value is null) + { + ReportMissing(AnnotationNames.ThreeDD, "Table 309"); + } + + return value; + } + } + + /// Gets the default view (3DV): a view dictionary, an index, a name or a keyword, as stored, or . + /// ISO 32000-2 §13.6.2, Table 309. + public CosObject? DefaultView => Get(AnnotationNames.ThreeDV); + + /// Gets the activation dictionary (3DA), as stored, or . + /// ISO 32000-2 §13.6.2, Table 309. + public CosDictionary? Activation => ReadDictionary(AnnotationNames.ThreeDA); + + /// Gets a value indicating whether the artwork is interactive (3DI); default . + /// ISO 32000-2 §13.6.2, Table 309. + public bool IsInteractive => ReadBoolean(AnnotationNames.ThreeDI, fallback: true); + + /// Gets the 3D view box in the annotation's target coordinate system (3DB), or . + /// ISO 32000-2 §13.6.2, Table 309. + public PdfRectangle? ViewBox => AnnotationValues.ReadRectangle(Document, Get(AnnotationNames.ThreeDB)); + + /// Gets the units dictionary (3DU, PDF 2.0), as stored, or . + /// ISO 32000-2 §13.6.2, Table 309. + public CosDictionary? Units => ReadDictionary(AnnotationNames.ThreeDU); + + /// Gets the geospatial information (GEO, PDF 2.0), as stored, or . + /// ISO 32000-2 §13.6.2, Table 309, and §12.10. + public CosDictionary? Geospatial => ReadDictionary(AnnotationNames.GEO); +} diff --git a/src/Broadside/Annotations/PdfAnnotation.cs b/src/Broadside/Annotations/PdfAnnotation.cs new file mode 100644 index 00000000..14c9a5e5 --- /dev/null +++ b/src/Broadside/Annotations/PdfAnnotation.cs @@ -0,0 +1,1042 @@ +using Broadside.Diagnostics; +using Broadside.Graphics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Annotations; + +/// An annotation: an object on a page, such as a note, a link or a form field's widget. A live view over the annotation dictionary. +/// +/// +/// ISO 32000-2 §12.5. lists a page's annotations; each is an instance of the class its +/// Subtype selects (Table 171), and any other subtype, or none, is a . Markup annotations +/// (§12.5.6.2) derive from . +/// +/// +/// Every property reads the dictionary when called and returns the default the specification gives when an entry is absent, +/// without writing it. A malformed entry reads as its default and records a diagnostic the first time it is read (lenient mode); in +/// strict mode the property throws. Values such as , and are snapshots +/// computed per call. +/// +/// +/// The same annotation dictionary always gives the same instance, whether it is reached from the page or from another annotation +/// (, , ). +/// +/// +public abstract class PdfAnnotation +{ + private protected PdfAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page, PdfAnnotationKind kind) + { + Document = document; + Dictionary = dictionary; + Reference = reference; + Page = page; + Kind = kind; + } + + /// Gets the annotation dictionary. + /// ISO 32000-2 §12.5.2, Table 166. + public CosDictionary Dictionary { get; } + + /// Gets the indirect reference to the annotation dictionary, or when the page's Annots array holds it directly. + /// ISO 32000-2 §7.7.3.3, Table 31: Annots "shall contain indirect references". + public CosReference? Reference { get; } + + /// + /// Gets the page whose Annots array holds the annotation, or when no page holds it (an annotation reached only + /// from another one). Not the P entry, which is advisory: see . + /// + /// + /// ISO 32000-2 §12.5.2: "A given annotation dictionary shall be referenced from the Annots array of only one page." When a file + /// breaks that rule, this is the first page that listed the annotation, and the others record AnnotationSharedAcrossPages. + /// + public PdfPage? Page { get; } + + /// Gets the standard type the annotation is, from its Subtype when it was read; for any other. + /// ISO 32000-2 §12.5.6.1, Table 171. + public PdfAnnotationKind Kind { get; } + + /// Gets the Subtype entry as stored (a string reads as the name it spells), or when it is absent. + /// ISO 32000-2 §12.5.2, Table 166 (required). + public CosName? Subtype => ReadSubtype(Document, Dictionary, out _); + + /// Gets the annotation rectangle in default user space, normalized; [0 0 0 0] when Rect is missing or malformed. + /// ISO 32000-2 §12.5.2, Table 166 (required), and §7.9.5: any two diagonally opposite corners, so an unnormalized rectangle is legal. + public PdfRectangle Rect + { + get + { + if (AnnotationValues.ReadRectangle(Document, Get(AnnotationNames.Rect)) is { } rect) + { + return rect; + } + + Report(DiagnosticCodes.AnnotationRectInvalid, "The annotation's Rect entry is missing or not four numbers; it reads as [0 0 0 0]."); + return default; + } + } + + /// Gets the text displayed for the annotation, or an alternate description of it (Contents); when absent. + /// ISO 32000-2 §12.5.2, Table 166; a text string (§7.9.2.2). + public string? Contents => ReadText(AnnotationNames.Contents); + + /// Gets the page object the P entry names (PDF 1.3), or . Advisory: is the page that holds the annotation. + /// ISO 32000-2 §12.5.2, Table 166. + public CosDictionary? PageObject => Get(AnnotationNames.P) as CosDictionary; + + /// Gets the annotation name, unique among the annotations of its page (NM, PDF 1.4), or . + /// ISO 32000-2 §12.5.2, Table 166. + public string? Name => ReadText(AnnotationNames.NM); + + /// Gets the modification date as stored (M, PDF 1.1), or : a date string or text in any format. + /// ISO 32000-2 §12.5.2, Table 166: processors "shall accept and display a string in any format". + public string? ModifiedText => ReadText(AnnotationNames.M); + + /// Gets the modification date (M) when it is a date (§7.9.4); when absent or in another format, which is legal. + /// ISO 32000-2 §12.5.2, Table 166, and §7.9.4. + public PdfDate? Modified => PdfDate.TryParse(ModifiedText, out PdfDate date) ? date : null; + + /// Gets the annotation flags (F, PDF 1.1), every bit as stored; when absent. + /// + /// ISO 32000-2 §12.5.3, Table 167. A real number is truncated, and bits the table does not define are kept; both record a + /// diagnostic. Text annotations behave as if and + /// were set, whatever this says (§12.5.6.4). + /// + public PdfAnnotationFlags Flags + { + get + { + long bits; + switch (Get(AnnotationNames.F)) + { + case null: + return PdfAnnotationFlags.None; + case CosInteger integer: + bits = integer.Value; + break; + case CosReal real when double.IsFinite(real.Value) && Math.Abs(real.Value) <= uint.MaxValue: + bits = (long)real.Value; + Report(DiagnosticCodes.AnnotationFlagsInvalid, "The annotation's F entry shall be an integer; it is a real number, truncated."); + break; + default: + Report(DiagnosticCodes.AnnotationFlagsInvalid, "The annotation's F entry shall be an integer; it reads as 0."); + return PdfAnnotationFlags.None; + } + + if ((bits & ~0x3FFL) != 0) + { + Report(DiagnosticCodes.AnnotationFlagsInvalid, "The annotation's F entry sets bits Table 167 does not define, which shall be 0; they are kept."); + } + + return (PdfAnnotationFlags)(int)(uint)bits; + } + } + + /// Gets the appearance dictionary (AP, PDF 1.2), or when the annotation has none. + /// + /// ISO 32000-2 §12.5.5, Table 170, and §12.5.2, Table 166. Every annotation shall have one except a popup, link or projection + /// annotation and one whose rectangle has zero width and zero height; that wording is PDF 2.0's, so a missing one records + /// AppearanceMissing only in a PDF 2.0 file. + /// + public PdfAppearanceDictionary? AppearanceDictionary + { + get + { + switch (Get(AnnotationNames.AP)) + { + case CosDictionary dictionary: + return new PdfAppearanceDictionary(this, dictionary); + case null: + if (RequiresAppearance()) + { + Report(DiagnosticCodes.AppearanceMissing, "The annotation has no appearance dictionary, which a PDF 2.0 annotation of its type shall have; it has no appearance."); + } + + return null; + default: + Report(DiagnosticCodes.AppearanceEntryInvalid, "The annotation's AP entry is not a dictionary; it has no appearance."); + return null; + } + } + } + + /// Gets the appearance state (AS, PDF 1.2) that selects an appearance from a state subdictionary, or . + /// ISO 32000-2 §12.5.2, Table 166, and §12.5.5. + public CosName? AppearanceState => ReadName(AnnotationNames.AS); + + /// Gets the border: from BS when present, else from Border, else solid and 1 point wide. + /// ISO 32000-2 §12.5.4, Table 168, and §12.5.2, Table 166 (Border, default [0 0 1]). + public PdfAnnotationBorder Border => ReadBorder(); + + /// Gets the annotation's colour (C, PDF 1.1): its icon background, pop-up title bar or link border; when absent. + /// ISO 32000-2 §12.5.2, Table 166. An empty array is transparent; 2 or more than 4 numbers read as absent with a diagnostic. + public PdfDeviceColor? Color => ReadColor(AnnotationNames.C); + + /// Gets the annotation's key in the structural parent tree (StructParent, PDF 1.3), or . + /// ISO 32000-2 §12.5.2, Table 166, and §14.7.5.4. + public int? StructParent => ReadInteger(AnnotationNames.StructParent); + + /// Gets the optional content group or membership dictionary that decides whether the annotation is visible (OC, PDF 1.5), or . + /// ISO 32000-2 §12.5.2, Table 166, and §8.11.3.3. + public CosDictionary? OptionalContent => ReadDictionary(AnnotationNames.OC); + + /// Gets the files associated with the annotation (AF, PDF 2.0); empty when there are none. + /// ISO 32000-2 §12.5.2, Table 166, and §14.13.9; read as reads any owner's. + public IReadOnlyList AssociatedFiles => Document.ReadAssociatedFiles(Dictionary, DiagnosticReference); + + /// Gets the stroking opacity used when the appearance is regenerated (CA, PDF 1.4); default 1.0. + /// ISO 32000-2 §12.5.2, Table 166. Not used when the annotation has an appearance stream. + public double StrokingOpacity => ReadNumber(AnnotationNames.StrokingOpacity, 1.0); + + /// Gets the non-stroking opacity used when the appearance is regenerated (ca, PDF 2.0); default . + /// ISO 32000-2 §12.5.2, Table 166: "If a ca entry is not present ... the value of this CA entry shall also be used for nonstroking operations". + public double NonStrokingOpacity => ReadOptionalNumber(AnnotationNames.NonStrokingOpacity) ?? StrokingOpacity; + + /// Gets the blend mode used when painting the annotation onto the page (BM, PDF 2.0); default . + /// ISO 32000-2 §12.5.2, Table 166, and §11.3.5, Tables 134 and 135. A name the tables do not list reads as Normal with a diagnostic. + public BlendMode BlendMode + { + get + { + CosName? name = ReadName(AnnotationNames.BM); + if (name is null || name.Value is "Normal" or "Compatible") + { + return BlendMode.Normal; + } + + foreach (BlendMode mode in Enum.GetValues()) + { + if (string.Equals(Enum.GetName(mode), name.Value, StringComparison.Ordinal)) + { + return mode; + } + } + + Report(DiagnosticCodes.AnnotationValueInvalid, "The annotation's BM entry is not a standard blend mode; Normal is used."); + return BlendMode.Normal; + } + } + + /// Gets the natural language of the annotation's text (Lang, PDF 2.0), or . + /// ISO 32000-2 §12.5.2, Table 166, and §14.9.2. + public string? Language => ReadText(AnnotationNames.Lang); + + internal PdfDocument Document { get; } + + /// Gets the reference diagnostics name: the annotation's own, or the page's when the annotation is direct. + private protected CosReference? DiagnosticReference => Reference ?? Page?.Reference; + + /// Gets the subtype the view was created for, to tell when a mutation changed it. + internal CosName? CreatedSubtype { get; private set; } + + /// Returns whether the annotation's optional content (OC) leaves it visible in . + /// Group states from the document's , such as its default states. + /// only when the annotation is optional content that is hidden; flags such as are not applied. + /// ISO 32000-2 §12.5.2, Table 166 (OC, PDF 1.5), and §8.11.3.3, through . + public bool IsVisible(PdfOptionalContentState state) + { + ArgumentNullException.ThrowIfNull(state); + return Document.OptionalContent is not { } properties + || !Dictionary.TryGetValue(AnnotationNames.OC, out CosObject? value) + || properties.IsVisible(value, state); + } + + /// + /// Computes the matrix that maps an appearance's form space to default user space so that the appearance fills the annotation + /// rectangle: Algorithm "Appearance streams" of ISO 32000-2 §12.5.5. + /// + /// The annotation rectangle (normalized). + /// The appearance's BBox, in form space. + /// The appearance's Matrix. + /// + /// The matrix AA = Matrix × A, where A maps the transformed bounding box onto the rectangle; + /// when either has zero width or height (nothing can be drawn). + /// + /// + /// ISO 32000-2 §12.5.5: the bounding box is transformed by the form matrix and the smallest upright rectangle containing the + /// result is mapped onto (lower-left to lower-left, upper-right to upper-right). The appearance's content + /// is painted with this matrix concatenated to the page's CTM and clipped to its bounding box in form space; the form matrix + /// is already part of the result and shall not be applied again. + /// + public static Matrix? ComputeAppearanceMatrix(PdfRectangle rect, PdfRectangle boundingBox, Matrix matrix) + { + PathPoint a = matrix.Transform(boundingBox.Left, boundingBox.Bottom); + PathPoint b = matrix.Transform(boundingBox.Right, boundingBox.Bottom); + PathPoint c = matrix.Transform(boundingBox.Right, boundingBox.Top); + PathPoint d = matrix.Transform(boundingBox.Left, boundingBox.Top); + double left = Math.Min(Math.Min(a.X, b.X), Math.Min(c.X, d.X)); + double right = Math.Max(Math.Max(a.X, b.X), Math.Max(c.X, d.X)); + double bottom = Math.Min(Math.Min(a.Y, b.Y), Math.Min(c.Y, d.Y)); + double top = Math.Max(Math.Max(a.Y, b.Y), Math.Max(c.Y, d.Y)); + if (right - left <= 0 || top - bottom <= 0 || rect.Width <= 0 || rect.Height <= 0) + { + return null; + } + + double scaleX = rect.Width / (right - left); + double scaleY = rect.Height / (top - bottom); + var toRect = new Matrix(scaleX, 0, 0, scaleY, rect.Left - (left * scaleX), rect.Bottom - (bottom * scaleY)); + return Matrix.Multiply(matrix, toRect); + } + + /// Returns the normal appearance for the current appearance state. + /// The form XObject, or when there is none for the state. + /// ISO 32000-2 §12.5.5. As with . + public PdfFormXObject? GetAppearance() => GetAppearance(PdfAppearanceMode.Normal); + + /// Returns the appearance for and the current appearance state (). + /// Normal, rollover or down. + /// + /// The form XObject; when the annotation has no appearance, or when the entry is a state subdictionary + /// and AS is absent (a diagnostic: Table 166 requires it) or names a state the subdictionary lacks (legal: nothing is shown). + /// + /// + /// ISO 32000-2 §12.5.5, Table 170. A missing rollover or down entry falls back to the normal one; a rollover or down state + /// subdictionary that lacks the state falls back to the normal appearance of that state. + /// + public PdfFormXObject? GetAppearance(PdfAppearanceMode mode) + { + if (AppearanceDictionary is not { } appearance) + { + return null; + } + + if (AppearanceState is { } state) + { + return Select(appearance, mode, state); + } + + if (appearance.GetEntry(mode) is not { } entry) + { + return null; + } + + if (!entry.HasStates) + { + return Checked(entry.Form); + } + + Report(DiagnosticCodes.AppearanceStateMissing, "The annotation's appearance has states but no AS entry selects one, which Table 166 requires; it has no appearance."); + return null; + } + + /// Returns the appearance for in the appearance state , whatever AS says. + /// Normal, rollover or down. + /// The appearance state, such as On or Off; ignored when the entry is a single stream. + /// The form XObject, or when there is none. + /// ISO 32000-2 §12.5.5, Table 170, with the fallbacks of . + public PdfFormXObject? GetAppearance(PdfAppearanceMode mode, CosName state) + { + ArgumentNullException.ThrowIfNull(state); + return AppearanceDictionary is { } appearance ? Select(appearance, mode, state) : null; + } + + /// Computes the matrix that places on the annotation rectangle (§12.5.5). + /// One of this annotation's appearances. + /// The matrix from form space to default user space, or when nothing can be drawn. + /// + /// ISO 32000-2 §12.5.5, as with . An + /// appearance without a bounding box uses [0 0 width height] of the rectangle, as pdf.js does. NoZoom, + /// NoRotate and a watermark's FixedPrint add transformations of their own, which are the renderer's. + /// + public Matrix? GetAppearanceMatrix(PdfFormXObject appearance) + { + ArgumentNullException.ThrowIfNull(appearance); + PdfRectangle rect = Rect; + PdfRectangle box = appearance.BoundingBox ?? new PdfRectangle(0, 0, rect.Width, rect.Height); + return ComputeAppearanceMatrix(rect, box, appearance.Matrix); + } + + /// Creates the view of the class the dictionary's subtype selects, recording what the dictionary's type entries lack. + internal static PdfAnnotation Create(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + { + CosName? subtype = ReadSubtype(document, dictionary, out bool isString); + CosReference? diagnosticReference = reference ?? page?.Reference; + if (subtype is null) + { + Report(document, DiagnosticCodes.AnnotationSubtypeMissing, "The annotation has no Subtype name, which Table 166 requires; it reads as an annotation of unknown type.", diagnosticReference); + } + else if (isString) + { + Report(document, DiagnosticCodes.AnnotationSubtypeNotName, "The annotation's Subtype entry shall be a name; it is a string, read as the name it spells.", diagnosticReference); + } + + if (dictionary.TryGetValue(AnnotationNames.Type, out CosObject? type) && document.Resolve(type) is not CosNull and var typeValue && !AnnotationNames.Annot.Equals(typeValue)) + { + Report(document, DiagnosticCodes.AnnotationTypeInvalid, "The annotation's Type entry, if present, shall be Annot; it is ignored.", diagnosticReference); + } + + PdfAnnotation annotation = subtype?.Value switch + { + "Text" => new PdfTextAnnotation(document, dictionary, reference, page), + "Link" => new PdfLinkAnnotation(document, dictionary, reference, page), + "FreeText" => new PdfFreeTextAnnotation(document, dictionary, reference, page), + "Line" => new PdfLineAnnotation(document, dictionary, reference, page), + "Square" => new PdfSquareAnnotation(document, dictionary, reference, page), + "Circle" => new PdfCircleAnnotation(document, dictionary, reference, page), + "Polygon" => new PdfPolygonAnnotation(document, dictionary, reference, page), + "PolyLine" => new PdfPolyLineAnnotation(document, dictionary, reference, page), + "Highlight" => new PdfHighlightAnnotation(document, dictionary, reference, page), + "Underline" => new PdfUnderlineAnnotation(document, dictionary, reference, page), + "Squiggly" => new PdfSquigglyAnnotation(document, dictionary, reference, page), + "StrikeOut" => new PdfStrikeOutAnnotation(document, dictionary, reference, page), + "Caret" => new PdfCaretAnnotation(document, dictionary, reference, page), + "Stamp" => new PdfStampAnnotation(document, dictionary, reference, page), + "Ink" => new PdfInkAnnotation(document, dictionary, reference, page), + "Popup" => new PdfPopupAnnotation(document, dictionary, reference, page), + "FileAttachment" => new PdfFileAttachmentAnnotation(document, dictionary, reference, page), + "Sound" => new PdfSoundAnnotation(document, dictionary, reference, page), + "Movie" => new PdfMovieAnnotation(document, dictionary, reference, page), + "Screen" => new PdfScreenAnnotation(document, dictionary, reference, page), + "Widget" => new PdfWidgetAnnotation(document, dictionary, reference, page), + "PrinterMark" => new PdfPrinterMarkAnnotation(document, dictionary, reference, page), + "TrapNet" => new PdfTrapNetAnnotation(document, dictionary, reference, page), + "Watermark" => new PdfWatermarkAnnotation(document, dictionary, reference, page), + "3D" => new Pdf3DAnnotation(document, dictionary, reference, page), + "Redact" => new PdfRedactAnnotation(document, dictionary, reference, page), + "Projection" => new PdfProjectionAnnotation(document, dictionary, reference, page), + "RichMedia" => new PdfRichMediaAnnotation(document, dictionary, reference, page), + _ => new PdfUnknownAnnotation(document, dictionary, reference, page), + }; + return annotation.WithCreatedSubtype(subtype); + } + + /// Reads Subtype: a name, or a string read as a name (); otherwise. + internal static CosName? ReadSubtype(PdfDocument document, CosDictionary dictionary, out bool isString) + { + isString = false; + switch (dictionary.TryGetValue(AnnotationNames.Subtype, out CosObject? value) ? document.Resolve(value) : null) + { + case CosName name: + return name; + case CosString text when !text.Bytes.Contains((byte)0): + isString = true; + return new CosName(text.Bytes); + default: + return null; + } + } + + /// Whether an appearance dictionary is required: PDF 2.0, not a popup, link or projection, rectangle not of zero size. + internal bool RequiresAppearance() + { + if (Kind is PdfAnnotationKind.Popup or PdfAnnotationKind.Link or PdfAnnotationKind.Projection || Document.Version < new PdfVersion(2, 0)) + { + return false; + } + + return !(Get(AnnotationNames.Rect) is CosArray { Count: 4 } rect + && AnnotationValues.ReadNumber(Document, rect[0]) is { } x1 && x1 == AnnotationValues.ReadNumber(Document, rect[2]) + && AnnotationValues.ReadNumber(Document, rect[1]) is { } y1 && y1 == AnnotationValues.ReadNumber(Document, rect[3])); + } + + /// Reports a deviation in this annotation. + internal void Report(string code, string message, DiagnosticSeverity severity = DiagnosticSeverity.Warning) => + Document.DiagnosticSink.Report(code, severity, message, objectReference: DiagnosticReference); + + /// Returns the entry for , resolved; when absent or a reference to nothing. + private protected CosObject? Get(CosName key) => + Dictionary.TryGetValue(key, out CosObject? value) && Document.Resolve(value) is not CosNull and var resolved ? resolved : null; + + /// Records that a required entry is absent. + private protected void ReportMissing(CosName key, string table) => + Report(DiagnosticCodes.AnnotationRequiredEntryMissing, $"The {Kind} annotation has no {key.Value} entry, which {table} requires."); + + /// Records that an entry has the wrong type and is ignored. + private protected void ReportInvalid(CosName key, string expected) => + Report(DiagnosticCodes.AnnotationValueInvalid, $"The annotation's {key.Value} entry shall be {expected}; it is ignored."); + + /// Reads a text string entry (§7.9.2.2). + private protected string? ReadText(CosName key) + { + switch (Get(key)) + { + case null: + return null; + case CosString text: + return text.DecodeText(); + default: + ReportInvalid(key, "a text string"); + return null; + } + } + + /// Reads a text string or text stream entry (§7.9.3): a stream's decoded bytes read as a text string. + private protected string? ReadTextOrStream(CosName key) + { + switch (Get(key)) + { + case null: + return null; + case CosString text: + return text.DecodeText(); + case CosStream stream: + return new CosString(Document.DecodeStream(stream).Span).DecodeText(); + default: + ReportInvalid(key, "a text string or text stream"); + return null; + } + } + + /// Reads a byte string entry, such as a default appearance string, as Latin-1 text. + private protected string? ReadByteString(CosName key) + { + switch (Get(key)) + { + case null: + return null; + case CosString text: + return System.Text.Encoding.Latin1.GetString(text.Bytes); + default: + ReportInvalid(key, "a string"); + return null; + } + } + + /// Reads a boolean entry. + private protected bool ReadBoolean(CosName key, bool fallback) + { + switch (Get(key)) + { + case null: + return fallback; + case CosBoolean boolean: + return boolean.Value; + default: + ReportInvalid(key, "a boolean"); + return fallback; + } + } + + /// Reads a number entry. + private protected double ReadNumber(CosName key, double fallback) => ReadOptionalNumber(key) ?? fallback; + + /// Reads an optional number entry. + private protected double? ReadOptionalNumber(CosName key) + { + CosObject? value = Get(key); + if (value is null) + { + return null; + } + + if (AnnotationValues.ReadNumber(Document, value) is { } number) + { + return number; + } + + ReportInvalid(key, "a number"); + return null; + } + + /// Reads an integer entry. + private protected int? ReadInteger(CosName key) + { + CosObject? value = Get(key); + if (value is null) + { + return null; + } + + if (AnnotationValues.ReadInteger(Document, value) is { } integer) + { + return integer; + } + + ReportInvalid(key, "an integer"); + return null; + } + + /// Reads a name entry. + private protected CosName? ReadName(CosName key) + { + switch (Get(key)) + { + case null: + return null; + case CosName name: + return name; + default: + ReportInvalid(key, "a name"); + return null; + } + } + + /// Reads a name entry from a fixed set; an unknown name reads as silently (the sets are open), another type with a diagnostic. + private protected T ReadChoice(CosName key, T fallback, params ReadOnlySpan<(string Name, T Value)> choices) + { + if (ReadName(key) is { } name) + { + foreach ((string text, T value) in choices) + { + if (string.Equals(name.Value, text, StringComparison.Ordinal)) + { + return value; + } + } + } + + return fallback; + } + + /// Reads a dictionary entry. + private protected CosDictionary? ReadDictionary(CosName key) + { + switch (Get(key)) + { + case null: + return null; + case CosDictionary dictionary: + return dictionary; + default: + ReportInvalid(key, "a dictionary"); + return null; + } + } + + /// Reads a stream entry. + private protected CosStream? ReadStream(CosName key) + { + switch (Get(key)) + { + case null: + return null; + case CosStream stream: + return stream; + default: + ReportInvalid(key, "a stream"); + return null; + } + } + + /// Reads an array entry. + private protected CosArray? ReadArray(CosName key) + { + switch (Get(key)) + { + case null: + return null; + case CosArray array: + return array; + default: + ReportInvalid(key, "an array"); + return null; + } + } + + /// Reads a colour array entry (Table 166 C). + private protected PdfDeviceColor? ReadColor(CosName key) + { + PdfDeviceColor? color = AnnotationValues.ReadColor(Document, Get(key), out bool valid); + if (!valid) + { + Report(DiagnosticCodes.ColorArrayInvalid, $"The annotation's {key.Value} entry is not an array of 0, 1, 3 or 4 numbers; it reads as absent."); + } + + return color; + } + + /// Reads an action entry (§12.6). + private protected PdfAction? ReadAction(CosName key) => + Dictionary.TryGetValue(key, out CosObject? value) ? PdfAction.Create(Document, value, DiagnosticReference) : null; + + /// Reads a form XObject entry (§8.10). + private protected PdfFormXObject? ReadForm(CosName key) => + ReadStream(key) is not null && Dictionary.TryGetValue(key, out CosObject? value) ? PdfFormXObject.Create(Document, value) : null; + + /// Reads a date entry (§7.9.4), recording a deviation from the date format. + private protected PdfDate? ReadDate(CosName key) + { + if (ReadText(key) is not { } text) + { + return null; + } + + switch (PdfDate.Parse(text, out PdfDate date)) + { + case DateParseOutcome.Valid: + return date; + case DateParseOutcome.Repaired: + Report(DiagnosticCodes.DateInvalid, $"The annotation's {key.Value} entry does not follow the date format of §7.9.4; it is read with the deviating fields repaired."); + return date; + default: + Report(DiagnosticCodes.DateUnreadable, $"The annotation's {key.Value} entry is not a date (§7.9.4)."); + return null; + } + } + + /// Reads a flat array of x y pairs, such as Vertices or L; an odd count or a non-number records a diagnostic. + private protected IReadOnlyList ReadPoints(CosName key, bool required, string table) + { + CosObject? value = Get(key); + if (value is null) + { + if (required) + { + ReportMissing(key, table); + } + + return []; + } + + List? numbers = AnnotationValues.ReadNumbers(Document, value, out bool complete); + if (numbers is null || !complete || numbers.Count % 2 != 0) + { + ReportInvalid(key, "an array of pairs of numbers"); + if (numbers is null) + { + return []; + } + } + + var points = new PathPoint[numbers.Count / 2]; + for (int index = 0; index < points.Length; index++) + { + points[index] = new PathPoint(numbers[2 * index], numbers[(2 * index) + 1]); + } + + return points; + } + + /// Reads an array of arrays of x y pairs, such as InkList. + private protected IReadOnlyList> ReadPointLists(CosName key, bool required, string table) + { + CosObject? value = Get(key); + if (value is null) + { + if (required) + { + ReportMissing(key, table); + } + + return []; + } + + if (value is not CosArray outer) + { + ReportInvalid(key, "an array of arrays of numbers"); + return []; + } + + var lists = new List>(outer.Count); + bool valid = true; + foreach (CosObject element in outer) + { + List? numbers = AnnotationValues.ReadNumbers(Document, element, out bool complete); + valid &= numbers is not null && complete && numbers.Count % 2 == 0; + if (numbers is null) + { + continue; + } + + var points = new PathPoint[numbers.Count / 2]; + for (int index = 0; index < points.Length; index++) + { + points[index] = new PathPoint(numbers[2 * index], numbers[(2 * index) + 1]); + } + + lists.Add(points); + } + + if (!valid) + { + ReportInvalid(key, "an array of arrays of pairs of numbers"); + } + + return lists; + } + + /// Reads Path (PDF 2.0): arrays of 2 numbers (a point) or 6 (a Bézier curve's two control points and end point). + private protected IReadOnlyList>? ReadPath() + { + if (ReadArray(AnnotationNames.Path) is not { } outer) + { + return null; + } + + var segments = new List>(outer.Count); + bool valid = true; + foreach (CosObject element in outer) + { + List? numbers = AnnotationValues.ReadNumbers(Document, element, out bool complete); + bool shape = numbers is not null && complete && (numbers.Count == 2 || (numbers.Count == 6 && segments.Count > 0)); + valid &= shape; + if (shape) + { + segments.Add(numbers!); + } + } + + if (!valid) + { + ReportInvalid(AnnotationNames.Path, "an array of arrays of 2 or 6 numbers, the first of 2"); + } + + return segments; + } + + /// Reads QuadPoints: complete quadrilaterals only; a count not a multiple of 8 or a non-number records a diagnostic. + private protected IReadOnlyList ReadQuadPoints(bool required, string table) + { + CosObject? value = Get(AnnotationNames.QuadPoints); + if (value is null) + { + if (required) + { + ReportMissing(AnnotationNames.QuadPoints, table); + } + + return []; + } + + List? numbers = AnnotationValues.ReadNumbers(Document, value, out bool complete); + if (numbers is null || !complete || numbers.Count % 8 != 0 || numbers.Count == 0) + { + Report(DiagnosticCodes.QuadPointsInvalid, "The annotation's QuadPoints entry is not an array of 8n numbers; only its complete quadrilaterals are read."); + if (numbers is null) + { + return []; + } + } + + var quads = new PdfQuadrilateral[numbers.Count / 8]; + for (int index = 0; index < quads.Length; index++) + { + int at = index * 8; + quads[index] = new PdfQuadrilateral( + new PathPoint(numbers[at], numbers[at + 1]), + new PathPoint(numbers[at + 2], numbers[at + 3]), + new PathPoint(numbers[at + 4], numbers[at + 5]), + new PathPoint(numbers[at + 6], numbers[at + 7])); + } + + return quads; + } + + /// Reads RD: four non-negative numbers. + private protected PdfRectangleDifferences? ReadRectangleDifferences() + { + CosObject? value = Get(AnnotationNames.RD); + if (value is null) + { + return null; + } + + Span numbers = stackalloc double[4]; + if (value is CosArray { Count: 4 } array && AnnotationValues.TryReadNumbers(Document, array, numbers) + && numbers[0] >= 0 && numbers[1] >= 0 && numbers[2] >= 0 && numbers[3] >= 0) + { + return new PdfRectangleDifferences(numbers[0], numbers[1], numbers[2], numbers[3]); + } + + ReportInvalid(AnnotationNames.RD, "an array of four non-negative numbers"); + return null; + } + + /// Reads a line ending name (Table 179); unknown names read as None. + private protected static PdfLineEnding ParseLineEnding(CosObject? value) => value is CosName name + ? name.Value switch + { + "Square" => PdfLineEnding.Square, + "Circle" => PdfLineEnding.Circle, + "Diamond" => PdfLineEnding.Diamond, + "OpenArrow" => PdfLineEnding.OpenArrow, + "ClosedArrow" => PdfLineEnding.ClosedArrow, + "Butt" => PdfLineEnding.Butt, + "ROpenArrow" => PdfLineEnding.ROpenArrow, + "RClosedArrow" => PdfLineEnding.RClosedArrow, + "Slash" => PdfLineEnding.Slash, + _ => PdfLineEnding.None, + } + : PdfLineEnding.None; + + /// Reads LE as two line endings, start and end (line and polyline annotations). + private protected (PdfLineEnding Start, PdfLineEnding End) ReadLineEndings() + { + switch (Get(AnnotationNames.LE)) + { + case null: + return (PdfLineEnding.None, PdfLineEnding.None); + case CosArray { Count: 2 } array: + return (ParseLineEnding(Document.Resolve(array[0])), ParseLineEnding(Document.Resolve(array[1]))); + default: + ReportInvalid(AnnotationNames.LE, "an array of two names"); + return (PdfLineEnding.None, PdfLineEnding.None); + } + } + + /// Reads the border effect dictionary BE (Table 169). + private protected PdfBorderEffect? ReadBorderEffect() + { + if (ReadDictionary(AnnotationNames.BE) is not { } effect) + { + return null; + } + + var view = new DictionaryView(Document, effect, DiagnosticReference); + PdfBorderEffectStyle style = view.Get(AnnotationNames.S) is CosName { Value: "C" } ? PdfBorderEffectStyle.Cloudy : PdfBorderEffectStyle.None; + double intensity = AnnotationValues.ReadNumber(Document, view.Get(AnnotationNames.I)) ?? 0; + if (intensity is < 0 or > 2) + { + Report(DiagnosticCodes.AnnotationValueInvalid, "The border effect's intensity I shall be from 0 to 2; it is clamped."); + intensity = Math.Clamp(intensity, 0, 2); + } + + return new PdfBorderEffect(style, intensity); + } + + /// Reads the icon name entry Name, with the subtype's default. + private protected string ReadIconName(string fallback) => ReadName(AnnotationNames.Name)?.Value ?? fallback; + + private static void Report(PdfDocument document, string code, string message, CosReference? reference) => + document.DiagnosticSink.Report(code, DiagnosticSeverity.Warning, message, objectReference: reference); + + private PdfAnnotation WithCreatedSubtype(CosName? subtype) + { + CreatedSubtype = subtype; + return this; + } + + private PdfFormXObject? Select(PdfAppearanceDictionary appearance, PdfAppearanceMode mode, CosName state) + { + if (appearance.GetEntry(mode) is not { } entry) + { + return null; + } + + if (!entry.HasStates) + { + return Checked(entry.Form); + } + + if (entry.GetAppearance(state) is { } form) + { + return Checked(form); + } + + // A rollover or down subdictionary without the state shows the normal appearance of that state. + return mode != PdfAppearanceMode.Normal && appearance.Normal is { HasStates: true } normal ? Checked(normal.GetAppearance(state)) : null; + } + + private PdfFormXObject? Checked(PdfFormXObject? form) + { + if (form is null) + { + return null; + } + + if (!form.IsForm) + { + Report(DiagnosticCodes.AppearanceNotForm, "An appearance stream's Subtype is not Form (§8.10.1, Table 93); it is read as a form XObject."); + } + + if (form.BoundingBox is null) + { + Report(DiagnosticCodes.AppearanceBBoxMissing, "An appearance stream has no BBox of four numbers, which Table 93 requires; the annotation rectangle's size is used."); + } + + return form; + } + + private PdfAnnotationBorder ReadBorder() + { + if (Get(AnnotationNames.BS) is { } styleValue) + { + if (styleValue is CosDictionary style) + { + return ReadBorderStyle(style); + } + + ReportInvalid(AnnotationNames.BS, "a border style dictionary"); + } + + CosObject? border = Get(AnnotationNames.Border); + if (border is null) + { + return new PdfAnnotationBorder(1, PdfBorderStyle.Solid, [], 0, 0, PdfBorderSource.Default); + } + + if (border is not CosArray array) + { + Report(DiagnosticCodes.BorderArrayInvalid, "The annotation's Border entry is not an array; the default border is used."); + return new PdfAnnotationBorder(1, PdfBorderStyle.Solid, [], 0, 0, PdfBorderSource.Default); + } + + Span numbers = stackalloc double[3]; + bool valid = array.Count is 3 or 4; + for (int index = 0; index < 3; index++) + { + double? number = index < array.Count ? AnnotationValues.ReadNumber(Document, array[index]) : null; + valid &= number is not null; + numbers[index] = number ?? 0; + } + + double[] dashes = []; + if (array.Count >= 4) + { + List? pattern = AnnotationValues.ReadNumbers(Document, array[3], out bool complete); + valid &= pattern is not null && complete && pattern.TrueForAll(dash => dash >= 0); + dashes = pattern is not null && complete && pattern.TrueForAll(dash => dash >= 0) && pattern.Exists(dash => dash > 0) ? [.. pattern] : []; + } + + if (!valid) + { + Report(DiagnosticCodes.BorderArrayInvalid, "The annotation's Border entry is not three numbers and an optional dash array; missing elements read as 0."); + } + + return new PdfAnnotationBorder(numbers[2], dashes.Length > 0 ? PdfBorderStyle.Dashed : PdfBorderStyle.Solid, dashes, numbers[0], numbers[1], PdfBorderSource.BorderArray); + } + + private PdfAnnotationBorder ReadBorderStyle(CosDictionary style) + { + var view = new DictionaryView(Document, style, DiagnosticReference); + if (view.Get(AnnotationNames.Type) is { } type && !(type is CosName { Value: "Border" })) + { + Report(DiagnosticCodes.BorderStyleTypeInvalid, "The border style dictionary's Type, if present, shall be Border; the dictionary is used anyway."); + } + + double width = 1; + if (view.Get(AnnotationNames.W) is { } widthValue) + { + if (AnnotationValues.ReadNumber(Document, widthValue) is { } number && number >= 0) + { + width = number; + } + else + { + Report(DiagnosticCodes.AnnotationValueInvalid, "The border style's width W is not a non-negative number; 1 is used."); + } + } + + PdfBorderStyle kind = view.Get(AnnotationNames.S) is CosName name + ? name.Value switch + { + "D" => PdfBorderStyle.Dashed, + "B" => PdfBorderStyle.Beveled, + "I" => PdfBorderStyle.Inset, + "U" => PdfBorderStyle.Underline, + _ => PdfBorderStyle.Solid, + } + : PdfBorderStyle.Solid; + + double[] dashes = []; + if (kind == PdfBorderStyle.Dashed) + { + dashes = [3]; + if (view.Get(AnnotationNames.D) is { } dashValue) + { + List? pattern = AnnotationValues.ReadNumbers(Document, dashValue, out bool complete); + if (pattern is not null && complete && pattern.Count > 0 && pattern.TrueForAll(dash => dash >= 0) && pattern.Exists(dash => dash > 0)) + { + dashes = [.. pattern]; + } + else + { + Report(DiagnosticCodes.AnnotationValueInvalid, "The border style's dash array D is not a dash pattern; [3] is used."); + } + } + } + + return new PdfAnnotationBorder(width, kind, dashes, 0, 0, PdfBorderSource.BorderStyle); + } +} diff --git a/src/Broadside/Annotations/PdfAnnotationBorder.cs b/src/Broadside/Annotations/PdfAnnotationBorder.cs new file mode 100644 index 00000000..82091ed0 --- /dev/null +++ b/src/Broadside/Annotations/PdfAnnotationBorder.cs @@ -0,0 +1,48 @@ +namespace Broadside.Annotations; + +/// +/// The border of an annotation: its width, style, dash pattern and corner radii, from the border style dictionary (BS) when +/// there is one, else from the Border array, else the default (solid, 1 point wide, square corners). +/// +/// +/// ISO 32000-2 §12.5.4, Table 168, and §12.5.2, Table 166 (Border, default [0 0 1]). "If an annotation dictionary +/// includes the BS entry, then the Border entry is ignored." A snapshot computed when is read. +/// A conforming reader ignores the border when it renders an appearance stream (§12.5.2). +/// +public sealed class PdfAnnotationBorder +{ + private readonly double[] _dashes; + + internal PdfAnnotationBorder(double width, PdfBorderStyle style, ReadOnlySpan dashes, double horizontalCornerRadius, double verticalCornerRadius, PdfBorderSource source) + { + Width = width; + Style = style; + _dashes = dashes.ToArray(); + HorizontalCornerRadius = horizontalCornerRadius; + VerticalCornerRadius = verticalCornerRadius; + Source = source; + } + + /// Gets the border width in points; 0 draws no border. + /// ISO 32000-2 §12.5.4, Table 168 (W, default 1), or the third element of Border. + public double Width { get; } + + /// Gets the border style. + /// ISO 32000-2 §12.5.4, Table 168 (S, default solid); a Border array with a dash array is dashed. + public PdfBorderStyle Style { get; } + + /// Gets the dash pattern of a dashed border: alternating dash and gap lengths, phase 0; empty for a solid one. + /// ISO 32000-2 §12.5.4, Table 168 (D, default [3]), or the fourth element of Border (PDF 1.1). + public IReadOnlyList DashPattern => _dashes; + + /// Gets the horizontal corner radius (the first element of Border); 0 for square corners and for a BS border. + /// ISO 32000-2 §12.5.2, Table 166. + public double HorizontalCornerRadius { get; } + + /// Gets the vertical corner radius (the second element of Border); 0 for square corners and for a BS border. + /// ISO 32000-2 §12.5.2, Table 166. + public double VerticalCornerRadius { get; } + + /// Gets the entry the border was read from. + public PdfBorderSource Source { get; } +} diff --git a/src/Broadside/Annotations/PdfAnnotationFlags.cs b/src/Broadside/Annotations/PdfAnnotationFlags.cs new file mode 100644 index 00000000..67b3b51b --- /dev/null +++ b/src/Broadside/Annotations/PdfAnnotationFlags.cs @@ -0,0 +1,43 @@ +namespace Broadside.Annotations; + +/// The annotation flags, the bits of an annotation dictionary's F entry. +/// +/// ISO 32000-2 §12.5.3, Table 167. Bit n of the entry is 1 << (n − 1). "All other bits of the integer shall be set to +/// 0"; a file that sets them keeps them ( returns every bit as stored). +/// +[Flags] +public enum PdfAnnotationFlags +{ + /// No flag is set (the default). + None = 0, + + /// Bit 1 (PDF 1.0): for an annotation of a type the processor has no handler for, do not display or print it. + Invisible = 1 << 0, + + /// Bit 2 (PDF 1.2): do not display or print the annotation nor let the user interact with it. + Hidden = 1 << 1, + + /// Bit 3 (PDF 1.2): print the annotation when the page is printed (unless is set). + Print = 1 << 2, + + /// Bit 4 (PDF 1.3): do not scale the appearance with the page magnification; the upper-left corner of the rectangle stays fixed. + NoZoom = 1 << 3, + + /// Bit 5 (PDF 1.3): do not rotate the appearance with the page; the upper-left corner of the rectangle stays fixed. + NoRotate = 1 << 4, + + /// Bit 6 (PDF 1.3): do not display the annotation on the screen nor let the user interact with it; it may still print. + NoView = 1 << 5, + + /// Bit 7 (PDF 1.3): do not let the user interact with the annotation. Ignored for widget annotations. + ReadOnly = 1 << 6, + + /// Bit 8 (PDF 1.4): do not let the user delete the annotation or change its properties. + Locked = 1 << 7, + + /// Bit 9 (PDF 1.5): invert for certain events, such as the mouse hovering over the annotation. + ToggleNoView = 1 << 8, + + /// Bit 10 (PDF 1.7): do not let the user change the annotation's contents (its properties may still change). + LockedContents = 1 << 9, +} diff --git a/src/Broadside/Annotations/PdfAnnotationKind.cs b/src/Broadside/Annotations/PdfAnnotationKind.cs new file mode 100644 index 00000000..c31da098 --- /dev/null +++ b/src/Broadside/Annotations/PdfAnnotationKind.cs @@ -0,0 +1,93 @@ +namespace Broadside.Annotations; + +/// The standard annotation types, the values of an annotation dictionary's Subtype entry. +/// ISO 32000-2 §12.5.6.1, Table 171. The set is extensible (§12.5.2): any other subtype reads as . +public enum PdfAnnotationKind +{ + /// A subtype Table 171 does not list, or no subtype at all: a . + Unknown, + + /// Text (PDF 1.0, markup): a sticky note. ISO 32000-2 §12.5.6.4. + Text, + + /// Link (PDF 1.0): a hypertext link. ISO 32000-2 §12.5.6.5. + Link, + + /// FreeText (PDF 1.3, markup): text displayed on the page. ISO 32000-2 §12.5.6.6. + FreeText, + + /// Line (PDF 1.3, markup): a straight line. ISO 32000-2 §12.5.6.7. + Line, + + /// Square (PDF 1.3, markup): a rectangle. ISO 32000-2 §12.5.6.8. + Square, + + /// Circle (PDF 1.3, markup): an ellipse. ISO 32000-2 §12.5.6.8. + Circle, + + /// Polygon (PDF 1.5, markup): a closed polygon. ISO 32000-2 §12.5.6.9. + Polygon, + + /// PolyLine (PDF 1.5, markup): an open polygon. ISO 32000-2 §12.5.6.9. + PolyLine, + + /// Highlight (PDF 1.3, markup): highlighted text. ISO 32000-2 §12.5.6.10. + Highlight, + + /// Underline (PDF 1.3, markup): underlined text. ISO 32000-2 §12.5.6.10. + Underline, + + /// Squiggly (PDF 1.4, markup): text with a jagged underline. ISO 32000-2 §12.5.6.10. + Squiggly, + + /// StrikeOut (PDF 1.3, markup): struck-out text. ISO 32000-2 §12.5.6.10. + StrikeOut, + + /// Caret (PDF 1.5, markup): a text insertion point. ISO 32000-2 §12.5.6.11. + Caret, + + /// Stamp (PDF 1.3, markup): a rubber stamp. ISO 32000-2 §12.5.6.12. + Stamp, + + /// Ink (PDF 1.3, markup): freehand paths. ISO 32000-2 §12.5.6.13. + Ink, + + /// Popup (PDF 1.3): the pop-up window of a markup annotation. ISO 32000-2 §12.5.6.14. + Popup, + + /// FileAttachment (PDF 1.3, markup): an attached file. ISO 32000-2 §12.5.6.15. + FileAttachment, + + /// Sound (PDF 1.2, markup; deprecated in PDF 2.0): a sound clip. ISO 32000-2 §12.5.6.16. + Sound, + + /// Movie (PDF 1.2; deprecated in PDF 2.0): a movie. ISO 32000-2 §12.5.6.17. + Movie, + + /// Screen (PDF 1.5): a region where media clips play. ISO 32000-2 §12.5.6.18. + Screen, + + /// Widget (PDF 1.2): the appearance of an interactive form field. ISO 32000-2 §12.5.6.19. + Widget, + + /// PrinterMark (PDF 1.4): a printer's mark. ISO 32000-2 §12.5.6.20 and §14.11.3. + PrinterMark, + + /// TrapNet (PDF 1.3; deprecated in PDF 2.0): a trap network. ISO 32000-2 §12.5.6.21 and §14.11.6.2. + TrapNet, + + /// Watermark (PDF 1.6): content printed at a fixed size and position on the media. ISO 32000-2 §12.5.6.22. + Watermark, + + /// 3D (PDF 1.6): 3D artwork. ISO 32000-2 §12.5.6.25 and §13.6.2. + ThreeD, + + /// Redact (PDF 1.7, markup): content to be removed. ISO 32000-2 §12.5.6.23. + Redact, + + /// Projection (PDF 2.0, markup): a projection annotation. ISO 32000-2 §12.5.6.24. + Projection, + + /// RichMedia (PDF 2.0): rich media content. ISO 32000-2 §12.5.6.25 and §13.7.2. + RichMedia, +} diff --git a/src/Broadside/Annotations/PdfAppearanceCharacteristics.cs b/src/Broadside/Annotations/PdfAppearanceCharacteristics.cs new file mode 100644 index 00000000..0e27090f --- /dev/null +++ b/src/Broadside/Annotations/PdfAppearanceCharacteristics.cs @@ -0,0 +1,144 @@ +using Broadside.Graphics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Annotations; + +/// An appearance characteristics dictionary: what a processor needs to construct a widget's or screen's appearance. A live view over MK. +/// ISO 32000-2 §12.5.6.19, Table 192. Captions and icons apply to button fields; the colours and rotation to any widget. +public sealed class PdfAppearanceCharacteristics +{ + private readonly PdfAnnotation _owner; + + internal PdfAppearanceCharacteristics(PdfAnnotation owner, CosDictionary dictionary) + { + _owner = owner; + Dictionary = dictionary; + } + + /// Gets the appearance characteristics dictionary. + /// ISO 32000-2 §12.5.6.19, Table 192. + public CosDictionary Dictionary { get; } + + /// Gets the number of degrees the annotation is rotated counterclockwise relative to the page (R): a multiple of 90; default 0. + /// ISO 32000-2 §12.5.6.19, Table 192. A value that is not an integer multiple of 90 reads as 0 with a diagnostic. + public int Rotation + { + get + { + CosObject? value = Get(AnnotationNames.R); + if (value is null) + { + return 0; + } + + if (AnnotationValues.ReadInteger(_owner.Document, value) is { } degrees && degrees % 90 == 0) + { + return ((degrees % 360) + 360) % 360; + } + + _owner.Report(DiagnosticCodes.AnnotationValueInvalid, "The appearance characteristics' rotation R is not a multiple of 90; it reads as 0."); + return 0; + } + } + + /// Gets the border colour (BC), or for none. + /// ISO 32000-2 §12.5.6.19, Table 192. + public PdfDeviceColor? BorderColor => ReadColor(AnnotationNames.BC); + + /// Gets the background colour (BG), or for none. + /// ISO 32000-2 §12.5.6.19, Table 192. + public PdfDeviceColor? BackgroundColor => ReadColor(AnnotationNames.BG); + + /// Gets the normal caption (CA, button fields), or . + /// ISO 32000-2 §12.5.6.19, Table 192. + public string? NormalCaption => ReadText(AnnotationNames.StrokingOpacity); + + /// Gets the rollover caption (RC, push buttons), or . + /// ISO 32000-2 §12.5.6.19, Table 192. + public string? RolloverCaption => ReadText(AnnotationNames.RC); + + /// Gets the alternate (down) caption (AC, push buttons), or . + /// ISO 32000-2 §12.5.6.19, Table 192. + public string? AlternateCaption => ReadText(AnnotationNames.AC); + + /// Gets the normal icon (I, push buttons), or . + /// ISO 32000-2 §12.5.6.19, Table 192. + public PdfFormXObject? NormalIcon => ReadForm(AnnotationNames.I); + + /// Gets the rollover icon (RI, push buttons), or . + /// ISO 32000-2 §12.5.6.19, Table 192. + public PdfFormXObject? RolloverIcon => ReadForm(AnnotationNames.RI); + + /// Gets the alternate (down) icon (IX, push buttons), or . + /// ISO 32000-2 §12.5.6.19, Table 192. + public PdfFormXObject? AlternateIcon => ReadForm(AnnotationNames.IX); + + /// Gets the icon fit dictionary (IF, push buttons), as stored, or . + /// ISO 32000-2 §12.5.6.19, Table 192, and §12.7.8.2, Table 250. + public CosDictionary? IconFit => _owner.Document.Resolve(Get(AnnotationNames.IF)) as CosDictionary; + + /// Gets where the caption is placed relative to the icon (TP, push buttons): 0 caption only (the default) to 6 overlaid. + /// ISO 32000-2 §12.5.6.19, Table 192. A value outside 0 to 6 reads as 0 with a diagnostic. + public int TextPosition + { + get + { + CosObject? value = Get(AnnotationNames.TP); + if (value is null) + { + return 0; + } + + if (AnnotationValues.ReadInteger(_owner.Document, value) is { } position and >= 0 and <= 6) + { + return position; + } + + _owner.Report(DiagnosticCodes.AnnotationValueInvalid, "The appearance characteristics' TP is not an integer from 0 to 6; it reads as 0."); + return 0; + } + } + + private CosObject? Get(CosName key) => + Dictionary.TryGetValue(key, out CosObject? value) && _owner.Document.Resolve(value) is not CosNull and var resolved ? resolved : null; + + private PdfDeviceColor? ReadColor(CosName key) + { + PdfDeviceColor? color = AnnotationValues.ReadColor(_owner.Document, Get(key), out bool valid); + if (!valid) + { + _owner.Report(DiagnosticCodes.ColorArrayInvalid, $"The appearance characteristics' {key.Value} entry is not an array of 0, 1, 3 or 4 numbers; it reads as absent."); + } + + return color; + } + + private string? ReadText(CosName key) + { + switch (Get(key)) + { + case null: + return null; + case CosString text: + return text.DecodeText(); + default: + _owner.Report(DiagnosticCodes.AnnotationValueInvalid, $"The appearance characteristics' {key.Value} entry shall be a text string; it is ignored."); + return null; + } + } + + private PdfFormXObject? ReadForm(CosName key) + { + switch (Get(key)) + { + case null: + return null; + case CosStream: + return PdfFormXObject.Create(_owner.Document, Dictionary[key]); + default: + _owner.Report(DiagnosticCodes.AnnotationValueInvalid, $"The appearance characteristics' {key.Value} entry shall be a form XObject; it is ignored."); + return null; + } + } +} diff --git a/src/Broadside/Annotations/PdfAppearanceDictionary.cs b/src/Broadside/Annotations/PdfAppearanceDictionary.cs new file mode 100644 index 00000000..276c1fe8 --- /dev/null +++ b/src/Broadside/Annotations/PdfAppearanceDictionary.cs @@ -0,0 +1,70 @@ +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Annotations; + +/// An annotation's appearance dictionary: its normal, rollover and down appearances. A live view over the AP dictionary. +/// +/// ISO 32000-2 §12.5.5, Table 170. Each entry is a form XObject or a subdictionary of them keyed by appearance state +/// (). and default to when absent. +/// +public sealed class PdfAppearanceDictionary +{ + private readonly PdfAnnotation _owner; + + internal PdfAppearanceDictionary(PdfAnnotation owner, CosDictionary dictionary) + { + _owner = owner; + Dictionary = dictionary; + } + + /// Gets the appearance dictionary. + /// ISO 32000-2 §12.5.5, Table 170. + public CosDictionary Dictionary { get; } + + /// Gets the normal appearance (N, required), or when it is missing or neither a stream nor a dictionary. + /// ISO 32000-2 §12.5.5, Table 170. + public PdfAppearanceEntry? Normal => Read(AnnotationNames.N, required: true); + + /// Gets the rollover appearance (R); the normal appearance when absent. + /// ISO 32000-2 §12.5.5, Table 170: "Default value: the value of the N entry". + public PdfAppearanceEntry? Rollover => Dictionary.ContainsKey(AnnotationNames.R) ? Read(AnnotationNames.R, required: false) : Normal; + + /// Gets the down appearance (D); the normal appearance when absent. + /// ISO 32000-2 §12.5.5, Table 170: "Default value: the value of the N entry". + public PdfAppearanceEntry? Down => Dictionary.ContainsKey(AnnotationNames.D) ? Read(AnnotationNames.D, required: false) : Normal; + + /// Gets a value indicating whether the dictionary has its own rollover entry (R). + public bool HasRollover => Dictionary.ContainsKey(AnnotationNames.R); + + /// Gets a value indicating whether the dictionary has its own down entry (D). + public bool HasDown => Dictionary.ContainsKey(AnnotationNames.D); + + /// Returns the entry for , with the defaults of and . + /// Normal, rollover or down. + /// The entry, or . + /// ISO 32000-2 §12.5.5, Table 170. + public PdfAppearanceEntry? GetEntry(PdfAppearanceMode mode) => mode switch + { + PdfAppearanceMode.Rollover => Rollover, + PdfAppearanceMode.Down => Down, + _ => Normal, + }; + + private PdfAppearanceEntry? Read(CosName key, bool required) + { + CosObject? raw = Dictionary.TryGetValue(key, out CosObject? value) ? value : null; + switch (_owner.Document.Resolve(raw)) + { + case CosStream or CosDictionary: + return new PdfAppearanceEntry(_owner, raw!); + case CosNull when !required: + return null; + default: + _owner.Report( + DiagnosticCodes.AppearanceEntryInvalid, + $"The appearance dictionary's {key.Value} entry is {(raw is null ? "missing" : "neither a stream nor a dictionary")}; it gives no appearance."); + return null; + } + } +} diff --git a/src/Broadside/Annotations/PdfAppearanceEntry.cs b/src/Broadside/Annotations/PdfAppearanceEntry.cs new file mode 100644 index 00000000..655a8ff8 --- /dev/null +++ b/src/Broadside/Annotations/PdfAppearanceEntry.cs @@ -0,0 +1,89 @@ +using Broadside.Graphics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Annotations; + +/// One entry of an appearance dictionary: a single appearance stream, or a subdictionary of streams keyed by appearance state. +/// +/// ISO 32000-2 §12.5.5, Table 170: "Each entry ... shall contain either a single appearance stream or an appearance subdictionary", +/// whose keys are state names such as On and Off. A state value that is not a stream is skipped with a diagnostic. +/// +public sealed class PdfAppearanceEntry +{ + private readonly PdfAnnotation _owner; + + internal PdfAppearanceEntry(PdfAnnotation owner, CosObject value) + { + _owner = owner; + Value = value; + } + + /// Gets the entry as stored: a stream, a dictionary, or a reference to one. + public CosObject Value { get; } + + /// Gets a value indicating whether the entry is a subdictionary of appearance states rather than one stream. + /// ISO 32000-2 §12.5.5. + public bool HasStates => _owner.Document.Resolve(Value) is CosDictionary; + + /// Gets the single appearance stream, or when the entry is a state subdictionary. + /// ISO 32000-2 §12.5.5, Table 170. + public PdfFormXObject? Form => PdfFormXObject.Create(_owner.Document, Value); + + /// Gets the names of the appearance states whose value is a stream, in the subdictionary's order; empty for a single stream. + /// ISO 32000-2 §12.5.5. + public IReadOnlyList StateNames + { + get + { + if (_owner.Document.Resolve(Value) is not CosDictionary states) + { + return []; + } + + var names = new List(states.Count); + foreach (KeyValuePair state in states) + { + if (IsStream(state.Key, state.Value)) + { + names.Add(state.Key); + } + } + + return names; + } + } + + /// Returns the appearance stream of the state . + /// The state name. + /// + /// The form XObject; for a single-stream entry, that stream whatever the state; when the subdictionary has no + /// stream for the state (legal: an absent state shows nothing). + /// + /// ISO 32000-2 §12.5.5. + public PdfFormXObject? GetAppearance(CosName state) + { + ArgumentNullException.ThrowIfNull(state); + CosObject resolved = _owner.Document.Resolve(Value); + if (resolved is CosStream) + { + return Form; + } + + return resolved is CosDictionary states && states.TryGetValue(state, out CosObject? value) && IsStream(state, value) + ? PdfFormXObject.Create(_owner.Document, value) + : null; + } + + private bool IsStream(CosName state, CosObject value) + { + switch (_owner.Document.Resolve(value)) + { + case CosStream: + return true; + default: + _owner.Report(DiagnosticCodes.AppearanceEntryInvalid, $"The appearance state {state.Value} is not a stream; it is skipped."); + return false; + } + } +} diff --git a/src/Broadside/Annotations/PdfAppearanceMode.cs b/src/Broadside/Annotations/PdfAppearanceMode.cs new file mode 100644 index 00000000..b520b9ed --- /dev/null +++ b/src/Broadside/Annotations/PdfAppearanceMode.cs @@ -0,0 +1,15 @@ +namespace Broadside.Annotations; + +/// Which of an annotation's appearances to use: normal, rollover or down. +/// ISO 32000-2 §12.5.5, Table 170: N, R and D; the rollover and down appearances default to the normal one. +public enum PdfAppearanceMode +{ + /// N: the appearance when the user is not interacting with the annotation. + Normal, + + /// R: the appearance when the cursor is over the annotation without the mouse button pressed. + Rollover, + + /// D: the appearance when the mouse button is pressed or held down within the annotation. + Down, +} diff --git a/src/Broadside/Annotations/PdfBorderEffect.cs b/src/Broadside/Annotations/PdfBorderEffect.cs new file mode 100644 index 00000000..d09529f7 --- /dev/null +++ b/src/Broadside/Annotations/PdfBorderEffect.cs @@ -0,0 +1,20 @@ +namespace Broadside.Annotations; + +/// A border effect: how the border of a square, circle, polygon or free text annotation is drawn (plain or cloudy). +/// ISO 32000-2 §12.5.4, Table 169 (PDF 1.5). A snapshot computed when the annotation's BorderEffect is read. +public sealed class PdfBorderEffect +{ + internal PdfBorderEffect(PdfBorderEffectStyle style, double intensity) + { + Style = style; + Intensity = intensity; + } + + /// Gets the effect (S, default no effect). + /// ISO 32000-2 §12.5.4, Table 169. + public PdfBorderEffectStyle Style { get; } + + /// Gets the intensity of the effect, from 0 to 2 (I, default 0); meaningful only for . + /// ISO 32000-2 §12.5.4, Table 169. + public double Intensity { get; } +} diff --git a/src/Broadside/Annotations/PdfBorderEffectStyle.cs b/src/Broadside/Annotations/PdfBorderEffectStyle.cs new file mode 100644 index 00000000..c9066260 --- /dev/null +++ b/src/Broadside/Annotations/PdfBorderEffectStyle.cs @@ -0,0 +1,12 @@ +namespace Broadside.Annotations; + +/// The style of a border effect, the S entry of a border effect dictionary. +/// ISO 32000-2 §12.5.4, Table 169. Any other name reads as . +public enum PdfBorderEffectStyle +{ + /// S: no effect (the default). + None, + + /// C: the border is drawn as a series of convex curves, as a cloud. + Cloudy, +} diff --git a/src/Broadside/Annotations/PdfBorderSource.cs b/src/Broadside/Annotations/PdfBorderSource.cs new file mode 100644 index 00000000..212ddc0a --- /dev/null +++ b/src/Broadside/Annotations/PdfBorderSource.cs @@ -0,0 +1,15 @@ +namespace Broadside.Annotations; + +/// Where an annotation's border was read from. +/// ISO 32000-2 §12.5.4 and §12.5.2, Table 166: BS wins over Border; with neither, the default applies. +public enum PdfBorderSource +{ + /// Neither entry is present: solid, 1 point, square corners (§12.5.4). + Default, + + /// The Border array (Table 166). + BorderArray, + + /// The border style dictionary BS (Table 168). + BorderStyle, +} diff --git a/src/Broadside/Annotations/PdfBorderStyle.cs b/src/Broadside/Annotations/PdfBorderStyle.cs new file mode 100644 index 00000000..555cdcc4 --- /dev/null +++ b/src/Broadside/Annotations/PdfBorderStyle.cs @@ -0,0 +1,24 @@ +namespace Broadside.Annotations; + +/// The style of an annotation's border, the S entry of a border style dictionary. +/// +/// ISO 32000-2 §12.5.4, Table 168. A name the table does not list reads as ("a PDF processor shall tolerate +/// other border styles"), without a diagnostic. +/// +public enum PdfBorderStyle +{ + /// S: a solid rectangle surrounding the annotation (the default). + Solid, + + /// D: a dashed rectangle, with the dash pattern of . + Dashed, + + /// B: a simulated embossed rectangle that appears raised above the page. + Beveled, + + /// I: a simulated engraved rectangle that appears recessed into the page. + Inset, + + /// U: a single line along the bottom of the annotation rectangle. + Underline, +} diff --git a/src/Broadside/Annotations/PdfCaretAnnotation.cs b/src/Broadside/Annotations/PdfCaretAnnotation.cs new file mode 100644 index 00000000..28ef609e --- /dev/null +++ b/src/Broadside/Annotations/PdfCaretAnnotation.cs @@ -0,0 +1,21 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A caret annotation: a symbol marking where text is to be inserted. +/// ISO 32000-2 §12.5.6.11, Table 183 (PDF 1.5). +public sealed class PdfCaretAnnotation : PdfMarkupAnnotation +{ + internal PdfCaretAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Caret) + { + } + + /// Gets the differences between the annotation rectangle and the drawn rectangle (RD, PDF 1.5), or . + /// ISO 32000-2 §12.5.6.11, Table 183. + public PdfRectangleDifferences? RectangleDifferences => ReadRectangleDifferences(); + + /// Gets the symbol associated with the caret (Sy); default none. + /// ISO 32000-2 §12.5.6.11, Table 183. + public PdfCaretSymbol Symbol => ReadChoice(AnnotationNames.Sy, PdfCaretSymbol.None, ("P", PdfCaretSymbol.Paragraph), ("None", PdfCaretSymbol.None)); +} diff --git a/src/Broadside/Annotations/PdfCaretSymbol.cs b/src/Broadside/Annotations/PdfCaretSymbol.cs new file mode 100644 index 00000000..725e4832 --- /dev/null +++ b/src/Broadside/Annotations/PdfCaretSymbol.cs @@ -0,0 +1,12 @@ +namespace Broadside.Annotations; + +/// The symbol associated with a caret annotation, its Sy entry. +/// ISO 32000-2 §12.5.6.11, Table 183. Default ; other names read as the default. +public enum PdfCaretSymbol +{ + /// None: no symbol (the default). + None, + + /// P: a new paragraph symbol (¶). + Paragraph, +} diff --git a/src/Broadside/Annotations/PdfCircleAnnotation.cs b/src/Broadside/Annotations/PdfCircleAnnotation.cs new file mode 100644 index 00000000..95839e71 --- /dev/null +++ b/src/Broadside/Annotations/PdfCircleAnnotation.cs @@ -0,0 +1,25 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A circle annotation: an ellipse inscribed in the annotation rectangle (inset by ). +/// ISO 32000-2 §12.5.6.8, Table 180 (PDF 1.3). The border is . +public sealed class PdfCircleAnnotation : PdfMarkupAnnotation +{ + internal PdfCircleAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Circle) + { + } + + /// Gets the interior colour (IC, PDF 1.4), or for none. + /// ISO 32000-2 §12.5.6.8, Table 180: it fills the shape. + public PdfDeviceColor? InteriorColor => ReadColor(AnnotationNames.IC); + + /// Gets the border effect (BE, PDF 1.5), or for none. + /// ISO 32000-2 §12.5.6.8, Table 180, and §12.5.4, Table 169. + public PdfBorderEffect? BorderEffect => ReadBorderEffect(); + + /// Gets the differences between the annotation rectangle and the drawn rectangle (RD, PDF 1.5), or . + /// ISO 32000-2 §12.5.6.8, Table 180. + public PdfRectangleDifferences? RectangleDifferences => ReadRectangleDifferences(); +} diff --git a/src/Broadside/Annotations/PdfDeviceColor.cs b/src/Broadside/Annotations/PdfDeviceColor.cs new file mode 100644 index 00000000..6498f281 --- /dev/null +++ b/src/Broadside/Annotations/PdfDeviceColor.cs @@ -0,0 +1,64 @@ +using System.Globalization; + +namespace Broadside.Annotations; + +/// +/// A colour given as an array of 0, 1, 3 or 4 numbers whose count selects the device colour space, as annotation entries such as +/// C and IC and appearance characteristics such as BC and BG give it. +/// +/// +/// ISO 32000-2 §12.5.2, Table 166 (C): 0 elements is no colour (transparent), 1 DeviceGray, 3 DeviceRGB, 4 DeviceCMYK, each +/// component from 0.0 to 1.0. The components are kept as the file gives them, never clamped. A snapshot: reading the entry again +/// returns a new instance. +/// +public sealed class PdfDeviceColor : IEquatable +{ + private readonly double[] _components; + + /// Initializes a new instance of the class. + /// 0, 1, 3 or 4 components. + /// has 2 or more than 4 elements. + public PdfDeviceColor(params ReadOnlySpan components) + { + ColorSpace = components.Length switch + { + 0 => PdfDeviceColorSpace.None, + 1 => PdfDeviceColorSpace.Gray, + 3 => PdfDeviceColorSpace.Rgb, + 4 => PdfDeviceColorSpace.Cmyk, + _ => throw new ArgumentException("A device colour has 0, 1, 3 or 4 components.", nameof(components)), + }; + _components = components.ToArray(); + } + + /// Gets the colour space the number of components selects. + public PdfDeviceColorSpace ColorSpace { get; } + + /// Gets the components, in the order of the colour space (gray; red, green, blue; cyan, magenta, yellow, black). + public IReadOnlyList Components => _components; + + /// Gets a value indicating whether this is no colour at all (an empty array): transparent. + public bool IsTransparent => ColorSpace == PdfDeviceColorSpace.None; + + /// + public bool Equals(PdfDeviceColor? other) => other is not null && _components.AsSpan().SequenceEqual(other._components); + + /// + public override bool Equals(object? obj) => Equals(obj as PdfDeviceColor); + + /// + public override int GetHashCode() + { + var hash = default(HashCode); + foreach (double component in _components) + { + hash.Add(component); + } + + return hash.ToHashCode(); + } + + /// Returns the colour as a PDF array would write it, such as [1 0 0]. + /// The colour text. + public override string ToString() => "[" + string.Join(' ', _components.Select(component => component.ToString(CultureInfo.InvariantCulture))) + "]"; +} diff --git a/src/Broadside/Annotations/PdfDeviceColorSpace.cs b/src/Broadside/Annotations/PdfDeviceColorSpace.cs new file mode 100644 index 00000000..cb3950d5 --- /dev/null +++ b/src/Broadside/Annotations/PdfDeviceColorSpace.cs @@ -0,0 +1,18 @@ +namespace Broadside.Annotations; + +/// The device colour space of a , selected by its number of components. +/// ISO 32000-2 §12.5.2, Table 166 (C), and §8.6.4. +public enum PdfDeviceColorSpace +{ + /// No components: no colour, transparent. + None, + + /// One component: DeviceGray (§8.6.4.2). + Gray, + + /// Three components: DeviceRGB (§8.6.4.3). + Rgb, + + /// Four components: DeviceCMYK (§8.6.4.4). + Cmyk, +} diff --git a/src/Broadside/Annotations/PdfFileAttachmentAnnotation.cs b/src/Broadside/Annotations/PdfFileAttachmentAnnotation.cs new file mode 100644 index 00000000..fd6ad6d9 --- /dev/null +++ b/src/Broadside/Annotations/PdfFileAttachmentAnnotation.cs @@ -0,0 +1,33 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A file attachment annotation: a file embedded in or referred to by the page, shown as an icon. +/// ISO 32000-2 §12.5.6.15, Table 187 (PDF 1.3). Its description is , not the file specification's. +public sealed class PdfFileAttachmentAnnotation : PdfMarkupAnnotation +{ + internal PdfFileAttachmentAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.FileAttachment) + { + } + + /// Gets the file associated with the annotation (FS, required), or when absent or not a file specification. + /// ISO 32000-2 §12.5.6.15, Table 187, and §7.11. + public PdfFileSpecification? FileSpecification + { + get + { + if (!Dictionary.TryGetValue(AnnotationNames.FS, out CosObject? value) || Document.Resolve(value) is CosNull) + { + ReportMissing(AnnotationNames.FS, "Table 187"); + return null; + } + + return Document.GetFileSpecification(value); + } + } + + /// Gets the name of the icon (Name): Graph, PushPin (the default), Paperclip, Tag or another name. + /// ISO 32000-2 §12.5.6.15, Table 187. + public string IconName => ReadIconName("PushPin"); +} diff --git a/src/Broadside/Annotations/PdfFixedPrint.cs b/src/Broadside/Annotations/PdfFixedPrint.cs new file mode 100644 index 00000000..0733e650 --- /dev/null +++ b/src/Broadside/Annotations/PdfFixedPrint.cs @@ -0,0 +1,87 @@ +using Broadside.Graphics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Annotations; + +/// A fixed print dictionary: how a watermark annotation is placed relative to the target media. A live view. +/// +/// ISO 32000-2 §12.5.6.22, Table 194. The rectangle is translated to the origin, transformed by and its bounding +/// box used in place of the annotation rectangle in the appearance algorithm (§12.5.5); then it is translated by +/// and , fractions of the media's size. +/// +public sealed class PdfFixedPrint +{ + private readonly PdfAnnotation _owner; + + internal PdfFixedPrint(PdfAnnotation owner, CosDictionary dictionary) + { + _owner = owner; + Dictionary = dictionary; + } + + /// Gets the fixed print dictionary. + /// ISO 32000-2 §12.5.6.22, Table 194. + public CosDictionary Dictionary { get; } + + /// Gets the matrix that transforms the annotation rectangle before rendering (Matrix); the identity by default. + /// ISO 32000-2 §12.5.6.22, Table 194. + public Matrix Matrix + { + get + { + if (!Dictionary.TryGetValue(AnnotationNames.Matrix, out CosObject? value)) + { + return Matrix.Identity; + } + + if (AnnotationValues.ReadMatrix(_owner.Document, value) is { } matrix) + { + return matrix; + } + + _owner.Report(DiagnosticCodes.AnnotationValueInvalid, "The fixed print dictionary's Matrix is not six numbers; the identity is used."); + return Matrix.Identity; + } + } + + /// Gets the horizontal translation as a fraction of the media's width (H; 1.0 is 100%); default 0. + /// ISO 32000-2 §12.5.6.22, Table 194. + public double HorizontalTranslation => ReadNumber(AnnotationNames.H); + + /// Gets the vertical translation as a fraction of the media's height (V; 1.0 is 100%); default 0. + /// ISO 32000-2 §12.5.6.22, Table 194. + public double VerticalTranslation => ReadNumber(AnnotationNames.V); + + /// Gets a value indicating whether Type is FixedPrint, as Table 194 requires. + /// ISO 32000-2 §12.5.6.22, Table 194. + public bool HasValidType + { + get + { + bool valid = Dictionary.TryGetValue(AnnotationNames.Type, out CosObject? type) && _owner.Document.Resolve(type) is CosName { Value: "FixedPrint" }; + if (!valid) + { + _owner.Report(DiagnosticCodes.AnnotationValueInvalid, "The fixed print dictionary's Type shall be FixedPrint."); + } + + return valid; + } + } + + private double ReadNumber(CosName key) + { + if (!Dictionary.TryGetValue(key, out CosObject? value)) + { + return 0; + } + + if (AnnotationValues.ReadNumber(_owner.Document, value) is { } number) + { + return number; + } + + _owner.Report(DiagnosticCodes.AnnotationValueInvalid, $"The fixed print dictionary's {key.Value} entry is not a number; 0 is used."); + return 0; + } +} diff --git a/src/Broadside/Annotations/PdfFreeTextAnnotation.cs b/src/Broadside/Annotations/PdfFreeTextAnnotation.cs new file mode 100644 index 00000000..7c84287d --- /dev/null +++ b/src/Broadside/Annotations/PdfFreeTextAnnotation.cs @@ -0,0 +1,58 @@ +using Broadside.Graphics; +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A free text annotation: text displayed directly on the page, without a pop-up window. +/// ISO 32000-2 §12.5.6.6, Table 177 (PDF 1.3). The default appearance string and the rich text are exposed as text, not parsed. +public sealed class PdfFreeTextAnnotation : PdfMarkupAnnotation +{ + internal PdfFreeTextAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.FreeText) + { + } + + /// Gets the default appearance string used to format the text (DA, required), or when absent. + /// ISO 32000-2 §12.5.6.6, Table 177, and §12.7.4.3. + public string? DefaultAppearance + { + get + { + if (!Dictionary.ContainsKey(AnnotationNames.DA)) + { + ReportMissing(AnnotationNames.DA, "Table 177"); + } + + return ReadByteString(AnnotationNames.DA); + } + } + + /// Gets the justification of the text (Q, PDF 1.4); default left. + /// ISO 32000-2 §12.5.6.6, Table 177. + public PdfTextJustification Justification => ReadInteger(AnnotationNames.Q) switch + { + 1 => PdfTextJustification.Centered, + 2 => PdfTextJustification.Right, + _ => PdfTextJustification.Left, + }; + + /// Gets the default style string for the rich text (DS, PDF 1.5), or . + /// ISO 32000-2 §12.5.6.6, Table 177, and §12.7.4.4. + public string? DefaultStyle => ReadText(AnnotationNames.DS); + + /// Gets the callout line (CL, PDF 1.6): two or three points, from the point the callout points at; empty when absent. + /// ISO 32000-2 §12.5.6.6, Table 177: used only with the intent FreeTextCallout. + public IReadOnlyList CalloutLine => ReadPoints(AnnotationNames.CL, required: false, "Table 177"); + + /// Gets the border effect (BE, PDF 1.5), or for none. + /// ISO 32000-2 §12.5.6.6, Table 177, and §12.5.4, Table 169. + public PdfBorderEffect? BorderEffect => ReadBorderEffect(); + + /// Gets the differences between the annotation rectangle and the drawn rectangle (RD, PDF 1.5), or . + /// ISO 32000-2 §12.5.6.6, Table 177. + public PdfRectangleDifferences? RectangleDifferences => ReadRectangleDifferences(); + + /// Gets the line ending at the start of the callout line (LE, PDF 1.6); default none. + /// ISO 32000-2 §12.5.6.6, Table 177, and Table 179. + public PdfLineEnding LineEnding => ParseLineEnding(Get(AnnotationNames.LE)); +} diff --git a/src/Broadside/Annotations/PdfHighlightAnnotation.cs b/src/Broadside/Annotations/PdfHighlightAnnotation.cs new file mode 100644 index 00000000..f7ce64a3 --- /dev/null +++ b/src/Broadside/Annotations/PdfHighlightAnnotation.cs @@ -0,0 +1,13 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A Highlight text markup annotation (PDF 1.3). +/// ISO 32000-2 §12.5.6.10, Table 182. +public sealed class PdfHighlightAnnotation : PdfTextMarkupAnnotation +{ + internal PdfHighlightAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Highlight) + { + } +} diff --git a/src/Broadside/Annotations/PdfHighlightMode.cs b/src/Broadside/Annotations/PdfHighlightMode.cs new file mode 100644 index 00000000..d28326bb --- /dev/null +++ b/src/Broadside/Annotations/PdfHighlightMode.cs @@ -0,0 +1,21 @@ +namespace Broadside.Annotations; + +/// The visual effect when a link or widget annotation is activated, its H entry. +/// +/// ISO 32000-2 §12.5.6.5, Table 176 (PDF 1.2), and §12.5.6.19, Table 191. Default ; widgets also accept +/// T, the same as P. Any other name reads as the default. +/// +public enum PdfHighlightMode +{ + /// N: no highlighting. + None, + + /// I: invert the colours of the annotation rectangle (the default). + Invert, + + /// O: invert the annotation's border. + Outline, + + /// P (or T for a widget): display the down appearance, or offset the annotation as if pushed below the page. + Push, +} diff --git a/src/Broadside/Annotations/PdfInkAnnotation.cs b/src/Broadside/Annotations/PdfInkAnnotation.cs new file mode 100644 index 00000000..328fd823 --- /dev/null +++ b/src/Broadside/Annotations/PdfInkAnnotation.cs @@ -0,0 +1,22 @@ +using Broadside.Graphics; +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// An ink annotation: one or more freehand paths. +/// ISO 32000-2 §12.5.6.13, Table 185 (PDF 1.3). +public sealed class PdfInkAnnotation : PdfMarkupAnnotation +{ + internal PdfInkAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Ink) + { + } + + /// Gets the paths (InkList, required): each a list of points in default user space; empty when absent. + /// ISO 32000-2 §12.5.6.13, Table 185. + public IReadOnlyList> InkList => ReadPointLists(AnnotationNames.InkList, required: true, "Table 185"); + + /// Gets the path (Path, PDF 2.0): arrays of 2 numbers (the start point, then straight segments) or 6 (a cubic Bézier curve's two control points and end point); when absent. + /// ISO 32000-2 §12.5.6.13, Table 185. + public IReadOnlyList>? Path => ReadPath(); +} diff --git a/src/Broadside/Annotations/PdfLineAnnotation.cs b/src/Broadside/Annotations/PdfLineAnnotation.cs new file mode 100644 index 00000000..376e2a23 --- /dev/null +++ b/src/Broadside/Annotations/PdfLineAnnotation.cs @@ -0,0 +1,85 @@ +using Broadside.Graphics; +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A line annotation: a single straight line, optionally a dimension line with leader lines and a caption. +/// ISO 32000-2 §12.5.6.7, Table 178 (PDF 1.3). +public sealed class PdfLineAnnotation : PdfMarkupAnnotation +{ + internal PdfLineAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Line) + { + } + + /// Gets the start point of the line (L, required), in default user space; the origin when L is missing or malformed. + /// ISO 32000-2 §12.5.6.7, Table 178: the endpoints, or the leader line endpoints when LL is present. + public PathPoint Start => ReadLine().Start; + + /// Gets the end point of the line (L, required); the origin when L is missing or malformed. + /// ISO 32000-2 §12.5.6.7, Table 178. + public PathPoint End => ReadLine().End; + + /// Gets the line ending at the first point (LE, PDF 1.4); default none. + /// ISO 32000-2 §12.5.6.7, Table 178, and Table 179. + public PdfLineEnding StartLineEnding => ReadLineEndings().Start; + + /// Gets the line ending at the last point (LE, PDF 1.4); default none. + /// ISO 32000-2 §12.5.6.7, Table 178, and Table 179. + public PdfLineEnding EndLineEnding => ReadLineEndings().End; + + /// Gets the interior colour (IC, PDF 1.4), or for none. + /// ISO 32000-2 §12.5.6.7, Table 178: it fills the line endings. + public PdfDeviceColor? InteriorColor => ReadColor(AnnotationNames.IC); + + /// Gets the length of the leader lines (LL, PDF 1.6); default 0. Positive values extend above the line, negative below. + /// ISO 32000-2 §12.5.6.7, Table 178. + public double LeaderLineLength => ReadNumber(AnnotationNames.LL, 0); + + /// Gets the length of the leader line extensions (LLE, PDF 1.6); default 0. + /// ISO 32000-2 §12.5.6.7, Table 178. + public double LeaderLineExtension => ReadNumber(AnnotationNames.LLE, 0); + + /// Gets the length of the leader line offset (LLO, PDF 1.7); default 0. + /// ISO 32000-2 §12.5.6.7, Table 178. + public double LeaderLineOffset => ReadNumber(AnnotationNames.LLO, 0); + + /// Gets a value indicating whether the text is shown as a caption with the line (Cap, PDF 1.6); default . + /// ISO 32000-2 §12.5.6.7, Table 178. + public bool HasCaption => ReadBoolean(AnnotationNames.Cap, fallback: false); + + /// Gets where the caption is placed (CP, PDF 1.7); default inline. + /// ISO 32000-2 §12.5.6.7, Table 178. + public PdfLineCaptionPosition CaptionPosition => ReadChoice(AnnotationNames.CP, PdfLineCaptionPosition.Inline, ("Inline", PdfLineCaptionPosition.Inline), ("Top", PdfLineCaptionPosition.Top)); + + /// Gets the offset of the caption from its position (CO, PDF 1.7); default (0, 0). + /// ISO 32000-2 §12.5.6.7, Table 178. + public PathPoint CaptionOffset + { + get + { + IReadOnlyList offset = ReadPoints(AnnotationNames.CO, required: false, "Table 178"); + return offset.Count == 1 ? offset[0] : new PathPoint(0, 0); + } + } + + /// Gets the measure dictionary giving the scale and units of the annotation (Measure, PDF 1.7), as stored, or . + /// ISO 32000-2 §12.5.6.7, Table 178, and §12.9, Table 266. + public CosDictionary? Measure => ReadDictionary(AnnotationNames.Measure); + + private (PathPoint Start, PathPoint End) ReadLine() + { + IReadOnlyList points = ReadPoints(AnnotationNames.L, required: true, "Table 178"); + if (points.Count == 2) + { + return (points[0], points[1]); + } + + if (points.Count != 0) + { + ReportInvalid(AnnotationNames.L, "an array of four numbers"); + } + + return (new PathPoint(0, 0), new PathPoint(0, 0)); + } +} diff --git a/src/Broadside/Annotations/PdfLineCaptionPosition.cs b/src/Broadside/Annotations/PdfLineCaptionPosition.cs new file mode 100644 index 00000000..4001561e --- /dev/null +++ b/src/Broadside/Annotations/PdfLineCaptionPosition.cs @@ -0,0 +1,12 @@ +namespace Broadside.Annotations; + +/// Where the caption of a line annotation is drawn, its CP entry. +/// ISO 32000-2 §12.5.6.7, Table 178 (PDF 1.7). Default ; other names read as the default. +public enum PdfLineCaptionPosition +{ + /// Inline: centred inside the line (the default). + Inline, + + /// Top: on top of the line. + Top, +} diff --git a/src/Broadside/Annotations/PdfLineEnding.cs b/src/Broadside/Annotations/PdfLineEnding.cs new file mode 100644 index 00000000..86300c50 --- /dev/null +++ b/src/Broadside/Annotations/PdfLineEnding.cs @@ -0,0 +1,36 @@ +namespace Broadside.Annotations; + +/// A line ending style, as the LE entry of line, polyline and free text annotations names it. +/// ISO 32000-2 §12.5.6.7, Table 179. A name the table does not list reads as , as viewers draw it. +public enum PdfLineEnding +{ + /// None: no line ending (the default). + None, + + /// Square: a square filled with the interior colour. + Square, + + /// Circle: a circle filled with the interior colour. + Circle, + + /// Diamond: a diamond filled with the interior colour. + Diamond, + + /// OpenArrow: two short lines meeting in an acute angle to form an open arrowhead. + OpenArrow, + + /// ClosedArrow: two short lines meeting in an acute angle, closed and filled with the interior colour. + ClosedArrow, + + /// Butt (PDF 1.5): a short line at the endpoint perpendicular to the line. + Butt, + + /// ROpenArrow (PDF 1.5): an open arrowhead pointing the other way. + ROpenArrow, + + /// RClosedArrow (PDF 1.5): a closed arrowhead pointing the other way. + RClosedArrow, + + /// Slash (PDF 1.6): a short line at the endpoint, 30 degrees clockwise from perpendicular to the line. + Slash, +} diff --git a/src/Broadside/Annotations/PdfLinkAnnotation.cs b/src/Broadside/Annotations/PdfLinkAnnotation.cs new file mode 100644 index 00000000..97a2fe0a --- /dev/null +++ b/src/Broadside/Annotations/PdfLinkAnnotation.cs @@ -0,0 +1,77 @@ +using Broadside.Graphics; +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A link annotation: a hypertext link to a destination or an action. +/// ISO 32000-2 §12.5.6.5, Table 176 (PDF 1.0). A link needs no appearance stream (§12.5.2). Dest is not permitted with A; when a file has both, both are exposed, LinkActionAndDest is recorded, and is the one to perform. +public sealed class PdfLinkAnnotation : PdfAnnotation +{ + internal PdfLinkAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Link) + { + } + + /// Gets the action performed when the link is activated (A, PDF 1.1), or . + /// ISO 32000-2 §12.5.6.5, Table 176, and §12.6. + public PdfAction? Action + { + get + { + CheckActionAndDest(); + return ReadAction(AnnotationNames.A); + } + } + + /// Gets the destination displayed when the link is activated (Dest): explicit or named; when absent. + /// ISO 32000-2 §12.5.6.5, Table 176, and §12.3.2. + public PdfDestination? Destination + { + get + { + CheckActionAndDest(); + return Dictionary.TryGetValue(AnnotationNames.Dest, out CosObject? value) ? PdfDestination.Create(Document, value, isRemote: false, DiagnosticReference) : null; + } + } + + /// Gets the visual effect when the link is activated (H, PDF 1.2); default invert. + /// ISO 32000-2 §12.5.6.5, Table 176. + public PdfHighlightMode HighlightMode => ReadChoice(AnnotationNames.H, PdfHighlightMode.Invert, ("N", PdfHighlightMode.None), ("I", PdfHighlightMode.Invert), ("O", PdfHighlightMode.Outline), ("P", PdfHighlightMode.Push)); + + /// Gets the URI action formerly associated with the link, for reordering the actions of a link (PA, PDF 1.3), or . + /// ISO 32000-2 §12.5.6.5, Table 176. + public PdfAction? PreviousUriAction => ReadAction(AnnotationNames.PA); + + /// Gets the quadrilaterals of the link's region (QuadPoints, PDF 1.6), as stored; empty when absent. + /// ISO 32000-2 §12.5.6.5, Table 176. + public IReadOnlyList QuadPoints => ReadQuadPoints(required: false, "Table 176"); + + /// Gets the region that activates the link: when present and inside the rectangle, else the rectangle as one quadrilateral. + /// ISO 32000-2 §12.5.6.5, Table 176: when QuadPoints is absent or any of its coordinates lie outside Rect, Rect is used. + public IReadOnlyList ActivationRegion + { + get + { + PdfRectangle rect = Rect; + IReadOnlyList quads = QuadPoints; + bool inside = quads.Count > 0; + foreach (PdfQuadrilateral quad in quads) + { + PdfRectangle bounds = quad.Bounds; + inside &= bounds.Left >= rect.Left && bounds.Right <= rect.Right && bounds.Bottom >= rect.Bottom && bounds.Top <= rect.Top; + } + + return inside + ? quads + : [new PdfQuadrilateral(new PathPoint(rect.Left, rect.Bottom), new PathPoint(rect.Right, rect.Bottom), new PathPoint(rect.Right, rect.Top), new PathPoint(rect.Left, rect.Top))]; + } + } + + private void CheckActionAndDest() + { + if (Dictionary.ContainsKey(AnnotationNames.A) && Dictionary.ContainsKey(AnnotationNames.Dest)) + { + Report(Parsing.DiagnosticCodes.LinkActionAndDest, "The link has both A and Dest, which Table 176 does not permit; the action is the one to perform."); + } + } +} diff --git a/src/Broadside/Annotations/PdfMarkupAnnotation.cs b/src/Broadside/Annotations/PdfMarkupAnnotation.cs new file mode 100644 index 00000000..10f2a07d --- /dev/null +++ b/src/Broadside/Annotations/PdfMarkupAnnotation.cs @@ -0,0 +1,118 @@ +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Annotations; + +/// A markup annotation: one that marks up the document and can carry an author, a pop-up window, replies and a review state. +/// +/// ISO 32000-2 §12.5.6.2, Tables 172 and 173. The markup types are those Table 171 marks: text, free text, line, square, circle, +/// polygon, polyline, the text markup types, caret, stamp, ink, file attachment, sound, redaction and projection. +/// +public abstract class PdfMarkupAnnotation : PdfAnnotation +{ + private protected PdfMarkupAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page, PdfAnnotationKind kind) + : base(document, dictionary, reference, page, kind) + { + } + + /// Gets the text label of the pop-up window's title bar, by convention the author (T, PDF 1.1), or . + /// ISO 32000-2 §12.5.6.2, Table 172. + public string? Title => ReadText(AnnotationNames.T); + + /// Gets the pop-up annotation for entering or editing the text (Popup, PDF 1.3), or . + /// + /// ISO 32000-2 §12.5.6.2, Table 172. The same instance as on the page. When the pop-up's own Parent names another + /// annotation, PopupLinkMismatch is recorded: this entry says which pop-up belongs to this annotation, the pop-up's + /// Parent which annotation the pop-up belongs to. + /// + public PdfPopupAnnotation? Popup + { + get + { + if (!Dictionary.TryGetValue(AnnotationNames.Popup, out CosObject? value) || Document.Resolve(value) is CosNull) + { + return null; + } + + if (Document.AnnotationIndex.Find(value, this) is not PdfPopupAnnotation popup) + { + ReportInvalid(AnnotationNames.Popup, "a popup annotation"); + return null; + } + + if (popup.Dictionary.TryGetValue(AnnotationNames.Parent, out CosObject? parent) + && Document.Resolve(parent) is CosDictionary parentDictionary + && !ReferenceEquals(parentDictionary, Dictionary)) + { + Report(DiagnosticCodes.PopupLinkMismatch, "The annotation's pop-up names another annotation as its Parent."); + } + + return popup; + } + } + + /// Gets the rich text shown in the pop-up window (RC, PDF 1.5), as stored (XHTML), or . Not parsed. + /// ISO 32000-2 §12.5.6.2, Table 172, and §12.7.4.4: a text string or a text stream. + public string? RichText => ReadTextOrStream(AnnotationNames.RC); + + /// Gets the date and time the annotation was created (CreationDate, PDF 1.5), or . + /// ISO 32000-2 §12.5.6.2, Table 172, and §7.9.4. + public PdfDate? CreationDate => ReadDate(AnnotationNames.CreationDate); + + /// Gets the annotation this one is a reply to or grouped with (IRT, PDF 1.5), or . + /// + /// ISO 32000-2 §12.5.6.2, Table 172: it shall be on the same page; one on another page records InReplyToOtherPage, a + /// value that is not an annotation dictionary (or the annotation itself) InReplyToInvalid. + /// + public PdfAnnotation? InReplyTo + { + get + { + if (!Dictionary.TryGetValue(AnnotationNames.IRT, out CosObject? value) || Document.Resolve(value) is CosNull) + { + return null; + } + + PdfAnnotation? target = Document.AnnotationIndex.Find(value, this); + if (target is null || ReferenceEquals(target, this)) + { + Report(DiagnosticCodes.InReplyToInvalid, "The annotation's IRT entry is not another annotation's dictionary; it is ignored."); + return null; + } + + if (Page is not null && !ReferenceEquals(target.Page, Page)) + { + Report(DiagnosticCodes.InReplyToOtherPage, "The annotation replies to an annotation that is not on its page, which IRT shall name."); + } + + return target; + } + } + + /// Gets the subject of the annotation (Subj, PDF 1.5), or . + /// ISO 32000-2 §12.5.6.2, Table 172. + public string? Subject => ReadText(AnnotationNames.Subj); + + /// Gets how the annotation relates to (RT, PDF 1.6): a reply (the default) or a group. + /// ISO 32000-2 §12.5.6.2, Table 172: meaningful only with IRT, which is required when RT is present. + public PdfReplyType ReplyType + { + get + { + if (Dictionary.ContainsKey(AnnotationNames.RT) && !Dictionary.ContainsKey(AnnotationNames.IRT)) + { + Report(DiagnosticCodes.ReplyTypeWithoutInReplyTo, "The annotation has an RT entry but no IRT entry, which Table 172 requires with it."); + } + + return ReadChoice(AnnotationNames.RT, PdfReplyType.Reply, ("R", PdfReplyType.Reply), ("Group", PdfReplyType.Group)); + } + } + + /// Gets the intent of the annotation (IT, PDF 1.6), such as FreeTextCallout, or . + /// ISO 32000-2 §12.5.6.2, Table 172. Absent, or equal to the subtype, means no explicit intent. + public CosName? Intent => ReadName(AnnotationNames.IT); + + /// Gets the external data dictionary (ExData, PDF 1.7), such as 3D markup, as stored, or . + /// ISO 32000-2 §12.5.6.2, Tables 172 and 173. + public CosDictionary? ExternalData => ReadDictionary(AnnotationNames.ExData); +} diff --git a/src/Broadside/Annotations/PdfMovieAnnotation.cs b/src/Broadside/Annotations/PdfMovieAnnotation.cs new file mode 100644 index 00000000..289e9fe6 --- /dev/null +++ b/src/Broadside/Annotations/PdfMovieAnnotation.cs @@ -0,0 +1,36 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A movie annotation: a movie to be played. Deprecated in PDF 2.0. +/// ISO 32000-2 §12.5.6.17, Table 189 (PDF 1.2). Parse-and-preserve: the movie and its activation are exposed as data and never played. +public sealed class PdfMovieAnnotation : PdfAnnotation +{ + internal PdfMovieAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Movie) + { + } + + /// Gets the title of the annotation (T), used by movie actions to name it, or . + /// ISO 32000-2 §12.5.6.17, Table 189. + public string? MovieTitle => ReadText(AnnotationNames.T); + + /// Gets the movie dictionary (Movie, required), as stored, or . + /// ISO 32000-2 §12.5.6.17, Table 189, and §13.4. + public CosDictionary? Movie + { + get + { + if (!Dictionary.ContainsKey(AnnotationNames.Movie)) + { + ReportMissing(AnnotationNames.Movie, "Table 189"); + } + + return ReadDictionary(AnnotationNames.Movie); + } + } + + /// Gets the activation entry (A) as stored: a boolean saying whether to play the movie when activated, or a movie activation dictionary; when absent (play, the default). Not an action. + /// ISO 32000-2 §12.5.6.17, Table 189, and §13.4, Table 307. + public CosObject? Activation => Get(AnnotationNames.A); +} diff --git a/src/Broadside/Annotations/PdfPolyLineAnnotation.cs b/src/Broadside/Annotations/PdfPolyLineAnnotation.cs new file mode 100644 index 00000000..1d9ed000 --- /dev/null +++ b/src/Broadside/Annotations/PdfPolyLineAnnotation.cs @@ -0,0 +1,38 @@ +using Broadside.Graphics; +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A polyline annotation: an open polygon. +/// ISO 32000-2 §12.5.6.9, Table 181 (PDF 1.5). +public sealed class PdfPolyLineAnnotation : PdfMarkupAnnotation +{ + internal PdfPolyLineAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.PolyLine) + { + } + + /// Gets the vertices in default user space (Vertices); empty when absent. Ignored when is present. + /// ISO 32000-2 §12.5.6.9, Table 181: required unless Path is present, and then it shall not be present. + public IReadOnlyList Vertices => ReadPoints(AnnotationNames.Vertices, required: !Dictionary.ContainsKey(AnnotationNames.Path), "Table 181"); + + /// Gets the path (Path, PDF 2.0): arrays of 2 numbers (the start point, then straight segments) or 6 (a cubic Bézier curve's two control points and end point); when absent. + /// ISO 32000-2 §12.5.6.9, Table 181. + public IReadOnlyList>? Path => ReadPath(); + + /// Gets the line ending at the first point (LE, PDF 1.4); default none. + /// ISO 32000-2 §12.5.6.9, Table 181, and Table 179. + public PdfLineEnding StartLineEnding => ReadLineEndings().Start; + + /// Gets the line ending at the last point (LE, PDF 1.4); default none. + /// ISO 32000-2 §12.5.6.9, Table 181, and Table 179. + public PdfLineEnding EndLineEnding => ReadLineEndings().End; + + /// Gets the interior colour (IC, PDF 1.4), or for none. + /// ISO 32000-2 §12.5.6.9, Table 181: it fills the line endings. + public PdfDeviceColor? InteriorColor => ReadColor(AnnotationNames.IC); + + /// Gets the measure dictionary giving the scale and units of the annotation (Measure, PDF 1.7), as stored, or . + /// ISO 32000-2 §12.5.6.9, Table 181, and §12.9, Table 266. + public CosDictionary? Measure => ReadDictionary(AnnotationNames.Measure); +} diff --git a/src/Broadside/Annotations/PdfPolygonAnnotation.cs b/src/Broadside/Annotations/PdfPolygonAnnotation.cs new file mode 100644 index 00000000..042f0e40 --- /dev/null +++ b/src/Broadside/Annotations/PdfPolygonAnnotation.cs @@ -0,0 +1,34 @@ +using Broadside.Graphics; +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A polygon annotation: a closed polygon. +/// ISO 32000-2 §12.5.6.9, Table 181 (PDF 1.5). +public sealed class PdfPolygonAnnotation : PdfMarkupAnnotation +{ + internal PdfPolygonAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Polygon) + { + } + + /// Gets the vertices in default user space (Vertices); empty when absent. Ignored when is present. + /// ISO 32000-2 §12.5.6.9, Table 181: required unless Path is present, and then it shall not be present. + public IReadOnlyList Vertices => ReadPoints(AnnotationNames.Vertices, required: !Dictionary.ContainsKey(AnnotationNames.Path), "Table 181"); + + /// Gets the path (Path, PDF 2.0): arrays of 2 numbers (the start point, then straight segments) or 6 (a cubic Bézier curve's two control points and end point); when absent. + /// ISO 32000-2 §12.5.6.9, Table 181. + public IReadOnlyList>? Path => ReadPath(); + + /// Gets the interior colour (IC, PDF 1.4), or for none. + /// ISO 32000-2 §12.5.6.9, Table 181: it fills the polygon. + public PdfDeviceColor? InteriorColor => ReadColor(AnnotationNames.IC); + + /// Gets the border effect (BE, PDF 1.5), or for none. + /// ISO 32000-2 §12.5.6.9, Table 181, and §12.5.4, Table 169. + public PdfBorderEffect? BorderEffect => ReadBorderEffect(); + + /// Gets the measure dictionary giving the scale and units of the annotation (Measure, PDF 1.7), as stored, or . + /// ISO 32000-2 §12.5.6.9, Table 181, and §12.9, Table 266. + public CosDictionary? Measure => ReadDictionary(AnnotationNames.Measure); +} diff --git a/src/Broadside/Annotations/PdfPopupAnnotation.cs b/src/Broadside/Annotations/PdfPopupAnnotation.cs new file mode 100644 index 00000000..56075e2c --- /dev/null +++ b/src/Broadside/Annotations/PdfPopupAnnotation.cs @@ -0,0 +1,65 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A pop-up annotation: the window that displays the text of its parent markup annotation. +/// ISO 32000-2 §12.5.6.14, Table 186 (PDF 1.3). It has no appearance stream or actions of its own; the parent's Contents, M, C and T are the ones to display. +public sealed class PdfPopupAnnotation : PdfAnnotation +{ + internal PdfPopupAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Popup) + { + } + + /// Gets the annotation this pop-up belongs to: its Parent, or, when absent, the markup annotation of the same page whose Popup names it; when there is none. + /// ISO 32000-2 §12.5.6.14, Table 186. A parent that is not a markup annotation records PopupParentInvalid; one whose Popup names another pop-up, PopupLinkMismatch. + public PdfAnnotation? Parent + { + get + { + if (Dictionary.TryGetValue(AnnotationNames.Parent, out CosObject? value) && Document.Resolve(value) is not CosNull) + { + PdfAnnotation? parent = Document.AnnotationIndex.Find(value, this); + if (parent is null || ReferenceEquals(parent, this)) + { + ReportInvalid(AnnotationNames.Parent, "an annotation dictionary"); + return null; + } + + if (parent is not PdfMarkupAnnotation) + { + Report(Parsing.DiagnosticCodes.PopupParentInvalid, "The pop-up's Parent is not a markup annotation."); + } + else if (parent.Dictionary.TryGetValue(AnnotationNames.Popup, out CosObject? popup) + && Document.Resolve(popup) is CosDictionary popupDictionary + && !ReferenceEquals(popupDictionary, Dictionary)) + { + Report(Parsing.DiagnosticCodes.PopupLinkMismatch, "The pop-up's Parent names another annotation as its Popup."); + } + + return parent; + } + + if (Page is null) + { + return null; + } + + foreach (PdfAnnotation candidate in Page.Annotations) + { + if (candidate is PdfMarkupAnnotation + && candidate.Dictionary.TryGetValue(AnnotationNames.Popup, out CosObject? popup) + && ReferenceEquals(Document.Resolve(popup), Dictionary)) + { + return candidate; + } + } + + return null; + } + } + + /// Gets a value indicating whether the pop-up is initially displayed open (Open); default . + /// ISO 32000-2 §12.5.6.14, Table 186. + public bool IsOpen => ReadBoolean(AnnotationNames.Open, fallback: false); +} diff --git a/src/Broadside/Annotations/PdfPrinterMarkAnnotation.cs b/src/Broadside/Annotations/PdfPrinterMarkAnnotation.cs new file mode 100644 index 00000000..e87184d2 --- /dev/null +++ b/src/Broadside/Annotations/PdfPrinterMarkAnnotation.cs @@ -0,0 +1,17 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A printer's mark annotation: a production symbol such as a registration target, colour bar or cut mark. +/// ISO 32000-2 §12.5.6.20 and §14.11.3, Table 398 (PDF 1.4). +public sealed class PdfPrinterMarkAnnotation : PdfAnnotation +{ + internal PdfPrinterMarkAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.PrinterMark) + { + } + + /// Gets the name of the kind of mark (MN), such as ColorBar or RegistrationTarget, or . + /// ISO 32000-2 §14.11.3, Table 398. + public CosName? MarkName => ReadName(AnnotationNames.MN); +} diff --git a/src/Broadside/Annotations/PdfProjectionAnnotation.cs b/src/Broadside/Annotations/PdfProjectionAnnotation.cs new file mode 100644 index 00000000..2421e492 --- /dev/null +++ b/src/Broadside/Annotations/PdfProjectionAnnotation.cs @@ -0,0 +1,13 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A projection annotation: a markup annotation that projects, for example, a measurement onto 3D or geospatial content. +/// ISO 32000-2 §12.5.6.24 (PDF 2.0). It has the entries of Tables 166 and 172 only; with a zero-size rectangle it shall have no appearance. +public sealed class PdfProjectionAnnotation : PdfMarkupAnnotation +{ + internal PdfProjectionAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Projection) + { + } +} diff --git a/src/Broadside/Annotations/PdfQuadrilateral.cs b/src/Broadside/Annotations/PdfQuadrilateral.cs new file mode 100644 index 00000000..1cd4fe7a --- /dev/null +++ b/src/Broadside/Annotations/PdfQuadrilateral.cs @@ -0,0 +1,73 @@ +using System.Globalization; +using Broadside.Graphics; + +namespace Broadside.Annotations; + +/// A quadrilateral of a QuadPoints array: four points in default user space, as the file gives them. +/// +/// ISO 32000-2 §12.5.6.10, Table 182, and §12.5.6.5, Table 176. The specification orders the points counterclockwise with the text +/// running along the edge from to ; many writers use another order (top-left, top-right, +/// bottom-left, bottom-right), which cannot be told apart from rotated text, so the points are never reordered. +/// +public readonly struct PdfQuadrilateral : IEquatable +{ + /// Initializes a new instance of the struct. + /// The first point, (x1, y1). + /// The second point, (x2, y2). + /// The third point, (x3, y3). + /// The fourth point, (x4, y4). + public PdfQuadrilateral(PathPoint point1, PathPoint point2, PathPoint point3, PathPoint point4) + { + Point1 = point1; + Point2 = point2; + Point3 = point3; + Point4 = point4; + } + + /// Gets the first point. + public PathPoint Point1 { get; } + + /// Gets the second point. + public PathPoint Point2 { get; } + + /// Gets the third point. + public PathPoint Point3 { get; } + + /// Gets the fourth point. + public PathPoint Point4 { get; } + + /// Gets the smallest upright rectangle containing the four points. + public PdfRectangle Bounds => new( + Math.Min(Math.Min(Point1.X, Point2.X), Math.Min(Point3.X, Point4.X)), + Math.Min(Math.Min(Point1.Y, Point2.Y), Math.Min(Point3.Y, Point4.Y)), + Math.Max(Math.Max(Point1.X, Point2.X), Math.Max(Point3.X, Point4.X)), + Math.Max(Math.Max(Point1.Y, Point2.Y), Math.Max(Point3.Y, Point4.Y))); + + /// Returns whether two quadrilaterals have the same points in the same order. + /// The first quadrilateral. + /// The second quadrilateral. + /// when they are equal. + public static bool operator ==(PdfQuadrilateral left, PdfQuadrilateral right) => left.Equals(right); + + /// Returns whether two quadrilaterals differ. + /// The first quadrilateral. + /// The second quadrilateral. + /// when they differ. + public static bool operator !=(PdfQuadrilateral left, PdfQuadrilateral right) => !left.Equals(right); + + /// + public bool Equals(PdfQuadrilateral other) => + Point1.Equals(other.Point1) && Point2.Equals(other.Point2) && Point3.Equals(other.Point3) && Point4.Equals(other.Point4); + + /// + public override bool Equals(object? obj) => obj is PdfQuadrilateral other && Equals(other); + + /// + public override int GetHashCode() => HashCode.Combine(Point1, Point2, Point3, Point4); + + /// Returns the eight coordinates as a QuadPoints array would write them. + /// The text. + public override string ToString() => string.Create( + CultureInfo.InvariantCulture, + $"[{Point1.X} {Point1.Y} {Point2.X} {Point2.Y} {Point3.X} {Point3.Y} {Point4.X} {Point4.Y}]"); +} diff --git a/src/Broadside/Annotations/PdfRectangleDifferences.cs b/src/Broadside/Annotations/PdfRectangleDifferences.cs new file mode 100644 index 00000000..c7434f00 --- /dev/null +++ b/src/Broadside/Annotations/PdfRectangleDifferences.cs @@ -0,0 +1,12 @@ +namespace Broadside.Annotations; + +/// +/// The RD entry of a free text, square, circle or caret annotation: the distances from each edge of the annotation rectangle +/// inward to the rectangle where the annotation is drawn. +/// +/// ISO 32000-2 §12.5.6.6 Table 177, §12.5.6.8 Table 180, §12.5.6.11 Table 183 (PDF 1.5). Each difference shall be at least 0. +/// The difference at the left edge. +/// The difference at the top edge. +/// The difference at the right edge. +/// The difference at the bottom edge. +public readonly record struct PdfRectangleDifferences(double Left, double Top, double Right, double Bottom); diff --git a/src/Broadside/Annotations/PdfRedactAnnotation.cs b/src/Broadside/Annotations/PdfRedactAnnotation.cs new file mode 100644 index 00000000..a0b39e2a --- /dev/null +++ b/src/Broadside/Annotations/PdfRedactAnnotation.cs @@ -0,0 +1,58 @@ +using Broadside.Graphics; +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A redaction annotation: content marked for removal, and how the removed region looks afterwards. +/// ISO 32000-2 §12.5.6.23, Table 195 (PDF 1.7). Reading never applies the redaction. +public sealed class PdfRedactAnnotation : PdfMarkupAnnotation +{ + internal PdfRedactAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Redact) + { + } + + /// Gets the quadrilaterals of the content to remove (QuadPoints), as stored; empty when absent, in which case the rectangle is the region. + /// ISO 32000-2 §12.5.6.23, Table 195. + public IReadOnlyList QuadPoints => ReadQuadPoints(required: false, "Table 195"); + + /// Gets the interior colour (IC, PDF 1.4), or for none. + /// ISO 32000-2 §12.5.6.23, Table 195: the fill of the redacted region (DeviceRGB); ignored when is present. + public PdfDeviceColor? InteriorColor => ReadColor(AnnotationNames.IC); + + /// Gets the form XObject drawn over the redacted region (RO), or ; it takes precedence over the colour, text and justification entries. + /// ISO 32000-2 §12.5.6.23, Table 195. + public PdfFormXObject? Overlay => ReadForm(AnnotationNames.RO); + + /// Gets the text drawn over the redacted region (OverlayText), or . + /// ISO 32000-2 §12.5.6.23, Table 195. + public string? OverlayText => ReadText(AnnotationNames.OverlayText); + + /// Gets a value indicating whether the overlay text repeats to fill the region (Repeat); default . + /// ISO 32000-2 §12.5.6.23, Table 195. + public bool RepeatsOverlayText => ReadBoolean(AnnotationNames.Repeat, fallback: false); + + /// Gets the default appearance string of the overlay text (DA, required with OverlayText), or . + /// ISO 32000-2 §12.5.6.23, Table 195, and §12.7.4.3. + public string? DefaultAppearance + { + get + { + if (!Dictionary.ContainsKey(AnnotationNames.DA) && Dictionary.ContainsKey(AnnotationNames.OverlayText)) + { + ReportMissing(AnnotationNames.DA, "Table 195 (with OverlayText)"); + } + + return ReadByteString(AnnotationNames.DA); + } + } + + /// Gets the justification of the text (Q, PDF 1.4); default left. + /// ISO 32000-2 §12.5.6.23, Table 195. + public PdfTextJustification Justification => ReadInteger(AnnotationNames.Q) switch + { + 1 => PdfTextJustification.Centered, + 2 => PdfTextJustification.Right, + _ => PdfTextJustification.Left, + }; +} diff --git a/src/Broadside/Annotations/PdfReplyType.cs b/src/Broadside/Annotations/PdfReplyType.cs new file mode 100644 index 00000000..d84ba69d --- /dev/null +++ b/src/Broadside/Annotations/PdfReplyType.cs @@ -0,0 +1,12 @@ +namespace Broadside.Annotations; + +/// The relationship between a markup annotation and the one it is in reply to, its RT entry. +/// ISO 32000-2 §12.5.6.2, Table 172 (PDF 1.6). Any other name reads as the default, . +public enum PdfReplyType +{ + /// R: a reply to the annotation (the default). + Reply, + + /// Group: grouped with the annotation; the group's attributes come from the primary annotation. + Group, +} diff --git a/src/Broadside/Annotations/PdfRichMediaAnnotation.cs b/src/Broadside/Annotations/PdfRichMediaAnnotation.cs new file mode 100644 index 00000000..0214f392 --- /dev/null +++ b/src/Broadside/Annotations/PdfRichMediaAnnotation.cs @@ -0,0 +1,32 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A rich media annotation: video, audio or interactive content. +/// ISO 32000-2 §12.5.6.25 and §13.7.2, Table 333 (PDF 2.0). Parse-and-preserve (rich media is out of scope): exposed as data, never played. +public sealed class PdfRichMediaAnnotation : PdfAnnotation +{ + internal PdfRichMediaAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.RichMedia) + { + } + + /// Gets the rich media content dictionary (RichMediaContent, required), as stored, or . + /// ISO 32000-2 §13.7.2, Table 333. + public CosDictionary? Content + { + get + { + if (!Dictionary.ContainsKey(AnnotationNames.RichMediaContent)) + { + ReportMissing(AnnotationNames.RichMediaContent, "Table 333"); + } + + return ReadDictionary(AnnotationNames.RichMediaContent); + } + } + + /// Gets the rich media settings dictionary (RichMediaSettings), as stored, or . + /// ISO 32000-2 §13.7.2, Table 333. + public CosDictionary? Settings => ReadDictionary(AnnotationNames.RichMediaSettings); +} diff --git a/src/Broadside/Annotations/PdfScreenAnnotation.cs b/src/Broadside/Annotations/PdfScreenAnnotation.cs new file mode 100644 index 00000000..0c835989 --- /dev/null +++ b/src/Broadside/Annotations/PdfScreenAnnotation.cs @@ -0,0 +1,25 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A screen annotation: a region of the page where media clips may be played. +/// ISO 32000-2 §12.5.6.18, Table 190 (PDF 1.5). Media are parse-and-preserve: the annotation's actions are exposed and never performed. Additional actions (AA) are read through until the action ticket types them. +public sealed class PdfScreenAnnotation : PdfAnnotation +{ + internal PdfScreenAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Screen) + { + } + + /// Gets the title of the annotation (T), or . + /// ISO 32000-2 §12.5.6.18, Table 190. + public string? ScreenTitle => ReadText(AnnotationNames.T); + + /// Gets the appearance characteristics dictionary used to construct the appearance (MK), or . + /// ISO 32000-2 §12.5.6.18, Table 190, and §12.5.6.19, Table 192. + public PdfAppearanceCharacteristics? AppearanceCharacteristics => ReadDictionary(AnnotationNames.MK) is { } characteristics ? new PdfAppearanceCharacteristics(this, characteristics) : null; + + /// Gets the action performed when the annotation is activated (A, PDF 1.1), or . + /// ISO 32000-2 §12.5.6.18, Table 190, and §12.6. + public PdfAction? Action => ReadAction(AnnotationNames.A); +} diff --git a/src/Broadside/Annotations/PdfSoundAnnotation.cs b/src/Broadside/Annotations/PdfSoundAnnotation.cs new file mode 100644 index 00000000..f673b6d7 --- /dev/null +++ b/src/Broadside/Annotations/PdfSoundAnnotation.cs @@ -0,0 +1,32 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A sound annotation: a sound recorded or attached at a point on the page. Deprecated in PDF 2.0. +/// ISO 32000-2 §12.5.6.16, Table 188 (PDF 1.2). Parse-and-preserve: the sound is exposed as data and never played. +public sealed class PdfSoundAnnotation : PdfMarkupAnnotation +{ + internal PdfSoundAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Sound) + { + } + + /// Gets the sound stream (Sound, required), as stored, or . + /// ISO 32000-2 §12.5.6.16, Table 188, and §13.3. + public CosStream? Sound + { + get + { + if (!Dictionary.ContainsKey(AnnotationNames.Sound)) + { + ReportMissing(AnnotationNames.Sound, "Table 188"); + } + + return ReadStream(AnnotationNames.Sound); + } + } + + /// Gets the name of the icon (Name): Speaker (the default), Mic or another name. + /// ISO 32000-2 §12.5.6.16, Table 188. + public string IconName => ReadIconName("Speaker"); +} diff --git a/src/Broadside/Annotations/PdfSquareAnnotation.cs b/src/Broadside/Annotations/PdfSquareAnnotation.cs new file mode 100644 index 00000000..8bec8405 --- /dev/null +++ b/src/Broadside/Annotations/PdfSquareAnnotation.cs @@ -0,0 +1,25 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A square annotation: a rectangle inscribed in the annotation rectangle (inset by ). +/// ISO 32000-2 §12.5.6.8, Table 180 (PDF 1.3). The border is . +public sealed class PdfSquareAnnotation : PdfMarkupAnnotation +{ + internal PdfSquareAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Square) + { + } + + /// Gets the interior colour (IC, PDF 1.4), or for none. + /// ISO 32000-2 §12.5.6.8, Table 180: it fills the shape. + public PdfDeviceColor? InteriorColor => ReadColor(AnnotationNames.IC); + + /// Gets the border effect (BE, PDF 1.5), or for none. + /// ISO 32000-2 §12.5.6.8, Table 180, and §12.5.4, Table 169. + public PdfBorderEffect? BorderEffect => ReadBorderEffect(); + + /// Gets the differences between the annotation rectangle and the drawn rectangle (RD, PDF 1.5), or . + /// ISO 32000-2 §12.5.6.8, Table 180. + public PdfRectangleDifferences? RectangleDifferences => ReadRectangleDifferences(); +} diff --git a/src/Broadside/Annotations/PdfSquigglyAnnotation.cs b/src/Broadside/Annotations/PdfSquigglyAnnotation.cs new file mode 100644 index 00000000..9ddc51fe --- /dev/null +++ b/src/Broadside/Annotations/PdfSquigglyAnnotation.cs @@ -0,0 +1,13 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A Squiggly text markup annotation (PDF 1.4). +/// ISO 32000-2 §12.5.6.10, Table 182. +public sealed class PdfSquigglyAnnotation : PdfTextMarkupAnnotation +{ + internal PdfSquigglyAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Squiggly) + { + } +} diff --git a/src/Broadside/Annotations/PdfStampAnnotation.cs b/src/Broadside/Annotations/PdfStampAnnotation.cs new file mode 100644 index 00000000..45548b33 --- /dev/null +++ b/src/Broadside/Annotations/PdfStampAnnotation.cs @@ -0,0 +1,29 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A rubber stamp annotation: text or graphics that look as if stamped on the page. +/// ISO 32000-2 §12.5.6.12, Table 184 (PDF 1.3). +public sealed class PdfStampAnnotation : PdfMarkupAnnotation +{ + internal PdfStampAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Stamp) + { + } + + /// Gets the name of the stamp's icon (Name), such as Approved or Draft (the default); when the intent is StampImage or StampSnapshot and no name is given. + /// ISO 32000-2 §12.5.6.12, Table 184: Name shall not be present when IT is present and not Stamp (PDF 2.0). + public string? IconName + { + get + { + CosName? name = ReadName(AnnotationNames.Name); + if (name is not null) + { + return name.Value; + } + + return Intent is { } intent && intent.Value != "Stamp" ? null : "Draft"; + } + } +} diff --git a/src/Broadside/Annotations/PdfStrikeOutAnnotation.cs b/src/Broadside/Annotations/PdfStrikeOutAnnotation.cs new file mode 100644 index 00000000..c319ec95 --- /dev/null +++ b/src/Broadside/Annotations/PdfStrikeOutAnnotation.cs @@ -0,0 +1,13 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A StrikeOut text markup annotation (PDF 1.3). +/// ISO 32000-2 §12.5.6.10, Table 182. +public sealed class PdfStrikeOutAnnotation : PdfTextMarkupAnnotation +{ + internal PdfStrikeOutAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.StrikeOut) + { + } +} diff --git a/src/Broadside/Annotations/PdfTextAnnotation.cs b/src/Broadside/Annotations/PdfTextAnnotation.cs new file mode 100644 index 00000000..e83d5f4b --- /dev/null +++ b/src/Broadside/Annotations/PdfTextAnnotation.cs @@ -0,0 +1,41 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A text annotation: a sticky note attached to a point on the page, shown as an icon. +/// ISO 32000-2 §12.5.6.4, Table 175 (PDF 1.0). It behaves as if the NoZoom and NoRotate flags were always set. A reply with and records a review state of the annotation it replies to (§12.5.6.3, Table 174). +public sealed class PdfTextAnnotation : PdfMarkupAnnotation +{ + internal PdfTextAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Text) + { + } + + /// Gets a value indicating whether the annotation is initially displayed open (Open); default . + /// ISO 32000-2 §12.5.6.4, Table 175. + public bool IsOpen => ReadBoolean(AnnotationNames.Open, fallback: false); + + /// Gets the name of the icon (Name): Comment, Key, Note (the default), Help, NewParagraph, Paragraph, Insert or another name. + /// ISO 32000-2 §12.5.6.4, Table 175. + public string IconName => ReadIconName("Note"); + + /// Gets the state this annotation sets on the one it replies to (State, PDF 1.5), such as Accepted, or . + /// ISO 32000-2 §12.5.6.4, Table 175, and §12.5.6.3, Table 174. Without a StateModel, which is then required, StateModelMissing is recorded. + public string? State + { + get + { + string? state = ReadText(AnnotationNames.State); + if (state is not null && !Dictionary.ContainsKey(AnnotationNames.StateModel)) + { + Report(Parsing.DiagnosticCodes.StateModelMissing, "The text annotation has a State but no StateModel, which Table 175 requires with it."); + } + + return state; + } + } + + /// Gets the state model belongs to (StateModel, PDF 1.5): Marked, Review or another, or . + /// ISO 32000-2 §12.5.6.4, Table 175, and §12.5.6.3, Table 174. + public string? StateModel => ReadText(AnnotationNames.StateModel); +} diff --git a/src/Broadside/Annotations/PdfTextJustification.cs b/src/Broadside/Annotations/PdfTextJustification.cs new file mode 100644 index 00000000..d772db61 --- /dev/null +++ b/src/Broadside/Annotations/PdfTextJustification.cs @@ -0,0 +1,15 @@ +namespace Broadside.Annotations; + +/// The justification of the text of a free text or redaction annotation, its Q entry. +/// ISO 32000-2 §12.5.6.6, Table 177 (PDF 1.4), and §12.5.6.23, Table 195. Default ; other values read as the default. +public enum PdfTextJustification +{ + /// 0: left-justified (the default). + Left = 0, + + /// 1: centred. + Centered = 1, + + /// 2: right-justified. + Right = 2, +} diff --git a/src/Broadside/Annotations/PdfTextMarkupAnnotation.cs b/src/Broadside/Annotations/PdfTextMarkupAnnotation.cs new file mode 100644 index 00000000..2de6d7ef --- /dev/null +++ b/src/Broadside/Annotations/PdfTextMarkupAnnotation.cs @@ -0,0 +1,17 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A text markup annotation: highlighted, underlined, squiggly-underlined or struck-out text. +/// ISO 32000-2 §12.5.6.10, Table 182. +public abstract class PdfTextMarkupAnnotation : PdfMarkupAnnotation +{ + private protected PdfTextMarkupAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page, PdfAnnotationKind kind) + : base(document, dictionary, reference, page, kind) + { + } + + /// Gets the quadrilaterals that enclose the marked-up text (QuadPoints, required), as stored; empty when absent. + /// ISO 32000-2 §12.5.6.10, Table 182. Counterclockwise, with the text along the edge from the first point to the second; written in other orders too (). + public IReadOnlyList QuadPoints => ReadQuadPoints(required: true, "Table 182"); +} diff --git a/src/Broadside/Annotations/PdfTrapNetAnnotation.cs b/src/Broadside/Annotations/PdfTrapNetAnnotation.cs new file mode 100644 index 00000000..de8f04fb --- /dev/null +++ b/src/Broadside/Annotations/PdfTrapNetAnnotation.cs @@ -0,0 +1,40 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A trap network annotation: the trapping of a page. Deprecated in PDF 2.0. +/// ISO 32000-2 §12.5.6.21 and §14.11.6.2, Table 403 (PDF 1.3). A page shall have at most one, and it shall be the last of its annotations (TrapNetPlacementInvalid). The entries are exposed as data. +public sealed class PdfTrapNetAnnotation : PdfAnnotation +{ + internal PdfTrapNetAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.TrapNet) + { + } + + /// Gets the date the trap network was last modified (LastModified), or ; required when Version and AnnotStates are absent. + /// ISO 32000-2 §14.11.6.2, Table 403. + public PdfDate? LastModified + { + get + { + if (!Dictionary.ContainsKey(AnnotationNames.LastModified) && !(Dictionary.ContainsKey(AnnotationNames.Version) && Dictionary.ContainsKey(AnnotationNames.AnnotStates))) + { + ReportMissing(AnnotationNames.LastModified, "Table 403 (without Version and AnnotStates)"); + } + + return ReadDate(AnnotationNames.LastModified); + } + } + + /// Gets the objects the trap network depends on (Version), as stored, or . + /// ISO 32000-2 §14.11.6.2, Table 403. + public CosArray? Version => ReadArray(AnnotationNames.Version); + + /// Gets the appearance states of the page's annotations when the trap network was generated (AnnotStates), as stored, or . + /// ISO 32000-2 §14.11.6.2, Table 403. + public CosArray? AnnotationStates => ReadArray(AnnotationNames.AnnotStates); + + /// Gets the fonts substituted during trapping (FontFauxing), as stored, or . + /// ISO 32000-2 §14.11.6.2, Table 403. + public CosArray? FontFauxing => ReadArray(AnnotationNames.FontFauxing); +} diff --git a/src/Broadside/Annotations/PdfUnderlineAnnotation.cs b/src/Broadside/Annotations/PdfUnderlineAnnotation.cs new file mode 100644 index 00000000..9716ae8c --- /dev/null +++ b/src/Broadside/Annotations/PdfUnderlineAnnotation.cs @@ -0,0 +1,13 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A Underline text markup annotation (PDF 1.3). +/// ISO 32000-2 §12.5.6.10, Table 182. +public sealed class PdfUnderlineAnnotation : PdfTextMarkupAnnotation +{ + internal PdfUnderlineAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Underline) + { + } +} diff --git a/src/Broadside/Annotations/PdfUnknownAnnotation.cs b/src/Broadside/Annotations/PdfUnknownAnnotation.cs new file mode 100644 index 00000000..7d343996 --- /dev/null +++ b/src/Broadside/Annotations/PdfUnknownAnnotation.cs @@ -0,0 +1,13 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// An annotation of a type Table 171 does not list, or without a subtype: its common entries only. +/// ISO 32000-2 §12.5.2 and §12.5.6.1: the set of subtypes is extensible. gives the raw name; a processor without a handler for it displays the normal appearance unless the Invisible flag is set (§12.5.3). +public sealed class PdfUnknownAnnotation : PdfAnnotation +{ + internal PdfUnknownAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Unknown) + { + } +} diff --git a/src/Broadside/Annotations/PdfWatermarkAnnotation.cs b/src/Broadside/Annotations/PdfWatermarkAnnotation.cs new file mode 100644 index 00000000..d72d9f1a --- /dev/null +++ b/src/Broadside/Annotations/PdfWatermarkAnnotation.cs @@ -0,0 +1,17 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A watermark annotation: graphics printed at a fixed size and position relative to the media. +/// ISO 32000-2 §12.5.6.22, Table 193 (PDF 1.6). It has no pop-up window or other interactive elements. +public sealed class PdfWatermarkAnnotation : PdfAnnotation +{ + internal PdfWatermarkAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Watermark) + { + } + + /// Gets the fixed print dictionary (FixedPrint), or when the annotation is drawn without regard to the media. + /// ISO 32000-2 §12.5.6.22, Tables 193 and 194. + public PdfFixedPrint? FixedPrint => ReadDictionary(AnnotationNames.FixedPrint) is { } fixedPrint ? new PdfFixedPrint(this, fixedPrint) : null; +} diff --git a/src/Broadside/Annotations/PdfWidgetAnnotation.cs b/src/Broadside/Annotations/PdfWidgetAnnotation.cs new file mode 100644 index 00000000..dc41e89b --- /dev/null +++ b/src/Broadside/Annotations/PdfWidgetAnnotation.cs @@ -0,0 +1,29 @@ +using Broadside.Objects; + +namespace Broadside.Annotations; + +/// A widget annotation: the appearance of an interactive form field on a page. +/// ISO 32000-2 §12.5.6.19, Table 191 (PDF 1.2). A field with one widget may merge both into one dictionary; the field's entries are read through the form field model. Additional actions (AA) are read through until the action ticket types them. +public sealed class PdfWidgetAnnotation : PdfAnnotation +{ + internal PdfWidgetAnnotation(PdfDocument document, CosDictionary dictionary, CosReference? reference, PdfPage? page) + : base(document, dictionary, reference, page, PdfAnnotationKind.Widget) + { + } + + /// Gets the visual effect when the widget is activated (H); default invert. T (toggle) reads as push. + /// ISO 32000-2 §12.5.6.19, Table 191. + public PdfHighlightMode HighlightMode => ReadChoice(AnnotationNames.H, PdfHighlightMode.Invert, ("N", PdfHighlightMode.None), ("I", PdfHighlightMode.Invert), ("O", PdfHighlightMode.Outline), ("P", PdfHighlightMode.Push), ("T", PdfHighlightMode.Push)); + + /// Gets the appearance characteristics dictionary used to construct the appearance (MK), or . + /// ISO 32000-2 §12.5.6.19, Table 191, and §12.5.6.19, Table 192. + public PdfAppearanceCharacteristics? AppearanceCharacteristics => ReadDictionary(AnnotationNames.MK) is { } characteristics ? new PdfAppearanceCharacteristics(this, characteristics) : null; + + /// Gets the action performed when the annotation is activated (A, PDF 1.1), or . + /// ISO 32000-2 §12.5.6.19, Table 191, and §12.6. + public PdfAction? Action => ReadAction(AnnotationNames.A); + + /// Gets the field dictionary this widget is a kid of (Parent), as stored, or ; required when the field has several widgets. + /// ISO 32000-2 §12.5.6.19, Table 191, and §12.7.4. + public CosDictionary? Parent => ReadDictionary(AnnotationNames.Parent); +} diff --git a/src/Broadside/Graphics/PdfFormXObject.cs b/src/Broadside/Graphics/PdfFormXObject.cs new file mode 100644 index 00000000..78d9182e --- /dev/null +++ b/src/Broadside/Graphics/PdfFormXObject.cs @@ -0,0 +1,80 @@ +using Broadside.Annotations; +using Broadside.Objects; + +namespace Broadside.Graphics; + +/// A form XObject: a self-contained content stream with its own bounding box, matrix and resources. A live view over the stream. +/// +/// +/// ISO 32000-2 §8.10.1, Table 93. Annotation appearances (§12.5.5) are form XObjects. Every property reads the stream dictionary on +/// every call and returns the default the table gives when an entry is absent or malformed (the identity matrix, no bounding box), +/// without a diagnostic: the object that uses the form (an annotation's appearance, the content interpreter's Do) reports +/// what it cannot use. +/// +/// The content is never interpreted here; returns its bytes through the document's filters. +/// +public sealed class PdfFormXObject +{ + private readonly PdfDocument _document; + + internal PdfFormXObject(PdfDocument document, CosStream stream, CosReference? reference) + { + _document = document; + Stream = stream; + Reference = reference; + } + + /// Gets the form's stream. + /// ISO 32000-2 §8.10.1, Table 93. + public CosStream Stream { get; } + + /// Gets the stream's dictionary. + public CosDictionary Dictionary => Stream.Dictionary; + + /// Gets the indirect reference to the stream, or when it was reached directly. + public CosReference? Reference { get; } + + /// Gets a value indicating whether the stream's Subtype is Form, as Table 93 requires. + /// ISO 32000-2 §8.10.1, Table 93 (Subtype, required). + public bool IsForm => _document.Resolve(Get(AnnotationNames.Subtype)) is CosName { Value: "Form" }; + + /// Gets the form's bounding box in form space, its clip; when BBox is absent or not four numbers. + /// ISO 32000-2 §8.10.1, Table 93 (BBox, required). + public PdfRectangle? BoundingBox => AnnotationValues.ReadRectangle(_document, Get(AnnotationNames.BBox)); + + /// Gets the form matrix, which maps form space to the user space of the content that paints it; the identity when absent or not six numbers. + /// ISO 32000-2 §8.10.1, Table 93 (Matrix, default [1 0 0 1 0 0]). + public Matrix Matrix => AnnotationValues.ReadMatrix(_document, Get(AnnotationNames.Matrix)) ?? Matrix.Identity; + + /// Gets the resources the form's content uses, or when the form has none of its own. + /// ISO 32000-2 §8.10.1, Table 93 (Resources), and §7.8.3. + public CosDictionary? Resources => _document.Resolve(Get(AnnotationNames.Resources)) as CosDictionary; + + /// Gets the group attributes dictionary that makes the form a transparency group, or . + /// ISO 32000-2 §8.10.3, Table 94, and §11.6.6 (Group, PDF 1.4). + public CosDictionary? Group => _document.Resolve(Get(AnnotationNames.Group)) as CosDictionary; + + /// Gets the optional content group or membership dictionary of the form, or . + /// ISO 32000-2 §8.10.1, Table 93 (OC, PDF 1.5), and §8.11.3.3. + public CosDictionary? OptionalContent => _document.Resolve(Get(AnnotationNames.OC)) as CosDictionary; + + /// Gets the form's key in the structural parent tree when it is one content item, or . + /// ISO 32000-2 §8.10.1, Table 93 (StructParent, PDF 1.3), and §14.7.5.4. + public int? StructParent => AnnotationValues.ReadInteger(_document, Get(AnnotationNames.StructParent)); + + /// Gets the form's key in the structural parent tree for the marked content in it, or . + /// ISO 32000-2 §8.10.1, Table 93 (StructParents, PDF 1.3), and §14.7.5.4. + public int? StructParents => AnnotationValues.ReadInteger(_document, Get(AnnotationNames.StructParents)); + + /// Returns the form's content decoded through the filters its Filter entry names. + /// The content stream bytes. + /// In strict mode, for the first deviation found while decoding. + /// ISO 32000-2 §7.3.8.2 and §7.4; as . + public ReadOnlyMemory Decode() => _document.DecodeStream(Stream); + + /// Returns the form view over when it is a stream, else . + internal static PdfFormXObject? Create(PdfDocument document, CosObject? value) => + document.Resolve(value) is CosStream stream ? new PdfFormXObject(document, stream, value as CosReference) : null; + + private CosObject? Get(CosName key) => Stream.Dictionary.TryGetValue(key, out CosObject? value) ? value : null; +} diff --git a/src/Broadside/Parsing/DiagnosticCodes.Annotations.cs b/src/Broadside/Parsing/DiagnosticCodes.Annotations.cs new file mode 100644 index 00000000..de69b5b9 --- /dev/null +++ b/src/Broadside/Parsing/DiagnosticCodes.Annotations.cs @@ -0,0 +1,44 @@ +namespace Broadside.Parsing; + +/// Diagnostic codes for annotations and their appearances (issue #71). +internal static partial class DiagnosticCodes +{ + // The page's Annots array (§7.7.3.3, Table 31; §12.5.2). + public const string AnnotsInvalid = nameof(AnnotsInvalid); + public const string AnnotsInherited = nameof(AnnotsInherited); + public const string AnnotationEntryInvalid = nameof(AnnotationEntryInvalid); + public const string AnnotationNotIndirect = nameof(AnnotationNotIndirect); + public const string AnnotationDuplicate = nameof(AnnotationDuplicate); + public const string AnnotationSharedAcrossPages = nameof(AnnotationSharedAcrossPages); + public const string AnnotationPageMismatch = nameof(AnnotationPageMismatch); + + // Annotation dictionaries (§12.5.2 to §12.5.4, Tables 166 to 169). + public const string AnnotationTypeInvalid = nameof(AnnotationTypeInvalid); + public const string AnnotationSubtypeMissing = nameof(AnnotationSubtypeMissing); + public const string AnnotationSubtypeNotName = nameof(AnnotationSubtypeNotName); + public const string AnnotationRectInvalid = nameof(AnnotationRectInvalid); + public const string AnnotationFlagsInvalid = nameof(AnnotationFlagsInvalid); + public const string AnnotationValueInvalid = nameof(AnnotationValueInvalid); + public const string AnnotationRequiredEntryMissing = nameof(AnnotationRequiredEntryMissing); + public const string BorderArrayInvalid = nameof(BorderArrayInvalid); + public const string BorderStyleTypeInvalid = nameof(BorderStyleTypeInvalid); + public const string ColorArrayInvalid = nameof(ColorArrayInvalid); + public const string QuadPointsInvalid = nameof(QuadPointsInvalid); + + // Appearance streams (§12.5.5, Table 170). + public const string AppearanceMissing = nameof(AppearanceMissing); + public const string AppearanceStateMissing = nameof(AppearanceStateMissing); + public const string AppearanceEntryInvalid = nameof(AppearanceEntryInvalid); + public const string AppearanceBBoxMissing = nameof(AppearanceBBoxMissing); + public const string AppearanceNotForm = nameof(AppearanceNotForm); + + // Relations between annotations (§12.5.6.2, §12.5.6.3, §12.5.6.14, §12.5.6.21). + public const string PopupLinkMismatch = nameof(PopupLinkMismatch); + public const string PopupParentInvalid = nameof(PopupParentInvalid); + public const string InReplyToInvalid = nameof(InReplyToInvalid); + public const string InReplyToOtherPage = nameof(InReplyToOtherPage); + public const string ReplyTypeWithoutInReplyTo = nameof(ReplyTypeWithoutInReplyTo); + public const string StateModelMissing = nameof(StateModelMissing); + public const string LinkActionAndDest = nameof(LinkActionAndDest); + public const string TrapNetPlacementInvalid = nameof(TrapNetPlacementInvalid); +} diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 5a06c0b2..4220f1ff 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -1,5 +1,6 @@ using System.Buffers; using System.Runtime.CompilerServices; +using Broadside.Annotations; using Broadside.Diagnostics; using Broadside.Filters; using Broadside.Fonts; @@ -63,6 +64,7 @@ public sealed partial class PdfDocument : IDisposable private readonly ConditionalWeakTable _nameTrees = []; private readonly ConditionalWeakTable _numberTrees = []; private StructureContext? _structure; + private AnnotationIndex? _annotationIndex; private PdfOptionalContentProperties? _optionalContent; private PdfDocument( @@ -613,6 +615,16 @@ public async Task SaveAsync(Stream stream, PdfSaveOptions? options = null, Cance /// Gets the diagnostics sink, for document-model views that report what they find on first read. internal DiagnosticSink DiagnosticSink => _diagnostics; + + /// Gets the document's annotation views and the page each belongs to (issue #71). + internal AnnotationIndex AnnotationIndex + { + get + { + AnnotationIndex? index = Volatile.Read(ref _annotationIndex); + return index ?? Interlocked.CompareExchange(ref _annotationIndex, new AnnotationIndex(this), null) ?? _annotationIndex!; + } + } /// Gets the document's optional content (layers), or when the catalog has no OCProperties. /// /// ISO 32000-2 §8.11 and §7.7.2, Table 29 (PDF 1.5). Without OCProperties every optional content structure is ignored and all diff --git a/src/Broadside/PdfPage.cs b/src/Broadside/PdfPage.cs index cfa3044e..68e1b374 100644 --- a/src/Broadside/PdfPage.cs +++ b/src/Broadside/PdfPage.cs @@ -1,3 +1,4 @@ +using Broadside.Annotations; using Broadside.Content; using Broadside.Diagnostics; using Broadside.Fonts; @@ -25,6 +26,7 @@ public sealed class PdfPage private readonly PdfDocument _document; private readonly PageTreeAncestor? _ancestors; + private volatile AnnotationList? _annotations; internal PdfPage(PdfDocument document, CosDictionary dictionary, CosReference? reference, PageTreeAncestor? ancestors) { @@ -95,6 +97,36 @@ internal PdfPage(PdfDocument document, CosDictionary dictionary, CosReference? r /// ISO 32000-2 §7.7.3.3, Table 31 (PDF 2.0), and §14.13.4. Read on every call; see . public IReadOnlyList AssociatedFiles => _document.ReadAssociatedFiles(Dictionary, Reference); + /// Gets the page's annotations, in the order of its Annots array, each typed by its subtype. + /// In strict mode, for the first deviation found in the Annots array. + /// + /// + /// ISO 32000-2 §7.7.3.3, Table 31 (Annots), and §12.5. The list is built on first use and rebuilt when the page's + /// Annots entry or array, or an annotation's Subtype, changes; each annotation is a live view over its dictionary, and the same dictionary always + /// gives the same instance. An element that is not an annotation dictionary is skipped; one listed twice appears twice. An + /// Annots entry on a page tree node above the page, which is not inheritable, is used as viewers use it. + /// + /// Deviations in the array are recorded in when the list is built. + /// + public IReadOnlyList Annotations + { + get + { + (CosObject? entry, bool inherited) = FindAnnots(); + var array = _document.Resolve(entry) as CosArray; + AnnotationList? cached = _annotations; + if (cached is not null && ReferenceEquals(cached.Entry, entry) && ReferenceEquals(cached.Array, array) && cached.ArrayVersion == (array?.Version ?? 0) + && cached.Items.All(annotation => Equals(annotation.CreatedSubtype, PdfAnnotation.ReadSubtype(_document, annotation.Dictionary, out _)))) + { + return cached.Items; + } + + IReadOnlyList items = _document.AnnotationIndex.Read(this, entry, inherited); + _annotations = new AnnotationList(entry, array, array?.Version ?? 0, items); + return items; + } + } + /// Runs the page's content through the content interpreter and reports what it paints to . /// The processor; for several at once, a . /// In strict mode, for the first deviation found in the content. @@ -204,6 +236,25 @@ private PdfRectangle ClipToMediaBox(CosName key, bool inheritable, PdfRectangle return box.Intersect(MediaBox) ?? fallback; } + /// The page's Annots entry as stored, else the nearest ancestor's (not inheritable, but read as viewers read it). + private (CosObject? Entry, bool Inherited) FindAnnots() + { + if (Dictionary.TryGetValue(AnnotationNames.Annots, out CosObject? own)) + { + return (own, false); + } + + for (PageTreeAncestor? node = _ancestors; node is not null; node = node.Parent) + { + if (node.Dictionary.TryGetValue(AnnotationNames.Annots, out CosObject? value)) + { + return (value, true); + } + } + + return (null, false); + } + /// The page's own entry, resolved; when absent or a reference to nothing. private CosObject? Find(CosName key) => Dictionary.TryGetValue(key, out CosObject? value) && _document.Resolve(value) is not CosNull and var resolved ? resolved : null; @@ -233,6 +284,9 @@ private PdfRectangle ClipToMediaBox(CosName key, bool inheritable, PdfRectangle /// The node above it, or for the root. internal sealed record PageTreeAncestor(CosDictionary Dictionary, PageTreeAncestor? Parent); +/// A page's annotation list and the Annots entry, array and array version it was built from. +internal sealed record AnnotationList(CosObject? Entry, CosArray? Array, int ArrayVersion, IReadOnlyList Items); + /// What reading a page attribute found. internal enum PageAttributeState : byte { diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index 853234a6..1d2d5d5b 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -1,5 +1,326 @@ #nullable enable abstract Broadside.Objects.CosNumber.ToDouble() -> double +Broadside.Annotations.Pdf3DAnnotation +Broadside.Annotations.Pdf3DAnnotation.Activation.get -> Broadside.Objects.CosDictionary? +Broadside.Annotations.Pdf3DAnnotation.Artwork.get -> Broadside.Objects.CosObject? +Broadside.Annotations.Pdf3DAnnotation.DefaultView.get -> Broadside.Objects.CosObject? +Broadside.Annotations.Pdf3DAnnotation.Geospatial.get -> Broadside.Objects.CosDictionary? +Broadside.Annotations.Pdf3DAnnotation.IsInteractive.get -> bool +Broadside.Annotations.Pdf3DAnnotation.Units.get -> Broadside.Objects.CosDictionary? +Broadside.Annotations.Pdf3DAnnotation.ViewBox.get -> Broadside.PdfRectangle? +Broadside.Annotations.PdfAnnotation +Broadside.Annotations.PdfAnnotation.AppearanceDictionary.get -> Broadside.Annotations.PdfAppearanceDictionary? +Broadside.Annotations.PdfAnnotation.AppearanceState.get -> Broadside.Objects.CosName? +Broadside.Annotations.PdfAnnotation.AssociatedFiles.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Annotations.PdfAnnotation.BlendMode.get -> Broadside.Graphics.BlendMode +Broadside.Annotations.PdfAnnotation.Border.get -> Broadside.Annotations.PdfAnnotationBorder! +Broadside.Annotations.PdfAnnotation.Color.get -> Broadside.Annotations.PdfDeviceColor? +Broadside.Annotations.PdfAnnotation.Contents.get -> string? +Broadside.Annotations.PdfAnnotation.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Annotations.PdfAnnotation.Flags.get -> Broadside.Annotations.PdfAnnotationFlags +Broadside.Annotations.PdfAnnotation.GetAppearance() -> Broadside.Graphics.PdfFormXObject? +Broadside.Annotations.PdfAnnotation.GetAppearance(Broadside.Annotations.PdfAppearanceMode mode) -> Broadside.Graphics.PdfFormXObject? +Broadside.Annotations.PdfAnnotation.GetAppearance(Broadside.Annotations.PdfAppearanceMode mode, Broadside.Objects.CosName! state) -> Broadside.Graphics.PdfFormXObject? +Broadside.Annotations.PdfAnnotation.GetAppearanceMatrix(Broadside.Graphics.PdfFormXObject! appearance) -> Broadside.Graphics.Matrix? +Broadside.Annotations.PdfAnnotation.IsVisible(Broadside.PdfOptionalContentState! state) -> bool +Broadside.Annotations.PdfAnnotation.Kind.get -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotation.Language.get -> string? +Broadside.Annotations.PdfAnnotation.Modified.get -> Broadside.PdfDate? +Broadside.Annotations.PdfAnnotation.ModifiedText.get -> string? +Broadside.Annotations.PdfAnnotation.Name.get -> string? +Broadside.Annotations.PdfAnnotation.NonStrokingOpacity.get -> double +Broadside.Annotations.PdfAnnotation.OptionalContent.get -> Broadside.Objects.CosDictionary? +Broadside.Annotations.PdfAnnotation.Page.get -> Broadside.PdfPage? +Broadside.Annotations.PdfAnnotation.PageObject.get -> Broadside.Objects.CosDictionary? +Broadside.Annotations.PdfAnnotation.Rect.get -> Broadside.PdfRectangle +Broadside.Annotations.PdfAnnotation.Reference.get -> Broadside.Objects.CosReference? +Broadside.Annotations.PdfAnnotation.StrokingOpacity.get -> double +Broadside.Annotations.PdfAnnotation.StructParent.get -> int? +Broadside.Annotations.PdfAnnotation.Subtype.get -> Broadside.Objects.CosName? +Broadside.Annotations.PdfAnnotationBorder +Broadside.Annotations.PdfAnnotationBorder.DashPattern.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Annotations.PdfAnnotationBorder.HorizontalCornerRadius.get -> double +Broadside.Annotations.PdfAnnotationBorder.Source.get -> Broadside.Annotations.PdfBorderSource +Broadside.Annotations.PdfAnnotationBorder.Style.get -> Broadside.Annotations.PdfBorderStyle +Broadside.Annotations.PdfAnnotationBorder.VerticalCornerRadius.get -> double +Broadside.Annotations.PdfAnnotationBorder.Width.get -> double +Broadside.Annotations.PdfAnnotationFlags +Broadside.Annotations.PdfAnnotationFlags.Hidden = 2 -> Broadside.Annotations.PdfAnnotationFlags +Broadside.Annotations.PdfAnnotationFlags.Invisible = 1 -> Broadside.Annotations.PdfAnnotationFlags +Broadside.Annotations.PdfAnnotationFlags.Locked = 128 -> Broadside.Annotations.PdfAnnotationFlags +Broadside.Annotations.PdfAnnotationFlags.LockedContents = 512 -> Broadside.Annotations.PdfAnnotationFlags +Broadside.Annotations.PdfAnnotationFlags.None = 0 -> Broadside.Annotations.PdfAnnotationFlags +Broadside.Annotations.PdfAnnotationFlags.NoRotate = 16 -> Broadside.Annotations.PdfAnnotationFlags +Broadside.Annotations.PdfAnnotationFlags.NoView = 32 -> Broadside.Annotations.PdfAnnotationFlags +Broadside.Annotations.PdfAnnotationFlags.NoZoom = 8 -> Broadside.Annotations.PdfAnnotationFlags +Broadside.Annotations.PdfAnnotationFlags.Print = 4 -> Broadside.Annotations.PdfAnnotationFlags +Broadside.Annotations.PdfAnnotationFlags.ReadOnly = 64 -> Broadside.Annotations.PdfAnnotationFlags +Broadside.Annotations.PdfAnnotationFlags.ToggleNoView = 256 -> Broadside.Annotations.PdfAnnotationFlags +Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Caret = 13 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Circle = 6 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.FileAttachment = 17 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.FreeText = 3 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Highlight = 9 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Ink = 15 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Line = 4 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Link = 2 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Movie = 19 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Polygon = 7 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.PolyLine = 8 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Popup = 16 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.PrinterMark = 22 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Projection = 27 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Redact = 26 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.RichMedia = 28 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Screen = 20 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Sound = 18 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Square = 5 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Squiggly = 11 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Stamp = 14 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.StrikeOut = 12 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Text = 1 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.ThreeD = 25 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.TrapNet = 23 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Underline = 10 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Unknown = 0 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Watermark = 24 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAnnotationKind.Widget = 21 -> Broadside.Annotations.PdfAnnotationKind +Broadside.Annotations.PdfAppearanceCharacteristics +Broadside.Annotations.PdfAppearanceCharacteristics.AlternateCaption.get -> string? +Broadside.Annotations.PdfAppearanceCharacteristics.AlternateIcon.get -> Broadside.Graphics.PdfFormXObject? +Broadside.Annotations.PdfAppearanceCharacteristics.BackgroundColor.get -> Broadside.Annotations.PdfDeviceColor? +Broadside.Annotations.PdfAppearanceCharacteristics.BorderColor.get -> Broadside.Annotations.PdfDeviceColor? +Broadside.Annotations.PdfAppearanceCharacteristics.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Annotations.PdfAppearanceCharacteristics.IconFit.get -> Broadside.Objects.CosDictionary? +Broadside.Annotations.PdfAppearanceCharacteristics.NormalCaption.get -> string? +Broadside.Annotations.PdfAppearanceCharacteristics.NormalIcon.get -> Broadside.Graphics.PdfFormXObject? +Broadside.Annotations.PdfAppearanceCharacteristics.RolloverCaption.get -> string? +Broadside.Annotations.PdfAppearanceCharacteristics.RolloverIcon.get -> Broadside.Graphics.PdfFormXObject? +Broadside.Annotations.PdfAppearanceCharacteristics.Rotation.get -> int +Broadside.Annotations.PdfAppearanceCharacteristics.TextPosition.get -> int +Broadside.Annotations.PdfAppearanceDictionary +Broadside.Annotations.PdfAppearanceDictionary.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Annotations.PdfAppearanceDictionary.Down.get -> Broadside.Annotations.PdfAppearanceEntry? +Broadside.Annotations.PdfAppearanceDictionary.GetEntry(Broadside.Annotations.PdfAppearanceMode mode) -> Broadside.Annotations.PdfAppearanceEntry? +Broadside.Annotations.PdfAppearanceDictionary.HasDown.get -> bool +Broadside.Annotations.PdfAppearanceDictionary.HasRollover.get -> bool +Broadside.Annotations.PdfAppearanceDictionary.Normal.get -> Broadside.Annotations.PdfAppearanceEntry? +Broadside.Annotations.PdfAppearanceDictionary.Rollover.get -> Broadside.Annotations.PdfAppearanceEntry? +Broadside.Annotations.PdfAppearanceEntry +Broadside.Annotations.PdfAppearanceEntry.Form.get -> Broadside.Graphics.PdfFormXObject? +Broadside.Annotations.PdfAppearanceEntry.GetAppearance(Broadside.Objects.CosName! state) -> Broadside.Graphics.PdfFormXObject? +Broadside.Annotations.PdfAppearanceEntry.HasStates.get -> bool +Broadside.Annotations.PdfAppearanceEntry.StateNames.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Annotations.PdfAppearanceEntry.Value.get -> Broadside.Objects.CosObject! +Broadside.Annotations.PdfAppearanceMode +Broadside.Annotations.PdfAppearanceMode.Down = 2 -> Broadside.Annotations.PdfAppearanceMode +Broadside.Annotations.PdfAppearanceMode.Normal = 0 -> Broadside.Annotations.PdfAppearanceMode +Broadside.Annotations.PdfAppearanceMode.Rollover = 1 -> Broadside.Annotations.PdfAppearanceMode +Broadside.Annotations.PdfBorderEffect +Broadside.Annotations.PdfBorderEffect.Intensity.get -> double +Broadside.Annotations.PdfBorderEffect.Style.get -> Broadside.Annotations.PdfBorderEffectStyle +Broadside.Annotations.PdfBorderEffectStyle +Broadside.Annotations.PdfBorderEffectStyle.Cloudy = 1 -> Broadside.Annotations.PdfBorderEffectStyle +Broadside.Annotations.PdfBorderEffectStyle.None = 0 -> Broadside.Annotations.PdfBorderEffectStyle +Broadside.Annotations.PdfBorderSource +Broadside.Annotations.PdfBorderSource.BorderArray = 1 -> Broadside.Annotations.PdfBorderSource +Broadside.Annotations.PdfBorderSource.BorderStyle = 2 -> Broadside.Annotations.PdfBorderSource +Broadside.Annotations.PdfBorderSource.Default = 0 -> Broadside.Annotations.PdfBorderSource +Broadside.Annotations.PdfBorderStyle +Broadside.Annotations.PdfBorderStyle.Beveled = 2 -> Broadside.Annotations.PdfBorderStyle +Broadside.Annotations.PdfBorderStyle.Dashed = 1 -> Broadside.Annotations.PdfBorderStyle +Broadside.Annotations.PdfBorderStyle.Inset = 3 -> Broadside.Annotations.PdfBorderStyle +Broadside.Annotations.PdfBorderStyle.Solid = 0 -> Broadside.Annotations.PdfBorderStyle +Broadside.Annotations.PdfBorderStyle.Underline = 4 -> Broadside.Annotations.PdfBorderStyle +Broadside.Annotations.PdfCaretAnnotation +Broadside.Annotations.PdfCaretAnnotation.RectangleDifferences.get -> Broadside.Annotations.PdfRectangleDifferences? +Broadside.Annotations.PdfCaretAnnotation.Symbol.get -> Broadside.Annotations.PdfCaretSymbol +Broadside.Annotations.PdfCaretSymbol +Broadside.Annotations.PdfCaretSymbol.None = 0 -> Broadside.Annotations.PdfCaretSymbol +Broadside.Annotations.PdfCaretSymbol.Paragraph = 1 -> Broadside.Annotations.PdfCaretSymbol +Broadside.Annotations.PdfCircleAnnotation +Broadside.Annotations.PdfCircleAnnotation.BorderEffect.get -> Broadside.Annotations.PdfBorderEffect? +Broadside.Annotations.PdfCircleAnnotation.InteriorColor.get -> Broadside.Annotations.PdfDeviceColor? +Broadside.Annotations.PdfCircleAnnotation.RectangleDifferences.get -> Broadside.Annotations.PdfRectangleDifferences? +Broadside.Annotations.PdfDeviceColor +Broadside.Annotations.PdfDeviceColor.ColorSpace.get -> Broadside.Annotations.PdfDeviceColorSpace +Broadside.Annotations.PdfDeviceColor.Components.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Annotations.PdfDeviceColor.Equals(Broadside.Annotations.PdfDeviceColor? other) -> bool +Broadside.Annotations.PdfDeviceColor.IsTransparent.get -> bool +Broadside.Annotations.PdfDeviceColor.PdfDeviceColor(params System.ReadOnlySpan components) -> void +Broadside.Annotations.PdfDeviceColorSpace +Broadside.Annotations.PdfDeviceColorSpace.Cmyk = 3 -> Broadside.Annotations.PdfDeviceColorSpace +Broadside.Annotations.PdfDeviceColorSpace.Gray = 1 -> Broadside.Annotations.PdfDeviceColorSpace +Broadside.Annotations.PdfDeviceColorSpace.None = 0 -> Broadside.Annotations.PdfDeviceColorSpace +Broadside.Annotations.PdfDeviceColorSpace.Rgb = 2 -> Broadside.Annotations.PdfDeviceColorSpace +Broadside.Annotations.PdfFileAttachmentAnnotation +Broadside.Annotations.PdfFileAttachmentAnnotation.FileSpecification.get -> Broadside.PdfFileSpecification? +Broadside.Annotations.PdfFileAttachmentAnnotation.IconName.get -> string! +Broadside.Annotations.PdfFixedPrint +Broadside.Annotations.PdfFixedPrint.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Annotations.PdfFixedPrint.HasValidType.get -> bool +Broadside.Annotations.PdfFixedPrint.HorizontalTranslation.get -> double +Broadside.Annotations.PdfFixedPrint.Matrix.get -> Broadside.Graphics.Matrix +Broadside.Annotations.PdfFixedPrint.VerticalTranslation.get -> double +Broadside.Annotations.PdfFreeTextAnnotation +Broadside.Annotations.PdfFreeTextAnnotation.BorderEffect.get -> Broadside.Annotations.PdfBorderEffect? +Broadside.Annotations.PdfFreeTextAnnotation.CalloutLine.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Annotations.PdfFreeTextAnnotation.DefaultAppearance.get -> string? +Broadside.Annotations.PdfFreeTextAnnotation.DefaultStyle.get -> string? +Broadside.Annotations.PdfFreeTextAnnotation.Justification.get -> Broadside.Annotations.PdfTextJustification +Broadside.Annotations.PdfFreeTextAnnotation.LineEnding.get -> Broadside.Annotations.PdfLineEnding +Broadside.Annotations.PdfFreeTextAnnotation.RectangleDifferences.get -> Broadside.Annotations.PdfRectangleDifferences? +Broadside.Annotations.PdfHighlightAnnotation +Broadside.Annotations.PdfHighlightMode +Broadside.Annotations.PdfHighlightMode.Invert = 1 -> Broadside.Annotations.PdfHighlightMode +Broadside.Annotations.PdfHighlightMode.None = 0 -> Broadside.Annotations.PdfHighlightMode +Broadside.Annotations.PdfHighlightMode.Outline = 2 -> Broadside.Annotations.PdfHighlightMode +Broadside.Annotations.PdfHighlightMode.Push = 3 -> Broadside.Annotations.PdfHighlightMode +Broadside.Annotations.PdfInkAnnotation +Broadside.Annotations.PdfInkAnnotation.InkList.get -> System.Collections.Generic.IReadOnlyList!>! +Broadside.Annotations.PdfInkAnnotation.Path.get -> System.Collections.Generic.IReadOnlyList!>? +Broadside.Annotations.PdfLineAnnotation +Broadside.Annotations.PdfLineAnnotation.CaptionOffset.get -> Broadside.Graphics.PathPoint +Broadside.Annotations.PdfLineAnnotation.CaptionPosition.get -> Broadside.Annotations.PdfLineCaptionPosition +Broadside.Annotations.PdfLineAnnotation.End.get -> Broadside.Graphics.PathPoint +Broadside.Annotations.PdfLineAnnotation.EndLineEnding.get -> Broadside.Annotations.PdfLineEnding +Broadside.Annotations.PdfLineAnnotation.HasCaption.get -> bool +Broadside.Annotations.PdfLineAnnotation.InteriorColor.get -> Broadside.Annotations.PdfDeviceColor? +Broadside.Annotations.PdfLineAnnotation.LeaderLineExtension.get -> double +Broadside.Annotations.PdfLineAnnotation.LeaderLineLength.get -> double +Broadside.Annotations.PdfLineAnnotation.LeaderLineOffset.get -> double +Broadside.Annotations.PdfLineAnnotation.Measure.get -> Broadside.Objects.CosDictionary? +Broadside.Annotations.PdfLineAnnotation.Start.get -> Broadside.Graphics.PathPoint +Broadside.Annotations.PdfLineAnnotation.StartLineEnding.get -> Broadside.Annotations.PdfLineEnding +Broadside.Annotations.PdfLineCaptionPosition +Broadside.Annotations.PdfLineCaptionPosition.Inline = 0 -> Broadside.Annotations.PdfLineCaptionPosition +Broadside.Annotations.PdfLineCaptionPosition.Top = 1 -> Broadside.Annotations.PdfLineCaptionPosition +Broadside.Annotations.PdfLineEnding +Broadside.Annotations.PdfLineEnding.Butt = 6 -> Broadside.Annotations.PdfLineEnding +Broadside.Annotations.PdfLineEnding.Circle = 2 -> Broadside.Annotations.PdfLineEnding +Broadside.Annotations.PdfLineEnding.ClosedArrow = 5 -> Broadside.Annotations.PdfLineEnding +Broadside.Annotations.PdfLineEnding.Diamond = 3 -> Broadside.Annotations.PdfLineEnding +Broadside.Annotations.PdfLineEnding.None = 0 -> Broadside.Annotations.PdfLineEnding +Broadside.Annotations.PdfLineEnding.OpenArrow = 4 -> Broadside.Annotations.PdfLineEnding +Broadside.Annotations.PdfLineEnding.RClosedArrow = 8 -> Broadside.Annotations.PdfLineEnding +Broadside.Annotations.PdfLineEnding.ROpenArrow = 7 -> Broadside.Annotations.PdfLineEnding +Broadside.Annotations.PdfLineEnding.Slash = 9 -> Broadside.Annotations.PdfLineEnding +Broadside.Annotations.PdfLineEnding.Square = 1 -> Broadside.Annotations.PdfLineEnding +Broadside.Annotations.PdfLinkAnnotation +Broadside.Annotations.PdfLinkAnnotation.Action.get -> Broadside.PdfAction? +Broadside.Annotations.PdfLinkAnnotation.ActivationRegion.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Annotations.PdfLinkAnnotation.Destination.get -> Broadside.PdfDestination? +Broadside.Annotations.PdfLinkAnnotation.HighlightMode.get -> Broadside.Annotations.PdfHighlightMode +Broadside.Annotations.PdfLinkAnnotation.PreviousUriAction.get -> Broadside.PdfAction? +Broadside.Annotations.PdfLinkAnnotation.QuadPoints.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Annotations.PdfMarkupAnnotation +Broadside.Annotations.PdfMarkupAnnotation.CreationDate.get -> Broadside.PdfDate? +Broadside.Annotations.PdfMarkupAnnotation.ExternalData.get -> Broadside.Objects.CosDictionary? +Broadside.Annotations.PdfMarkupAnnotation.InReplyTo.get -> Broadside.Annotations.PdfAnnotation? +Broadside.Annotations.PdfMarkupAnnotation.Intent.get -> Broadside.Objects.CosName? +Broadside.Annotations.PdfMarkupAnnotation.Popup.get -> Broadside.Annotations.PdfPopupAnnotation? +Broadside.Annotations.PdfMarkupAnnotation.ReplyType.get -> Broadside.Annotations.PdfReplyType +Broadside.Annotations.PdfMarkupAnnotation.RichText.get -> string? +Broadside.Annotations.PdfMarkupAnnotation.Subject.get -> string? +Broadside.Annotations.PdfMarkupAnnotation.Title.get -> string? +Broadside.Annotations.PdfMovieAnnotation +Broadside.Annotations.PdfMovieAnnotation.Activation.get -> Broadside.Objects.CosObject? +Broadside.Annotations.PdfMovieAnnotation.Movie.get -> Broadside.Objects.CosDictionary? +Broadside.Annotations.PdfMovieAnnotation.MovieTitle.get -> string? +Broadside.Annotations.PdfPolygonAnnotation +Broadside.Annotations.PdfPolygonAnnotation.BorderEffect.get -> Broadside.Annotations.PdfBorderEffect? +Broadside.Annotations.PdfPolygonAnnotation.InteriorColor.get -> Broadside.Annotations.PdfDeviceColor? +Broadside.Annotations.PdfPolygonAnnotation.Measure.get -> Broadside.Objects.CosDictionary? +Broadside.Annotations.PdfPolygonAnnotation.Path.get -> System.Collections.Generic.IReadOnlyList!>? +Broadside.Annotations.PdfPolygonAnnotation.Vertices.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Annotations.PdfPolyLineAnnotation +Broadside.Annotations.PdfPolyLineAnnotation.EndLineEnding.get -> Broadside.Annotations.PdfLineEnding +Broadside.Annotations.PdfPolyLineAnnotation.InteriorColor.get -> Broadside.Annotations.PdfDeviceColor? +Broadside.Annotations.PdfPolyLineAnnotation.Measure.get -> Broadside.Objects.CosDictionary? +Broadside.Annotations.PdfPolyLineAnnotation.Path.get -> System.Collections.Generic.IReadOnlyList!>? +Broadside.Annotations.PdfPolyLineAnnotation.StartLineEnding.get -> Broadside.Annotations.PdfLineEnding +Broadside.Annotations.PdfPolyLineAnnotation.Vertices.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Annotations.PdfPopupAnnotation +Broadside.Annotations.PdfPopupAnnotation.IsOpen.get -> bool +Broadside.Annotations.PdfPopupAnnotation.Parent.get -> Broadside.Annotations.PdfAnnotation? +Broadside.Annotations.PdfPrinterMarkAnnotation +Broadside.Annotations.PdfPrinterMarkAnnotation.MarkName.get -> Broadside.Objects.CosName? +Broadside.Annotations.PdfProjectionAnnotation +Broadside.Annotations.PdfQuadrilateral +Broadside.Annotations.PdfQuadrilateral.Bounds.get -> Broadside.PdfRectangle +Broadside.Annotations.PdfQuadrilateral.Equals(Broadside.Annotations.PdfQuadrilateral other) -> bool +Broadside.Annotations.PdfQuadrilateral.PdfQuadrilateral() -> void +Broadside.Annotations.PdfQuadrilateral.PdfQuadrilateral(Broadside.Graphics.PathPoint point1, Broadside.Graphics.PathPoint point2, Broadside.Graphics.PathPoint point3, Broadside.Graphics.PathPoint point4) -> void +Broadside.Annotations.PdfQuadrilateral.Point1.get -> Broadside.Graphics.PathPoint +Broadside.Annotations.PdfQuadrilateral.Point2.get -> Broadside.Graphics.PathPoint +Broadside.Annotations.PdfQuadrilateral.Point3.get -> Broadside.Graphics.PathPoint +Broadside.Annotations.PdfQuadrilateral.Point4.get -> Broadside.Graphics.PathPoint +Broadside.Annotations.PdfRectangleDifferences +Broadside.Annotations.PdfRectangleDifferences.Bottom.get -> double +Broadside.Annotations.PdfRectangleDifferences.Bottom.init -> void +Broadside.Annotations.PdfRectangleDifferences.Left.get -> double +Broadside.Annotations.PdfRectangleDifferences.Left.init -> void +Broadside.Annotations.PdfRectangleDifferences.PdfRectangleDifferences() -> void +Broadside.Annotations.PdfRectangleDifferences.PdfRectangleDifferences(double Left, double Top, double Right, double Bottom) -> void +Broadside.Annotations.PdfRectangleDifferences.Right.get -> double +Broadside.Annotations.PdfRectangleDifferences.Right.init -> void +Broadside.Annotations.PdfRectangleDifferences.Top.get -> double +Broadside.Annotations.PdfRectangleDifferences.Top.init -> void +Broadside.Annotations.PdfRedactAnnotation +Broadside.Annotations.PdfRedactAnnotation.DefaultAppearance.get -> string? +Broadside.Annotations.PdfRedactAnnotation.InteriorColor.get -> Broadside.Annotations.PdfDeviceColor? +Broadside.Annotations.PdfRedactAnnotation.Justification.get -> Broadside.Annotations.PdfTextJustification +Broadside.Annotations.PdfRedactAnnotation.Overlay.get -> Broadside.Graphics.PdfFormXObject? +Broadside.Annotations.PdfRedactAnnotation.OverlayText.get -> string? +Broadside.Annotations.PdfRedactAnnotation.QuadPoints.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Annotations.PdfRedactAnnotation.RepeatsOverlayText.get -> bool +Broadside.Annotations.PdfReplyType +Broadside.Annotations.PdfReplyType.Group = 1 -> Broadside.Annotations.PdfReplyType +Broadside.Annotations.PdfReplyType.Reply = 0 -> Broadside.Annotations.PdfReplyType +Broadside.Annotations.PdfRichMediaAnnotation +Broadside.Annotations.PdfRichMediaAnnotation.Content.get -> Broadside.Objects.CosDictionary? +Broadside.Annotations.PdfRichMediaAnnotation.Settings.get -> Broadside.Objects.CosDictionary? +Broadside.Annotations.PdfScreenAnnotation +Broadside.Annotations.PdfScreenAnnotation.Action.get -> Broadside.PdfAction? +Broadside.Annotations.PdfScreenAnnotation.AppearanceCharacteristics.get -> Broadside.Annotations.PdfAppearanceCharacteristics? +Broadside.Annotations.PdfScreenAnnotation.ScreenTitle.get -> string? +Broadside.Annotations.PdfSoundAnnotation +Broadside.Annotations.PdfSoundAnnotation.IconName.get -> string! +Broadside.Annotations.PdfSoundAnnotation.Sound.get -> Broadside.Objects.CosStream? +Broadside.Annotations.PdfSquareAnnotation +Broadside.Annotations.PdfSquareAnnotation.BorderEffect.get -> Broadside.Annotations.PdfBorderEffect? +Broadside.Annotations.PdfSquareAnnotation.InteriorColor.get -> Broadside.Annotations.PdfDeviceColor? +Broadside.Annotations.PdfSquareAnnotation.RectangleDifferences.get -> Broadside.Annotations.PdfRectangleDifferences? +Broadside.Annotations.PdfSquigglyAnnotation +Broadside.Annotations.PdfStampAnnotation +Broadside.Annotations.PdfStampAnnotation.IconName.get -> string? +Broadside.Annotations.PdfStrikeOutAnnotation +Broadside.Annotations.PdfTextAnnotation +Broadside.Annotations.PdfTextAnnotation.IconName.get -> string! +Broadside.Annotations.PdfTextAnnotation.IsOpen.get -> bool +Broadside.Annotations.PdfTextAnnotation.State.get -> string? +Broadside.Annotations.PdfTextAnnotation.StateModel.get -> string? +Broadside.Annotations.PdfTextJustification +Broadside.Annotations.PdfTextJustification.Centered = 1 -> Broadside.Annotations.PdfTextJustification +Broadside.Annotations.PdfTextJustification.Left = 0 -> Broadside.Annotations.PdfTextJustification +Broadside.Annotations.PdfTextJustification.Right = 2 -> Broadside.Annotations.PdfTextJustification +Broadside.Annotations.PdfTextMarkupAnnotation +Broadside.Annotations.PdfTextMarkupAnnotation.QuadPoints.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Annotations.PdfTrapNetAnnotation +Broadside.Annotations.PdfTrapNetAnnotation.AnnotationStates.get -> Broadside.Objects.CosArray? +Broadside.Annotations.PdfTrapNetAnnotation.FontFauxing.get -> Broadside.Objects.CosArray? +Broadside.Annotations.PdfTrapNetAnnotation.LastModified.get -> Broadside.PdfDate? +Broadside.Annotations.PdfTrapNetAnnotation.Version.get -> Broadside.Objects.CosArray? +Broadside.Annotations.PdfUnderlineAnnotation +Broadside.Annotations.PdfUnknownAnnotation +Broadside.Annotations.PdfWatermarkAnnotation +Broadside.Annotations.PdfWatermarkAnnotation.FixedPrint.get -> Broadside.Annotations.PdfFixedPrint? +Broadside.Annotations.PdfWidgetAnnotation +Broadside.Annotations.PdfWidgetAnnotation.Action.get -> Broadside.PdfAction? +Broadside.Annotations.PdfWidgetAnnotation.AppearanceCharacteristics.get -> Broadside.Annotations.PdfAppearanceCharacteristics? +Broadside.Annotations.PdfWidgetAnnotation.HighlightMode.get -> Broadside.Annotations.PdfHighlightMode +Broadside.Annotations.PdfWidgetAnnotation.Parent.get -> Broadside.Objects.CosDictionary? Broadside.Content.ClipEvent Broadside.Content.ClipEvent.ClipEvent() -> void Broadside.Content.ClipEvent.Ctm.get -> Broadside.Graphics.Matrix @@ -358,6 +679,19 @@ Broadside.Graphics.PathView.PathView() -> void Broadside.Graphics.PathView.PathView(System.ReadOnlySpan verbs, System.ReadOnlySpan points) -> void Broadside.Graphics.PathView.Points.get -> System.ReadOnlySpan Broadside.Graphics.PathView.Verbs.get -> System.ReadOnlySpan +Broadside.Graphics.PdfFormXObject +Broadside.Graphics.PdfFormXObject.BoundingBox.get -> Broadside.PdfRectangle? +Broadside.Graphics.PdfFormXObject.Decode() -> System.ReadOnlyMemory +Broadside.Graphics.PdfFormXObject.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Graphics.PdfFormXObject.Group.get -> Broadside.Objects.CosDictionary? +Broadside.Graphics.PdfFormXObject.IsForm.get -> bool +Broadside.Graphics.PdfFormXObject.Matrix.get -> Broadside.Graphics.Matrix +Broadside.Graphics.PdfFormXObject.OptionalContent.get -> Broadside.Objects.CosDictionary? +Broadside.Graphics.PdfFormXObject.Reference.get -> Broadside.Objects.CosReference? +Broadside.Graphics.PdfFormXObject.Resources.get -> Broadside.Objects.CosDictionary? +Broadside.Graphics.PdfFormXObject.Stream.get -> Broadside.Objects.CosStream! +Broadside.Graphics.PdfFormXObject.StructParent.get -> int? +Broadside.Graphics.PdfFormXObject.StructParents.get -> int? Broadside.Graphics.RenderingIntent Broadside.Graphics.RenderingIntent.AbsoluteColorimetric = 1 -> Broadside.Graphics.RenderingIntent Broadside.Graphics.RenderingIntent.Perceptual = 3 -> Broadside.Graphics.RenderingIntent @@ -437,6 +771,7 @@ Broadside.Objects.CosString.CosString(System.ReadOnlySpan bytes, bool hexa Broadside.Objects.CosString.DecodeText() -> string! Broadside.Objects.CosString.Equals(Broadside.Objects.CosString? other) -> bool Broadside.Objects.CosString.IsHexadecimal.get -> bool +Broadside.PdfPage.Annotations.get -> System.Collections.Generic.IReadOnlyList! Broadside.PdfPage.ProcessContent(Broadside.Content.ContentProcessor! processor) -> void Broadside.PdfPage.ProcessContent(Broadside.Content.ContentProcessor! processor, Broadside.Content.ContentOptions! options) -> void const Broadside.Content.ContentOptions.DefaultMaxNestingDepth = 50 -> int @@ -769,6 +1104,12 @@ Broadside.PdfVisibilityPolicy.AllOn = 0 -> Broadside.PdfVisibilityPolicy Broadside.PdfVisibilityPolicy.AnyOff = 2 -> Broadside.PdfVisibilityPolicy Broadside.PdfVisibilityPolicy.AnyOn = 1 -> Broadside.PdfVisibilityPolicy const Broadside.Objects.CosReference.MaxGeneration = 65535 -> int +override Broadside.Annotations.PdfDeviceColor.Equals(object? obj) -> bool +override Broadside.Annotations.PdfDeviceColor.GetHashCode() -> int +override Broadside.Annotations.PdfDeviceColor.ToString() -> string! +override Broadside.Annotations.PdfQuadrilateral.Equals(object? obj) -> bool +override Broadside.Annotations.PdfQuadrilateral.GetHashCode() -> int +override Broadside.Annotations.PdfQuadrilateral.ToString() -> string! override Broadside.Content.CompositeContentProcessor.BeginForm(in Broadside.Content.FormEvent form, Broadside.Content.ContentContext! context) -> Broadside.Content.ContentVisit override Broadside.Content.CompositeContentProcessor.BeginMarkedContent(in Broadside.Content.MarkedContentEvent mc, Broadside.Content.ContentContext! context) -> void override Broadside.Content.CompositeContentProcessor.BeginRun(Broadside.Content.ContentContext! context) -> void @@ -811,6 +1152,9 @@ override Broadside.Objects.CosReference.GetHashCode() -> int override Broadside.Objects.CosStream.IsDirty.get -> bool override Broadside.Objects.CosString.Equals(object? obj) -> bool override Broadside.Objects.CosString.GetHashCode() -> int +static Broadside.Annotations.PdfAnnotation.ComputeAppearanceMatrix(Broadside.PdfRectangle rect, Broadside.PdfRectangle boundingBox, Broadside.Graphics.Matrix matrix) -> Broadside.Graphics.Matrix? +static Broadside.Annotations.PdfQuadrilateral.operator !=(Broadside.Annotations.PdfQuadrilateral left, Broadside.Annotations.PdfQuadrilateral right) -> bool +static Broadside.Annotations.PdfQuadrilateral.operator ==(Broadside.Annotations.PdfQuadrilateral left, Broadside.Annotations.PdfQuadrilateral right) -> bool static Broadside.Graphics.Matrix.CreateScale(double sx, double sy) -> Broadside.Graphics.Matrix static Broadside.Graphics.Matrix.CreateTranslation(double tx, double ty) -> Broadside.Graphics.Matrix static Broadside.Graphics.Matrix.Identity.get -> Broadside.Graphics.Matrix diff --git a/tests/Broadside.Fuzz/Broadside.Fuzz.csproj b/tests/Broadside.Fuzz/Broadside.Fuzz.csproj index 06860c0b..db17b653 100644 --- a/tests/Broadside.Fuzz/Broadside.Fuzz.csproj +++ b/tests/Broadside.Fuzz/Broadside.Fuzz.csproj @@ -19,6 +19,8 @@ + + diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 0608bccc..eadaddf8 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -115,6 +115,30 @@ private static void Document(ReadOnlySpan data) } Navigation(document); + Annotations(document); + } + + /// + /// Reads every annotation of every page with every appearance (issue #71) and checks what the model promises: every rectangle + /// normalized, every annotation on the page that lists it, the same view for the same dictionary. + /// + /// ISO 32000-2 §12.5. + private static void Annotations(PdfDocument document) + { + _ = Broadside.TestSupport.AnnotationWalker.Walk(document); + foreach (PdfPage page in document.Pages) + { + IReadOnlyList annotations = page.Annotations; + for (int index = 0; index < annotations.Count; index++) + { + Broadside.Annotations.PdfAnnotation annotation = annotations[index]; + PdfRectangle rect = annotation.Rect; + if (!(rect.Left <= rect.Right && rect.Bottom <= rect.Top) || annotation.Page is null || !ReferenceEquals(annotation, page.Annotations[index])) + { + throw new InvalidOperationException("An annotation's rectangle is not normalized, it has no page, or a second read gave another view."); + } + } + } } /// diff --git a/tests/Broadside.TestSupport/AnnotationWalker.cs b/tests/Broadside.TestSupport/AnnotationWalker.cs new file mode 100644 index 00000000..52786b66 --- /dev/null +++ b/tests/Broadside.TestSupport/AnnotationWalker.cs @@ -0,0 +1,106 @@ +using System.Reflection; +using System.Runtime.ExceptionServices; +using Broadside.Annotations; +using Broadside.Graphics; +using Broadside.Objects; + +namespace Broadside.TestSupport; + +/// +/// Reads everything the annotation model exposes (issue #71): every public property of every annotation of every page, of its +/// appearance dictionary, entries, appearance characteristics and fixed print dictionary, every appearance in every mode with its +/// placement matrix, and every appearance state. Public API only (reflection over public properties, so a property added later is +/// read too). Exceptions the library throws propagate unwrapped. +/// +/// ISO 32000-2 §12.5. +public static class AnnotationWalker +{ + private static readonly PdfAppearanceMode[] Modes = [PdfAppearanceMode.Normal, PdfAppearanceMode.Rollover, PdfAppearanceMode.Down]; + + /// Walks the annotations of every page of . + /// An open document. + /// The number of annotations read (an annotation listed twice counts twice). + public static int Walk(PdfDocument document) + { + ArgumentNullException.ThrowIfNull(document); + int count = 0; + foreach (PdfPage page in document.Pages) + { + foreach (PdfAnnotation annotation in page.Annotations) + { + count++; + ReadProperties(annotation); + if (annotation.AppearanceDictionary is { } appearance) + { + ReadProperties(appearance); + foreach (PdfAppearanceMode mode in Modes) + { + if (appearance.GetEntry(mode) is { } entry) + { + ReadProperties(entry); + foreach (CosName state in entry.StateNames) + { + ReadForm(annotation, entry.GetAppearance(state)); + } + } + + ReadForm(annotation, annotation.GetAppearance(mode)); + } + } + + switch (annotation) + { + case PdfWidgetAnnotation { AppearanceCharacteristics: { } characteristics }: + ReadProperties(characteristics); + break; + case PdfScreenAnnotation { AppearanceCharacteristics: { } characteristics }: + ReadProperties(characteristics); + break; + case PdfWatermarkAnnotation { FixedPrint: { } fixedPrint }: + ReadProperties(fixedPrint); + break; + } + } + } + + return count; + } + + private static void ReadForm(PdfAnnotation annotation, PdfFormXObject? form) + { + if (form is not null) + { + ReadProperties(form); + _ = annotation.GetAppearanceMatrix(form); + _ = form.Decode().Length; + } + } + + private static void ReadProperties(object view) + { + foreach (PropertyInfo property in view.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + if (property.GetIndexParameters().Length > 0) + { + continue; + } + + try + { + object? value = property.GetValue(view); + if (value is System.Collections.IEnumerable sequence and not string and not CosObject) + { + foreach (object? item in sequence) + { + _ = item; + } + } + } + catch (TargetInvocationException exception) when (exception.InnerException is not null) + { + ExceptionDispatchInfo.Capture(exception.InnerException).Throw(); + throw; + } + } + } +} diff --git a/tests/Broadside.TestSupport/Corpus.cs b/tests/Broadside.TestSupport/Corpus.cs index 942b4dbc..421581b3 100644 --- a/tests/Broadside.TestSupport/Corpus.cs +++ b/tests/Broadside.TestSupport/Corpus.cs @@ -46,6 +46,8 @@ public static class Corpus "inline-image.pdf", "page-tree-inherited.pdf", "annotations-link.pdf", + "annotations-subtypes.pdf", + "annotations-appearance.pdf", "outline.pdf", "name-tree-dests.pdf", "metadata-xmp.pdf", @@ -80,6 +82,7 @@ public static class Corpus "encrypted-rc4-length-missing.pdf", "name-tree-broken.pdf", "outline-broken.pdf", + "annotations-malformed.pdf", ]; private static readonly (string FileName, string UserPassword)[] PasswordProtected = diff --git a/tests/Broadside.TestSupport/DocumentWalker.cs b/tests/Broadside.TestSupport/DocumentWalker.cs index 4c198c04..bab844f1 100644 --- a/tests/Broadside.TestSupport/DocumentWalker.cs +++ b/tests/Broadside.TestSupport/DocumentWalker.cs @@ -13,7 +13,7 @@ public sealed record DocumentWalkResult(int Pages, int Objects, int Streams, lon /// /// Reads everything the document model exposes, so that "the file opens" means more than "the trailer parsed" (objects load /// lazily, issue #45): version, trailer, revisions, linearization and hint tables, security, every page's boxes, rotation, user unit -/// and resources, the outline and every named destination (issue #70), every indirect object reachable from the trailer and every object number below the trailer's Size, and +/// and resources, the outline and every named destination (issue #70), every annotation with its appearances (issue #71), every indirect object reachable from the trailer and every object number below the trailer's Size, and /// every stream decoded through the filter pipeline (image filters that are not implemented yet end in a diagnostic, not an /// exception). Used by the real-world corpus gate (issue #47) and meant to be shared with the open-and-walk fuzz target and /// benchmark (issue #48): link this file as source there, as is. Public API only. @@ -60,6 +60,7 @@ public static DocumentWalkResult Walk(PdfDocument document) ReadCatalogEssentials(document); WalkNavigation(document); + _ = AnnotationWalker.Walk(document); var walk = new GraphWalk(document); walk.Visit(document.Trailer); diff --git a/tests/Broadside.Tests/Annotations/AnnotationSubtypeTests.cs b/tests/Broadside.Tests/Annotations/AnnotationSubtypeTests.cs new file mode 100644 index 00000000..74635d87 --- /dev/null +++ b/tests/Broadside.Tests/Annotations/AnnotationSubtypeTests.cs @@ -0,0 +1,248 @@ +using Broadside.Annotations; +using Broadside.Graphics; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Annotations; + +/// Every annotation type of ISO 32000-2 Table 171 and its entries (§12.5.6, Tables 172 to 195, 309, 333, 398, 403). +public class AnnotationSubtypeTests +{ + [Fact] + public void Annotations_subtypes_pdf_maps_each_standard_subtype_to_its_class_and_an_unknown_one_to_the_generic_class() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("annotations-subtypes.pdf")); + + IReadOnlyList annotations = document.Pages[0].Annotations; + + Assert.Equal( + [ + "Text PdfTextAnnotation", "Popup PdfPopupAnnotation", "Text PdfTextAnnotation", "Link PdfLinkAnnotation", + "FreeText PdfFreeTextAnnotation", "Line PdfLineAnnotation", "Square PdfSquareAnnotation", "Circle PdfCircleAnnotation", + "Polygon PdfPolygonAnnotation", "PolyLine PdfPolyLineAnnotation", "Highlight PdfHighlightAnnotation", + "Underline PdfUnderlineAnnotation", "Squiggly PdfSquigglyAnnotation", "StrikeOut PdfStrikeOutAnnotation", + "Caret PdfCaretAnnotation", "Stamp PdfStampAnnotation", "Ink PdfInkAnnotation", + "FileAttachment PdfFileAttachmentAnnotation", "Sound PdfSoundAnnotation", "Movie PdfMovieAnnotation", + "Screen PdfScreenAnnotation", "Widget PdfWidgetAnnotation", "PrinterMark PdfPrinterMarkAnnotation", + "Watermark PdfWatermarkAnnotation", "ThreeD Pdf3DAnnotation", "Redact PdfRedactAnnotation", + "Projection PdfProjectionAnnotation", "RichMedia PdfRichMediaAnnotation", "Unknown PdfUnknownAnnotation", + "TrapNet PdfTrapNetAnnotation", + ], + annotations.Select(annotation => $"{annotation.Kind} {annotation.GetType().Name}")); + Assert.Equal(28, annotations.Select(annotation => annotation.Kind).Where(kind => kind != PdfAnnotationKind.Unknown).Distinct().Count()); + Assert.Equal(new CosName("XBroadsideTest"), annotations[28].Subtype); + Assert.Equal(new CosName("3D"), annotations[24].Subtype); + Assert.All(annotations, annotation => Assert.Same(document.Pages[0], annotation.Page)); + Assert.Same(annotations[0], document.Pages[0].Annotations[0]); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Reading_every_entry_of_every_annotation_records_nothing_and_changes_nothing() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("annotations-subtypes.pdf")); + + int read = AnnotationWalker.Walk(document); + + Assert.Equal(30, read); + Assert.Empty(document.Diagnostics); + Assert.False(document.Pages[0].Dictionary.IsDirty); + Assert.All(document.Pages[0].Annotations, annotation => Assert.False(annotation.Dictionary.IsDirty)); + } + + [Fact] + public void Concurrent_readers_get_the_same_view_for_each_annotation() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("annotations-subtypes.pdf")); + var results = new PdfAnnotation?[64][]; + + Parallel.For(0, results.Length, index => + { + IReadOnlyList annotations = document.Pages[0].Annotations; + results[index] = [.. annotations, ((PdfTextAnnotation)annotations[2]).InReplyTo, ((PdfPopupAnnotation)annotations[1]).Parent]; + }); + + Assert.All(results, result => Assert.Equal(results[0], result, ReferenceEqualityComparer.Instance)); + Assert.Same(results[0][0], results[0][30]); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Flags_colours_borders_and_markup_entries_are_exposed() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("annotations-subtypes.pdf")); + IReadOnlyList annotations = document.Pages[0].Annotations; + + PdfTextAnnotation note = Assert.IsType(annotations[0]); + Assert.Equal(PdfAnnotationFlags.Print | PdfAnnotationFlags.NoZoom | PdfAnnotationFlags.NoRotate, note.Flags); + Assert.Equal(new PdfDeviceColor(1, 1, 0), note.Color); + Assert.Equal(PdfDeviceColorSpace.Rgb, note.Color!.ColorSpace); + Assert.Equal(("Note text", "note-1", "Alice", "Review"), (note.Contents, note.Name, note.Title, note.Subject)); + Assert.Equal("D:20240102030405Z", note.ModifiedText); + Assert.Equal(new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero), note.Modified?.Value); + Assert.Equal(new DateTimeOffset(2024, 1, 1, 12, 0, 0, TimeSpan.Zero), note.CreationDate?.Value); + Assert.Equal(("Comment", true), (note.IconName, note.IsOpen)); + Assert.Null(note.State); + Assert.Equal(PdfBorderSource.Default, note.Border.Source); + Assert.Equal((1.0, PdfBorderStyle.Solid), (note.Border.Width, note.Border.Style)); + + PdfAnnotation unknown = annotations[28]; + Assert.Equal( + PdfAnnotationFlags.Invisible | PdfAnnotationFlags.Hidden | PdfAnnotationFlags.Print | PdfAnnotationFlags.NoZoom + | PdfAnnotationFlags.NoRotate | PdfAnnotationFlags.NoView | PdfAnnotationFlags.ReadOnly | PdfAnnotationFlags.Locked + | PdfAnnotationFlags.ToggleNoView | PdfAnnotationFlags.LockedContents, + unknown.Flags); + + PdfSquareAnnotation square = Assert.IsType(annotations[6]); + Assert.Equal((2.0, PdfBorderStyle.Dashed, PdfBorderSource.BorderStyle), (square.Border.Width, square.Border.Style, square.Border.Source)); + Assert.Equal([3.0, 2.0], square.Border.DashPattern); + Assert.Equal(new PdfDeviceColor(0, 0, 1), square.InteriorColor); + Assert.Equal((PdfBorderEffectStyle.Cloudy, 1.0), (square.BorderEffect!.Style, square.BorderEffect.Intensity)); + Assert.Equal(new PdfRectangleDifferences(1, 2, 3, 4), square.RectangleDifferences); + + PdfCircleAnnotation circle = Assert.IsType(annotations[7]); + Assert.Equal((2.0, PdfBorderStyle.Dashed, PdfBorderSource.BorderArray), (circle.Border.Width, circle.Border.Style, circle.Border.Source)); + Assert.Equal([4.0, 1.0], circle.Border.DashPattern); + Assert.Equal(PdfDeviceColorSpace.Gray, circle.InteriorColor!.ColorSpace); + Assert.Equal(PdfDeviceColorSpace.Cmyk, circle.Color!.ColorSpace); + Assert.Null(circle.BorderEffect); + + PdfLinkAnnotation link = Assert.IsType(annotations[3]); + Assert.Equal((2.0, PdfBorderStyle.Underline), (link.Border.Width, link.Border.Style)); + Assert.Equal(PdfHighlightMode.Outline, link.HighlightMode); + Assert.Equal(new PdfQuadrilateral(new PathPoint(222, 702), new PathPoint(278, 702), new PathPoint(278, 738), new PathPoint(222, 738)), Assert.Single(link.QuadPoints)); + Assert.Equal(link.QuadPoints, link.ActivationRegion); + PdfExplicitDestination destination = Assert.IsType(link.Destination); + Assert.Equal((PdfDestinationView.Fit, (int?)0), (destination.View, destination.PageIndex)); + Assert.Null(link.Action); + + PdfStrikeOutAnnotation strikeOut = Assert.IsType(annotations[13]); + Assert.Equal(2, strikeOut.QuadPoints.Count); + Assert.Equal(new PdfRectangle(60, 70, 90, 80), strikeOut.QuadPoints[1].Bounds); + Assert.Equal(new PathPoint(10, 10), Assert.IsType(annotations[10]).QuadPoints[0].Point1); + + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Popup_and_parent_refer_to_each_other_and_replies_carry_their_state() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("annotations-subtypes.pdf")); + IReadOnlyList annotations = document.Pages[0].Annotations; + + PdfTextAnnotation note = (PdfTextAnnotation)annotations[0]; + PdfPopupAnnotation popup = Assert.IsType(note.Popup); + Assert.Same(annotations[1], popup); + Assert.Same(note, popup.Parent); + Assert.True(popup.IsOpen); + Assert.Null(popup.AppearanceDictionary); + + PdfTextAnnotation reply = Assert.IsType(annotations[2]); + Assert.Same(note, reply.InReplyTo); + Assert.Equal(PdfReplyType.Reply, reply.ReplyType); + Assert.Equal(("Accepted", "Review", "Bob"), (reply.State, reply.StateModel, reply.Title)); + Assert.Equal("Note", reply.IconName); + Assert.Null(note.InReplyTo); + Assert.Null(reply.Popup); + + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Subtype_specific_entries_are_typed() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("annotations-subtypes.pdf")); + IReadOnlyList annotations = document.Pages[0].Annotations; + + PdfFreeTextAnnotation freeText = Assert.IsType(annotations[4]); + Assert.Equal(("/Helv 12 Tf 0 g", PdfTextJustification.Centered), (freeText.DefaultAppearance, freeText.Justification)); + Assert.Equal(new CosName("FreeTextCallout"), freeText.Intent); + Assert.Equal([new PathPoint(10, 10), new PathPoint(50, 50), new PathPoint(60, 50)], freeText.CalloutLine); + Assert.Equal(PdfLineEnding.OpenArrow, freeText.LineEnding); + Assert.Equal(("font: 12pt Helvetica", "

rich

"), (freeText.DefaultStyle, freeText.RichText)); + + PdfLineAnnotation line = Assert.IsType(annotations[5]); + Assert.Equal((new PathPoint(100, 100), new PathPoint(200, 200)), (line.Start, line.End)); + Assert.Equal((PdfLineEnding.Circle, PdfLineEnding.ClosedArrow), (line.StartLineEnding, line.EndLineEnding)); + Assert.Equal(new PdfDeviceColor(1, 0, 0), line.InteriorColor); + Assert.Equal((10.0, 2.0, 1.0, true), (line.LeaderLineLength, line.LeaderLineExtension, line.LeaderLineOffset, line.HasCaption)); + Assert.Equal((PdfLineCaptionPosition.Top, new PathPoint(0, 5)), (line.CaptionPosition, line.CaptionOffset)); + Assert.Null(line.Measure); + + PdfPolygonAnnotation polygon = Assert.IsType(annotations[8]); + Assert.Equal([new PathPoint(10, 10), new PathPoint(50, 10), new PathPoint(30, 40)], polygon.Vertices); + Assert.Null(polygon.Path); + Assert.Equal(2, polygon.BorderEffect!.Intensity); + + PdfPolyLineAnnotation polyLine = Assert.IsType(annotations[9]); + Assert.Empty(polyLine.Vertices); + Assert.Equal([[10.0, 10], [50.0, 10], [60.0, 20, 70, 30, 80, 10]], polyLine.Path!); + Assert.Equal((PdfLineEnding.Square, PdfLineEnding.Slash), (polyLine.StartLineEnding, polyLine.EndLineEnding)); + + PdfCaretAnnotation caret = Assert.IsType(annotations[14]); + Assert.Equal((PdfCaretSymbol.Paragraph, new PdfRectangleDifferences(1, 1, 1, 1)), (caret.Symbol, caret.RectangleDifferences)); + + PdfStampAnnotation stamp = Assert.IsType(annotations[15]); + Assert.Null(stamp.IconName); + Assert.Equal(new CosName("StampImage"), stamp.Intent); + + PdfInkAnnotation ink = Assert.IsType(annotations[16]); + Assert.Equal([3, 2], ink.InkList.Select(path => path.Count)); + Assert.Equal(new PathPoint(50, 50), ink.InkList[1][1]); + + PdfFileAttachmentAnnotation attachment = Assert.IsType(annotations[17]); + Assert.Equal(("Paperclip", "a.txt", "An attached file"), (attachment.IconName, attachment.FileSpecification?.FileName, attachment.Contents)); + Assert.Equal("attached"u8.ToArray(), attachment.FileSpecification!.EmbeddedFile!.Decode().ToArray()); + Assert.Equal("a.txt", Assert.Single(attachment.AssociatedFiles).FileName); + + PdfSoundAnnotation sound = Assert.IsType(annotations[18]); + Assert.Equal((4, "Mic"), (sound.Sound!.EncodedData.Length, sound.IconName)); + + PdfMovieAnnotation movie = Assert.IsType(annotations[19]); + Assert.Equal("Clip", movie.MovieTitle); + Assert.NotNull(movie.Movie); + Assert.Equal(CosBoolean.False, movie.Activation); + + PdfScreenAnnotation screen = Assert.IsType(annotations[20]); + Assert.Equal("Screen", screen.ScreenTitle); + Assert.Equal((90, "Play"), (screen.AppearanceCharacteristics!.Rotation, screen.AppearanceCharacteristics.NormalCaption)); + Assert.Equal((new PdfDeviceColor(1, 0, 0), new PdfDeviceColor(1)), (screen.AppearanceCharacteristics.BorderColor, screen.AppearanceCharacteristics.BackgroundColor)); + Assert.Equal("https://example.org/media", Assert.IsType(screen.Action).Uri); + + PdfWidgetAnnotation widget = Assert.IsType(annotations[21]); + Assert.Equal((PdfHighlightMode.Push, "Push", 0), (widget.HighlightMode, widget.AppearanceCharacteristics!.NormalCaption, widget.AppearanceCharacteristics.TextPosition)); + Assert.Null(widget.Parent); + Assert.Null(widget.Action); + + PdfPrinterMarkAnnotation mark = Assert.IsType(annotations[22]); + Assert.Equal((new CosName("ColorBar"), PdfAnnotationFlags.Print | PdfAnnotationFlags.ReadOnly), (mark.MarkName, mark.Flags)); + + PdfWatermarkAnnotation watermark = Assert.IsType(annotations[23]); + Assert.Equal((new Matrix(1, 0, 0, 1, 72, -72), 0.0, 1.0, true), (watermark.FixedPrint!.Matrix, watermark.FixedPrint.HorizontalTranslation, watermark.FixedPrint.VerticalTranslation, watermark.FixedPrint.HasValidType)); + + Pdf3DAnnotation model = Assert.IsType(annotations[24]); + Assert.IsType(model.Artwork); + Assert.Equal((false, new PdfRectangle(0, 0, 60, 40)), (model.IsInteractive, model.ViewBox)); + Assert.Null(model.DefaultView); + + PdfRedactAnnotation redact = Assert.IsType(annotations[25]); + Assert.Equal(("X", true, "/Helv 10 Tf 0 g", PdfTextJustification.Right), (redact.OverlayText, redact.RepeatsOverlayText, redact.DefaultAppearance, redact.Justification)); + Assert.Single(redact.QuadPoints); + Assert.Null(redact.Overlay); + + PdfProjectionAnnotation projection = Assert.IsType(annotations[26]); + Assert.Equal(default, projection.Rect); + Assert.Null(projection.AppearanceDictionary); + + PdfRichMediaAnnotation richMedia = Assert.IsType(annotations[27]); + Assert.NotNull(richMedia.Content); + Assert.NotNull(richMedia.Settings); + + PdfTrapNetAnnotation trapNet = Assert.IsType(annotations[29]); + Assert.Equal(new DateTimeOffset(2024, 1, 1, 0, 0, 0, TimeSpan.Zero), trapNet.LastModified?.Value); + Assert.Equal(new CosName("T1"), trapNet.AppearanceState); + Assert.NotNull(trapNet.GetAppearance()); + + Assert.Empty(document.Diagnostics); + } +} diff --git a/tests/Broadside.Tests/Annotations/AppearanceTests.cs b/tests/Broadside.Tests/Annotations/AppearanceTests.cs new file mode 100644 index 00000000..5ad63bce --- /dev/null +++ b/tests/Broadside.Tests/Annotations/AppearanceTests.cs @@ -0,0 +1,95 @@ +using Broadside.Annotations; +using Broadside.Graphics; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Annotations; + +/// Appearance streams (ISO 32000-2 §12.5.5, Table 170) and Algorithm "Appearance streams". +public class AppearanceTests +{ + public static TheoryData AlgorithmVectors => new() + { + // (a) rotated form matrix: T = (-50, 0, 0, 100), A = [1 0 0 1 150 100]. + { [100, 100, 150, 200], [0, 0, 100, 50], [0, 1, -1, 0, 0, 0], [0, 1, -1, 0, 150, 100] }, + + // (b) identity matrix, scaled to the rectangle. + { [10, 10, 50, 30], [0, 0, 20, 20], [1, 0, 0, 1, 0, 0], [2, 0, 0, 1, 10, 10] }, + + // (c) the same rectangle written unnormalized (§7.9.5) gives the same matrix. + { [50, 30, 10, 10], [0, 0, 20, 20], [1, 0, 0, 1, 0, 0], [2, 0, 0, 1, 10, 10] }, + + // A bounding box offset from the origin maps its lower-left corner to the rectangle's. + { [0, 0, 10, 10], [5, 5, 15, 15], [1, 0, 0, 1, 0, 0], [1, 0, 0, 1, -5, -5] }, + + // Degenerate: a zero-area bounding box or rectangle cannot be drawn. + { [10, 10, 50, 30], [0, 0, 0, 0], [1, 0, 0, 1, 0, 0], null }, + { [10, 10, 10, 10], [0, 0, 20, 20], [1, 0, 0, 1, 0, 0], null }, + }; + + [Theory] + [MemberData(nameof(AlgorithmVectors))] + public void The_appearance_matrix_maps_the_transformed_bounding_box_onto_the_rectangle(double[] rect, double[] bbox, double[] matrix, double[]? expected) + { + Matrix? actual = PdfAnnotation.ComputeAppearanceMatrix( + new PdfRectangle(rect[0], rect[1], rect[2], rect[3]), + new PdfRectangle(bbox[0], bbox[1], bbox[2], bbox[3]), + new Matrix(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5])); + + Assert.Equal(expected is null ? null : new Matrix(expected[0], expected[1], expected[2], expected[3], expected[4], expected[5]), actual); + } + + [Fact] + public void A_form_point_lands_where_the_algorithm_puts_it() + { + Matrix aa = PdfAnnotation.ComputeAppearanceMatrix(new PdfRectangle(100, 100, 150, 200), new PdfRectangle(0, 0, 100, 50), new Matrix(0, 1, -1, 0, 0, 0))!.Value; + + Assert.Equal(new PathPoint(100, 200), aa.Transform(100, 50)); + Assert.Equal(new PathPoint(150, 100), aa.Transform(0, 0)); + } + + [Fact] + public void Annotations_appearance_pdf_places_each_appearance_on_its_rectangle() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("annotations-appearance.pdf")); + IReadOnlyList annotations = document.Pages[0].Annotations; + + PdfFormXObject rotated = annotations[0].GetAppearance()!; + Assert.Equal((new PdfRectangle(0, 0, 100, 50), new Matrix(0, 1, -1, 0, 0, 0)), (rotated.BoundingBox, rotated.Matrix)); + Assert.Equal(new Matrix(0, 1, -1, 0, 150, 100), annotations[0].GetAppearanceMatrix(rotated)); + Assert.Equal("1 0 0 rg 0 0 100 50 re f"u8.ToArray(), rotated.Decode().ToArray()); + Assert.True(rotated.IsForm); + + PdfAnnotation circle = annotations[1]; + Assert.Equal(new PdfRectangle(10, 10, 50, 30), circle.Rect); + Assert.Equal(new Matrix(2, 0, 0, 1, 10, 10), circle.GetAppearanceMatrix(circle.GetAppearance()!)); + + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void States_select_the_appearance_and_missing_entries_fall_back_to_the_normal_one() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("annotations-appearance.pdf")); + PdfAnnotation square = document.Pages[0].Annotations[2]; + PdfAppearanceDictionary appearance = square.AppearanceDictionary!; + var on = new CosName("On"); + var off = new CosName("Off"); + + Assert.Equal(on, square.AppearanceState); + Assert.True(appearance.Normal!.HasStates); + Assert.Null(appearance.Normal.Form); + Assert.Equal([on, off], appearance.Normal.StateNames); + Assert.False(appearance.HasRollover); + Assert.True(appearance.HasDown); + + Assert.Equal(new CosReference(6, 0), square.GetAppearance()!.Reference); + Assert.Equal(new CosReference(6, 0), square.GetAppearance(PdfAppearanceMode.Rollover)!.Reference); + Assert.Equal(new CosReference(8, 0), square.GetAppearance(PdfAppearanceMode.Down)!.Reference); + Assert.Equal(new CosReference(7, 0), square.GetAppearance(PdfAppearanceMode.Normal, off)!.Reference); + Assert.Equal(new CosReference(7, 0), square.GetAppearance(PdfAppearanceMode.Down, off)!.Reference); + Assert.Null(square.GetAppearance(PdfAppearanceMode.Normal, new CosName("Missing"))); + + Assert.Empty(document.Diagnostics); + } +} diff --git a/tests/Broadside.Tests/Annotations/LinkAnnotationTests.cs b/tests/Broadside.Tests/Annotations/LinkAnnotationTests.cs new file mode 100644 index 00000000..1eab2384 --- /dev/null +++ b/tests/Broadside.Tests/Annotations/LinkAnnotationTests.cs @@ -0,0 +1,32 @@ +using Broadside.Annotations; +using Broadside.TestSupport; + +namespace Broadside.Tests.Annotations; + +/// Link annotations (ISO 32000-2 §12.5.6.5, Table 176) and the common entries they share (§12.5.2, Table 166). +public class LinkAnnotationTests +{ + [Fact] + public void Annotations_link_pdf_yields_one_link_whose_action_is_a_uri_action() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("annotations-link.pdf")); + + PdfLinkAnnotation link = Assert.IsType(Assert.Single(document.Pages[0].Annotations)); + + Assert.Equal(PdfAnnotationKind.Link, link.Kind); + Assert.Equal("Link", link.Subtype?.Value); + Assert.Equal(new PdfRectangle(72, 700, 300, 724), link.Rect); + PdfUriAction action = Assert.IsType(link.Action); + Assert.Equal("https://example.com/", action.Uri); + Assert.Null(link.Destination); + Assert.Equal(0, link.Border.Width); + Assert.Equal(PdfBorderStyle.Solid, link.Border.Style); + Assert.Equal(PdfHighlightMode.Invert, link.HighlightMode); + Assert.Null(link.AppearanceDictionary); + Assert.Null(link.GetAppearance()); + Assert.Same(document.Pages[0], link.Page); + Assert.Equal(PdfAnnotationFlags.None, link.Flags); + Assert.Empty(link.QuadPoints); + Assert.Empty(document.Diagnostics); + } +} diff --git a/tests/Broadside.Tests/Annotations/MalformedAnnotationTests.cs b/tests/Broadside.Tests/Annotations/MalformedAnnotationTests.cs new file mode 100644 index 00000000..eaa1defd --- /dev/null +++ b/tests/Broadside.Tests/Annotations/MalformedAnnotationTests.cs @@ -0,0 +1,203 @@ +using Broadside.Annotations; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Tests.Document; +using Broadside.TestSupport; + +namespace Broadside.Tests.Annotations; + +/// Real-world deviations in Annots arrays and annotation dictionaries: lenient repairs with diagnostics, strict throws (ISO 32000-2 §12.5, ADR 0005). +public class MalformedAnnotationTests +{ + [Fact] + public void Annotations_malformed_pdf_reads_what_it_can_with_exactly_the_documented_diagnostics() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("annotations-malformed.pdf")); + Assert.Empty(document.Diagnostics); + + IReadOnlyList first = document.Pages[0].Annotations; + + Assert.Equal( + ["Square 10", "Square 10", "Unknown 11", "Circle 12", "Highlight 13", "Square 14", "Square 15", "Square 16", "Square -"], + first.Select(annotation => $"{annotation.Kind} {annotation.Reference?.ObjectNumber.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "-"}")); + Assert.Same(first[0], first[1]); + Assert.Equal( + [ + "AnnotationEntryInvalid 3", // element 0 is null + "AnnotationEntryInvalid 9", // element 1 refers to an integer + "AnnotationDuplicate 10", + "AnnotationSubtypeMissing 11", + "AnnotationPageMismatch 16", // P names page 4 + "AnnotationNotIndirect 3", + ], + document.Diagnostics.Select(Describe)); + + Assert.Equal(default, first[3].Rect); + Assert.Empty(((PdfHighlightAnnotation)first[4]).QuadPoints); + Assert.Null(first[5].GetAppearance()); + Assert.NotNull(first[6].GetAppearance()); + Assert.Null(first[6].GetAppearance()!.BoundingBox); + Assert.Equal(new Broadside.Graphics.Matrix(1, 0, 0, 1, 90, 10), first[6].GetAppearanceMatrix(first[6].GetAppearance()!)); + + IReadOnlyList second = document.Pages[1].Annotations; + Assert.Same(first[7], second[0]); + Assert.Same(document.Pages[0], second[0].Page); + + PdfTextAnnotation text = Assert.IsType(second[1]); + Assert.Equal(PdfReplyType.Group, text.ReplyType); + Assert.Same(second[2], text.Popup); + Assert.Equal("Accepted", text.State); + Assert.Equal((PdfAnnotationFlags)2048, text.Flags); + Assert.Null(text.Color); + Assert.Equal((0.0, PdfBorderSource.BorderArray), (text.Border.Width, text.Border.Source)); + Assert.Same(second[3], ((PdfPopupAnnotation)second[2]).Parent); + PdfLinkAnnotation link = Assert.IsType(second[3]); + Assert.IsType(link.Action); + Assert.IsType(link.Destination); + + Assert.Equal( + [ + "AnnotationFlagsInvalid 17", + "AnnotationRectInvalid 12", + "AnnotationSharedAcrossPages 16", + "AppearanceBBoxMissing 15", + "AppearanceStateMissing 14", + "BorderArrayInvalid 17", + "ColorArrayInvalid 17", + "LinkActionAndDest 19", + "PopupLinkMismatch 17", + "PopupParentInvalid 18", + "QuadPointsInvalid 13", + "ReplyTypeWithoutInReplyTo 17", + "StateModelMissing 17", + ], + document.Diagnostics.Skip(6).Select(Describe).Order(StringComparer.Ordinal)); + + int count = document.Diagnostics.Count; + AnnotationWalker.Walk(document); + Assert.Equal(count, document.Diagnostics.Count); + } + + [Fact] + public void Strict_mode_throws_from_the_annotation_list_not_from_open() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("annotations-malformed.pdf"), new PdfOptions().UseStrict()); + PdfPage page = document.Pages[0]; + + DiagnosticException error = Assert.Throws(() => page.Annotations); + + Assert.Equal("AnnotationEntryInvalid", error.Diagnostic.Code); + } + + [Fact] + public void Strict_mode_throws_from_the_property_that_reads_a_malformed_entry() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> /Annots [4 0 R] >>", + "<< /Type /Annot /Subtype /Square /Rect [0 0 10] >>"); + using PdfDocument document = PdfDocument.Open(file, new PdfOptions().UseStrict()); + PdfAnnotation square = Assert.Single(document.Pages[0].Annotations); + + Assert.Equal("AnnotationRectInvalid", Assert.Throws(() => square.Rect).Diagnostic.Code); + } + + public static TheoryData ArrayAndTypeDeviations => new() + { + { "/Annots 5 0 R", "AnnotsInvalid", "/Type /Annot /Subtype /Square" }, + { "/Annots [4 0 R]", "AnnotationSubtypeNotName", "/Type /Annot /Subtype (Square)" }, + { "/Annots [4 0 R]", "AnnotationTypeInvalid", "/Type /Annotation /Subtype /Square" }, + { "/Annots [4 0 R]", "AnnotationSubtypeMissing", "/Type /Annot /Subtype <00>" }, + }; + + [Theory] + [MemberData(nameof(ArrayAndTypeDeviations))] + public void A_deviation_in_the_annots_array_or_the_type_entries_is_recorded_once(string pageEntries, string code, string annotationEntries) + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + $"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> {pageEntries} >>", + $"<< {annotationEntries} /Rect [0 0 10 10] >>", + "42"); + using PdfDocument document = PdfDocument.Open(file); + + IReadOnlyList annotations = document.Pages[0].Annotations; + _ = document.Pages[0].Annotations; + + Assert.Equal(code, Assert.Single(document.Diagnostics).Code); + Assert.Equal(code == "AnnotsInvalid" ? 0 : 1, annotations.Count); + } + + [Fact] + public void A_trap_network_that_is_not_the_last_annotation_is_recorded() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> /Annots [4 0 R 5 0 R] >>", + "<< /Type /Annot /Subtype /TrapNet /Rect [0 0 10 10] /Version [] /AnnotStates [] >>", + "<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] >>"); + using PdfDocument document = PdfDocument.Open(file); + + _ = document.Pages[0].Annotations; + + Assert.Equal("TrapNetPlacementInvalid 4", Describe(Assert.Single(document.Diagnostics))); + } + + [Fact] + public void Annots_on_a_page_tree_node_is_used_with_a_diagnostic() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 /Annots [4 0 R] >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>", + "<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] >>"); + using PdfDocument document = PdfDocument.Open(file); + + Assert.IsType(Assert.Single(document.Pages[0].Annotations)); + Assert.Equal("AnnotsInherited 3", Describe(Assert.Single(document.Diagnostics))); + } + + [Fact] + public void An_appearance_is_required_only_in_a_pdf_2_0_file() + { + const string annotation = "<< /Type /Annot /Subtype /Square /Rect [0 0 10 10] >>"; + byte[] legacy = Build("%PDF-1.7", annotation); + byte[] modern = Build("%PDF-2.0", annotation); + + using PdfDocument before = PdfDocument.Open(legacy); + using PdfDocument after = PdfDocument.Open(modern); + Assert.Null(Assert.Single(before.Pages[0].Annotations).AppearanceDictionary); + Assert.Null(Assert.Single(after.Pages[0].Annotations).AppearanceDictionary); + + Assert.Empty(before.Diagnostics); + Assert.Contains("AppearanceMissing 4", after.Diagnostics.Select(Describe)); + + static byte[] Build(string header, string annotation) => new TestPdf { Header = header, TrailerEntries = "/ID [<00112233445566778899AABBCCDDEEFF> <00112233445566778899AABBCCDDEEFF>]" }.Build( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> /Annots [4 0 R] >>", + annotation); + } + + [Fact] + public void A_mutation_that_changes_the_annots_array_or_the_subtype_is_seen_on_the_next_read() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("annotations-link.pdf")); + PdfPage page = document.Pages[0]; + PdfAnnotation link = Assert.Single(page.Annotations); + + var annots = (CosArray)document.Resolve(page.Dictionary[new CosName("Annots")]); + annots.Add(annots[0]); + Assert.Equal(2, page.Annotations.Count); + Assert.Same(link, page.Annotations[1]); + + link.Dictionary[new CosName("Subtype")] = new CosName("Square"); + Assert.IsType(page.Annotations[0]); + } + + private static string Describe(Diagnostic diagnostic) => + $"{diagnostic.Code} {diagnostic.ObjectReference?.ObjectNumber.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "-"}"; +} diff --git a/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt b/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt index ff652729..0c0b76f0 100644 --- a/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt +++ b/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt @@ -1,6 +1,6 @@ pdfjs: 989 files - Clean: 670 - Diagnostics: 305 + Clean: 663 + Diagnostics: 312 PasswordRequired: 12 CertificateRequired: 0 EncryptionUnsupported: 0 @@ -26,6 +26,7 @@ DictionaryKeyNotName: 5 HeaderInvalid: 5 PageTreeCountMismatch: 5 + AnnotationRectInvalid: 4 CatalogTypeInvalid: 4 DictionaryDuplicateKey: 4 PageMediaBoxMissing: 4 @@ -35,6 +36,9 @@ FileIdentifierInvalid: 3 PageTreeNodeTypeInvalid: 3 PagesMissing: 3 + AnnotationEntryInvalid: 2 + AppearanceEntryInvalid: 2 + AppearanceNotForm: 2 ArrayUnterminated: 2 DateUnreadable: 2 DecodeParmsInvalid: 2 @@ -49,6 +53,11 @@ TrailerIdMissing: 2 TrailerMissing: 2 XmpMalformed: 2 + AnnotationRequiredEntryMissing: 1 + AnnotationSubtypeMissing: 1 + AnnotationValueInvalid: 1 + AppearanceBBoxMissing: 1 + AppearanceStateMissing: 1 DictionaryValueMissing: 1 EncryptDictionaryInvalid: 1 EncryptedDataInvalid: 1 @@ -71,6 +80,8 @@ PageTreeCycle: 1 PageTreeKidInvalid: 1 PageTreeKidNotIndirect: 1 + PopupLinkMismatch: 1 + PopupParentInvalid: 1 RootNotIndirect: 1 StringUnterminated: 1 TrailerEntryFromOlderRevision: 1 @@ -79,8 +90,8 @@ XrefStreamSizeInvalid: 1 XrefSubsectionNumberingInvalid: 1 pdfbox: 137 files - Clean: 105 - Diagnostics: 24 + Clean: 101 + Diagnostics: 28 PasswordRequired: 3 CertificateRequired: 4 EncryptionUnsupported: 0 @@ -93,6 +104,8 @@ pdfbox: 137 files EndOfFileMarkerMissing: 4 XrefEntryInvalid: 3 XrefEntryOffsetInvalid: 3 + AppearanceNotForm: 2 + DestinationInvalid: 2 RootMissing: 2 CatalogTypeInvalid: 1 DateUnreadable: 1 @@ -105,8 +118,8 @@ pdfbox: 137 files StartxrefInvalid: 1 StreamLengthInvalid: 1 qpdf: 639 files - Clean: 432 - Diagnostics: 170 + Clean: 418 + Diagnostics: 184 PasswordRequired: 23 CertificateRequired: 0 EncryptionUnsupported: 1 @@ -125,6 +138,7 @@ qpdf: 639 files RootMissing: 10 StreamLengthInvalid: 10 DestinationInvalid: 8 + PopupLinkMismatch: 8 CatalogTypeInvalid: 7 ObjectStreamIndexMismatch: 7 XrefEntryInvalid: 7 @@ -141,6 +155,7 @@ qpdf: 639 files DeveloperExtensionInvalid: 4 PageMediaBoxMissing: 4 PredictorInvalid: 4 + AnnotationSharedAcrossPages: 3 EndOfFileMarkerNotLast: 3 EndstreamMissing: 3 FileIdentifierInvalid: 3 @@ -163,6 +178,10 @@ qpdf: 639 files TrailerMissing: 2 XrefPrevLoop: 2 XrefSectionInvalid: 2 + AnnotationEntryInvalid: 1 + AnnotationNotIndirect: 1 + AppearanceEntryInvalid: 1 + AppearanceNotForm: 1 EncryptionEntryLengthInvalid: 1 EncryptionIdMissing: 1 EncryptionKeyLengthInvalid: 1 @@ -189,8 +208,8 @@ qpdf: 639 files XrefStreamWidthsInvalid: 1 XrefSubsectionHeaderInvalid: 1 pdfium-tests: 840 files - Clean: 281 - Diagnostics: 552 + Clean: 231 + Diagnostics: 602 PasswordRequired: 2 CertificateRequired: 4 EncryptionUnsupported: 0 @@ -204,6 +223,7 @@ pdfium-tests: 840 files StartxrefInvalid: 99 StreamLengthInvalid: 92 XrefSectionInvalid: 84 + AppearanceNotForm: 82 PredictorInvalid: 72 DateInvalid: 56 XmpMalformed: 43 @@ -224,14 +244,17 @@ pdfium-tests: 840 files PageResourcesMissing: 5 PageTreeNodeTypeInvalid: 5 PageTreeParentMismatch: 5 + AnnotationRequiredEntryMissing: 4 DestinationInvalid: 4 DictionaryUnterminated: 4 StartxrefMissing: 4 XrefEntryFormatInvalid: 4 + AnnotationValueInvalid: 3 DictionaryKeyNotName: 3 MetadataNotEncrypted: 3 NameTreeLimitsInvalid: 3 StringUnterminated: 3 + AppearanceStateMissing: 2 ArrayUnterminated: 2 EncryptionRevisionInvalid: 2 EndOfFileMarkerNotLast: 2 @@ -240,6 +263,11 @@ pdfium-tests: 840 files ViewerPreferenceInvalid: 2 XrefSubsectionHeaderInvalid: 2 ActionInvalid: 1 + AnnotationDuplicate: 1 + AnnotationEntryInvalid: 1 + AnnotationFlagsInvalid: 1 + AnnotationRectInvalid: 1 + AppearanceEntryInvalid: 1 DictionaryValueMissing: 1 EncryptDictionaryInvalid: 1 EndOfFileMarkerMissing: 1 @@ -247,6 +275,7 @@ pdfium-tests: 840 files HeaderMissing: 1 HexStringInvalidDigit: 1 LinearizationHintsInvalid: 1 + LinkActionAndDest: 1 NameTreeKeysUnsorted: 1 NumberTreeLimitsInvalid: 1 OutlineDestAndAction: 1 diff --git a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt index 93f07fb1..b6acd3d5 100644 --- a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt +++ b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt @@ -1,5 +1,8 @@ [ + annotations-appearance.pdf, annotations-link.pdf, + annotations-malformed.pdf, + annotations-subtypes.pdf, ascii85-stream.pdf, asciihex-stream.pdf, associated-files.pdf, diff --git a/tests/Broadside.Tests/Writing/SaveTests.cs b/tests/Broadside.Tests/Writing/SaveTests.cs index df3a3ef6..0ad0ef73 100644 --- a/tests/Broadside.Tests/Writing/SaveTests.cs +++ b/tests/Broadside.Tests/Writing/SaveTests.cs @@ -13,7 +13,7 @@ public class SaveTests /// Broken files whose damage is in a document-model structure read lazily (a name tree, an outline), not in the file structure: /// they open without a diagnostic and save byte for byte, damage included, so qpdf reports it again. ///
- private static readonly HashSet DamagedInTheDocumentModel = new(StringComparer.Ordinal) { "name-tree-broken.pdf", "outline-broken.pdf" }; + private static readonly HashSet DamagedInTheDocumentModel = new(StringComparer.Ordinal) { "name-tree-broken.pdf", "outline-broken.pdf", "annotations-malformed.pdf" }; /// /// Well-formed files qpdf 12.4.2 warns about because it compares name tree keys as decoded text, not byte by byte as ISO 32000-2 diff --git a/tests/Corpus/README.md b/tests/Corpus/README.md index 7b0ec03f..48472964 100644 --- a/tests/Corpus/README.md +++ b/tests/Corpus/README.md @@ -70,6 +70,8 @@ Verification was run with qpdf 12.4.2 (`qpdf --check`), poppler (`pdfinfo`, `pdf | `inline-image.pdf` | Content stream with a 2x2 8-bit DeviceGray inline image (`BI /W 2 /H 2 /CS /G /BPC 8 ID ... EI`) scaled to 100x100 at (72, 600). | 8.9.7 | `pdftoppm` renders a checkerboard (black top-left and bottom-right) | clean | | `page-tree-inherited.pdf` | Root `/Pages` (2) with one intermediate `/Pages` node (3) that carries `/MediaBox` and `/Resources`; the two leaf pages (4, 5) have neither. | 7.7.3.2, 7.7.3.4 | `pdfinfo` shows 2 Letter pages; `pdftotext` prints `Page 1` and `Page 2` (the font comes from the inherited resources) | clean | | `annotations-link.pdf` | One `/Link` annotation with a `/URI` action in the page's `/Annots`. | 12.5.2, 12.5.6.5, 12.6.4.8 | `qpdf --check`; `qpdf --json --json-key=qpdf` shows the `/Link` dictionary | clean | +| `annotations-subtypes.pdf` | PDF 2.0, one page with one annotation of each of the 28 subtypes of Table 171 (objects 10-27, 30, 32-41, 43) plus `/Subtype /XBroadsideTest` (42, `/F 1023`: every flag bit); all but Popup 11, Link 13 and the zero-size Projection 40 share the normal appearance form 4; TrapNet 43 is last, with a state subdictionary and `/AS /T1`. Text 10 and Popup 11 point at each other; reply 12 has `/IRT 10 0 R /RT /R /State (Accepted) /StateModel (Review)`; colours with 1, 3 and 4 components; `Border` with a dash array (Circle), `BS` and `BE` (Square), `QuadPoints` (Link, text markup, Redact), `Path` without `Vertices` (PolyLine), an embedded file specification with `AF` (FileAttachment), a push-button widget listed in `/AcroForm`. | 12.5.2-12.5.6, Tables 166-195, 309, 333, 398, 403 | `qpdf --check`; `qpdf --json --json-key=pages` lists 30 annotations | qpdf clean; pdfinfo: `Bad Annot Polygon Vertices` for the PolyLine (poppler does not read the PDF 2.0 `Path` entry). Zero diagnostics when every entry is read. | +| `annotations-appearance.pdf` | Appearance placement (12.5.5 Algorithm): Square 10 with an N stream of `/BBox [0 0 100 50] /Matrix [0 1 -1 0 0 0]` on `/Rect [100 100 150 200]` (AA `[0 1 -1 0 150 100]`); Circle 11 with `/Rect [50 30 10 10]` (unnormalized, 7.9.5) and N `/BBox [0 0 20 20]` (AA `[2 0 0 1 10 10]`); Square 12 with `/AS /On`, N states On (6) and Off (7), D with only On (8), no R. | 12.5.5 Table 170, 7.9.5, 8.10.1 | `qpdf --check`; `pdftoppm -r 72` | clean; the page renders red over x 100-150, y 100-200, blue over x 10-50, y 10-30 and green (state On) over x 300-340. | | `outline.pdf` | `/Outlines` root with two sibling items linked by `/First /Last /Next /Prev /Parent`, each with an explicit destination; `/PageMode /UseOutlines`. | 12.3.3, 12.3.2.2 | `qpdf --check`; `qpdf --json --json-key=outlines` lists both items with their destinations | clean | | `name-tree-dests.pdf` | `/Names << /Dests ... >>` name tree with a root `/Kids` node and two leaves carrying `/Limits` and `/Names` for `alpha`, `beta`, `gamma`. | 7.9.6, 12.3.2.3 | `qpdf --check` | clean | | `metadata-xmp.pdf` | Catalog `/Metadata` stream (`/Type /Metadata /Subtype /XML`) with a minimal XMP packet whose `dc:title` is `Broadside`, plus a trailer `/Info` dictionary with the same `/Title`. | 14.3.2, 14.3.3 | `pdfinfo` shows `Title: Broadside` | clean | @@ -109,6 +111,7 @@ Each file is `empty-page.pdf` (or `text-standard14.pdf`) with exactly one defect | `encrypted-rc4-length-missing.pdf` | R3 (`/V 2`) RC4 with a 128-bit key but no `/Length` entry, so the key is 40 bits by Table 20's default. The case of qpdf's `bad-encryption-length.pdf`, which the real-world corpus gate (issue #47) found reported as "password required". | 7.6.2 Table 20 | qpdf (exit 3): `object 6 0 ... dictionary key /Length: operation for integer attempted on object of type null: returning 0`, then opens it (qpdf assumes 128 bits when Length is missing). pdfinfo and pdftotext: `Command Line Error: Incorrect password`. | No key of the default 40 bits authenticates, so 128 bits are tried: the empty user password authenticates, record `EncryptionKeyLengthInvalid` (Warning, no offset or object); `PdfSecurity.KeyLength` is 128 and the content decrypts to `RC4 128-bit (R3), no Length`. Strict mode throws it at open. | | `name-tree-broken.pdf` | A `/Dests` name tree broken six ways: leaf 7's `/Limits [(a) (c)]` do not hold its key `(d)`; leaf 8's keys are out of order (`(f)` before `(e)`); intermediate node 6 has no `/Limits`; `(g)` is in leaf 8 and again in leaf 9; node 6's `/Kids` list the root 4 (a cycle); leaf 9's `/Names` has an odd length (a dangling `(i)`). | 7.9.6 | qpdf (exit 3): `keys are not sorted in validate` (object 4), `items array doesn't have enough elements` (object 9), `loop detected while traversing name/number tree` (object 4). pdfinfo: clean. | Opens with no diagnostic (the tree is read lazily). Walking the tree records, once per node and in this order: `NameTreeLimitsInvalid` 7, `NameTreeKeysUnsorted` 8, `NameTreeLimitsInvalid` 6, `NameTreeCycle` 4 (Error), `NameTreeNodeInvalid` 9, `NameTreeDuplicateKey` 9. Keys `a b d f e g h` resolve (`(g)` to leaf 8's value, the first in tree order); `(i)` has no value. Strict mode throws `NameTreeLimitsInvalid` 7 from the first lookup that needs the whole tree. | | `outline-broken.pdf` | An outline broken six ways: item 5 has both `/Dest` and `/A`; item 6 has no `/Title`; item 7's `/Next` points back at item 6 (a cycle in the sibling chain); item 8's `/First` points at its ancestor 5; the outline's `/Last` names 6, not 7 where the chain ends; item 7 has a child but `/Count 0`; the outline's `/Count -5` is negative. | 12.3.3 Tables 150-151 | qpdf (exit 3): `Loop detected loop in /Outlines tree` (objects 5, 6 and 7). pdfinfo: clean. | Opens with no diagnostic (the outline is read lazily). Walking it records, in this order: `OutlineDestAndAction` 5, `OutlineItemInvalid` 6 (title read as empty), `OutlineCycle` 6 (Error), `OutlineLinkInconsistent` 4, `OutlineCycle` 5 (Error), `OutlineCountInvalid` 4, `OutlineCountInvalid` 7. The tree read is One (child One.One, no grandchildren), an untitled item, Three (child Three.One). Strict mode throws `OutlineDestAndAction` 5 from the walk. | +| `annotations-malformed.pdf` | Two pages. Page 3's `/Annots [null 9 0 R 10 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R 15 0 R 16 0 R << direct >>]`: 9 is the integer 42, 10 is listed twice, 11 has no `/Subtype`, 12 has `/Rect [1 2 3]`, Highlight 13 has 7 `QuadPoints` numbers, 14 has an N state subdictionary but no `/AS`, 15's N stream has no `/BBox`, 16's `/P` names page 4, the last element is a direct dictionary. Page 4 lists 16 again, Text 17 (`/RT` without `/IRT`, `/Popup 18 0 R`, `/State` without `/StateModel`, `/F 2048`, `/C [1 0]`, `/Border [1]`), Popup 18 whose `/Parent` is Link 19, and Link 19 with both `/A` and `/Dest`. PDF 1.7. | 7.7.3.3 Table 31, 12.5.2-12.5.6 | qpdf (exit 3): `kid 0 (from 0) Annots has duplicate entry for annotation 10 0`. pdfinfo: `Bad bounding box for annotation`, `Invalid or missing AS value in annotation containing one or more appearance subdictionaries`. | Opens with no diagnostic. Page 3's list (10, 10, 11 unknown, 12, 13, 14, 15, 16, direct) records `AnnotationEntryInvalid` 3 and 9, `AnnotationDuplicate` 10, `AnnotationSubtypeMissing` 11, `AnnotationPageMismatch` 16, `AnnotationNotIndirect` 3; page 4's adds `AnnotationSharedAcrossPages` 16. Reading the entries records `AnnotationRectInvalid` 12, `QuadPointsInvalid` 13, `AppearanceStateMissing` 14, `AppearanceBBoxMissing` 15, and for 17 `ReplyTypeWithoutInReplyTo`, `PopupLinkMismatch`, `StateModelMissing`, `AnnotationFlagsInvalid`, `ColorArrayInvalid`, `BorderArrayInvalid`; `PopupParentInvalid` 18; `LinkActionAndDest` 19. Strict mode throws `AnnotationEntryInvalid` from page 3's `Annotations`. | ## Password-protected files diff --git a/tests/Corpus/annotations-appearance.pdf b/tests/Corpus/annotations-appearance.pdf new file mode 100644 index 0000000000000000000000000000000000000000..293ac1adcce924b3669b32f34f06edc009d58356 GIT binary patch literal 1511 zcmb`HPjBKd5XJBL6m#L&+D>8!Qiaq%%VoC(K@XLx9s)RQDw^yXBenbK_l-%x4Wg>r zCPX2V@%(09UeXy~4Nuf*FH$6_o;^lqXC!W4{umOMxyx7elEgS)nl;5pn9yJlnQFm_ zeEoL8Hc$L47i+ptIQ;=t>P_WH1q=Dk;X=k(gVZfYT$@FiU)0ZZFOlC>G4=W}>P^hL z-q<-BLZ^cPiSw$e9e|4SCZu=}oP3#w0Gl3Q??$snGj}AWo0;_$f75peGtz%rcpRMV@_$En%ZsVWPpA7FYnzIC}bYGAhM z-whnkj)n(eUltgL<|oWbpO4w%;)d9{{N`~Bjdi@s-!Fez+WBf%9#sA{Fs_vf=QpPDI&C;L~^%L zSL;MmLHk&r{9UT{F^z(}1u>;Ca4Qxk(6<#!GQ3Nzn3gbkE7px6Rx8$n4DA@Mo7leR zOhb;=+P*$uD47NfXY+Dptp7?+%YO#Cz(94)U)ZgB_zdONdDWE4bkynm7!9NU{E&s7 literal 0 HcmV?d00001 diff --git a/tests/Corpus/annotations-malformed.pdf b/tests/Corpus/annotations-malformed.pdf new file mode 100644 index 0000000000000000000000000000000000000000..2cffc1d1ca22aaef4b257ac9263ca6e5345f9e37 GIT binary patch literal 2181 zcmcIm-*4J55Pr{JaW9qHht+Y&FQy6!+ObXR27^wTRP`Z%OVfpzC5}Y**YC~_gg7gj zCM_a~e6jEQ?(Vx2XVaVU8-5u%99)o#XXok)*xk!k0J~09lF2o&X|fh2c(`E(gMlOR z6>X$-`+(WUKBcP??t6N>PtOPRC97Pai{?0e?;a|Ychu1px*(BqmP@W6Zv^{dH%b_#4> zEtJm4{AY#i2z{vxBXrK)2V_9^J~QO>KZM2&Jsugdv3coOkI^ZXHv0F;;+YsXfsAFb z0X8}$whn{cihQk}fX5U~sS1&792eH;k>aEuhW|)$)*ovv5VOC-{8t1DlMsAwpJgOt zgPyLJ3BYr~!-}yf7zs3G&v!e*CUl(^%j_T^jt$ZKGnH<4*seaL z>!%EFEUTdxXnLVVkA1C@)l{ZAHHQWS9|8y=I@XNtgLVOJyteiu4HnyA!zuM6`=Xzd z9D%6kus`+hP`R!|PowoU8h2lXGo8@}>1y&c2sirRjX=zBI1&hT-svpeiQSV50IJ{ND({KsB~I*S?sGpWU0$9*G89GdlF zoGSb_)H<01`!@S%9_LR=ZOgZeiCwbUX5w-wH|(MiEx=4!Htu0&En5$J+_w24>dD#{#Mtqc4VSg;m`m3dV(-{z!+w`v6m{c>eH;%K zZl6@tws99LZQFP^HtzYI9Pplpm9qT#5jL)63vdz~Y^q4oOceS*#60~aNc?Ojr2-nQ W`p-kDl0xYU@`wk{+1b0v*!c|^YAh@O literal 0 HcmV?d00001 diff --git a/tests/Corpus/annotations-subtypes.pdf b/tests/Corpus/annotations-subtypes.pdf new file mode 100644 index 0000000000000000000000000000000000000000..b769df6b2842cc0fe67b31037e4997a74e2dd010 GIT binary patch literal 6851 zcmb_h+iv2>7MrAdgQsRaxMNP=~EmC{*7GscX*SWAt z8=Y4-QjSdG(L#_L8Ad@rc@_^Qo^M;W@VoX`VNB&F*=BP{3<)8S(Oa*R970-rZYnHl zii;*=ks0ok0>bk2U0Yv#ed*{+S6ysP#nx18O~uw!Y)!@1RBTPf)>It5&(Rwky+PYe zIC_JlH#o%x&Ck{QT+Pqb+g-Jt_TCwroU6wEa`*U6&U0bRwvV}TsB)Xp-`flZu}oNO zEZ58YNmw1y+vJ%HR%fPIf+8Q_E0bbDPQ{OfgOx$6OqH!mEbrwrB$!f;2WaA(B!{a@ zz7wIXVDu&`nr?-*ADuQx);XNL5v|)Kmm&w9pM`OIBU*5#d~e|f--jP;({@eEv`xo! zP4C}W9tpdH{qQ$}ifryhs~1OeiQiy~Z=yAoKO*@jZU;~`kCOE;0E+`L%d$=UBe6-6 zZqr@J7`MTSd6BGEj6>rtm1~h_TUqjhimuZ((KHLAIIu<=Z`V`SDO;rocV%TH-mBag z4yU=5Jzyhv=>og+78k&7{p1lwxSrlK2$&}Zz8bj9a%HmKd@j>mhBPf#Zjw;O2Lm6% zQ>EEyLC4Yh`z};Y2s)G-#8MGBqbP^PKEgP{_zf;djL2(`gj;TODsIKc}{Je9gvIxu=!mi#G<;Y_p^$ea%#o92QHWFE}} z(4G!N>mt3(qWRN>kzW2>)|T+o=p00Tk;h%FsmG9QOk^dv&U$2(z#G;dUx^1}5M}e2 z`4lG`87d9%)3wT6L>nI)GwyJ?qMOF!JKARuq&n%0!34>jq*%IR5%9Ph#zP>fY}ztpLP5N=aq$V}xV4dm2ivKh=d?hd)`V-JKC?WFzRNp8`XNJ=K(Nz476<_ef%K;eDuxy$!-~Rae(IG@RnX@0HUJLp zg=E4~NG5EvkTVz?$gDApO;`mkRCC;9q+kV9*9KztkvFrinK$78oyaP^USVh{`=%NE zuMhnPi#eGxjo!d?{e2vGpLJq!NWUV%^*~*}b(06eAgm1-PPN=#9`vsht(6>u66YH>sSn z^=<{{x$4wEmA>~zQyHs9d-FuLXtx7lT#Z!WL%XgA9Rpj6uNA~rYt?|cT0P1zlp#68 z-@EySL&Cr8Q5pvkYE3cKl!uy~iuF+j7}J=#m{U<+b~r0s?BOiq`b{u0Q#&0!!4*Tq zO*AjXg8HqhquzvGyMs|=uZ_!1#T53_FMs|0iYCpNc#~lM*=fQSL8*eMYE}g^!2qFy z@X$omA%JMDNb!7?x@;>EI${yTn{xW8dAF+IaYH?uqoc0$2o#Hu^Cq$Mb_({JimNHX z&*+!B$^NfsA=t*C_nyST%T8A6z!6}2tv^~%d7f@Q7>0ZXki_yl$(F{7rwwYyA%oTQ zep;!|QMf$dD6x!65zCsD8Uf4tIV>_-pmcgT9pEUNZZ}WR5;M~MC5>nzM>jzmmxSOH(GiJwZRc6m<1bbrK z8`wwBGE_<^*Xtg9bXYWQ0@Pic6fp&nwZgZ>d!L6zA8~8^p}X#qW1FGbK})}f0!K9` z@GHyg$&SJq4)GM2Vup5x*F~P-Yrip#5$4$a-~ zRE7ahjkIz^2c;eS(X8E3zr@O|+9Z6UUg4JgWM#s;`+;^bcu|9N>kHy~DpQ=v6a!vq zN;b<=GJAR|N4voEO~^gT5}t%{8Z6Y}9{evkt3;4NQnmOoR828NtK-KVJtj8I#Kdkk z(|&tVe;Krd&HegJ=6SSU?oKdEvNePImwuK6;U)@kI)R>KAEa79rgO7^BlrqOnkBx? zo$Y-Vq_+pCqkRu&vXk9O-$(()IN0PkDvA~n+Ktk=8&BQzxmyo_e2-y&e=*X&|-+c+kwK4)7N9CEZ~cWScOu2-|Y z-8SoceYgHxr(2WRG21oy9II24&%vSav3w3sT90IQ+B}x8>f!iq&F4towns-!J98G bMe`$S2-)O8maA;{I(GN$-Mg#1(b@k14eGgT literal 0 HcmV?d00001 diff --git a/tests/Corpus/generate.py b/tests/Corpus/generate.py index 558e5b66..97a795c1 100644 --- a/tests/Corpus/generate.py +++ b/tests/Corpus/generate.py @@ -1253,6 +1253,136 @@ def gen_annotations_link() -> bytes: ]) +def annotation(subtype: bytes, rect: bytes, extra: bytes = b"", ap: bool = True) -> bytes: + """12.5.2 Table 166: an annotation dictionary on page 3 (/P) whose normal appearance is form 4.""" + body = b"<< /Type /Annot /Subtype /" + subtype + b" /Rect " + rect + b" /P 3 0 R" + if ap: + body += b" /AP << /N 4 0 R >>" + return body + extra + b" >>" + + +def gen_annotations_subtypes() -> bytes: + """12.5.6 Table 171: one annotation of each of the 28 standard subtypes on one page, plus one of the + unknown subtype XBroadsideTest with every flag bit of Table 167 set; TrapNet is last (12.5.6.21). Every + annotation that needs one (12.5.2: all but Popup, Link and a zero-size Projection) shares the normal + appearance form 4. Relations: Text 10 <-> Popup 11 (Popup/Parent), reply 12 (IRT 10, RT R, State + Accepted in the Review model); colours C/IC with 1, 3 and 4 components; Border array with a dash, BS + and BE dictionaries; QuadPoints on Link, text markup and Redact; the Widget is a push button field + listed in the catalog's AcroForm.""" + def rect(i: int) -> bytes: + x, y = 40 + (i % 6) * 90, 700 - (i // 6) * 90 + return b"[%d %d %d %d]" % (x, y, x + 60, y + 40) + + objects: list[tuple[int, bytes]] = [ + (1, catalog(b" /AcroForm << /Fields [34 0 R] >>")), + (2, pages()), + (3, page(extra=b" /Annots [%s]" % b" ".join(b"%d 0 R" % n for n in [ + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 30, 32, 33, 34, 35, 36, + 37, 39, 40, 41, 42, 43]))), + (4, stream(b"/Type /XObject /Subtype /Form /BBox [0 0 10 10]", b"0 g 0 0 10 10 re f")), + (10, annotation(b"Text", rect(0), b" /Contents (Note text) /NM (note-1) /M (D:20240102030405Z)" + b" /F 28 /C [1 1 0] /T (Alice) /Subj (Review) /CreationDate (D:20240101120000Z)" + b" /Popup 11 0 R /Name /Comment /Open true")), + (11, annotation(b"Popup", b"[300 600 450 700]", b" /Parent 10 0 R /Open true", ap=False)), + (12, annotation(b"Text", rect(2), b" /T (Bob) /IRT 10 0 R /RT /R /State (Accepted) /StateModel (Review)")), + (13, annotation(b"Link", b"[220 700 280 740]", b" /Dest [3 0 R /Fit] /H /O" + b" /QuadPoints [222 702 278 702 278 738 222 738] /BS << /W 2 /S /U >>", ap=False)), + (14, annotation(b"FreeText", rect(4), b" /DA (/Helv 12 Tf 0 g) /Q 1 /IT /FreeTextCallout" + b" /CL [10 10 50 50 60 50] /LE /OpenArrow /DS (font: 12pt Helvetica) /RC (

rich

)")), + (15, annotation(b"Line", rect(5), b" /L [100 100 200 200] /LE [/Circle /ClosedArrow] /IC [1 0 0]" + b" /LL 10 /LLE 2 /LLO 1 /Cap true /CP /Top /CO [0 5] /IT /LineDimension")), + (16, annotation(b"Square", rect(6), b" /BS << /Type /Border /W 2 /S /D /D [3 2] >> /IC [0 0 1]" + b" /BE << /S /C /I 1 >> /RD [1 2 3 4]")), + (17, annotation(b"Circle", rect(7), b" /Border [0 0 2 [4 1]] /IC [0.5] /C [0 0 0 1]")), + (18, annotation(b"Polygon", rect(8), b" /Vertices [10 10 50 10 30 40] /IT /PolygonCloud /BE << /S /C /I 2 >>")), + (19, annotation(b"PolyLine", rect(9), b" /Path [[10 10] [50 10] [60 20 70 30 80 10]] /LE [/Square /Slash]")), + (20, annotation(b"Highlight", rect(10), b" /QuadPoints [10 10 50 10 50 20 10 20]")), + (21, annotation(b"Underline", rect(11), b" /QuadPoints [10 30 50 30 50 40 10 40]")), + (22, annotation(b"Squiggly", rect(12), b" /QuadPoints [10 50 50 50 50 60 10 60]")), + (23, annotation(b"StrikeOut", rect(13), b" /QuadPoints [10 70 50 70 50 80 10 80 60 70 90 70 90 80 60 80]")), + (24, annotation(b"Caret", rect(14), b" /Sy /P /RD [1 1 1 1]")), + (25, annotation(b"Stamp", rect(15), b" /IT /StampImage")), + (26, annotation(b"Ink", rect(16), b" /InkList [[10 10 20 20 30 10] [40 40 50 50]]")), + (27, annotation(b"FileAttachment", rect(17), b" /FS 28 0 R /Name /Paperclip /Contents (An attached file)" + b" /AF [28 0 R]")), + (28, b"<< /Type /Filespec /F (a.txt) /UF (a.txt) /AFRelationship /Data /EF << /F 29 0 R /UF 29 0 R >> >>"), + (29, stream(b"/Type /EmbeddedFile /Subtype /text#2Fplain", b"attached")), + (30, annotation(b"Sound", rect(18), b" /Sound 31 0 R /Name /Mic")), + (31, stream(b"/Type /Sound /R 8000", b"\x00\x40\x80\xc0")), + (32, annotation(b"Movie", rect(19), b" /T (Clip) /Movie << /F (movie.mp4) >> /A false")), + (33, annotation(b"Screen", rect(20), b" /T (Screen) /MK << /R 90 /BC [1 0 0] /BG [1] /CA (Play) >>" + b" /A << /S /URI /URI (https://example.org/media) >>")), + (34, annotation(b"Widget", rect(21), b" /FT /Btn /Ff 65536 /T (push) /H /P /MK << /CA (Push) /TP 0 >>")), + (35, annotation(b"PrinterMark", rect(22), b" /F 68 /MN /ColorBar")), + (36, annotation(b"Watermark", rect(23), b" /FixedPrint << /Type /FixedPrint /Matrix [1 0 0 1 72 -72] /H 0 /V 1 >>")), + (37, annotation(b"3D", rect(24), b" /3DD 38 0 R /3DI false /3DB [0 0 60 40]")), + (38, stream(b"/Type /3D /Subtype /U3D", b"U3D\x00")), + (39, annotation(b"Redact", rect(25), b" /QuadPoints [10 10 50 10 50 20 10 20] /IC [1 0 0]" + b" /OverlayText (X) /Repeat true /DA (/Helv 10 Tf 0 g) /Q 2")), + (40, annotation(b"Projection", b"[0 0 0 0]", ap=False)), + (41, annotation(b"RichMedia", rect(27), b" /RichMediaContent << >> /RichMediaSettings << >>")), + (42, annotation(b"XBroadsideTest", rect(28), b" /F 1023")), + (43, annotation(b"TrapNet", b"[0 0 612 792]", b" /F 68 /LastModified (D:20240101000000Z) /AS /T1", ap=False)[:-3] + + b" /AP << /N << /T1 4 0 R >> >> >>"), + ] + id0 = file_id("annotations-subtypes").hex().encode() + return simple_file(objects, version="2.0", trailer_extra=b" /ID [<%s> <%s>]" % (id0, id0)) + + +def gen_annotations_appearance() -> bytes: + """12.5.5 Algorithm "Appearance streams" and Table 170. Square 10: N stream with BBox [0 0 100 50] and + Matrix [0 1 -1 0 0 0] on Rect [100 100 150 200] (AA = [0 1 -1 0 150 100]). Circle 11: Rect written + unnormalized as [50 30 10 10] (7.9.5) with N BBox [0 0 20 20] (AA = [2 0 0 1 10 10]). Square 12: N is a + state subdictionary (On, Off), D has only On, R is absent, AS /On.""" + objects: list[tuple[int, bytes]] = [ + (1, catalog()), + (2, pages()), + (3, page(extra=b" /Annots [10 0 R 11 0 R 12 0 R]")), + (4, stream(b"/Type /XObject /Subtype /Form /BBox [0 0 100 50] /Matrix [0 1 -1 0 0 0]", b"1 0 0 rg 0 0 100 50 re f")), + (5, stream(b"/Type /XObject /Subtype /Form /BBox [0 0 20 20]", b"0 0 1 rg 0 0 20 20 re f")), + (6, stream(b"/Type /XObject /Subtype /Form /BBox [0 0 10 10]", b"0 1 0 rg 0 0 10 10 re f")), + (7, stream(b"/Type /XObject /Subtype /Form /BBox [0 0 10 10]", b"0.5 g 0 0 10 10 re f")), + (8, stream(b"/Type /XObject /Subtype /Form /BBox [0 0 10 10]", b"0 g 0 0 10 10 re f")), + (10, b"<< /Type /Annot /Subtype /Square /Rect [100 100 150 200] /AP << /N 4 0 R >> >>"), + (11, b"<< /Type /Annot /Subtype /Circle /Rect [50 30 10 10] /AP << /N 5 0 R >> >>"), + (12, b"<< /Type /Annot /Subtype /Square /Rect [300 300 340 340] /AS /On" + b" /AP << /N << /On 6 0 R /Off 7 0 R >> /D << /On 8 0 R >> >> >>"), + ] + return simple_file(objects) + + +def gen_annotations_malformed() -> bytes: + """12.5 real-world deviations, two pages. Page 3's Annots: [null 9 0 R (an integer) 10 10 11 12 13 14 15 + 16 << direct >>]: 10 is listed twice; 11 has no Subtype; 12 has a three-number Rect; 13 is a Highlight + with 7 QuadPoints numbers; 14 has an N state subdictionary but no AS; 15's N stream has no BBox; 16's P + names page 4, whose Annots lists 16 too. Page 4 also holds 17: a Line with RT but no IRT, Popup -> 18 + (a Popup whose Parent is 19), State without StateModel, F 2048, C with two components, Border [1], + and a Link 19 with both A and Dest. PDF 1.7, so a missing appearance is not a deviation.""" + objects: list[tuple[int, bytes]] = [ + (1, catalog()), + (2, pages([3, 4])), + (3, page(extra=b" /Annots [null 9 0 R 10 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R 15 0 R 16 0 R" + b" << /Type /Annot /Subtype /Square /Rect [0 0 10 10] >>]")), + (4, page(extra=b" /Annots [16 0 R 17 0 R 18 0 R 19 0 R]")), + (5, stream(b"/Type /XObject /Subtype /Form /BBox [0 0 10 10]", b"0 g 0 0 10 10 re f")), + (6, stream(b"/Type /XObject /Subtype /Form", b"0 g 0 0 10 10 re f")), + (9, b"42"), + (10, b"<< /Type /Annot /Subtype /Square /Rect [10 10 20 20] /P 3 0 R >>"), + (11, b"<< /Type /Annot /Rect [30 10 40 20] /P 3 0 R >>"), + (12, b"<< /Type /Annot /Subtype /Circle /Rect [1 2 3] /P 3 0 R >>"), + (13, b"<< /Type /Annot /Subtype /Highlight /Rect [50 10 60 20] /P 3 0 R /QuadPoints [1 2 3 4 5 6 7] >>"), + (14, b"<< /Type /Annot /Subtype /Square /Rect [70 10 80 20] /P 3 0 R /AP << /N << /On 5 0 R >> >> >>"), + (15, b"<< /Type /Annot /Subtype /Square /Rect [90 10 100 20] /P 3 0 R /AP << /N 6 0 R >> >>"), + (16, b"<< /Type /Annot /Subtype /Square /Rect [110 10 120 20] /P 4 0 R >>"), + (17, b"<< /Type /Annot /Subtype /Text /Rect [10 50 20 60] /P 4 0 R /RT /Group /Popup 18 0 R" + b" /State (Accepted) /F 2048 /C [1 0] /Border [1] >>"), + (18, b"<< /Type /Annot /Subtype /Popup /Rect [30 50 90 90] /P 4 0 R /Parent 19 0 R >>"), + (19, b"<< /Type /Annot /Subtype /Link /Rect [10 100 50 120] /P 4 0 R /Dest [4 0 R /Fit]" + b" /A << /S /URI /URI (https://example.com/) >> >>"), + ] + return simple_file(objects) + + def gen_outline() -> bytes: return simple_file([ (1, catalog(b" /Outlines 4 0 R /PageMode /UseOutlines")), @@ -1953,6 +2083,9 @@ def gen_functions() -> bytes: "inline-image.pdf": gen_inline_image, "page-tree-inherited.pdf": gen_page_tree_inherited, "annotations-link.pdf": gen_annotations_link, + "annotations-subtypes.pdf": gen_annotations_subtypes, + "annotations-appearance.pdf": gen_annotations_appearance, + "annotations-malformed.pdf": gen_annotations_malformed, "outline.pdf": gen_outline, "name-tree-dests.pdf": gen_name_tree_dests, "metadata-xmp.pdf": gen_metadata_xmp, From 3504f8c70477bb1a5107a5bfd84dd29231766db7 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:33:51 -0500 Subject: [PATCH 044/152] fix(cos): bound cross-reference stream entries; refuse sparse saves (#48) Two allocation bombs the scheduled workflow's libFuzzer run found in the save target on its first (5-minute) trial on GitHub's runners: - An 11 KB file made the reader allocate 2.3 GB: Flate expands a cross-reference stream about 1000 times and each entry costs tens of bytes in the cross-reference dictionaries. A document now reads at most one cross-reference stream entry per byte of the file (at least 2^20, XrefEntryBudget shared by all its sections); the rest are dropped with CrossReferenceEntryLimitExceeded (Error). - A file whose one object is numbered 6,600,016 saved to 132 MB (a classic table lists every number up to the largest) and took 2.3 GB to open again. Save now refuses, like numbers above 8,388,607, a numbering above 2^20 that is more than 16 times sparser than the objects (renumbering is not supported yet). Both replays now peak at 27 MB. Regression tests: CrossReferenceStreamTests.A_cross_reference_stream_holds_no_more_entries_than_the_file_has_bytes, SaveTests.A_document_whose_numbering_is_far_sparser_than_its_objects_is_not_saved and ..._with_a_sparse_numbering_below_a_million_is_saved. Co-Authored-By: Claude Opus 5.5 --- src/Broadside/Parsing/CrossReference.cs | 35 +++++++++++++++++++ src/Broadside/Parsing/CrossReferenceReader.cs | 17 +++++---- src/Broadside/Parsing/DiagnosticCodes.cs | 1 + src/Broadside/Parsing/XrefStreamReader.cs | 19 ++++++++-- src/Broadside/PdfDocument.cs | 10 +++--- src/Broadside/Writing/SavePlan.cs | 34 +++++++++++++++++- .../Document/CrossReferenceStreamTests.cs | 28 +++++++++++++++ tests/Broadside.Tests/Writing/SaveTests.cs | 34 ++++++++++++++++++ 8 files changed, 163 insertions(+), 15 deletions(-) diff --git a/src/Broadside/Parsing/CrossReference.cs b/src/Broadside/Parsing/CrossReference.cs index 897048a3..a584c7da 100644 --- a/src/Broadside/Parsing/CrossReference.cs +++ b/src/Broadside/Parsing/CrossReference.cs @@ -1,3 +1,4 @@ +using Broadside.IO; using Broadside.Objects; namespace Broadside.Parsing; @@ -33,6 +34,40 @@ internal readonly record struct XrefEntry(XrefEntryKind Kind, long Offset, int G public static readonly XrefEntry Free = new(XrefEntryKind.Free, 0, 0); } +/// +/// How many cross-reference stream entries one document may still read: one per byte of the file, and at least +/// . A classic table spends 20 bytes of the file per entry (§7.5.4), but a cross-reference stream's data is +/// filtered (§7.5.8), so Flate lets a few kilobytes describe millions of entries, each of which costs tens of bytes in the +/// cross-reference dictionaries: without a budget an 11 KB file made the reader allocate 2.3 GB (libFuzzer finding, issue #48). +/// A real file spends far more than a byte on each object it holds, so the budget only cuts entries no file needs. +/// +/// ISO 32000-2 §7.5.8.2 and §7.5.8.3. +internal sealed class XrefEntryBudget(long limit) +{ + /// The smallest budget, whatever the file length: 2^20 entries, enough for any small file's sparse numbering. + public const long Minimum = 1 << 20; + + private long _remaining = limit; + + /// Returns the budget for one document read from . + /// The file. + /// A new budget. + public static XrefEntryBudget For(PdfSource source) => new(Math.Max(Minimum, source.Length)); + + /// Spends one entry. + /// when the budget is spent. + public bool TryTake() + { + if (_remaining <= 0) + { + return false; + } + + _remaining--; + return true; + } +} + /// Whether a cross-reference section is a classic table (§7.5.4) or a cross-reference stream (§7.5.8). internal enum XrefSectionKind : byte { diff --git a/src/Broadside/Parsing/CrossReferenceReader.cs b/src/Broadside/Parsing/CrossReferenceReader.cs index 05d773fe..af4259a0 100644 --- a/src/Broadside/Parsing/CrossReferenceReader.cs +++ b/src/Broadside/Parsing/CrossReferenceReader.cs @@ -59,6 +59,7 @@ internal static class CrossReferenceReader var sections = new List(); var visited = new HashSet(); + XrefEntryBudget budget = XrefEntryBudget.For(source); long? next = first; while (next is { } offset) { @@ -72,14 +73,14 @@ internal static class CrossReferenceReader break; } - XrefSection? section = ReadSection(source, offset, isFirst: sections.Count == 0, streams, diagnostics, scan, visited); + XrefSection? section = ReadSection(source, offset, isFirst: sections.Count == 0, streams, diagnostics, scan, visited, budget); if (section is null) { break; } XrefSection? hybridStream = section.Kind == XrefSectionKind.Table - ? ReadHybridStream(source, header, section, visited, streams, diagnostics) + ? ReadHybridStream(source, header, section, visited, streams, diagnostics, budget) : null; if (hybridStream is not null) { @@ -186,7 +187,8 @@ private static bool TryReadStartxref(PdfSource source, FileHeader header, Diagno StreamDecoder streams, DiagnosticSink diagnostics, Lazy? scan, - HashSet visited) + HashSet visited, + XrefEntryBudget budget) { ReadOnlySpan window = source.GetWindow(offset).Span; var lexer = new CosLexer(window); @@ -210,7 +212,7 @@ private static bool TryReadStartxref(PdfSource source, FileHeader header, Diagno window = window[first.Start..]; } - return isTable ? ReadTable(source, offset, diagnostics) : XrefStreamReader.Read(source, offset, streams, diagnostics); + return isTable ? ReadTable(source, offset, diagnostics) : XrefStreamReader.Read(source, offset, streams, diagnostics, budget); } string stated = isFirst ? "startxref" : "Prev"; @@ -222,7 +224,7 @@ private static bool TryReadStartxref(PdfSource source, FileHeader header, Diagno string.Create(CultureInfo.InvariantCulture, $"The {stated} offset does not point at a cross-reference section; the section nearest to it, at offset {nearest}, is read instead."), offset); visited.Add(nearest); - return ReadSection(source, nearest, isFirst, streams, diagnostics, scan: null, visited); + return ReadSection(source, nearest, isFirst, streams, diagnostics, scan: null, visited, budget); } diagnostics.Report( @@ -320,7 +322,8 @@ void Consider(long candidate) XrefSection table, HashSet visited, StreamDecoder streams, - DiagnosticSink diagnostics) + DiagnosticSink diagnostics, + XrefEntryBudget budget) { if (!table.Trailer.TryGetValue(XRefStm, out CosObject? entry)) { @@ -370,7 +373,7 @@ void Consider(long candidate) offset += first.Start; } - return XrefStreamReader.Read(source, offset, streams, diagnostics) is { } section + return XrefStreamReader.Read(source, offset, streams, diagnostics, budget) is { } section ? section with { Trailer = new CosDictionary() } : null; } diff --git a/src/Broadside/Parsing/DiagnosticCodes.cs b/src/Broadside/Parsing/DiagnosticCodes.cs index 0f66f9e0..78c55ba9 100644 --- a/src/Broadside/Parsing/DiagnosticCodes.cs +++ b/src/Broadside/Parsing/DiagnosticCodes.cs @@ -42,6 +42,7 @@ internal static partial class DiagnosticCodes public const string XrefStreamWidthsInvalid = nameof(XrefStreamWidthsInvalid); public const string XrefStreamIndexInvalid = nameof(XrefStreamIndexInvalid); public const string XrefStreamSizeInvalid = nameof(XrefStreamSizeInvalid); + public const string CrossReferenceEntryLimitExceeded = nameof(CrossReferenceEntryLimitExceeded); public const string XrefStreamDataTruncated = nameof(XrefStreamDataTruncated); public const string TrailerXRefStmInvalid = nameof(TrailerXRefStmInvalid); diff --git a/src/Broadside/Parsing/XrefStreamReader.cs b/src/Broadside/Parsing/XrefStreamReader.cs index 57ea6598..548350ca 100644 --- a/src/Broadside/Parsing/XrefStreamReader.cs +++ b/src/Broadside/Parsing/XrefStreamReader.cs @@ -42,12 +42,14 @@ internal static class XrefStreamReader /// The absolute offset of the stream object. /// The document's filter pipeline. /// Where to report deviations. + /// The entries the document may still read, shared by its sections; a new one for the file when . /// /// The section, whose is the stream dictionary without the entries that describe the stream /// itself; when no cross-reference stream can be read there. /// - public static XrefSection? Read(PdfSource source, long offset, StreamDecoder streams, DiagnosticSink diagnostics) + public static XrefSection? Read(PdfSource source, long offset, StreamDecoder streams, DiagnosticSink diagnostics, XrefEntryBudget? budget = null) { + budget ??= XrefEntryBudget.For(source); if (!TryParseStreamObject(source, offset, diagnostics, out CosStream? stream, out CosReference? reference, out long end)) { return null; @@ -76,7 +78,7 @@ internal static class XrefStreamReader long? size = ReadSize(dictionary, offset, reference, diagnostics); List<(long First, long Count)> subsections = ReadIndex(dictionary, size ?? (data.Length / entryWidth), offset, reference, diagnostics); var entries = new Dictionary(); - ReadEntries(data, widths, subsections, size, entries, offset, reference, diagnostics); + ReadEntries(data, widths, subsections, size, entries, offset, reference, budget, diagnostics); return new XrefSection(offset, end, XrefSectionKind.Stream, entries, Trailer(dictionary)) { Stream = stream }; } @@ -281,6 +283,7 @@ private static void ReadEntries( Dictionary entries, long offset, CosReference? reference, + XrefEntryBudget budget, DiagnosticSink diagnostics) { int entryWidth = widths[0] + widths[1] + widths[2]; @@ -311,6 +314,18 @@ private static void ReadEntries( continue; } + if (!budget.TryTake()) + { + Report( + diagnostics, + DiagnosticCodes.CrossReferenceEntryLimitExceeded, + DiagnosticSeverity.Error, + string.Create(CultureInfo.InvariantCulture, $"The cross-reference streams describe more objects than the file has bytes (at least {XrefEntryBudget.Minimum}); the entries from object {number} on are not read."), + offset, + reference); + break; + } + beyondSize |= number >= size; string? problem = DecodeEntry(row, widths, out XrefEntry entry); if (problem is not null) diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 5a06c0b2..ddb40eb9 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -377,7 +377,7 @@ public static Task OpenAsync(Stream stream, PdfOptions options, Can /// Writes the document to as a complete file with a classic cross-reference table. /// Where to write, from its current position. It is not disposed. - /// The document is encrypted, or uses object numbers above 8,388,607; saving either arrives in a later version. + /// The document is encrypted, uses object numbers above 8,388,607, or numbers its objects above 1,048,576 more than 16 times as sparsely as it has objects; saving these arrives in a later version (renumbering). /// In strict mode, for the first deviation found while loading the objects to write. /// ISO 32000-2 §7.5. As with default . public void Save(Stream stream) => Save(stream, new PdfSaveOptions()); @@ -385,7 +385,7 @@ public static Task OpenAsync(Stream stream, PdfOptions options, Can /// Writes the document to as a complete file. /// Where to write, from its current position. It is not disposed. /// How to lay the file out. - /// The document is encrypted, or uses object numbers above 8,388,607; saving either arrives in a later version. + /// The document is encrypted, uses object numbers above 8,388,607, or numbers its objects above 1,048,576 more than 16 times as sparsely as it has objects; saving these arrives in a later version (renumbering). /// In strict mode, for the first deviation found while loading the objects to write. /// /// @@ -411,7 +411,7 @@ public void Save(Stream stream, PdfSaveOptions options) /// Writes the document to the file at , replacing it, with a classic cross-reference table. /// The file path. Do not name the file the document was opened from. - /// The document is encrypted, or uses object numbers above 8,388,607; saving either arrives in a later version. + /// The document is encrypted, uses object numbers above 8,388,607, or numbers its objects above 1,048,576 more than 16 times as sparsely as it has objects; saving these arrives in a later version (renumbering). /// In strict mode, for the first deviation found while loading the objects to write. /// ISO 32000-2 §7.5. As with default . public void Save(string path) => Save(path, new PdfSaveOptions()); @@ -419,7 +419,7 @@ public void Save(Stream stream, PdfSaveOptions options) /// Writes the document to the file at , replacing it. /// The file path. Do not name the file the document was opened from. /// How to lay the file out. - /// The document is encrypted, or uses object numbers above 8,388,607; saving either arrives in a later version. + /// The document is encrypted, uses object numbers above 8,388,607, or numbers its objects above 1,048,576 more than 16 times as sparsely as it has objects; saving these arrives in a later version (renumbering). /// In strict mode, for the first deviation found while loading the objects to write. /// ISO 32000-2 §7.5. As . public void Save(string path, PdfSaveOptions options) @@ -438,7 +438,7 @@ public void Save(string path, PdfSaveOptions options) /// How to lay the file out; for the defaults (a classic cross-reference table). /// Cancels the writes. /// A task that completes when the file is written. - /// The document is encrypted, or uses object numbers above 8,388,607; saving either arrives in a later version. + /// The document is encrypted, uses object numbers above 8,388,607, or numbers its objects above 1,048,576 more than 16 times as sparsely as it has objects; saving these arrives in a later version (renumbering). /// In strict mode, for the first deviation found while loading the objects to write. /// /// ISO 32000-2 §7.5. Writes exactly the bytes writes, from the same writer; only the diff --git a/src/Broadside/Writing/SavePlan.cs b/src/Broadside/Writing/SavePlan.cs index df3b8576..f188d7ae 100644 --- a/src/Broadside/Writing/SavePlan.cs +++ b/src/Broadside/Writing/SavePlan.cs @@ -29,6 +29,17 @@ internal static class SavePlan ///
public const int MaxObjectNumber = 8_388_607; + /// + /// The highest object number saved whatever the numbering's density. Above it, the highest number may be at most + /// times the number of objects: a classic table lists every number up to the highest (20 bytes + /// each), so a tiny file with one object numbered in the millions would save to a file a hundred megabytes long (libFuzzer + /// finding, issue #48). Such numberings need renumbering, which is not supported yet. + /// + public const int MaxSparseObjectNumber = 1 << 20; + + /// The most object numbers per object above . + public const int MaxNumbersPerObject = 16; + private static readonly CosName XRef = new("XRef"); private static readonly CosName ObjStm = new("ObjStm"); private static readonly CosName XRefStm = new("XRefStm"); @@ -39,7 +50,10 @@ internal static class SavePlan /// The document's linearization information, whose objects are dropped. /// The cross-reference layout. /// The writer. - /// The document is encrypted, or uses object numbers above . + /// + /// The document is encrypted, uses object numbers above , or numbers its objects far more sparsely + /// than numbers per object above . + /// public static FileWriter Create(PdfSource source, ObjectLoader loader, PdfLinearization? linearization, PdfCrossReferenceLayout layout) { CrossReference crossReference = loader.CrossReference; @@ -56,6 +70,24 @@ public static FileWriter Create(PdfSource source, ObjectLoader loader, PdfLinear $"The document uses object numbers above {MaxObjectNumber}; saving it needs renumbering, which is not supported yet."); } + int inUse = 0; + int highest = 0; + foreach (KeyValuePair entry in crossReference.Entries) + { + if (entry.Value.Kind != XrefEntryKind.Free) + { + inUse++; + highest = Math.Max(highest, entry.Key); + } + } + + if (highest > MaxSparseObjectNumber && highest > (long)MaxNumbersPerObject * inUse) + { + throw new NotSupportedException(string.Create( + System.Globalization.CultureInfo.InvariantCulture, + $"The document numbers {inUse} objects up to {highest}; saving a numbering that sparse needs renumbering, which is not supported yet.")); + } + var candidates = new HashSet(); if (linearization is not null) { diff --git a/tests/Broadside.Tests/Document/CrossReferenceStreamTests.cs b/tests/Broadside.Tests/Document/CrossReferenceStreamTests.cs index 8f9027d6..8d9d7994 100644 --- a/tests/Broadside.Tests/Document/CrossReferenceStreamTests.cs +++ b/tests/Broadside.Tests/Document/CrossReferenceStreamTests.cs @@ -153,6 +153,34 @@ public void Data_shorter_than_the_entries_ends_the_section_where_the_data_ends() Assert.Equal("XrefStreamDataTruncated", Assert.Single(document.Diagnostics).Code); } + // Found by libFuzzer (issue #48): Flate expands a cross-reference stream about 1000 times and every entry costs tens of bytes + // in the cross-reference dictionaries, so an 11 KB file made the reader allocate 2.3 GB. A document reads at most one stream + // entry per byte of the file (and at least 2^20), whatever the data holds. + [Fact] + public void A_cross_reference_stream_holds_no_more_entries_than_the_file_has_bytes() + { + const int FreeEntries = 8_000_000; + var pdf = new XrefStreamPdf().AddOnePage(); + byte[] head = XrefStreamPdf.Rows([1, 4, 0], (1, pdf.Offset(1), 0), (1, pdf.Offset(2), 0), (1, pdf.Offset(3), 0)); + byte[] data = new byte[head.Length + (FreeEntries * 5)]; + head.CopyTo(data, 0); + byte[] file = pdf.Finish(4, $"/Size {FreeEntries + 4} /Index [1 3 4 {FreeEntries}] /Root 1 0 R /W [1 4 0] /Filter /FlateDecode", FilterEncoders.Zlib(data)); + Assert.InRange(file.Length, 0, 100_000); + + long allocated = Allocations.Measure( + () => + { + using PdfDocument opened = PdfDocument.Open(file); + _ = opened.Pages.Count; + }, + warmUpCalls: 0); + using PdfDocument document = PdfDocument.Open(file); + + Assert.Single(document.Pages); + Assert.Equal(["CrossReferenceEntryLimitExceeded"], document.Diagnostics.Select(diagnostic => diagnostic.Code)); + Assert.InRange(allocated, 0, 384L << 20); // mostly the 40 MB of decoded data and its growing buffers; 8 million entries took gigabytes + } + [Fact] public void A_stream_without_type_XRef_is_read_with_a_diagnostic() { diff --git a/tests/Broadside.Tests/Writing/SaveTests.cs b/tests/Broadside.Tests/Writing/SaveTests.cs index df3a3ef6..90483308 100644 --- a/tests/Broadside.Tests/Writing/SaveTests.cs +++ b/tests/Broadside.Tests/Writing/SaveTests.cs @@ -270,6 +270,40 @@ public void A_document_with_object_numbers_beyond_the_limit_is_not_saved() Assert.Equal(0, output.Length); } + // Found by libFuzzer (issue #48): an 11 KB file whose one object is numbered 6,600,016 saved to a 132 MB file (a classic table + // lists every number up to the largest), which then took 2.3 GB to open again. Saving a numbering that sparse needs + // renumbering, so it is refused like numbers above the limit; a large but dense numbering still saves. + [Fact] + public void A_document_whose_numbering_is_far_sparser_than_its_objects_is_not_saved() + { + byte[] file = Document.TestPdf.AppendUpdate( + Document.TestPdf.OnePage(string.Empty), + "/Size 2000001 /Root 1 0 R", + (2_000_000, 0, "<< /Unused true >>")); + using PdfDocument source = PdfDocument.Open(file); + using var output = new MemoryStream(); + + NotSupportedException error = Assert.Throws(() => source.Save(output)); + Assert.Contains("renumbering", error.Message, StringComparison.Ordinal); + Assert.Equal(0, output.Length); + } + + [Fact] + public void A_document_with_a_sparse_numbering_below_a_million_is_saved() + { + byte[] file = Document.TestPdf.AppendUpdate( + Document.TestPdf.OnePage(string.Empty), + "/Size 1000001 /Root 1 0 R", + (1_000_000, 0, "<< /Unused true >>")); + using PdfDocument source = PdfDocument.Open(file); + using var output = new MemoryStream(); + + source.Save(output); + + using PdfDocument saved = PdfDocument.Open(output.ToArray()); + Assert.Single(saved.Pages); + } + [Fact] public void An_encrypted_document_is_not_saved() { From 4f41c662d8130696c9469df9fbf864801ff669dd Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:35:45 -0500 Subject: [PATCH 045/152] docs(conformance): note the entry budget and sparse-save refusal (#48) Co-Authored-By: Claude Opus 5.5 --- docs/conformance/iso-32000-2.md | 4 ++-- tests/Broadside.Tests/Document/CrossReferenceStreamTests.cs | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index 0f09419b..f4acfb82 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -32,11 +32,11 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.5.1 | General | done | `PdfDocument`, `CrossReferenceReader`, `PdfSource`, `MappedFileSource`, `StreamSource` | `Broadside.Tests.Document.OpenDocumentTests.A_file_opens_identically_from_a_path_a_stream_and_bytes_with_no_diagnostics`, `Broadside.Tests.Document.WellFormedCorpusTests.A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics`, `Broadside.Tests.Document.SourceTests.A_seekable_stream_is_read_in_place_only_where_objects_are_needed`, `Broadside.Tests.Document.SourceTests.A_non_seekable_stream_is_read_whole_when_opened`, `Broadside.Tests.Document.SourceTests.A_non_seekable_stream_longer_than_the_buffer_limit_is_read_through_a_temporary_file`, `Broadside.Tests.Document.SourceTests.OpenAsync_reads_a_non_seekable_stream_asynchronously`, `Broadside.Tests.Document.LargeFileTests.A_file_over_2_GiB_opens_and_reads_its_last_page_in_bounded_memory`, `Broadside.Tests.Document.RealWorldCorpusTests.A_real_world_file_opens_and_walks_leniently_without_an_exception`, `Broadside.Tests.Document.RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot` | Read from the end through startxref, the cross-reference table and the trailer, never serially; linearized files read through the same path (Annex F). Sources (#45): bytes (zero-copy), paths and FileStreams memory-mapped, other seekable streams read in place under a lock in growing windows, non-seekable streams copied at open (memory up to `StreamBufferLimit`, then a temporary file; `OpenAsync` copies asynchronously); fuzz `windowed-document`. Real-world gate (#47): 2,612 corpus files open and walk leniently with no crash or hang (30 s per file); per-corpus counts and diagnostic histograms in the `RealWorldCorpusTests` snapshot. | | 7.5.2 | File header | done | `FileHeader`, `PdfVersion`, `PdfDocument`, `FileWriter` | `Broadside.Tests.Document.FileStructureTests.Offsets_count_from_the_header_so_bytes_before_it_do_not_matter`, `Broadside.Tests.Document.FileStructureTests.A_file_without_a_header_opens_from_byte_0_with_a_diagnostic`, `Broadside.Tests.Document.VersionTests.The_catalog_version_overrides_the_header_only_when_later`, `Broadside.Tests.Document.VersionTests.A_header_without_a_valid_version_takes_the_catalog_version_with_a_diagnostic`, `Broadside.Tests.Document.RepairTests.Offsets_counted_from_byte_0_instead_of_the_header_are_repaired`, `Broadside.Tests.Writing.SaveTests.The_header_keeps_the_version_unless_the_layout_needs_a_later_one`, `Broadside.Tests.Writing.CreateTests.A_created_document_has_one_empty_letter_page_and_is_PDF_2_0`, `Broadside.Tests.Document.FileLayoutTests.A_layout_deviation_is_read_with_one_diagnostic`, `Broadside.Tests.Document.FileLayoutTests.Strict_mode_throws_on_a_layout_deviation`, `Broadside.Tests.Document.FileLayoutTests.A_header_ended_by_any_end_of_line_marker_has_no_diagnostic`, `Broadside.Tests.Document.VeraPdfAgreementTests.Strict_mode_agrees_with_veraPDF_or_the_disagreement_is_triaged` | Header searched in the first 1024 bytes; every stated offset is relative to it; missing header: offsets from byte 0, version 1.4 unless the catalog says otherwise; offsets a writer counted from byte 0 despite junk before the header are repaired by the nearest-section and object searches; written: `%PDF-n.m` LF, then a comment of four bytes above 127; the document version is kept and raised to 1.5 for cross-reference streams (ADR 0003); `Create` writes 2.0 (#44). A header whose version is not followed by an end-of-line marker: `HeaderInvalid` (#47). Not checked yet: the binary comment line a file with binary data shall have (needs a whole-file scan; follow-up from the #47 veraPDF triage). | | 7.5.3 | File body | done | `ObjectLoader`, `FileWriter`, `ObjectCache`, `OnceCache` | `Broadside.Tests.Document.FileStructureTests.Resolving_a_reference_twice_returns_the_same_instance_and_direct_objects_resolve_to_themselves`, `Broadside.Tests.Document.FileStructureTests.A_stream_takes_its_extent_from_an_indirect_length`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_reopens_with_the_same_objects_and_no_diagnostics`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_passes_qpdf_check`, `Broadside.Tests.Document.LazyLoadingTests.Opening_a_file_parses_the_catalog_and_nothing_else`, `Broadside.Tests.Document.LazyLoadingTests.Every_object_is_parsed_once_however_many_threads_read_it`, `Broadside.Tests.Document.LazyLoadingTests.An_object_stream_is_decoded_once_however_many_threads_read_its_members`, `Broadside.Tests.Document.LazyLoadingTests.Two_threads_each_loading_a_stream_whose_Length_is_the_other_one_do_not_deadlock`, `Broadside.Tests.Document.ConcurrencyTests.Every_page_and_object_reads_the_same_from_many_threads_as_from_one` | Objects load lazily by cross-reference entry, from the file body or an object stream (7.5.7); a full save writes every in-use object of the newest revision, dropping only old cross-reference streams, object streams and linearization data that nothing refers to (#44), parsed once per (number, generation) and object streams decoded once, under the concurrency contract on `PdfDocument` (#45); stream data stays in the source and is read on access; parses traced at Trace level (`ObjectParsed`, `ObjectStreamDecoded`); `bench/Broadside.Benchmarks/LazyLoadingBenchmarks.cs` (cached resolve allocates nothing) | -| 7.5.4 | Cross-reference table | done | `XrefTableReader`, `CrossReference`, `FileScan`, `CrossReferenceReconstructor`, `FileWriter` | `Broadside.Tests.Document.FileStructureTests.Entries_are_read_as_tokens_not_fixed_width_records`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_is_read_from_where_its_header_is_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation`, `Broadside.Tests.Document.RepairTests.Entries_that_are_not_20_bytes_long_are_read_with_one_diagnostic_per_section`, `Broadside.Tests.Document.RepairTests.A_subsection_numbered_from_1_whose_first_entry_is_the_free_list_head_is_renumbered_from_0`, `Broadside.Tests.Document.RepairTests.A_file_whose_line_endings_were_converted_to_crlf_opens_with_the_intact_pages`, `Broadside.Tests.Document.RepairTests.Rebuilding_an_updated_file_keeps_the_newest_copy_of_each_object_and_the_newest_trailer`, `Broadside.Tests.Document.RepairTests.A_repair_met_twice_is_recorded_once`, `Broadside.Tests.Document.BrokenCorpusTests.A_broken_file_opens_leniently_with_exactly_the_documented_diagnostics_and_the_intact_pages`, `Broadside.Tests.Document.BrokenCorpusTests.Strict_mode_throws_on_a_broken_file_with_the_code_of_its_first_diagnostic`, `Broadside.Tests.Writing.SaveTests.Startxref_gives_the_offset_of_the_cross_reference_information`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_passes_qpdf_check`, `Broadside.Tests.Document.FileLayoutTests.A_layout_deviation_is_read_with_one_diagnostic`, `Broadside.Tests.Document.FileLayoutTests.A_subsection_header_on_its_own_line_has_no_diagnostic_whatever_ends_the_xref_line`, `Broadside.Tests.Document.VeraPdfAgreementTests.Strict_mode_agrees_with_veraPDF_or_the_disagreement_is_triaged` | Subsections and n/f entries read as tokens; entries not 20 bytes long reported once per section (XrefEntryFormatInvalid); a subsection numbered from 1 whose first entry is the free-list head renumbered from 0 (XrefSubsectionNumberingInvalid); offset-0 in-use entries read as free; misplaced objects searched (7.3.10); an unreadable table is rebuilt by one windowed scan for N G obj headers (newest copy wins), object stream members and trailers (repair is informative, ADR 0005); comments inside a table are read silently; broken-xref-offsets.pdf, no-xref.pdf; fuzz `repair`; written as one subsection from 0 with 20-byte entries (CR LF), free entries linked from object 0 (generation 65535); offsets above ten digits refuse the table layout (#44). A subsection header that is not its own line of two integers separated by one space: `XrefSubsectionHeaderInvalid`, once per section (trailing spaces tolerated, as Acrobat writes them) (#47). | +| 7.5.4 | Cross-reference table | done | `XrefTableReader`, `CrossReference`, `FileScan`, `CrossReferenceReconstructor`, `FileWriter` | `Broadside.Tests.Writing.SaveTests.A_document_whose_numbering_is_far_sparser_than_its_objects_is_not_saved`, `Broadside.Tests.Document.FileStructureTests.Entries_are_read_as_tokens_not_fixed_width_records`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`, `Broadside.Tests.Document.FileStructureTests.An_entry_whose_offset_does_not_hold_the_object_is_read_from_where_its_header_is_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation`, `Broadside.Tests.Document.RepairTests.Entries_that_are_not_20_bytes_long_are_read_with_one_diagnostic_per_section`, `Broadside.Tests.Document.RepairTests.A_subsection_numbered_from_1_whose_first_entry_is_the_free_list_head_is_renumbered_from_0`, `Broadside.Tests.Document.RepairTests.A_file_whose_line_endings_were_converted_to_crlf_opens_with_the_intact_pages`, `Broadside.Tests.Document.RepairTests.Rebuilding_an_updated_file_keeps_the_newest_copy_of_each_object_and_the_newest_trailer`, `Broadside.Tests.Document.RepairTests.A_repair_met_twice_is_recorded_once`, `Broadside.Tests.Document.BrokenCorpusTests.A_broken_file_opens_leniently_with_exactly_the_documented_diagnostics_and_the_intact_pages`, `Broadside.Tests.Document.BrokenCorpusTests.Strict_mode_throws_on_a_broken_file_with_the_code_of_its_first_diagnostic`, `Broadside.Tests.Writing.SaveTests.Startxref_gives_the_offset_of_the_cross_reference_information`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_passes_qpdf_check`, `Broadside.Tests.Document.FileLayoutTests.A_layout_deviation_is_read_with_one_diagnostic`, `Broadside.Tests.Document.FileLayoutTests.A_subsection_header_on_its_own_line_has_no_diagnostic_whatever_ends_the_xref_line`, `Broadside.Tests.Document.VeraPdfAgreementTests.Strict_mode_agrees_with_veraPDF_or_the_disagreement_is_triaged` | Subsections and n/f entries read as tokens; entries not 20 bytes long reported once per section (XrefEntryFormatInvalid); a subsection numbered from 1 whose first entry is the free-list head renumbered from 0 (XrefSubsectionNumberingInvalid); offset-0 in-use entries read as free; misplaced objects searched (7.3.10); an unreadable table is rebuilt by one windowed scan for N G obj headers (newest copy wins), object stream members and trailers (repair is informative, ADR 0005); comments inside a table are read silently; broken-xref-offsets.pdf, no-xref.pdf; fuzz `repair`; written as one subsection from 0 with 20-byte entries (CR LF), free entries linked from object 0 (generation 65535); offsets above ten digits refuse the table layout (#44). A subsection header that is not its own line of two integers separated by one space: `XrefSubsectionHeaderInvalid`, once per section (trailing spaces tolerated, as Acrobat writes them) (#47).; saving refuses a numbering above 2^20 more than 16 times sparser than the objects (the table would list every number; renumbering is not supported yet; libFuzzer finding, #48) | | 7.5.5 | File trailer | partial | `CrossReferenceReader`, `CrossReference`, `PdfDocument`, `CrossReferenceReconstructor`, `FileWriter` | `Broadside.Tests.Document.FileStructureTests.A_startxref_offset_on_the_white_space_before_xref_is_repaired_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.A_file_with_no_startxref_is_rebuilt_by_scanning_and_keeps_its_trailer`, `Broadside.Tests.Document.FileStructureTests.A_trailer_without_root_is_repaired_by_finding_the_catalog_by_scanning`, `Broadside.Tests.Document.FileStructureTests.A_prev_chain_that_loops_ends_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic`, `Broadside.Tests.Document.RepairTests.A_wrong_prev_offset_reads_the_nearest_older_section`, `Broadside.Tests.Document.RepairTests.Rebuilding_an_encrypted_file_keeps_its_encryption_dictionary_and_identifier`, `Broadside.Tests.Document.RepairTests.A_compressed_catalog_is_found_when_no_trailer_survives`, `Broadside.Tests.Document.RepairTests.A_file_with_nothing_but_junk_cannot_be_read`, `Broadside.Tests.Document.BrokenCorpusTests.A_broken_file_opens_leniently_with_exactly_the_documented_diagnostics_and_the_intact_pages`, `Broadside.Tests.Writing.SaveTests.Saving_an_updated_file_collapses_its_revisions_into_one_with_the_newest_objects`, `Broadside.Tests.Writing.SaveTests.Startxref_gives_the_offset_of_the_cross_reference_information`, `Broadside.Tests.Document.FileLayoutTests.A_layout_deviation_is_read_with_one_diagnostic`, `Broadside.Tests.Document.FileLayoutTests.White_space_after_the_last_end_of_file_marker_has_no_diagnostic`, `Broadside.Tests.Document.FileLayoutTests.A_trailer_id_is_required_only_from_pdf_2_0`, `Broadside.Tests.Document.VeraPdfAgreementTests.Strict_mode_agrees_with_veraPDF_or_the_disagreement_is_triaged` | Last startxref, Prev chain with loop guard, Root; trailer merged newest-first; a startxref or Prev offset at neither xref nor N G obj reads the nearest section (table wins ties, never one already read); missing or unusable startxref, or a Root that does not lead to the catalog, rebuilds the cross-reference from a scan: newest trailer or xref-stream dictionary whose Root leads to a catalog, Encrypt/ID/Info from any trailer, else the newest /Catalog (TrailerMissing or RootMissing); no catalog at all throws CatalogNotFound; startxref-wrong.pdf, no-xref.pdf; ignoring entries beyond Size is not done; Encrypt and ID are read from the newest trailer (#42); written trailer: Size, the source trailer without Size, Prev, XRefStm and ID, then ID; startxref and %%EOF (#44). Data (not white-space) after the %%EOF that follows the last startxref: `EndOfFileMarkerNotLast`; a PDF 2.0 document (header or catalog Version) whose trailer has no ID: `TrailerIdMissing` (Table 15) (#47). | | 7.5.6 | Incremental updates | done | `CrossReference`, `RevisionReader`, `PdfRevision`, `PdfDocument` | `Broadside.Tests.Document.IncrementalUpdateTests.An_updated_file_has_one_revision_per_update_and_the_first_is_the_original_file`, `Broadside.Tests.Document.IncrementalUpdateTests.Deleted_objects_read_as_null_and_a_reused_number_resolves_only_with_its_new_generation`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_is_the_file_as_it_was_after_that_save`, `Broadside.Tests.Document.IncrementalUpdateTests.Each_revision_has_its_own_trailer`, `Broadside.Tests.Document.IncrementalUpdateTests.A_hybrid_file_has_its_main_section_and_its_update_section_as_two_revisions`, `Broadside.Tests.Document.IncrementalUpdateTests.An_update_trailer_that_drops_root_takes_it_from_the_older_trailer_with_a_diagnostic`, `Broadside.Tests.Document.IncrementalUpdateTests.An_earlier_revision_without_its_end_of_file_marker_ends_after_its_startxref_offset_with_a_diagnostic`, `Broadside.Tests.Document.FileStructureTests.The_newest_section_wins_and_older_sections_are_read_through_prev`, `Broadside.Tests.Writing.SaveTests.Saving_an_updated_file_collapses_its_revisions_into_one_with_the_newest_objects` | Revisions oldest first, each the byte prefix up to its %%EOF and end-of-line; newest section decides per object number, free hides older copies, a reference must match the live generation; Root, Info, Encrypt and ID missing from the newest trailer are taken from an older one with TrailerEntryFromOlderRevision; a linearized pair is one revision; a hybrid XRefStm stream joins its table's revision; a full save collapses the revisions into one (#44); writing an incremental update is Phase 4 | | 7.5.7 | Object streams | done | `ObjectStream`, `ObjectLoader`, `FileWriter` | `Broadside.Tests.Document.ObjectStreamTests.The_catalog_page_tree_and_page_resolve_from_an_object_stream`, `Broadside.Tests.Document.ObjectStreamTests.A_reference_to_a_member_with_a_generation_other_than_0_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.Members_need_no_white_space_between_them`, `Broadside.Tests.Document.ObjectStreamTests.A_member_at_another_index_than_its_entry_says_is_found_by_its_object_number`, `Broadside.Tests.Document.ObjectStreamTests.Offsets_out_of_order_bound_each_member_by_the_next_offset_in_sorted_order`, `Broadside.Tests.Document.ObjectStreamTests.A_member_the_object_stream_does_not_hold_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_whose_N_is_one_of_its_own_members_resolves_its_members_to_null`, `Broadside.Tests.Document.ObjectStreamTests.An_object_stream_listed_as_compressed_itself_is_not_read`, `Broadside.Tests.Document.ObjectStreamTests.A_type_2_entry_naming_an_object_that_is_not_a_stream_resolves_to_null`, `Broadside.Tests.Document.ObjectStreamTests.A_flate_encoded_object_stream_is_decoded_through_the_filters`, `Broadside.Tests.Document.ObjectStreamTests.Members_of_one_object_stream_resolve_to_the_same_instances_from_concurrent_threads`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file`, `Broadside.Tests.Document.RepairTests.Objects_in_object_streams_survive_a_damaged_cross_reference_stream`, `Broadside.Tests.Writing.SaveTests.Objects_that_were_not_changed_keep_their_source_bytes_in_any_layout`, `Broadside.Tests.Writing.SaveTests.The_information_dictionary_of_a_hybrid_file_survives_from_its_object_stream` | Members located by type 2 entries (index checked against the header, searched by number when wrong, with ObjectStreamIndexMismatch); each member parsed over exactly the bytes up to the next offset (NOTE 7); out-of-order offsets sorted; container decoded once per document and shared, decrypted as a whole (members skip hooks 1 and 2); nested containers and self-referencing N/First/Filter end with ObjectStreamNested/ObjectStreamCycle; /Extends ignored (grouping only); object-stream.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `object-stream`; written by `PdfCrossReferenceLayout.StreamWithObjectStreams`: every object with generation 0 that is not a stream or a bare reference, at most 100 per Flate-encoded object stream; unchanged members keep their bytes (#44); a rebuilt cross-reference indexes the members of every object stream found by scanning (#41) | -| 7.5.8 | Cross-reference streams | done | `XrefStreamReader`, `CrossReferenceReader`, `CrossReference`, `FileWriter`, `PdfCrossReferenceLayout` | `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file`, `Broadside.Tests.Document.CrossReferenceStreamTests.Strict_mode_opens_a_file_with_compressed_structures`, `Broadside.Tests.Document.CrossReferenceStreamTests.The_trailer_of_a_cross_reference_stream_is_its_dictionary_without_the_entries_that_describe_the_stream`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_type_field_makes_every_entry_type_1`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_generation_field_defaults_to_generation_0`, `Broadside.Tests.Document.CrossReferenceStreamTests.Index_with_two_subsections_numbers_the_entries_of_each_from_its_first_object_number`, `Broadside.Tests.Document.CrossReferenceStreamTests.Wide_fields_are_read_big_endian`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_entry_of_an_unknown_type_is_a_reference_to_the_null_object`, `Broadside.Tests.Document.CrossReferenceStreamTests.Data_shorter_than_the_entries_ends_the_section_where_the_data_ends`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_without_type_XRef_is_read_with_a_diagnostic`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_whose_W_cannot_be_read_is_not_a_cross_reference_section_so_the_file_is_rebuilt_by_scanning`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_update_written_as_a_cross_reference_stream_overrides_the_original_section`, `Broadside.Tests.Document.HybridFileTests.An_object_only_the_XRefStm_stream_lists_is_found`, `Broadside.Tests.Document.HybridFileTests.An_in_use_entry_in_the_table_of_a_section_takes_precedence_over_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.A_free_entry_in_the_table_of_a_section_gives_way_to_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.The_XRefStm_streams_dictionary_is_not_the_trailer_and_its_Prev_is_not_followed`, `Broadside.Tests.Document.HybridFileTests.An_XRefStm_offset_that_names_no_stream_is_reported_and_the_table_is_still_read`, `Broadside.Tests.Document.LinearizationTests.A_linearized_file_with_cross_reference_streams_has_its_first_page_and_main_streams_as_one_revision`, `Broadside.Tests.Writing.SaveTests.Startxref_gives_the_offset_of_the_cross_reference_information`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_passes_qpdf_check` | 7.5.8.1 to 7.5.8.4. W (0 to 8 bytes per field, W[0] = 0 means type 1), Index (default [0 Size]), Size, Prev; entries big-endian into long; type 0/1/2, other types are the null object; dictionary minus Type, Length, W, Index, Filter, DecodeParms, DL, F, FFilter, FDecodeParms is the trailer; data decoded through the filter pipeline under the engine's decoded-length limit, never decrypted; hybrid XRefStm read after its table and before Prev, its entries replacing the table's free entries (an in-use table entry wins), its own Prev not followed and its dictionary not a trailer; xref-stream.pdf, object-stream.pdf, png-predictor.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `xref-stream`; written by `PdfCrossReferenceLayout.Stream` and `StreamWithObjectStreams`: W [1 n 2] with n the fewest bytes for the largest offset, an entry for the stream itself, Flate with Predictor 12, trailer keys in its dictionary; hybrid files are not written (#44) | +| 7.5.8 | Cross-reference streams | done | `XrefStreamReader`, `CrossReferenceReader`, `CrossReference`, `FileWriter`, `PdfCrossReferenceLayout` | `Broadside.Tests.Document.CrossReferenceStreamTests.A_cross_reference_stream_holds_no_more_entries_than_the_file_has_bytes`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_file_with_compressed_structures_exposes_the_same_pages_and_objects_as_the_classic_file`, `Broadside.Tests.Document.CrossReferenceStreamTests.Strict_mode_opens_a_file_with_compressed_structures`, `Broadside.Tests.Document.CrossReferenceStreamTests.The_trailer_of_a_cross_reference_stream_is_its_dictionary_without_the_entries_that_describe_the_stream`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_type_field_makes_every_entry_type_1`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_missing_generation_field_defaults_to_generation_0`, `Broadside.Tests.Document.CrossReferenceStreamTests.Index_with_two_subsections_numbers_the_entries_of_each_from_its_first_object_number`, `Broadside.Tests.Document.CrossReferenceStreamTests.Wide_fields_are_read_big_endian`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_entry_of_an_unknown_type_is_a_reference_to_the_null_object`, `Broadside.Tests.Document.CrossReferenceStreamTests.Data_shorter_than_the_entries_ends_the_section_where_the_data_ends`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_without_type_XRef_is_read_with_a_diagnostic`, `Broadside.Tests.Document.CrossReferenceStreamTests.A_stream_whose_W_cannot_be_read_is_not_a_cross_reference_section_so_the_file_is_rebuilt_by_scanning`, `Broadside.Tests.Document.CrossReferenceStreamTests.An_update_written_as_a_cross_reference_stream_overrides_the_original_section`, `Broadside.Tests.Document.HybridFileTests.An_object_only_the_XRefStm_stream_lists_is_found`, `Broadside.Tests.Document.HybridFileTests.An_in_use_entry_in_the_table_of_a_section_takes_precedence_over_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.A_free_entry_in_the_table_of_a_section_gives_way_to_its_XRefStm_stream`, `Broadside.Tests.Document.HybridFileTests.The_XRefStm_streams_dictionary_is_not_the_trailer_and_its_Prev_is_not_followed`, `Broadside.Tests.Document.HybridFileTests.An_XRefStm_offset_that_names_no_stream_is_reported_and_the_table_is_still_read`, `Broadside.Tests.Document.LinearizationTests.A_linearized_file_with_cross_reference_streams_has_its_first_page_and_main_streams_as_one_revision`, `Broadside.Tests.Writing.SaveTests.Startxref_gives_the_offset_of_the_cross_reference_information`, `Broadside.Tests.Writing.SaveTests.A_well_formed_file_saved_in_any_layout_passes_qpdf_check` | 7.5.8.1 to 7.5.8.4. W (0 to 8 bytes per field, W[0] = 0 means type 1), Index (default [0 Size]), Size, Prev; entries big-endian into long; type 0/1/2, other types are the null object; dictionary minus Type, Length, W, Index, Filter, DecodeParms, DL, F, FFilter, FDecodeParms is the trailer; data decoded through the filter pipeline under the engine's decoded-length limit, never decrypted; hybrid XRefStm read after its table and before Prev, its entries replacing the table's free entries (an in-use table entry wins), its own Prev not followed and its dictionary not a trailer; xref-stream.pdf, object-stream.pdf, png-predictor.pdf, hybrid-xref.pdf, linearized-xref-stream.pdf; fuzz `xref-stream`; written by `PdfCrossReferenceLayout.Stream` and `StreamWithObjectStreams`: W [1 n 2] with n the fewest bytes for the largest offset, an entry for the stream itself, Flate with Predictor 12, trailer keys in its dictionary; hybrid files are not written (#44); a document reads at most one stream entry per byte of the file, and at least 2^20 (`XrefEntryBudget`, CrossReferenceEntryLimitExceeded; libFuzzer finding, #48) | | 7.6.1 | General | done | `PdfDocument`, `PdfSecurity` | `Broadside.Tests.Security.EncryptedCorpusTests.An_encrypted_file_opens_with_the_empty_user_password_and_its_content_stream_decrypts`, `Broadside.Tests.Security.EncryptedCorpusTests.An_unencrypted_document_permits_everything` | An encrypted file opens transparently: `PdfDocument.IsEncrypted`, `PdfDocument.Security`, `PdfDocument.Permissions` | | 7.6.2 | Application of encryption | done | `DocumentSecurity`, `DocumentDecryptor`, `SecurityHandlerRegistry`, `ISecurityHandler`, `SecurityHandlerContext`, `SecurityHandlerResult`, `PdfEncryptionNotSupportedException` | `Broadside.Tests.Security.EncryptedCorpusTests.Strings_are_decrypted_with_the_key_of_the_object_that_holds_them`, `Broadside.Tests.Security.EncryptedCorpusTests.The_encryption_dictionary_and_the_file_identifier_are_not_decrypted`, `Broadside.Tests.Security.EncryptedCorpusTests.Decrypting_marks_nothing_dirty`, `Broadside.Tests.Security.EncryptedCorpusTests.Concurrent_readers_see_the_same_decrypted_content`, `Broadside.Tests.Security.EncryptedCorpusTests.A_document_rebuilt_because_its_root_is_unusable_is_still_decrypted`, `Broadside.Tests.Security.EncryptedCorpusTests.A_document_whose_cross_reference_is_unreadable_is_rebuilt_and_decrypted`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.The_standard_handler_is_registered_by_default`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_handler_registered_for_standard_replaces_the_default`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.Two_engines_with_different_handlers_do_not_interfere`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_handler_that_supplies_the_key_another_way_decrypts_the_document`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_handler_is_chosen_by_subfilter_when_no_handler_has_the_filter_name`, `Broadside.Tests.Security.SecurityHandlerExtensionPointTests.A_document_whose_handler_is_not_registered_is_not_supported` | Every string and stream is decrypted as its indirect object loads (hook 2), never the Encrypt dictionary, the trailer (ID, AuthCode), object-stream members (their container is decrypted), cross-reference streams or a signature dictionary's Contents; decryption never marks objects dirty; handler chosen by Filter, else by SubFilter (`PdfOptions.UseSecurityHandler`, standard and public-key handlers by default); V 1-6 (V 3 read as V 2 with a diagnostic); newest trailer's Encrypt and ID; a missing ID is an empty identifier with EncryptionIdMissing; an Encrypt entry that does not resolve rebuilds the cross-reference (#41); fuzz `encrypted-document` | | 7.6.3 | General encryption algorithm | done | `DocumentDecryptor`, `Rc4`, `AesCipher`, `ManagedAes`, `Md5`, `ManagedMd5`, `CryptographyBackend` | `Broadside.Tests.Security.EncryptedCorpusTests.The_managed_cryptography_decrypts_like_the_platform_cryptography`, `Broadside.Tests.Security.CryptFilterTests.Aes_data_with_a_damaged_pad_is_kept_whole_with_a_diagnostic`, `Broadside.Tests.Security.CryptographyTests.Managed_md5_matches_rfc_1321`, `Broadside.Tests.Security.CryptographyTests.Managed_md5_agrees_with_the_platform_at_every_padding_boundary`, `Broadside.Tests.Security.CryptographyTests.Managed_aes_matches_fips_197_appendix_c`, `Broadside.Tests.Security.CryptographyTests.Managed_aes_cbc_agrees_with_the_platform`, `Broadside.Tests.Security.CryptographyTests.Rc4_matches_the_published_vectors`, `Broadside.Tests.Security.DecryptionAllocationTests.Rc4_allocates_nothing`, `Broadside.Tests.Security.DecryptionAllocationTests.Aes_cbc_into_a_buffer_allocates_nothing_per_block` | 7.6.3.1 to 7.6.3.3. Algorithm 1 (RC4, AES-128-CBC with "sAlT") and 1.A (AES-256-CBC), IV prefix, PKCS#5 padding; damaged AES data repaired like pdf.js with EncryptedDataInvalid (too short: nothing; partial block dropped; bad pad kept); RC4 managed; MD5 and AES from the BCL, with managed MD5 and AES selected at run time where the platform has none (browser); `SecurityBenchmarks`; fuzz `decrypt` | diff --git a/tests/Broadside.Tests/Document/CrossReferenceStreamTests.cs b/tests/Broadside.Tests/Document/CrossReferenceStreamTests.cs index 8d9d7994..30ebb571 100644 --- a/tests/Broadside.Tests/Document/CrossReferenceStreamTests.cs +++ b/tests/Broadside.Tests/Document/CrossReferenceStreamTests.cs @@ -159,12 +159,12 @@ public void Data_shorter_than_the_entries_ends_the_section_where_the_data_ends() [Fact] public void A_cross_reference_stream_holds_no_more_entries_than_the_file_has_bytes() { - const int FreeEntries = 8_000_000; + const int freeEntries = 8_000_000; var pdf = new XrefStreamPdf().AddOnePage(); byte[] head = XrefStreamPdf.Rows([1, 4, 0], (1, pdf.Offset(1), 0), (1, pdf.Offset(2), 0), (1, pdf.Offset(3), 0)); - byte[] data = new byte[head.Length + (FreeEntries * 5)]; + byte[] data = new byte[head.Length + (freeEntries * 5)]; head.CopyTo(data, 0); - byte[] file = pdf.Finish(4, $"/Size {FreeEntries + 4} /Index [1 3 4 {FreeEntries}] /Root 1 0 R /W [1 4 0] /Filter /FlateDecode", FilterEncoders.Zlib(data)); + byte[] file = pdf.Finish(4, $"/Size {freeEntries + 4} /Index [1 3 4 {freeEntries}] /Root 1 0 R /W [1 4 0] /Filter /FlateDecode", FilterEncoders.Zlib(data)); Assert.InRange(file.Length, 0, 100_000); long allocated = Allocations.Measure( From a1b614cb581967b1c23878e1cb8794a7cfcd2f58 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:47:43 -0500 Subject: [PATCH 046/152] feat(fonts): embedded TrueType glyph outlines and the font program parser extension point (#50) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Font program parser extension point (ISO 32000-2 §9.9): IFontProgramParser, FontProgram, FontProgramContext, FontCharacterMap, GlyphOutline (over the Broadside.Graphics PathView, PathVerb and PathPoint types), PdfOptions.UseFontProgramParser; per-engine registry, parser picked by signature then by the declared FontFile key and Subtype (Table 124). - TrueTypeFontProgramParser, the first managed default: sfnt directory and TrueType collections, head, hhea, hmtx, maxp, loca (short and long), glyf (simple glyphs with implied midpoints, composites with offsets, scales, 2x2 transforms, point matching, USE_MY_METRICS, depth/point/component limits and cycle checks), cmap formats 0, 2, 4, 6, 12, 13, post 1.0, 2.0, 2.5. Lenient repairs with diagnostics; allocation-free outlines. - PdfFont.Program parses the font file stream once per stream; PdfTrueTypeFont.GetGlyphId implements §9.6.5.4 for symbolic and nonsymbolic fonts, with Information diagnostics for the processor-chosen fallbacks. - Corpus: text-truetype-composite, -symbolic, -macroman, -loca-long; fuzz target font-truetype; TrueTypeBenchmarks; conformance 9.6.3, 9.6.5.4, 9.9.1, 9.9.2; the adding-a-font-program-parser skill's Contract section now has the real signatures. Co-Authored-By: Claude Opus 5.5 --- .../adding-a-font-program-parser/SKILL.md | 81 ++- .../TrueTypeBenchmarks.cs | 133 +++++ docs/conformance/iso-32000-2.md | 7 +- src/Broadside/EngineConfiguration.cs | 6 + src/Broadside/Fonts/FontCharacterMap.cs | 29 + src/Broadside/Fonts/FontNames.cs | 9 + src/Broadside/Fonts/FontProgram.cs | 85 +++ src/Broadside/Fonts/FontProgramContext.cs | 137 +++++ src/Broadside/Fonts/FontProgramFormat.cs | 21 + .../Fonts/FontProgramParserRegistry.cs | 111 ++++ src/Broadside/Fonts/FontProgramSource.cs | 18 + src/Broadside/Fonts/GlyphMetrics.cs | 10 + src/Broadside/Fonts/GlyphOutline.cs | 113 ++++ src/Broadside/Fonts/GlyphOutlineStatus.cs | 18 + src/Broadside/Fonts/IFontProgramParser.cs | 42 ++ src/Broadside/Fonts/PdfFont.cs | 48 ++ src/Broadside/Fonts/PdfTrueTypeFont.cs | 37 +- src/Broadside/Fonts/TrueType/CmapSubtable.cs | 406 +++++++++++++ src/Broadside/Fonts/TrueType/PostTable.cs | 193 ++++++ src/Broadside/Fonts/TrueType/SfntFile.cs | 313 ++++++++++ .../TrueType/TrueTypeFontProgram.Glyphs.cs | 559 ++++++++++++++++++ .../Fonts/TrueType/TrueTypeFontProgram.cs | 421 +++++++++++++ .../TrueType/TrueTypeFontProgramParser.cs | 97 +++ src/Broadside/Fonts/TrueTypeGlyphSelector.cs | 234 ++++++++ .../Parsing/DiagnosticCodes.Fonts.cs | 12 + src/Broadside/PdfDocument.Fonts.cs | 33 ++ src/Broadside/PdfDocument.cs | 27 +- src/Broadside/PdfOptions.cs | 21 + src/Broadside/PublicAPI.Unshipped.txt | 92 +++ tests/Broadside.Fuzz/FuzzTargets.cs | 123 ++++ tests/Broadside.Fuzz/README.md | 4 +- tests/Broadside.TestSupport/Corpus.cs | 4 + .../Broadside.TestSupport/TrueTypeBuilder.cs | 530 +++++++++++++++++ .../FontProgramParserRegistrationTests.cs | 152 +++++ tests/Broadside.Tests/Fonts/OutlineText.cs | 44 ++ .../Fonts/RealWorldTrueTypeTests.cs | 113 ++++ .../Fonts/TrueTypeCorpusTests.cs | 191 ++++++ .../Fonts/TrueTypeGlyphSelectionTests.cs | 173 ++++++ .../Fonts/TrueTypeProgramTests.cs | 399 +++++++++++++ ...pus_file_names_match_snapshot.verified.txt | 4 + tests/Corpus/README.md | 4 + tests/Corpus/generate.py | 371 ++++++++++++ tests/Corpus/text-truetype-composite.pdf | Bin 0 -> 2179 bytes tests/Corpus/text-truetype-loca-long.pdf | Bin 0 -> 1626 bytes tests/Corpus/text-truetype-macroman.pdf | Bin 0 -> 2065 bytes tests/Corpus/text-truetype-symbolic.pdf | Bin 0 -> 1882 bytes 46 files changed, 5413 insertions(+), 12 deletions(-) create mode 100644 bench/Broadside.Benchmarks/TrueTypeBenchmarks.cs create mode 100644 src/Broadside/Fonts/FontCharacterMap.cs create mode 100644 src/Broadside/Fonts/FontProgram.cs create mode 100644 src/Broadside/Fonts/FontProgramContext.cs create mode 100644 src/Broadside/Fonts/FontProgramFormat.cs create mode 100644 src/Broadside/Fonts/FontProgramParserRegistry.cs create mode 100644 src/Broadside/Fonts/FontProgramSource.cs create mode 100644 src/Broadside/Fonts/GlyphMetrics.cs create mode 100644 src/Broadside/Fonts/GlyphOutline.cs create mode 100644 src/Broadside/Fonts/GlyphOutlineStatus.cs create mode 100644 src/Broadside/Fonts/IFontProgramParser.cs create mode 100644 src/Broadside/Fonts/TrueType/CmapSubtable.cs create mode 100644 src/Broadside/Fonts/TrueType/PostTable.cs create mode 100644 src/Broadside/Fonts/TrueType/SfntFile.cs create mode 100644 src/Broadside/Fonts/TrueType/TrueTypeFontProgram.Glyphs.cs create mode 100644 src/Broadside/Fonts/TrueType/TrueTypeFontProgram.cs create mode 100644 src/Broadside/Fonts/TrueType/TrueTypeFontProgramParser.cs create mode 100644 src/Broadside/Fonts/TrueTypeGlyphSelector.cs create mode 100644 src/Broadside/PdfDocument.Fonts.cs create mode 100644 tests/Broadside.TestSupport/TrueTypeBuilder.cs create mode 100644 tests/Broadside.Tests/Fonts/FontProgramParserRegistrationTests.cs create mode 100644 tests/Broadside.Tests/Fonts/OutlineText.cs create mode 100644 tests/Broadside.Tests/Fonts/RealWorldTrueTypeTests.cs create mode 100644 tests/Broadside.Tests/Fonts/TrueTypeCorpusTests.cs create mode 100644 tests/Broadside.Tests/Fonts/TrueTypeGlyphSelectionTests.cs create mode 100644 tests/Broadside.Tests/Fonts/TrueTypeProgramTests.cs create mode 100644 tests/Corpus/text-truetype-composite.pdf create mode 100644 tests/Corpus/text-truetype-loca-long.pdf create mode 100644 tests/Corpus/text-truetype-macroman.pdf create mode 100644 tests/Corpus/text-truetype-symbolic.pdf diff --git a/.claude/skills/adding-a-font-program-parser/SKILL.md b/.claude/skills/adding-a-font-program-parser/SKILL.md index 3901590e..2879a2e7 100644 --- a/.claude/skills/adding-a-font-program-parser/SKILL.md +++ b/.claude/skills/adding-a-font-program-parser/SKILL.md @@ -5,18 +5,85 @@ description: "Use when implementing a parser for an embedded or substituted font # Adding a font program parser -> **The font program parser contract is defined by issue #50 (Embedded TrueType glyph outlines), the first Phase 2A Fonts ticket. When it lands, replace the "Contract" section of this skill with the real signatures from `src/Broadside/Fonts/` and `src/Broadside/PublicAPI.Unshipped.txt`.** Until then this is a design brief: responsibilities and deliverables, not method names. +> The contract below is the one #50 (Embedded TrueType glyph outlines) landed; the TrueType parser in `src/Broadside/Fonts/TrueType/` is the reference implementation. A font program is "the embedded or substituted glyph data in one of the formats PDF allows: TrueType, OpenType, CFF, Type 1, or Type 3 content streams" (`CONTEXT.md`). Font program parsers are extension points with a managed default (ADR 0001); the font resolver (which finds a program for a non-embedded font) is a separate extension point and not covered here. ## Where it lives - Contract and parsers: namespace `Broadside.Fonts` in `src/Broadside/`, one sub-namespace or folder per format (`Fonts/TrueType`, `Fonts/Cff`, `Fonts/Type1`). Standard 14 metrics (AFM) are in the core; their glyphs ship in `src/Broadside.Fonts.Standard14` (ADR 0007). Predefined CMaps ship in `src/Broadside.Fonts.Cmaps`. -- Tests: `tests/Broadside.Tests/Fonts//`, namespace `Broadside.Tests.Fonts`. +- Tests: `tests/Broadside.Tests/Fonts/` (`CorpusTests`, `ProgramTests`), namespace `Broadside.Tests.Fonts`. - Corpus: `tests/Corpus/text--embedded.pdf`. `text-truetype-embedded.pdf` exists, built by `minimal_truetype()` in `generate.py`; the font is synthesized (`.notdef`, `H`, `I` as rectangles), carries no licence, and every other format follows that pattern. Never embed a real typeface. - Fuzz: target `font-` over the raw program bytes. Benchmarks: `bench/Broadside.Benchmarks/Benchmarks.cs`. -## Contract (responsibilities, not signatures) +## Contract + +Defined by #50 in `src/Broadside/Fonts/` (namespace `Broadside.Fonts`); the public signatures are in `src/Broadside/PublicAPI.Unshipped.txt`. + +```csharp +public interface IFontProgramParser +{ + IReadOnlyList Formats { get; } // formats it reads (fallback selection) + bool CanParse(ReadOnlySpan data); // cheap signature sniff over the decoded program + FontProgram? Parse(ReadOnlyMemory data, FontProgramContext context); // null = nothing usable (after a diagnostic) +} + +public enum FontProgramFormat { TrueType, OpenType, Cff, Type1 } +public enum FontProgramSource { Unspecified, FontFile, FontFile2, FontFile3 } + +public sealed class FontProgramContext // public ctor = stand-alone (tests, fuzzing); documents build their own +{ + FontProgramSource Source { get; init; } // descriptor key + CosName? Subtype { get; init; } // FontFile3 /Subtype: Type1C, CIDFontType0C, OpenType + long? Length1 / Length2 / Length3 { get; init; } // Table 125, as written (may lie) + bool IsCidFont { get; init; } // a CIDFont's TrueType program needs no cmap (§9.9) + int FaceIndex { get; init; } string? FaceName { get; init; } // font collections + PdfReadingMode ReadingMode { get; init; } + int MaxCompositeDepth { get; init; } // 16; int MaxGlyphPoints { get; init; } // 65,536 + IReadOnlyList Diagnostics { get; } // first of each code + void Report(string code, DiagnosticSeverity severity, string message); // throws in strict mode (not for Information) +} + +public abstract class FontProgram // immutable, shared across threads; lookups never throw +{ + protected FontProgram(); + abstract FontProgramFormat Format { get; } + abstract int GlyphCount { get; } // glyph 0 is .notdef + abstract Matrix FontMatrix { get; } // glyph space -> text space (Broadside.Graphics.Matrix) + abstract GlyphOutlineStatus GetOutline(int glyphId, GlyphOutline outline); // clears the outline first + virtual string? PostScriptName { get; } // null + virtual PdfRectangle FontBBox { get; } // default + virtual double Ascender / Descender / LineGap { get; } // 0 + virtual IReadOnlyList CharacterMaps { get; } // [] ("cmap" subtables) + virtual GlyphMetrics GetMetrics(int glyphId); // default (advance, left side bearing) + virtual bool TryGetGlyphId(string glyphName, out int glyphId); // false (post / charset / CharStrings) + virtual string? GetGlyphName(int glyphId); // null +} + +public abstract class FontCharacterMap { protected FontCharacterMap(); abstract int PlatformId, EncodingId, Format { get; } abstract int GetGlyphId(int code); } +public enum GlyphOutlineStatus { Complete, Empty, Invalid } +public readonly record struct GlyphMetrics(double AdvanceWidth, double LeftSideBearing); + +public sealed class GlyphOutline // reusable buffer over Broadside.Graphics path types +{ + PathView Path { get; } bool IsEmpty { get; } void Clear(); + void MoveTo(double x, double y); void LineTo(double x, double y); + void QuadTo(double cx, double cy, double x, double y); + void CubicTo(double c1x, double c1y, double c2x, double c2y, double x, double y); + void Close(); +} +``` + +Registration and use: + +- `PdfOptions.UseFontProgramParser(IFontProgramParser)`; each engine snapshots the list into `EngineConfiguration.FontProgramParsers` (`FontProgramParserRegistry`, internal). Selection: the first parser whose `CanParse` accepts the bytes, registrations newest first, then the managed defaults (`FontProgramParserRegistry.Defaults`: add your parser there, one line); else the first whose `Formats` contain the format the stream declares (`FontProgramParserRegistry.DeclaredFormat`: `FontFile` Type1, `FontFile2` TrueType, `FontFile3` `Type1C`/`CIDFontType0C` Cff, `OpenType` OpenType); else `FontProgramUnsupported` (Information) and no program. A parser accepting bytes of another format than declared gets `FontProgramFormatMismatch` (Warning; an OpenType stream read by a TrueType parser is not a mismatch). An exception other than `DiagnosticException` from `Parse` becomes `FontProgramInvalid` (Error). +- `PdfFont.Program` (public) parses the descriptor's first font file stream through `PdfDocument.GetFontProgram` (internal): decoded with the document's filters, parsed once per stream (an `OnceCache` keyed by the stream and its `Version`, so a changed stream is parsed again), diagnostics recorded once per code against the font file stream's reference. +- Glyph selection belongs to the PDF font: `PdfTrueTypeFont.GetGlyphId(byte)` implements §9.6.5.4 (`TrueTypeGlyphSelector`). #51/#52 supply a simple font's built-in encoding through `PdfSimpleFont.GetProgramEncoding()` (internal virtual, #49) and add the lookups their format has as new virtual members of `FontProgram` (built-in encoding, CID to GID, FDSelect): adding a virtual member with a "not available" default does not break other parsers. +- The sfnt container (`Fonts/TrueType/SfntFile`: table directory, TTC face selection, "name") is internal and meant to be shared with the OpenType-CFF parser (#51); "cmap" (`CmapSubtable`) and "post" (`PostTable`) readers likewise. +- Diagnostic codes (`Parsing/DiagnosticCodes.Fonts.cs`): `FontProgramUnsupported`, `FontProgramFormatMismatch`, `FontProgramInvalid`, `FontProgramTruncated`, `FontTableInvalid`, `FontGlyphInvalid`, `FontCmapInvalid`, `FontGlyphMappingFallback`. Glyph-level problems are reported when the glyph is asked for, so strict mode throws from `GetOutline`. +- Hot path: `GetOutline` into a reused `GlyphOutline` allocates nothing once warm (pooled point buffers, stack-allocated ancestor stack): prove it with an allocation test and `Benchmarks.Outlines` (`Allocated` = `-`). + +### Responsibilities A parser for one format must: @@ -46,11 +113,15 @@ The core ships parsers for every format a PDF can embed: TrueType (`glyf`, `loca ## Worked example: the TrueType parser -`tests/Corpus/text-truetype-embedded.pdf` embeds a font with tables `head hhea maxp OS/2 hmtx cmap(3,1 format 4) loca glyf name post` and the glyph set `.notdef`, `H` (code 72), `I` (code 73), 1000 units per em. The parser reads the table directory, locates the tables by tag, resolves `loca` by `indexToLocFormat`, and returns two rectangles for `H` and `I` with the widths `hmtx` stores; `cmap` (3,1) maps 0x48 and 0x49 to glyphs 1 and 2. Tests assert exactly that, since the generator defines every value. A `font-truetype` fuzz target parses the whole program and walks every glyph; `TrueTypeBenchmarks.Outlines` extracts every glyph's outline and returns the segment count. Rows `9.9` and `9.6.3` become `partial` or `done` with those tests named. +What #50 shipped, as the pattern to follow: + +- Corpus: `text-truetype-embedded.pdf` (`.notdef`, `H`, `I`), plus `text-truetype-composite.pdf` (off-curve contours, every composite argument and transform form, USE_MY_METRICS, a monospace "hmtx" tail, lsb != xMin), `text-truetype-symbolic.pdf` ((3,0) before (1,0)), `text-truetype-macroman.pdf` ((1,0) format 6, Table 113, "post" 2.0) and `text-truetype-loca-long.pdf` (long "loca", odd glyph, (3,10) format 12), all from `ttf_font()` and `TtfGlyph` in `generate.py`, verified against poppler/FreeType renders. +- Tests in `tests/Broadside.Tests/Fonts/`: `TrueTypeCorpusTests` (document API over the corpus: exact outline text through `OutlineText`), `TrueTypeProgramTests` (the contract over in-memory programs from `tests/Broadside.TestSupport/TrueTypeBuilder.cs`: composite math vectors, every malformed-table case, strict mode, allocation-free outlines), `TrueTypeGlyphSelectionTests` (§9.6.5.4 corner cases, diagnostics on the font file stream, reparse after a change), `FontProgramParserRegistrationTests` (counting decorator parsed once, replacement parser, second engine unaffected), `RealWorldTrueTypeTests` (every embedded TrueType program of the fetched corpora outlines every glyph). +- Fuzz target `font-truetype` (an input starting with `%PDF-` is read from its first `00 01 00 00`, so the corpus files seed it) and `document` now outlines the glyph of every code of each TrueType font. Benchmark `TrueTypeBenchmarks` (`Outlines`, `GlyphIds`, `Parse`; composite and a real-world font). +- Conformance rows `9.6.3`, `9.6.5.4` (done) and `9.9.1` (partial: the other formats are yours to add to its types and tests), `9.9.2` (not started). ## Checklist -- [ ] Contract section of this skill replaced with the real signatures once the 2A contract issue has landed - [ ] Parser in `Broadside.Fonts`, managed only, `sealed`, clause-cited XML docs with the format reference - [ ] Registered through `PdfOptions`, not a static registry - [ ] Bounds-checked, recursion-capped, lenient on malformed programs with a `Diagnostic` diff --git a/bench/Broadside.Benchmarks/TrueTypeBenchmarks.cs b/bench/Broadside.Benchmarks/TrueTypeBenchmarks.cs new file mode 100644 index 00000000..283e0a42 --- /dev/null +++ b/bench/Broadside.Benchmarks/TrueTypeBenchmarks.cs @@ -0,0 +1,133 @@ +using BenchmarkDotNet.Attributes; +using Broadside.Fonts; +using Broadside.Fonts.TrueType; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Benchmarks; + +/// +/// Embedded TrueType programs (ISO 32000-2 §9.9, issue #50). decodes every glyph of the program into one +/// reused : glyph outlines are a hot path, so it must allocate nothing (Allocated = -). +/// is the cached §9.6.5.4 lookup the text interpreter makes per shown code, also allocation-free. +/// is the one-time cost per program (the table directory and the program object). +/// +/// +/// composite is the font of tests/Corpus/text-truetype-composite.pdf (every simple and composite form); +/// real-world is the TrueType program with the most glyphs among the first files of the fetched PDFBox corpus, or the +/// composite font again when the corpora are not fetched. +/// +[MemoryDiagnoser] +public class TrueTypeBenchmarks +{ + private PdfDocument? _document; + private PdfTrueTypeFont? _font; + private FontProgram? _program; + private byte[] _programBytes = []; + private GlyphOutline _outline = new(); + + /// Gets or sets which font is measured. + [Params("composite", "real-world")] + public string Font { get; set; } = "composite"; + + [GlobalSetup] + public void Setup() + { + (_document, _font) = Font == "real-world" && FindRealWorldFont() is { } found + ? found + : Open(File.ReadAllBytes(Path.Combine(CorpusLocator.CorpusDirectory, "text-truetype-composite.pdf"))); + _program = _font.Program!; + _programBytes = _document.DecodeStream(_font.Descriptor!.FontFile2!).ToArray(); + _outline = new GlyphOutline(); + _ = Outlines(); + _ = GlyphIds(); + } + + [GlobalCleanup] + public void Cleanup() => _document?.Dispose(); + + /// Every glyph's outline into one reused buffer; returns the number of segments. + [Benchmark] + public int Outlines() + { + int segments = 0; + for (int glyph = 0; glyph < _program!.GlyphCount; glyph++) + { + _program.GetOutline(glyph, _outline); + segments += _outline.Path.Verbs.Length; + } + + return segments; + } + + /// The glyph id of every code, once the font has worked them out. + [Benchmark(OperationsPerInvoke = 256)] + public int GlyphIds() + { + int total = 0; + for (int code = 0; code < 256; code++) + { + total += _font!.GetGlyphId((byte)code); + } + + return total; + } + + /// Parses the program from its bytes: table directory, "head", "hhea", "maxp", "loca" and the "cmap" subtable records. + [Benchmark] + public int Parse() => new TrueTypeFontProgramParser().Parse(_programBytes, new FontProgramContext())!.GlyphCount; + + private static (PdfDocument, PdfTrueTypeFont) Open(byte[] bytes) + { + PdfDocument document = PdfDocument.Open(bytes); + var font = (PdfTrueTypeFont)document.Pages[0].GetFont("F1")!; + return (document, font); + } + + /// The embedded TrueType font with the most glyphs among the first 40 files of the PDFBox corpus. + private static (PdfDocument, PdfTrueTypeFont)? FindRealWorldFont() + { + if (CorpusLocator.RealWorldCorpusDirectory is not { } root || !Directory.Exists(Path.Combine(root, "pdfbox"))) + { + return null; + } + + (string File, int Page, CosName Name, int Glyphs)? best = null; + foreach (string file in Directory.EnumerateFiles(Path.Combine(root, "pdfbox"), "*.pdf", SearchOption.AllDirectories).Order(StringComparer.Ordinal).Take(40)) + { + try + { + using PdfDocument document = PdfDocument.Open(File.ReadAllBytes(file)); + for (int page = 0; page < document.Pages.Count; page++) + { + if (document.Pages[page].Resources is not { } resources + || !resources.TryGetValue(new CosName("Font"), out CosObject? value) + || document.Resolve(value) is not CosDictionary fonts) + { + continue; + } + + foreach (KeyValuePair entry in fonts) + { + if (document.GetFont(entry.Value) is PdfTrueTypeFont { Program: { } program } && program.GlyphCount > (best?.Glyphs ?? 0)) + { + best = (file, page, entry.Key, program.GlyphCount); + } + } + } + } + catch (Exception exception) when (exception is not OutOfMemoryException) + { + // Files the reader rejects are not candidates. + } + } + + if (best is not { } chosen) + { + return null; + } + + PdfDocument opened = PdfDocument.Open(File.ReadAllBytes(chosen.File)); + return (opened, (PdfTrueTypeFont)opened.Pages[chosen.Page].GetFont(chosen.Name.Value)!); + } +} diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index 72fa46c0..5edaf824 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -102,17 +102,18 @@ Clause numbers at the second level; split rows to the third level as clauses are | 9.6.2.1 | General | done | `PdfType1Font`, `PdfSimpleFont`, `SimpleFontMetrics` | `Broadside.Tests.Fonts.WidthTests.Codes_in_range_take_their_widths_and_the_others_take_MissingWidth`, `Broadside.Tests.Fonts.WidthTests.A_missing_FirstChar_is_read_as_0_and_a_missing_LastChar_from_the_number_of_widths`, `Broadside.Tests.Fonts.WidthTests.A_widths_array_shorter_than_its_range_or_with_a_non_number_falls_back_to_MissingWidth`, `Broadside.Tests.Fonts.WidthTests.A_font_without_widths_that_is_not_a_standard_14_font_has_zero_widths_and_a_diagnostic`, `Broadside.Tests.Fonts.WidthTests.A_standard_14_font_with_widths_but_no_descriptor_takes_its_metrics_outside_the_range_with_a_diagnostic`, `Broadside.Tests.Fonts.WidthTests.Widths_follow_changes_to_the_widths_array_and_the_font_dictionary`, `Broadside.Tests.Fonts.WidthTests.Strict_mode_throws_from_the_first_lookup_of_a_font_with_malformed_widths`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.Widths_override_the_standard_14_metrics_and_other_codes_take_MissingWidth` | Table 109: FirstChar/LastChar/Widths with MissingWidth outside the range; missing FirstChar reads as 0, missing LastChar from the count, non-number elements take MissingWidth (FontWidthsInvalid); no Widths and not standard 14: widths 0 (FontWidthsMissing); a standard 14 font with some but not all four entries: FontStandard14EntriesIncomplete. text-standard14-widths.pdf | | 9.6.2.2 | Standard Type 1 fonts (standard 14 fonts) (PDF 1.0-1.7) | done | `Standard14Font`, `Standard14Data`, `PdfFontDescriptor`, `PdfSimpleFont` | `Broadside.Tests.Fonts.Standard14FontTests.Text_standard14_pdf_gives_each_code_its_glyph_name_and_its_Helvetica_width`, `Broadside.Tests.Fonts.Standard14MetricsTests.Every_glyph_of_every_font_has_its_AFM_width`, `Broadside.Tests.Fonts.Standard14MetricsTests.A_font_without_a_descriptor_gets_one_synthesized_from_its_AFM_file`, `Broadside.Tests.Fonts.Standard14MetricsTests.Synthesized_flags_follow_the_AFM_files`, `Broadside.Tests.Fonts.FontModelTests.A_non_embedded_font_named_after_a_standard_14_font_takes_its_metrics`, `Broadside.Tests.Fonts.FontModelTests.Fonts_whose_metrics_differ_from_the_standard_14_are_not_matched`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.A_non_embedded_Arial_bold_takes_the_Helvetica_bold_metrics_with_an_information_diagnostic`, `Broadside.Tests.Fonts.RealWorldFontTests.Every_font_of_a_real_world_corpus_reads_leniently_without_an_exception` | Metrics of the Adobe Core 14 AFM files generated into the core (`src/Broadside/Fonts/Data/generate.py`; MustRead.html and THIRD-PARTY-NOTICES ship in the package); widths only, no per-glyph boxes or kerning. A non-embedded Type 1 or TrueType font matches by name after pdf.js normalization, with the pdf.js and PDFBox aliases (Arial, TimesNewRoman, CourierNew families; not Arial Narrow/Black/Unicode) as FontStandard14Alias (Information). .notdef is 250 (Courier 600) as in Acrobat; a name the AFM lacks is measured through its AGL/uniXXXX Unicode value, else 0 (FontGlyphMissing, Information). Descriptor synthesized from the AFM when absent. Glyph programs: #59 | | 9.6.2.3 | Multiple master fonts | partial | `PdfType1Font` | `Broadside.Tests.Fonts.FontModelTests.A_multiple_master_instance_is_a_type_1_font` | MMType1 dictionaries read as Type 1 (`IsMultipleMaster`); the snapshot program is read with Type 1 programs (#52) | -| 9.6.3 | TrueType fonts | partial | `PdfTrueTypeFont` | `Broadside.Tests.Fonts.FontModelTests.The_subtype_selects_the_type_of_the_view`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.A_non_embedded_Arial_bold_takes_the_Helvetica_bold_metrics_with_an_information_diagnostic` | Dictionary view, widths and encoding names; the program and glyph selection are #50 | +| 9.6.3 | TrueType fonts | done | `PdfTrueTypeFont`, `PdfFont`, `FontProgram`, `TrueTypeFontProgramParser`, `TrueTypeFontProgram` | `Broadside.Tests.Fonts.FontModelTests.The_subtype_selects_the_type_of_the_view`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.A_non_embedded_Arial_bold_takes_the_Helvetica_bold_metrics_with_an_information_diagnostic`, `Broadside.Tests.Fonts.TrueTypeCorpusTests.Every_code_of_the_embedded_TrueType_page_has_its_quadratic_outline`, `Broadside.Tests.Fonts.TrueTypeCorpusTests.Long_loca_offsets_and_a_3_10_format_12_cmap_select_the_glyphs`, `Broadside.Tests.Fonts.TrueTypeGlyphSelectionTests.A_TrueType_program_in_a_FontFile3_OpenType_stream_is_read`, `Broadside.Tests.Fonts.RealWorldTrueTypeTests.Every_embedded_TrueType_program_of_a_real_world_corpus_outlines_every_glyph` | Dictionary view (#49); the embedded program through `PdfFont.Program` (TrueType and OpenType with "glyf" outlines, TrueType collections), its PostScript name from "name" (`FontProgram.PostScriptName`); glyph selection is 9.6.5.4. CFF-flavoured OpenType programs are #51 | | 9.6.4 | Type 3 fonts | partial | `PdfType3Font` | `Broadside.Tests.Fonts.EncodingTests.A_type_3_font_has_only_the_glyph_names_its_encoding_dictionary_gives` | Dictionary view with Widths (glyph space) and the encoding; FontMatrix, CharProcs and Resources are #57 | | 9.6.5.1 | General | done | `SimpleFontMetrics`, `GlyphNameTable`, `BuiltInEncoding` | `Broadside.Tests.Fonts.SimpleFontCorpusTests.Differences_without_a_base_encoding_change_StandardEncoding_for_a_nonsymbolic_font`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.Differences_on_the_Symbol_font_apply_to_its_built_in_encoding`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.The_Symbol_font_uses_its_built_in_encoding_and_ignores_a_named_encoding`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.A_symbolic_font_without_its_program_or_an_encoding_reads_names_from_StandardEncoding_with_a_diagnostic`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.Strict_mode_does_not_reject_the_compatibility_choices_on_legal_files`, `Broadside.Tests.Fonts.EncodingTests.Differences_take_codes_as_integers_or_whole_reals_and_later_runs_win`, `Broadside.Tests.Fonts.EncodingTests.Malformed_differences_are_skipped_with_a_diagnostic`, `Broadside.Tests.Fonts.EncodingTests.An_encoding_dictionary_with_a_base_encoding_applies_its_differences_to_it`, `Broadside.Tests.Fonts.EncodingTests.StandardEncoding_by_name_is_used_with_a_diagnostic_since_it_is_not_a_predefined_name`, `Broadside.Tests.Fonts.EncodingTests.An_unknown_or_malformed_encoding_falls_back_to_the_built_in_encoding_with_a_diagnostic`, `Broadside.Tests.Fonts.WidthTests.Glyph_names_follow_changes_to_the_differences_array` | Table 112: named encodings and encoding dictionaries; default base StandardEncoding for nonsymbolic, built-in for symbolic or embedded (Symbolic from the descriptor, or from the AFM for a standard 14 font without one); Differences runs in any order, later wins; /StandardEncoding accepted (FontEncodingInvalid), other names fall back to the built-in encoding; a named or base encoding on non-embedded Symbol/ZapfDingbats is ignored (FontEncodingIgnored, Information, as pdf.js); a non-embedded symbolic font that is not standard 14 uses StandardEncoding (FontBuiltInEncodingUnavailable, Information) | | 9.6.5.2 | Encodings for Type 1 fonts | partial | `SimpleFontMetrics`, `Standard14Data` | `Broadside.Tests.Fonts.Standard14MetricsTests.Without_an_encoding_each_code_has_the_glyph_the_AFM_file_encodes_and_other_codes_are_notdef`, `Broadside.Tests.Fonts.EncodingTests.An_embedded_font_without_an_encoding_uses_StandardEncoding_until_its_program_is_read`, `Broadside.Tests.Fonts.EncodingTests.A_glyph_name_the_metrics_do_not_use_is_measured_through_its_Unicode_value` | Encoding overrides the built-in encoding; codes without a name are .notdef. The built-in encoding of an embedded program is not read yet: StandardEncoding stands in (FontBuiltInEncodingUnavailable, Information) until #51/#52 supply it through `PdfSimpleFont.GetProgramEncoding` | | 9.6.5.3 | Encodings for Type 3 fonts | partial | `PdfType3Font`, `SimpleFontMetrics` | `Broadside.Tests.Fonts.EncodingTests.A_type_3_font_has_only_the_glyph_names_its_encoding_dictionary_gives`, `Broadside.Tests.Fonts.EncodingTests.A_type_3_font_without_an_encoding_dictionary_has_no_glyph_names_and_a_diagnostic` | Names from the encoding dictionary (Differences over a valid BaseEncoding); CharProcs lookup is #57 | -| 9.6.5.4 | Encodings for TrueType fonts | not started | | | #50. The Mac OS Roman table of Table 113 (`BuiltInEncoding.MacOSRoman`) and the Adobe Glyph List (`AdobeGlyphList`) it needs ship in the core with #49 | +| 9.6.5.4 | Encodings for TrueType fonts | done | `TrueTypeGlyphSelector`, `PdfTrueTypeFont`, `FontCharacterMap`, `CmapSubtable`, `PostTable`, `BuiltInEncoding`, `AdobeGlyphList` | `Broadside.Tests.Fonts.TrueTypeCorpusTests.Every_code_of_the_embedded_TrueType_page_has_its_quadratic_outline`, `Broadside.Tests.Fonts.TrueTypeCorpusTests.A_symbolic_font_selects_glyphs_by_code_through_3_0_with_the_F0_high_byte_before_1_0`, `Broadside.Tests.Fonts.TrueTypeCorpusTests.A_nonsymbolic_font_with_only_a_1_0_cmap_maps_names_through_Mac_OS_Roman_and_then_post`, `Broadside.Tests.Fonts.TrueTypeCorpusTests.Long_loca_offsets_and_a_3_10_format_12_cmap_select_the_glyphs`, `Broadside.Tests.Fonts.TrueTypeCorpusTests.A_format_4_glyph_id_array_entry_of_0_stays_the_missing_glyph`, `Broadside.Tests.Fonts.TrueTypeGlyphSelectionTests.A_symbolic_font_whose_program_has_no_cmap_uses_the_code_as_the_glyph_id`, `Broadside.Tests.Fonts.TrueTypeGlyphSelectionTests.A_symbolic_font_with_WinAnsiEncoding_and_only_a_unicode_cmap_falls_back_to_glyph_names`, `Broadside.Tests.Fonts.TrueTypeGlyphSelectionTests.Both_flags_with_a_Differences_array_select_by_name_as_for_a_nonsymbolic_font`, `Broadside.Tests.Fonts.TrueTypeGlyphSelectionTests.A_nonsymbolic_font_without_an_encoding_reads_names_from_StandardEncoding`, `Broadside.Tests.Fonts.TrueTypeProgramTests.Cmap_formats_0_2_4_6_12_and_13_map_codes_to_glyphs`, `Broadside.Tests.Fonts.TrueTypeProgramTests.Post_names_come_from_versions_1_2_and_2_5_and_the_first_glyph_of_a_name_wins` | Name route (Win/Mac encoding, encoding dictionary or Nonsymbolic: AGL Unicode through (3,1), else Mac OS Roman through (1,0), else "post") and code route ((3,0) with high byte 0x00/0xF0/0xF1/0xF2, else (1,0)). (0,3) (0,0) (0,1) (3,10) (0,4) stand in for (3,1). The "mapping of its choosing" fallbacks (other route, code as Unicode, code as glyph id for a symbolic program without a usable cmap) are recorded as `FontGlyphMappingFallback` Information | | 9.7 | Composite fonts | not started | | | | | 9.8.1 | General | done | `PdfFontDescriptor`, `SimpleFontMetrics` | `Broadside.Tests.Fonts.FontModelTests.The_descriptor_view_reads_every_entry_of_table_120`, `Broadside.Tests.Fonts.FontModelTests.Optional_descriptor_entries_default_and_the_view_follows_changes`, `Broadside.Tests.Fonts.FontModelTests.A_descriptor_missing_required_entries_or_with_two_programs_is_reported_once`, `Broadside.Tests.Fonts.Standard14MetricsTests.A_font_without_a_descriptor_gets_one_synthesized_from_its_AFM_file` | Every Table 120 entry as a live property with the table's defaults; FontDescriptorInvalid (once per descriptor, on the font) for a wrong Type, missing or malformed Flags/FontBBox/ItalicAngle/Ascent/Descent/StemV (ItalicAngle only for Type 3), or more than one FontFile*; `IsEmbedded` from FontFile/FontFile2/FontFile3 | | 9.8.2 | Font descriptor flags | done | `PdfFontFlags`, `PdfFontDescriptor` | `Broadside.Tests.Fonts.FontModelTests.The_descriptor_view_reads_every_entry_of_table_120`, `Broadside.Tests.Fonts.Standard14MetricsTests.Synthesized_flags_follow_the_AFM_files`, `Broadside.Tests.Fonts.SimpleFontCorpusTests.Differences_on_the_Symbol_font_apply_to_its_built_in_encoding` | Table 121 bits; the Symbolic flag decides the default base encoding (Symbolic wins when both are set); a non-integer Flags reads as none | | 9.8.3 | Font descriptors for CIDFonts | not started | | | CIDFont ticket (#53) | -| 9.9 | Embedded font programs | not started | | | | +| 9.9.1 | General | partial | `IFontProgramParser`, `FontProgram`, `FontProgramContext`, `FontProgramParserRegistry`, `FontProgramFormat`, `FontProgramSource`, `GlyphOutline`, `TrueTypeFontProgramParser`, `TrueTypeFontProgram`, `SfntFile`, `PdfOptions` | `Broadside.Tests.Fonts.FontProgramParserRegistrationTests.A_decorated_default_parser_parses_the_program_once_and_gives_the_same_outlines`, `Broadside.Tests.Fonts.FontProgramParserRegistrationTests.A_registered_parser_replaces_the_default_for_the_programs_it_accepts`, `Broadside.Tests.Fonts.FontProgramParserRegistrationTests.Another_engine_without_the_registration_still_uses_the_default`, `Broadside.Tests.Fonts.FontProgramParserRegistrationTests.A_program_no_parser_reads_is_reported_as_unsupported_information`, `Broadside.Tests.Fonts.TrueTypeCorpusTests.Composite_glyphs_apply_offsets_transforms_point_matching_and_nesting`, `Broadside.Tests.Fonts.TrueTypeCorpusTests.Simple_glyphs_start_contours_on_curve_and_imply_midpoints_between_off_curve_points`, `Broadside.Tests.Fonts.TrueTypeProgramTests.A_Length1_longer_than_the_data_is_reported_and_the_program_read`, `Broadside.Tests.Fonts.TrueTypeProgramTests.A_program_without_glyf_is_not_usable`, `Broadside.Tests.Fonts.TrueTypeProgramTests.Missing_head_hhea_and_maxp_are_replaced_by_defaults_with_diagnostics`, `Broadside.Tests.Fonts.TrueTypeGlyphSelectionTests.Diagnostics_of_the_program_are_recorded_against_the_font_file_stream`, `Broadside.Tests.Fonts.TrueTypeGlyphSelectionTests.A_CFF_OpenType_program_is_unsupported_until_a_parser_reads_it`, `Broadside.Tests.Fonts.TrueTypeGlyphSelectionTests.Data_of_another_format_than_declared_is_read_by_its_parser_with_a_diagnostic` | Font program parser extension point (Table 124 selection by signature, then declared key/Subtype) and FontFile2 / FontFile3 OpenType-with-glyf programs (Table 125 Length1 checked). FontFile (Type 1) is #52, FontFile3 Type1C is #51, CIDFontType0C is #54, CIDFontType2 programs are reached through #53 | +| 9.9.2 | Font subsets | not started | | | The subset tag is stripped only to pick a font from a TrueType collection (`PdfFont.Program`) | | 9.10 | Extraction of text content | not started | | | | | 10.1 | Rendering: General | not started | | | | | 10.2 | Raster output device native colour | not started | | | | diff --git a/src/Broadside/EngineConfiguration.cs b/src/Broadside/EngineConfiguration.cs index 0a451b27..854a7b21 100644 --- a/src/Broadside/EngineConfiguration.cs +++ b/src/Broadside/EngineConfiguration.cs @@ -1,5 +1,6 @@ using Broadside.Diagnostics; using Broadside.Filters; +using Broadside.Fonts; using Broadside.Security; using Microsoft.Extensions.Logging; @@ -42,6 +43,10 @@ internal sealed class EngineConfiguration /// Gets the credentials offered to encrypted documents opened without their own (issue #42). public PdfCredentials? Credentials { get; private init; } + + /// Gets the font program parsers: the options' registrations, newest first, then the managed defaults (issue #50). + public FontProgramParserRegistry FontProgramParsers { get; private init; } = FontProgramParserRegistry.Default; + /// Gets how many bytes of a non-seekable stream are copied into memory before a temporary file is used (issue #45). public long StreamBufferLimit { get; private init; } = PdfOptions.DefaultStreamBufferLimit; @@ -58,5 +63,6 @@ internal sealed class EngineConfiguration SecurityHandlers = options.SecurityHandlers.Count == 0 ? SecurityHandlerRegistry.Default : SecurityHandlerRegistry.Create(options.SecurityHandlers), Credentials = options.Credentials, StreamBufferLimit = options.StreamBufferLimit, + FontProgramParsers = FontProgramParserRegistry.Create(options.FontProgramParsers), }; } diff --git a/src/Broadside/Fonts/FontCharacterMap.cs b/src/Broadside/Fonts/FontCharacterMap.cs new file mode 100644 index 00000000..de21cd1a --- /dev/null +++ b/src/Broadside/Fonts/FontCharacterMap.cs @@ -0,0 +1,29 @@ +namespace Broadside.Fonts; + +/// One subtable of a TrueType or OpenType program's "cmap" table: a mapping from character codes to glyph ids. +/// +/// ISO 32000-2 §9.6.5.4: a subtable is identified by its platform and encoding ids, such as (3, 1) for Microsoft Unicode, (3, 0) for +/// Microsoft Symbol and (1, 0) for Macintosh Roman; the PDF font layer chooses among them (OpenType "cmap" table). Not to be +/// confused with a PDF CMap (§9.7.5). +/// +public abstract class FontCharacterMap +{ + /// Initializes a new instance of the class. + protected FontCharacterMap() + { + } + + /// Gets the platform id: 0 Unicode, 1 Macintosh, 3 Windows. + public abstract int PlatformId { get; } + + /// Gets the platform-specific encoding id, such as 1 for Unicode BMP or 0 for Symbol on the Windows platform. + public abstract int EncodingId { get; } + + /// Gets the subtable format: 0, 2, 4, 6, 12 or 13 (OpenType "cmap" table). + public abstract int Format { get; } + + /// Looks up the glyph id of a character code. + /// The character code: a byte for Macintosh subtables, a Unicode scalar value for Unicode subtables. + /// The glyph id; 0 (the missing glyph) when the subtable does not map the code. + public abstract int GetGlyphId(int code); +} diff --git a/src/Broadside/Fonts/FontNames.cs b/src/Broadside/Fonts/FontNames.cs index fb44bfae..1363e562 100644 --- a/src/Broadside/Fonts/FontNames.cs +++ b/src/Broadside/Fonts/FontNames.cs @@ -122,6 +122,15 @@ internal static class FontNames /// /FontFile3 (§9.8.1 Table 120). public static readonly CosName FontFile3 = new("FontFile3"); + /// /Length1 of a font file stream (§9.9 Table 125). + public static readonly CosName Length1 = new("Length1"); + + /// /Length2 of a font file stream (§9.9 Table 125). + public static readonly CosName Length2 = new("Length2"); + + /// /Length3 of a font file stream (§9.9 Table 125). + public static readonly CosName Length3 = new("Length3"); + /// /CharSet (§9.8.1 Table 120). public static readonly CosName CharSet = new("CharSet"); } diff --git a/src/Broadside/Fonts/FontProgram.cs b/src/Broadside/Fonts/FontProgram.cs new file mode 100644 index 00000000..1d9e847b --- /dev/null +++ b/src/Broadside/Fonts/FontProgram.cs @@ -0,0 +1,85 @@ +using Broadside.Graphics; + +namespace Broadside.Fonts; + +/// +/// A parsed font program: glyph outlines and metrics by glyph id, and the lookups its format has (glyph names, "cmap" subtables). +/// What an returns. +/// +/// +/// +/// ISO 32000-2 §9.9. A program is selected by glyph id; mapping character codes to glyph ids is the PDF font's job (§9.6.5 for simple +/// fonts, §9.7.4.2 for CIDFonts), which reads the lookups a program exposes. A lookup the format does not have returns its "not +/// available" value (an empty list, , ); none of them throw. +/// +/// +/// Thread safety: a program is immutable once returned by its parser and shared by every page and thread of its document; tables are +/// located when it is parsed and read lazily, once. Deviations found later (a damaged glyph) are reported through the +/// it was parsed with; in strict mode the call that finds one throws. +/// +/// +public abstract class FontProgram +{ + /// Initializes a new instance of the class. + protected FontProgram() + { + } + + /// Gets the format of the program. + public abstract FontProgramFormat Format { get; } + + /// Gets the number of glyphs: valid glyph ids are 0 to − 1, and glyph 0 is the missing glyph (.notdef). + public abstract int GlyphCount { get; } + + /// Gets the matrix that maps glyph space to text space, such as [1/unitsPerEm 0 0 1/unitsPerEm 0 0] for TrueType. + /// ISO 32000-2 §9.2.4. + public abstract Matrix FontMatrix { get; } + + /// Gets the PostScript name of the program, or when it records none. + /// ISO 32000-2 §9.6.3: a TrueType font's BaseFont comes from it (OpenType "name" table, name id 6). + public virtual string? PostScriptName => null; + + /// Gets the bounding box of all glyphs, in glyph space; empty at the origin when the program records none. + public virtual PdfRectangle FontBBox => default; + + /// Gets the typographic ascender, in glyph space units; 0 when the program records none. + public virtual double Ascender => 0; + + /// Gets the typographic descender (usually negative), in glyph space units; 0 when the program records none. + public virtual double Descender => 0; + + /// Gets the typographic line gap, in glyph space units; 0 when the program records none. + public virtual double LineGap => 0; + + /// Gets the subtables of the program's "cmap" table; empty when it has none (or its format has no such table). + /// ISO 32000-2 §9.6.5.4. + public virtual IReadOnlyList CharacterMaps => []; + + /// Writes a glyph's outline into , which is cleared first. + /// The glyph id. + /// The buffer to fill; reuse one for many glyphs. + /// Whether the glyph has an outline, draws nothing, or cannot be drawn. + /// In strict mode, when the glyph's data deviates from its format. + public abstract GlyphOutlineStatus GetOutline(int glyphId, GlyphOutline outline); + + /// Gets a glyph's horizontal metrics, in glyph space units; zero when the program records none or the glyph id is out of range. + /// The glyph id. + /// The advance width and left side bearing. + public virtual GlyphMetrics GetMetrics(int glyphId) => default; + + /// Looks up a glyph by name: the "post" table for TrueType, the charset for CFF, the CharStrings for Type 1. + /// The glyph name. + /// The glyph id; 0 when not found. + /// when the program has a glyph of that name. + /// ISO 32000-2 §9.6.5.4: the "post" fallback for TrueType fonts. + public virtual bool TryGetGlyphId(string glyphName, out int glyphId) + { + glyphId = 0; + return false; + } + + /// Gets a glyph's name, or when the program does not name it. + /// The glyph id. + /// The name. + public virtual string? GetGlyphName(int glyphId) => null; +} diff --git a/src/Broadside/Fonts/FontProgramContext.cs b/src/Broadside/Fonts/FontProgramContext.cs new file mode 100644 index 00000000..373ba66b --- /dev/null +++ b/src/Broadside/Fonts/FontProgramContext.cs @@ -0,0 +1,137 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Fonts; + +/// +/// Everything an may need beyond the program's bytes: where the program comes from, the font file +/// stream's length entries, the limits on hostile data, and the diagnostics sink. A parsed program keeps its context and reports +/// what it finds later (a damaged glyph) through it. +/// +/// +/// +/// ISO 32000-2 §9.9, Tables 124 and 125. A context created with the public constructor stands alone: its diagnostics are kept in +/// only, which is how a parser is tested or used outside a document. Inside a document, diagnostics are +/// recorded on the document against the font file stream, once per code. +/// +/// Thread safety: may be called from several threads at once (concurrent renders of one document). +/// +public sealed class FontProgramContext +{ + /// The default of . + public const int DefaultMaxCompositeDepth = 16; + + /// The default of . + public const int DefaultMaxGlyphPoints = 65536; + + private readonly DiagnosticSink? _sink; + private readonly CosReference? _objectReference; + private readonly List _diagnostics = []; + private readonly HashSet _codes = []; + + /// Initializes a new instance of the class that stands alone, outside any document. + public FontProgramContext() + { + } + + /// Initializes a new instance of the class for a font file stream of a document. + internal FontProgramContext(DiagnosticSink sink, CosReference? objectReference) + { + _sink = sink; + _objectReference = objectReference; + ReadingMode = sink.IsStrict ? PdfReadingMode.Strict : PdfReadingMode.Lenient; + } + + /// Gets the font descriptor entry the program comes from; outside a document. + /// ISO 32000-2 §9.8.1, Table 120. + public FontProgramSource Source { get; init; } + + /// Gets the font file stream's Subtype (Type1C, CIDFontType0C, OpenType), or . + /// ISO 32000-2 §9.9, Table 125 (required for FontFile3), and Table 124. + public CosName? Subtype { get; init; } + + /// + /// Gets the stream's Length1: the length of a TrueType program (the whole program), or of the clear-text portion of a Type 1 + /// program; when absent. + /// + /// ISO 32000-2 §9.9, Table 125. + public long? Length1 { get; init; } + + /// Gets the stream's Length2: the length of a Type 1 program's encrypted portion; when absent. + /// ISO 32000-2 §9.9, Table 125. + public long? Length2 { get; init; } + + /// Gets the stream's Length3: the length of a Type 1 program's fixed-content portion; when absent. + /// ISO 32000-2 §9.9, Table 125. + public long? Length3 { get; init; } + + /// + /// Gets a value indicating whether the program belongs to a CIDFont, which selects glyphs by CID rather than through the program's + /// "cmap" table (so a TrueType program for a CIDFont needs none). + /// + /// ISO 32000-2 §9.9 (the paragraph after Table 125) and §9.7.4.2. + public bool IsCidFont { get; init; } + + /// Gets which font of a font collection (a TrueType collection, "ttcf") to read when names none of them; default 0. + public int FaceIndex { get; init; } + + /// + /// Gets the PostScript name of the font to read from a font collection, such as the font's BaseFont without a subset + /// prefix; to use . + /// + public string? FaceName { get; init; } + + /// Gets how deviations are treated: in mode, throws. + /// ADR 0005. + public PdfReadingMode ReadingMode { get; init; } = PdfReadingMode.Lenient; + + /// Gets how deeply composite glyphs may nest; a deeper component is skipped with a diagnostic. Default 16. + /// Guards against hostile programs (OpenType "glyf": composite glyph descriptions); the program's own maximum is only a hint. + public int MaxCompositeDepth { get; init; } = DefaultMaxCompositeDepth; + + /// Gets how many points one glyph may have, components included; a larger glyph is dropped with a diagnostic. Default 65,536. + /// Guards against composite fan-out: a few levels of many components each multiply into billions of points. + public int MaxGlyphPoints { get; init; } = DefaultMaxGlyphPoints; + + /// Gets the diagnostics reported through this context: the first of each code, in order. + public IReadOnlyList Diagnostics + { + get + { + lock (_diagnostics) + { + return [.. _diagnostics]; + } + } + } + + /// Records a deviation found in the program and what the parser did about it. Only the first of each code is kept. + /// A stable PascalCase identifier of the kind of deviation, such as FontGlyphInvalid. + /// Whether the repair kept the glyphs () or lost some. + /// What was wrong and what the parser did. + /// In strict mode, unless the severity is . + /// ADR 0005. Inside a document the diagnostic is recorded on the document, against the font file stream. + public void Report(string code, DiagnosticSeverity severity, string message) + { + ArgumentNullException.ThrowIfNull(code); + ArgumentNullException.ThrowIfNull(message); + var diagnostic = new Diagnostic(code, severity, message, objectReference: _objectReference); + lock (_diagnostics) + { + if (_codes.Add(code)) + { + _diagnostics.Add(diagnostic); + } + } + + if (_sink is not null) + { + _sink.ReportOnce(code, severity, message, objectReference: _objectReference); + } + else if (ReadingMode == PdfReadingMode.Strict && severity != DiagnosticSeverity.Information) + { + throw new DiagnosticException(diagnostic); + } + } +} diff --git a/src/Broadside/Fonts/FontProgramFormat.cs b/src/Broadside/Fonts/FontProgramFormat.cs new file mode 100644 index 00000000..124ada2e --- /dev/null +++ b/src/Broadside/Fonts/FontProgramFormat.cs @@ -0,0 +1,21 @@ +namespace Broadside.Fonts; + +/// The formats a font program can have in a PDF file, as a font file stream declares them or its bytes show them. +/// +/// ISO 32000-2 §9.9, Table 124: FontFile holds a Type 1 program, FontFile2 a TrueType program, FontFile3 a +/// program whose format its Subtype names (Type1C and CIDFontType0C for CFF, OpenType). +/// +public enum FontProgramFormat +{ + /// A TrueType program: an sfnt container with "glyf" outlines (Apple TrueType Reference Manual, OpenType "glyf"), or a TrueType collection. + TrueType, + + /// An OpenType program (ISO/IEC 14496-22): an sfnt container whose outlines are "glyf" or "CFF " data. + OpenType, + + /// A bare Compact Font Format program (Adobe TN 5176), name-keyed or CID-keyed, with Type 2 charstrings. + Cff, + + /// A Type 1 program (Adobe Type 1 Font Format), in PFA or PFB form. + Type1, +} diff --git a/src/Broadside/Fonts/FontProgramParserRegistry.cs b/src/Broadside/Fonts/FontProgramParserRegistry.cs new file mode 100644 index 00000000..8edc51b4 --- /dev/null +++ b/src/Broadside/Fonts/FontProgramParserRegistry.cs @@ -0,0 +1,111 @@ +using Broadside.Diagnostics; +using Broadside.Fonts.TrueType; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Fonts; + +/// +/// One engine's font program parsers: those its options registered, newest first, then the managed defaults. Immutable; built once +/// when the engine is constructed and shared by every document it opens. There is no static or global registry. +/// +/// ISO 32000-2 §9.9, Table 124. The CFF (#51) and Type 1 (#52) parsers join the defaults as they land. +internal sealed class FontProgramParserRegistry +{ + private static readonly CosName Type1C = new("Type1C"); + private static readonly CosName CidFontType0C = new("CIDFontType0C"); + private static readonly CosName OpenType = new("OpenType"); + + private readonly IFontProgramParser[] _parsers; + + private FontProgramParserRegistry(IFontProgramParser[] parsers) => _parsers = parsers; + + /// Gets the managed default parsers, one stateless instance each, in the order they are tried. + public static IReadOnlyList Defaults { get; } = [new TrueTypeFontProgramParser()]; + + /// Gets the registry of the defaults only. + public static FontProgramParserRegistry Default { get; } = new([.. Defaults]); + + /// Builds a registry trying newest first, then the defaults. + /// The parsers registered through the options, in registration order. + /// The registry. + public static FontProgramParserRegistry Create(IReadOnlyList registrations) => + registrations.Count == 0 ? Default : new([.. registrations.Reverse(), .. Defaults]); + + /// The format a font file stream declares: its descriptor key, and for FontFile3 its Subtype (Table 124). + /// The descriptor key. + /// The stream's Subtype. + /// The format, or when nothing is declared or the subtype is unknown. + public static FontProgramFormat? DeclaredFormat(FontProgramSource source, CosName? subtype) => source switch + { + FontProgramSource.FontFile => FontProgramFormat.Type1, + FontProgramSource.FontFile2 => FontProgramFormat.TrueType, + FontProgramSource.FontFile3 when Type1C.Equals(subtype) || CidFontType0C.Equals(subtype) => FontProgramFormat.Cff, + FontProgramSource.FontFile3 when OpenType.Equals(subtype) => FontProgramFormat.OpenType, + _ => null, + }; + + /// Picks a parser for a program and parses it; reports why when no parser applies or the parser fails. + /// The decoded program. + /// The context, with the declared source and subtype. + /// The program, or . + public FontProgram? Parse(ReadOnlyMemory data, FontProgramContext context) + { + FontProgramFormat? declared = DeclaredFormat(context.Source, context.Subtype); + IFontProgramParser? parser = null; + foreach (IFontProgramParser candidate in _parsers) + { + if (candidate.CanParse(data.Span)) + { + parser = candidate; + break; + } + } + + if (parser is not null) + { + if (declared is { } format && !Handles(parser, format)) + { + context.Report( + DiagnosticCodes.FontProgramFormatMismatch, + DiagnosticSeverity.Warning, + $"The font file stream declares a {format} program (ISO 32000-2 §9.9, Table 124), but its data is a {string.Join(" or ", parser.Formats)} program; it is read as such."); + } + } + else if (declared is { } format) + { + parser = _parsers.FirstOrDefault(candidate => candidate.Formats.Contains(format)); + } + + if (parser is null) + { + context.Report( + DiagnosticCodes.FontProgramUnsupported, + DiagnosticSeverity.Information, + declared is { } format + ? $"No font program parser reads {format} programs yet (ISO 32000-2 §9.9); the font's glyphs are not available." + : "The font program's format is not recognized (ISO 32000-2 §9.9, Table 124); the font's glyphs are not available."); + return null; + } + + try + { + return parser.Parse(data, context); + } + catch (Exception exception) when (exception is not DiagnosticException) + { + context.Report( + DiagnosticCodes.FontProgramInvalid, + DiagnosticSeverity.Error, + $"The font program parser failed ({exception.GetType().Name}: {exception.Message}); the font's glyphs are not available."); + return null; + } + } + + /// + /// Whether a parser reads a declared format: an OpenType program may hold TrueType outlines (Table 124: OpenType with "glyf" + /// for TrueType fonts and CIDFontType2), so a TrueType parser handles it too. + /// + private static bool Handles(IFontProgramParser parser, FontProgramFormat format) => + parser.Formats.Contains(format) || (format == FontProgramFormat.OpenType && parser.Formats.Contains(FontProgramFormat.TrueType)); +} diff --git a/src/Broadside/Fonts/FontProgramSource.cs b/src/Broadside/Fonts/FontProgramSource.cs new file mode 100644 index 00000000..cbb6cd87 --- /dev/null +++ b/src/Broadside/Fonts/FontProgramSource.cs @@ -0,0 +1,18 @@ +namespace Broadside.Fonts; + +/// Where a font program comes from: the font descriptor entry that holds it. +/// ISO 32000-2 §9.8.1, Table 120, and §9.9, Table 124. +public enum FontProgramSource +{ + /// Not from a font descriptor: a program given to a parser directly. + Unspecified, + + /// The FontFile entry: a Type 1 program. + FontFile, + + /// The FontFile2 entry (PDF 1.1): a TrueType program. + FontFile2, + + /// The FontFile3 entry (PDF 1.2): a program whose format the stream's Subtype names. + FontFile3, +} diff --git a/src/Broadside/Fonts/GlyphMetrics.cs b/src/Broadside/Fonts/GlyphMetrics.cs new file mode 100644 index 00000000..610efc5d --- /dev/null +++ b/src/Broadside/Fonts/GlyphMetrics.cs @@ -0,0 +1,10 @@ +namespace Broadside.Fonts; + +/// The horizontal metrics a font program gives one glyph, in its glyph space units. +/// +/// OpenType "hmtx" table. PDF widths (Widths, W) take precedence over these for positioning text (ISO 32000-2 +/// §9.2.4, §9.6.2.1); a program's advance is the fallback when the font dictionary gives none. +/// +/// The distance from the glyph's origin to the next glyph's origin. +/// The distance from the glyph's origin to the left edge of its outline. +public readonly record struct GlyphMetrics(double AdvanceWidth, double LeftSideBearing); diff --git a/src/Broadside/Fonts/GlyphOutline.cs b/src/Broadside/Fonts/GlyphOutline.cs new file mode 100644 index 00000000..49bf5cc9 --- /dev/null +++ b/src/Broadside/Fonts/GlyphOutline.cs @@ -0,0 +1,113 @@ +using Broadside.Graphics; + +namespace Broadside.Fonts; + +/// +/// The outline of one glyph in glyph space, as the path type content stream paths use: a reusable buffer of +/// s and s that a fills and views. +/// +/// +/// +/// ISO 32000-2 §9.2.4 (glyph space) and §8.5.2. Coordinates are in the program's glyph space units (font units for TrueType, +/// mapped to text space by ). TrueType outlines use ; CFF and Type 1 +/// outlines use . Every contour starts with and ends with +/// . Glyph outlines are filled with the nonzero winding number rule. +/// +/// +/// One instance is meant to be reused for many glyphs: clears it first, and the buffers grow to +/// the largest glyph and stay, so extracting outlines allocates nothing once warm. Not thread-safe: use one per thread. +/// +/// +public sealed class GlyphOutline +{ + private PathVerb[] _verbs = new PathVerb[16]; + private PathPoint[] _points = new PathPoint[32]; + private int _verbCount; + private int _pointCount; + + /// Gets the outline as a path view over the buffers; valid until the outline is next changed. + public PathView Path => new(_verbs.AsSpan(0, _verbCount), _points.AsSpan(0, _pointCount)); + + /// Gets a value indicating whether the outline has no segments. + public bool IsEmpty => _verbCount == 0; + + /// Removes every segment, keeping the buffers. + public void Clear() + { + _verbCount = 0; + _pointCount = 0; + } + + /// Begins a contour at a point. + /// The x coordinate, in glyph space. + /// The y coordinate, in glyph space. + public void MoveTo(double x, double y) => Append(PathVerb.MoveTo, new PathPoint(x, y)); + + /// Adds a straight line from the current point. + /// The x coordinate of the end point. + /// The y coordinate of the end point. + public void LineTo(double x, double y) => Append(PathVerb.LineTo, new PathPoint(x, y)); + + /// Adds a quadratic Bézier curve from the current point (TrueType outlines). + /// The x coordinate of the control point. + /// The y coordinate of the control point. + /// The x coordinate of the end point. + /// The y coordinate of the end point. + public void QuadTo(double controlX, double controlY, double x, double y) + { + EnsureCapacity(2); + _verbs[_verbCount++] = PathVerb.QuadTo; + _points[_pointCount++] = new PathPoint(controlX, controlY); + _points[_pointCount++] = new PathPoint(x, y); + } + + /// Adds a cubic Bézier curve from the current point (CFF and Type 1 outlines). + /// The x coordinate of the first control point. + /// The y coordinate of the first control point. + /// The x coordinate of the second control point. + /// The y coordinate of the second control point. + /// The x coordinate of the end point. + /// The y coordinate of the end point. + public void CubicTo(double control1X, double control1Y, double control2X, double control2Y, double x, double y) + { + EnsureCapacity(3); + _verbs[_verbCount++] = PathVerb.CubicTo; + _points[_pointCount++] = new PathPoint(control1X, control1Y); + _points[_pointCount++] = new PathPoint(control2X, control2Y); + _points[_pointCount++] = new PathPoint(x, y); + } + + /// Closes the current contour with a straight line back to its first point. + public void Close() + { + EnsureCapacity(0); + _verbs[_verbCount++] = PathVerb.Close; + } + + private void Append(PathVerb verb, PathPoint point) + { + EnsureCapacity(1); + _verbs[_verbCount++] = verb; + _points[_pointCount++] = point; + } + + private void EnsureCapacity(int points) + { + if (_verbCount + 1 > _verbs.Length) + { + _verbs = Grow(_verbs, _verbCount); + } + + if (_pointCount + points > _points.Length) + { + _points = Grow(_points, _pointCount); + } + } + + private static T[] Grow(T[] array, int used) + { + var larger = new T[array.Length * 2]; + array.AsSpan(0, used).CopyTo(larger); + return larger; + } +} diff --git a/src/Broadside/Fonts/GlyphOutlineStatus.cs b/src/Broadside/Fonts/GlyphOutlineStatus.cs new file mode 100644 index 00000000..9c0be9c0 --- /dev/null +++ b/src/Broadside/Fonts/GlyphOutlineStatus.cs @@ -0,0 +1,18 @@ +namespace Broadside.Fonts; + +/// What found for a glyph. +/// ISO 32000-2 §9.9; the glyph description formats of the font program (OpenType "glyf", CFF charstrings, Type 1 charstrings). +public enum GlyphOutlineStatus +{ + /// The glyph has an outline, now in the . + Complete, + + /// The glyph is valid and draws nothing, such as a space; the outline is empty. + Empty, + + /// + /// The glyph cannot be drawn: its glyph id is outside the program, or its data is damaged and was dropped with a diagnostic. + /// The outline is empty. + /// + Invalid, +} diff --git a/src/Broadside/Fonts/IFontProgramParser.cs b/src/Broadside/Fonts/IFontProgramParser.cs new file mode 100644 index 00000000..8dd2be2a --- /dev/null +++ b/src/Broadside/Fonts/IFontProgramParser.cs @@ -0,0 +1,42 @@ +namespace Broadside.Fonts; + +/// +/// A font program parser: turns the decoded bytes of an embedded font program into a . The font program +/// parser extension point: every engine holds a list of parsers, the managed defaults after any registered with +/// . +/// +/// +/// +/// ISO 32000-2 §9.9. An engine picks the parser for a program in this order: the first parser, newest registration first and the +/// defaults last, whose accepts the bytes; else the first whose include the format the +/// font file stream declares (its descriptor key and Subtype, Table 124); else none, with a diagnostic, and the font has no +/// program. A parser accepting bytes of another format than declared is recorded as a diagnostic and used. +/// +/// +/// The parser receives the bytes after the stream's filters and decryption: it never sees Filter, DecodeParms or +/// encryption. It is called once per font program per document; the document caches the result. +/// +/// +/// Thread safety: one instance serves every document of every thread of the engines it is registered with, so it keeps no state +/// between calls. Leniency (ADR 0005): on malformed data a parser repairs what it can, reports each repair through +/// , and returns a program, or when nothing is usable; it does not +/// throw except for the strict mode raises. Any other exception is caught by the +/// engine and recorded as a diagnostic. +/// +/// +public interface IFontProgramParser +{ + /// Gets the formats the parser reads: an engine falls back to it for a program that declares one of them. + IReadOnlyList Formats { get; } + + /// Tells, cheaply, whether the bytes are a program this parser reads, from their signature (such as 00 01 00 00, OTTO, %!). + /// The decoded font program. + /// when the parser recognizes the bytes. + bool CanParse(ReadOnlySpan data); + + /// Parses a font program. + /// The decoded font program; the returned program may keep a reference to it. + /// Where the program comes from, the limits, and the diagnostics sink. + /// The program, or when nothing in the bytes is usable. + FontProgram? Parse(ReadOnlyMemory data, FontProgramContext context); +} diff --git a/src/Broadside/Fonts/PdfFont.cs b/src/Broadside/Fonts/PdfFont.cs index 4e2a1cc2..00592839 100644 --- a/src/Broadside/Fonts/PdfFont.cs +++ b/src/Broadside/Fonts/PdfFont.cs @@ -74,6 +74,25 @@ public PdfFontDescriptor? Descriptor /// ISO 32000-2 §9.8.1, Table 120, and §9.9. public bool IsEmbedded => DescriptorDictionary is { } descriptor && IsEmbeddedIn(descriptor); + /// + /// Gets the font's embedded font program, parsed by the engine's font program parsers; when the font is + /// not embedded, no parser reads the program's format, or the program is unusable (each recorded as a diagnostic). + /// + /// + /// + /// ISO 32000-2 §9.9: the program in the font descriptor's FontFile, FontFile2 or FontFile3 stream, decoded + /// through its filters. The parser is picked by the program's bytes, then by the format the stream declares (Table 124); see + /// . The managed default reads TrueType programs. + /// + /// + /// The program is parsed once per font file stream and shared by every font and thread that uses it; it is parsed again only + /// after the stream changes. Selecting a glyph for a character code is the font's job (§9.6.5): for a TrueType font, + /// . + /// + /// + /// In strict mode, when the program deviates from its format. + public FontProgram? Program => DescriptorDictionary is { } descriptor ? GetProgram(descriptor, isCidFont: false) : null; + /// Gets the document the font belongs to. internal PdfDocument Document { get; } @@ -141,6 +160,35 @@ internal bool IsEmbeddedIn(CosDictionary descriptor) => || GetFrom(descriptor, FontNames.FontFile2) is CosStream || GetFrom(descriptor, FontNames.FontFile3) is CosStream; + /// The program of a font descriptor's first font file stream, parsed once per stream (§9.9). + /// The font descriptor dictionary. + /// Whether the descriptor belongs to a CIDFont. + /// The program, or . + internal FontProgram? GetProgram(CosDictionary descriptor, bool isCidFont) + { + foreach ((CosName key, FontProgramSource source) in ProgramEntries) + { + if (descriptor.TryGetValue(key, out CosObject? value) && Document.Resolve(value) is CosStream stream) + { + return Document.GetFontProgram(stream, value as CosReference, source, isCidFont, this); + } + } + + return null; + } + + /// The font descriptor entries that hold a program, and what each holds (Table 120). + private static readonly (CosName Key, FontProgramSource Source)[] ProgramEntries = + [ + (FontNames.FontFile, FontProgramSource.FontFile), + (FontNames.FontFile2, FontProgramSource.FontFile2), + (FontNames.FontFile3, FontProgramSource.FontFile3), + ]; + + /// The BaseFont without a subset tag (six uppercase letters and a plus sign, §9.9.2). + internal string? FaceName => + BaseFont is { Length: > 7 } name && name[6] == '+' && name.AsSpan(0, 6).ContainsAnyExceptInRange('A', 'Z') is false ? name[7..] : BaseFont; + /// The font dictionary's entry, resolved; when absent or a reference to nothing. internal CosObject? Get(CosName key) => GetFrom(Dictionary, key); diff --git a/src/Broadside/Fonts/PdfTrueTypeFont.cs b/src/Broadside/Fonts/PdfTrueTypeFont.cs index 964613e6..2c667267 100644 --- a/src/Broadside/Fonts/PdfTrueTypeFont.cs +++ b/src/Broadside/Fonts/PdfTrueTypeFont.cs @@ -6,12 +6,47 @@ namespace Broadside.Fonts; /// /// ISO 32000-2 §9.6.3. The dictionary has the entries of a Type 1 font dictionary (Table 109). Glyph names from the encoding are /// what §9.6.5.4 maps through the font program's "cmap" table for a nonsymbolic font; a non-embedded TrueType font named after a -/// Standard 14 font (such as Arial) takes that font's metrics. +/// Standard 14 font (such as Arial) takes that font's metrics. selects the glyph of a character +/// code in the embedded program (). /// public sealed class PdfTrueTypeFont : PdfSimpleFont { + private volatile TrueTypeGlyphSelector? _selector; + internal PdfTrueTypeFont(PdfDocument document, CosDictionary dictionary, CosReference? reference) : base(document, dictionary, reference, PdfFontType.TrueType) { } + + /// Gets the glyph id that a character code selects in the font's program; 0, the missing glyph, when none. + /// The character code. + /// The glyph id in ; 0 for every code when the font has no program. + /// In strict mode, for the first deviation found in the font or its program. + /// + /// + /// ISO 32000-2 §9.6.5.4. A font with MacRomanEncoding or WinAnsiEncoding, an encoding dictionary, or the + /// Nonsymbolic flag selects by glyph name: the encoding's name for the code, its Unicode value from the Adobe Glyph List, and the + /// program's (3, 1) "cmap" subtable; without (3, 1), the name's Mac OS Roman code (Table 113) and the (1, 0) subtable; failing + /// both, the program's "post" names. A symbolic font, or one without an encoding, selects by the code: the (3, 0) subtable with the + /// high byte 0x00, 0xF0, 0xF1 or 0xF2, else the (1, 0) subtable. + /// + /// + /// When that finds nothing, the font falls back as viewers do and records an information diagnostic: the other route, the code as + /// a Unicode value, and for a symbolic program without a usable "cmap", the code as the glyph id. Each code is worked out once and + /// kept until the font dictionary, its encoding or descriptor, or the program changes. + /// + /// + public int GetGlyphId(byte code) + { + SimpleFontMetrics metrics = Metrics; + FontProgram? program = Program; + TrueTypeGlyphSelector? selector = _selector; + if (selector is null || selector.Metrics != metrics || selector.Program != program) + { + selector = new TrueTypeGlyphSelector(this, metrics, program); + _selector = selector; + } + + return selector.GetGlyphId(code); + } } diff --git a/src/Broadside/Fonts/TrueType/CmapSubtable.cs b/src/Broadside/Fonts/TrueType/CmapSubtable.cs new file mode 100644 index 00000000..9246010a --- /dev/null +++ b/src/Broadside/Fonts/TrueType/CmapSubtable.cs @@ -0,0 +1,406 @@ +using System.Buffers.Binary; +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Parsing; + +namespace Broadside.Fonts.TrueType; + +/// One "cmap" subtable, looked up in place over the program's bytes: nothing is copied into a dictionary. +/// +/// OpenType specification, "cmap — Character to glyph index mapping table": formats 0, 2, 4, 6, 12 and 13. Format 14 (variation +/// sequences) has no use in PDF text and is skipped; formats 8 and 10 are reported as unsupported. A glyph id at or past the +/// program's glyph count reads as 0 with a diagnostic. ISO 32000-2 §9.6.5.4 chooses among the subtables. +/// +internal sealed class CmapSubtable : FontCharacterMap +{ + private readonly ReadOnlyMemory _data; + private readonly int _glyphCount; + private readonly FontProgramContext _context; + private readonly bool _sorted; + + private CmapSubtable(int platformId, int encodingId, int format, ReadOnlyMemory data, int glyphCount, FontProgramContext context, bool sorted) + { + PlatformId = platformId; + EncodingId = encodingId; + Format = format; + _data = data; + _glyphCount = glyphCount; + _context = context; + _sorted = sorted; + } + + /// + public override int PlatformId { get; } + + /// + public override int EncodingId { get; } + + /// + public override int Format { get; } + + /// Reads the subtable records of a "cmap" table; reports what it cannot use. + /// The table. + /// The program's glyph count. + /// The diagnostics sink. + /// The usable subtables, in the order the table lists them. + public static CmapSubtable[] ReadAll(ReadOnlyMemory cmap, int glyphCount, FontProgramContext context) + { + ReadOnlySpan span = cmap.Span; + if (span.Length < 4) + { + Report(context, "the table is shorter than its header; it is ignored"); + return []; + } + + int count = BinaryPrimitives.ReadUInt16BigEndian(span[2..]); + var subtables = new List(count); + for (int index = 0; index < count; index++) + { + int record = 4 + (8 * index); + if (record + 8 > span.Length) + { + Report(context, "the table lists more subtables than it holds records for; the others are ignored"); + break; + } + + int platform = BinaryPrimitives.ReadUInt16BigEndian(span[record..]); + int encoding = BinaryPrimitives.ReadUInt16BigEndian(span[(record + 2)..]); + uint offset = BinaryPrimitives.ReadUInt32BigEndian(span[(record + 4)..]); + if (offset > (uint)(span.Length - 2)) + { + Report(context, string.Create(CultureInfo.InvariantCulture, $"the ({platform}, {encoding}) subtable starts past the end of the table; it is ignored")); + continue; + } + + if (Read(cmap, (int)offset, platform, encoding, glyphCount, context) is { } subtable) + { + subtables.Add(subtable); + } + } + + return [.. subtables]; + } + + /// + public override int GetGlyphId(int code) + { + if (code < 0) + { + return 0; + } + + ReadOnlySpan data = _data.Span; + int glyph = Format switch + { + 0 => code < 256 && 6 + code < data.Length ? data[6 + code] : 0, + 2 => LookUpFormat2(data, code), + 4 => LookUpFormat4(data, code), + 6 => LookUpFormat6(data, code), + 12 or 13 => LookUpGroups(data, (uint)code), + _ => 0, + }; + + if (glyph >= _glyphCount) + { + _context.Report( + DiagnosticCodes.FontCmapInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The ({PlatformId}, {EncodingId}) \"cmap\" subtable maps a code to glyph {glyph}, past the program's {_glyphCount} glyphs; the missing glyph is used.")); + return 0; + } + + return glyph; + } + + private static CmapSubtable? Read(ReadOnlyMemory cmap, int offset, int platform, int encoding, int glyphCount, FontProgramContext context) + { + ReadOnlySpan span = cmap.Span[offset..]; + int format = BinaryPrimitives.ReadUInt16BigEndian(span); + long length; + switch (format) + { + case 0 or 2 or 4 or 6: + length = span.Length >= 4 ? BinaryPrimitives.ReadUInt16BigEndian(span[2..]) : 0; + break; + case 12 or 13: + length = span.Length >= 8 ? BinaryPrimitives.ReadUInt32BigEndian(span[4..]) : 0; + break; + case 14: + return null; + case 8 or 10: + Report(context, string.Create(CultureInfo.InvariantCulture, $"the ({platform}, {encoding}) subtable has format {format}, which is not supported; it is ignored")); + return null; + default: + Report(context, string.Create(CultureInfo.InvariantCulture, $"the ({platform}, {encoding}) subtable has the unknown format {format}; it is ignored")); + return null; + } + + if (length > span.Length || length < MinimumLength(format)) + { + Report(context, string.Create(CultureInfo.InvariantCulture, $"the length of the ({platform}, {encoding}) format {format} subtable does not fit the table; the bytes present are read")); + length = span.Length; + } + + ReadOnlyMemory data = cmap.Slice(offset, (int)length); + if (data.Length < MinimumLength(format)) + { + Report(context, string.Create(CultureInfo.InvariantCulture, $"the ({platform}, {encoding}) format {format} subtable is truncated; it is ignored")); + return null; + } + + bool sorted = format switch + { + 4 => CheckFormat4(data.Span, platform, encoding, context), + 12 or 13 => CheckGroups(data.Span, platform, encoding, context), + _ => true, + }; + return new CmapSubtable(platform, encoding, format, data, glyphCount, context, sorted); + } + + private static int MinimumLength(int format) => format switch + { + 0 => 6, + 2 => 6 + 512, + 4 => 16, + 6 => 10, + _ => 16, + }; + + /// Format 2 (high-byte mapping): a byte whose subheader key is 0 is a single-byte code; others start two-byte codes. + private static int LookUpFormat2(ReadOnlySpan data, int code) + { + int high = code > 0xFF ? (code >> 8) & 0xFF : code; + int low = code > 0xFF ? code & 0xFF : code; + int key = BinaryPrimitives.ReadUInt16BigEndian(data[(6 + (2 * high))..]); + if (code <= 0xFF && key != 0) + { + return 0; + } + + if (code > 0xFFFF || (code > 0xFF && key == 0)) + { + return 0; + } + + int subHeader = 6 + 512 + key; + if (subHeader + 8 > data.Length) + { + return 0; + } + + int firstCode = BinaryPrimitives.ReadUInt16BigEndian(data[subHeader..]); + int entryCount = BinaryPrimitives.ReadUInt16BigEndian(data[(subHeader + 2)..]); + short delta = BinaryPrimitives.ReadInt16BigEndian(data[(subHeader + 4)..]); + int rangeOffset = BinaryPrimitives.ReadUInt16BigEndian(data[(subHeader + 6)..]); + if (low < firstCode || low >= firstCode + entryCount) + { + return 0; + } + + int address = subHeader + 6 + rangeOffset + (2 * (low - firstCode)); + if (address + 2 > data.Length) + { + return 0; + } + + int glyph = BinaryPrimitives.ReadUInt16BigEndian(data[address..]); + return glyph == 0 ? 0 : (glyph + delta) & 0xFFFF; + } + + /// Format 4 (segment mapping to delta values): the Windows Unicode BMP and Symbol subtables. + private int LookUpFormat4(ReadOnlySpan data, int code) + { + if (code > 0xFFFF) + { + return 0; + } + + int segments = Format4Segments(data); + int ends = 14; + int starts = ends + (2 * segments) + 2; + int deltas = starts + (2 * segments); + int rangeOffsets = deltas + (2 * segments); + int segment = -1; + if (_sorted) + { + int low = 0; + int high = segments - 1; + while (low <= high) + { + int middle = (low + high) >> 1; + if (BinaryPrimitives.ReadUInt16BigEndian(data[(ends + (2 * middle))..]) < code) + { + low = middle + 1; + } + else + { + high = middle - 1; + } + } + + segment = low < segments && BinaryPrimitives.ReadUInt16BigEndian(data[(starts + (2 * low))..]) <= code ? low : -1; + } + else + { + for (int index = 0; index < segments && segment < 0; index++) + { + if (BinaryPrimitives.ReadUInt16BigEndian(data[(starts + (2 * index))..]) <= code + && BinaryPrimitives.ReadUInt16BigEndian(data[(ends + (2 * index))..]) >= code) + { + segment = index; + } + } + } + + if (segment < 0) + { + return 0; + } + + int start = BinaryPrimitives.ReadUInt16BigEndian(data[(starts + (2 * segment))..]); + int delta = BinaryPrimitives.ReadUInt16BigEndian(data[(deltas + (2 * segment))..]); + int rangeOffsetPosition = rangeOffsets + (2 * segment); + int rangeOffset = BinaryPrimitives.ReadUInt16BigEndian(data[rangeOffsetPosition..]); + if (rangeOffset == 0) + { + return (code + delta) & 0xFFFF; + } + + // idRangeOffset counts bytes from its own position; a glyphIdArray value of 0 stays 0 (the missing glyph). + int address = rangeOffsetPosition + rangeOffset + (2 * (code - start)); + if (address + 2 > data.Length) + { + _context.Report( + DiagnosticCodes.FontCmapInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"A segment of the ({PlatformId}, {EncodingId}) format 4 \"cmap\" subtable points past its glyph id array; its codes map to the missing glyph.")); + return 0; + } + + int glyph = BinaryPrimitives.ReadUInt16BigEndian(data[address..]); + return glyph == 0 ? 0 : (glyph + delta) & 0xFFFF; + } + + private static int Format4Segments(ReadOnlySpan data) => + Math.Min(BinaryPrimitives.ReadUInt16BigEndian(data[6..]) / 2, Math.Max(0, (data.Length - 16) / 8)); + + /// Format 6 (trimmed table): a dense array of glyph ids for a range of codes. + private static int LookUpFormat6(ReadOnlySpan data, int code) + { + int first = BinaryPrimitives.ReadUInt16BigEndian(data[6..]); + int count = BinaryPrimitives.ReadUInt16BigEndian(data[8..]); + int index = code - first; + int address = 10 + (2 * index); + return index >= 0 && index < count && address + 2 <= data.Length ? BinaryPrimitives.ReadUInt16BigEndian(data[address..]) : 0; + } + + /// Formats 12 (segmented coverage) and 13 (many-to-one range mappings): sequential groups of 32-bit codes. + private int LookUpGroups(ReadOnlySpan data, uint code) + { + int groups = GroupCount(data); + int found = -1; + if (_sorted) + { + int low = 0; + int high = groups - 1; + while (low <= high) + { + int middle = (low + high) >> 1; + int group = 16 + (12 * middle); + if (BinaryPrimitives.ReadUInt32BigEndian(data[(group + 4)..]) < code) + { + low = middle + 1; + } + else + { + high = middle - 1; + } + } + + found = low < groups && BinaryPrimitives.ReadUInt32BigEndian(data[(16 + (12 * low))..]) <= code ? low : -1; + } + else + { + for (int index = 0; index < groups && found < 0; index++) + { + int group = 16 + (12 * index); + if (BinaryPrimitives.ReadUInt32BigEndian(data[group..]) <= code && BinaryPrimitives.ReadUInt32BigEndian(data[(group + 4)..]) >= code) + { + found = index; + } + } + } + + if (found < 0) + { + return 0; + } + + int offset = 16 + (12 * found); + uint start = BinaryPrimitives.ReadUInt32BigEndian(data[offset..]); + uint glyph = BinaryPrimitives.ReadUInt32BigEndian(data[(offset + 8)..]); + ulong result = Format == 12 ? glyph + (ulong)(code - start) : glyph; + return result > int.MaxValue ? int.MaxValue : (int)result; + } + + private static int GroupCount(ReadOnlySpan data) => + (int)Math.Min(BinaryPrimitives.ReadUInt32BigEndian(data[12..]), (uint)((data.Length - 16) / 12)); + + /// Format 4 needs ascending end codes for a binary search; when they are not, lookups scan and the first match wins. + private static bool CheckFormat4(ReadOnlySpan data, int platform, int encoding, FontProgramContext context) + { + int declared = BinaryPrimitives.ReadUInt16BigEndian(data[6..]) / 2; + int segments = Format4Segments(data); + if (segments < declared) + { + Report(context, string.Create(CultureInfo.InvariantCulture, $"the ({platform}, {encoding}) format 4 subtable declares {declared} segments but holds {segments}; those are read")); + } + + int previous = -1; + for (int index = 0; index < segments; index++) + { + int end = BinaryPrimitives.ReadUInt16BigEndian(data[(14 + (2 * index))..]); + int start = BinaryPrimitives.ReadUInt16BigEndian(data[(16 + (2 * segments) + (2 * index))..]); + if (end <= previous || start > end) + { + Report(context, string.Create(CultureInfo.InvariantCulture, $"the segments of the ({platform}, {encoding}) format 4 subtable are not in ascending order; it is searched in order")); + return false; + } + + previous = end; + } + + return true; + } + + /// Formats 12 and 13 need ascending, non-overlapping groups for a binary search; otherwise lookups scan. + private static bool CheckGroups(ReadOnlySpan data, int platform, int encoding, FontProgramContext context) + { + uint declared = BinaryPrimitives.ReadUInt32BigEndian(data[12..]); + int groups = GroupCount(data); + if (groups < declared) + { + Report(context, string.Create(CultureInfo.InvariantCulture, $"the ({platform}, {encoding}) subtable declares {declared} groups but holds {groups}; those are read")); + } + + long previous = -1; + for (int index = 0; index < groups; index++) + { + int group = 16 + (12 * index); + uint start = BinaryPrimitives.ReadUInt32BigEndian(data[group..]); + uint end = BinaryPrimitives.ReadUInt32BigEndian(data[(group + 4)..]); + if (start <= previous || end < start) + { + Report(context, string.Create(CultureInfo.InvariantCulture, $"the groups of the ({platform}, {encoding}) subtable are not in ascending order; it is searched in order")); + return false; + } + + previous = end; + } + + return true; + } + + private static void Report(FontProgramContext context, string problem) => + context.Report(DiagnosticCodes.FontCmapInvalid, DiagnosticSeverity.Warning, $"The font program's \"cmap\" table deviates from the OpenType specification: {problem}."); +} diff --git a/src/Broadside/Fonts/TrueType/PostTable.cs b/src/Broadside/Fonts/TrueType/PostTable.cs new file mode 100644 index 00000000..577e86ff --- /dev/null +++ b/src/Broadside/Fonts/TrueType/PostTable.cs @@ -0,0 +1,193 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Text; +using Broadside.Diagnostics; +using Broadside.Parsing; + +namespace Broadside.Fonts.TrueType; + +/// The glyph names of a "post" table, read once, and the reverse lookup from name to glyph id. +/// +/// OpenType specification, "post — PostScript table", and Apple TrueType Reference Manual, "The 'post' table": version 1.0 names +/// the first 258 glyphs with the standard Macintosh order; version 2.0 indexes that order or its own Pascal strings; version 2.5 +/// (deprecated) offsets the standard order; versions 3.0 and 4.0 name nothing. ISO 32000-2 §9.6.5.4 uses the names as the last +/// fallback for selecting a glyph. +/// +internal sealed class PostTable +{ + /// The 258 standard Macintosh glyph names, in their "post" order (Apple TrueType Reference Manual, "The 'post' table"). + internal static readonly string[] MacStandardNames = + [ + ".notdef", ".null", "nonmarkingreturn", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", + "quotesingle", "parenleft", "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", "zero", "one", "two", + "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", "equal", "greater", "question", "at", + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", + "Z", "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", "grave", "a", "b", "c", "d", "e", "f", "g", "h", + "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft", "bar", "braceright", + "asciitilde", "Adieresis", "Aring", "Ccedilla", "Eacute", "Ntilde", "Odieresis", "Udieresis", "aacute", "agrave", + "acircumflex", "adieresis", "atilde", "aring", "ccedilla", "eacute", "egrave", "ecircumflex", "edieresis", "iacute", "igrave", + "icircumflex", "idieresis", "ntilde", "oacute", "ograve", "ocircumflex", "odieresis", "otilde", "uacute", "ugrave", + "ucircumflex", "udieresis", "dagger", "degree", "cent", "sterling", "section", "bullet", "paragraph", "germandbls", + "registered", "copyright", "trademark", "acute", "dieresis", "notequal", "AE", "Oslash", "infinity", "plusminus", "lessequal", + "greaterequal", "yen", "mu", "partialdiff", "summation", "product", "pi", "integral", "ordfeminine", "ordmasculine", "Omega", + "ae", "oslash", "questiondown", "exclamdown", "logicalnot", "radical", "florin", "approxequal", "Delta", "guillemotleft", + "guillemotright", "ellipsis", "nonbreakingspace", "Agrave", "Atilde", "Otilde", "OE", "oe", "endash", "emdash", + "quotedblleft", "quotedblright", "quoteleft", "quoteright", "divide", "lozenge", "ydieresis", "Ydieresis", "fraction", + "currency", "guilsinglleft", "guilsinglright", "fi", "fl", "daggerdbl", "periodcentered", "quotesinglbase", "quotedblbase", + "perthousand", "Acircumflex", "Ecircumflex", "Aacute", "Edieresis", "Egrave", "Iacute", "Icircumflex", "Idieresis", "Igrave", + "Oacute", "Ocircumflex", "apple", "Ograve", "Uacute", "Ucircumflex", "Ugrave", "dotlessi", "circumflex", "tilde", "macron", + "breve", "dotaccent", "ring", "cedilla", "hungarumlaut", "ogonek", "caron", "Lslash", "lslash", "Scaron", "scaron", "Zcaron", + "zcaron", "brokenbar", "Eth", "eth", "Yacute", "yacute", "Thorn", "thorn", "minus", "multiply", "onesuperior", "twosuperior", + "threesuperior", "onehalf", "onequarter", "threequarters", "franc", "Gbreve", "gbreve", "Idotaccent", "Scedilla", "scedilla", + "Cacute", "cacute", "Ccaron", "ccaron", "dcroat", + ]; + + private readonly string?[] _names; + private Dictionary? _byName; + + private PostTable(string?[] names) => _names = names; + + /// Gets a table that names nothing. + public static PostTable None { get; } = new([]); + + /// Reads the glyph names; reports deviations. + /// The table. + /// The program's glyph count. + /// The diagnostics sink. + /// The names. + public static PostTable Read(ReadOnlySpan post, int glyphCount, FontProgramContext context) + { + if (post.Length < 32) + { + Report(context, "the table is shorter than its 32-byte header; no glyph has a name"); + return None; + } + + uint version = BinaryPrimitives.ReadUInt32BigEndian(post); + switch (version) + { + case 0x00010000: + return new PostTable([.. MacStandardNames.Take(Math.Min(glyphCount, MacStandardNames.Length))]); + case 0x00020000: + return ReadVersion2(post, glyphCount, context); + case 0x00025000: + return ReadVersion25(post, glyphCount, context); + case 0x00030000 or 0x00040000: + return None; + default: + Report(context, string.Create(CultureInfo.InvariantCulture, $"the version 0x{version:X8} is unknown; no glyph has a name")); + return None; + } + } + + /// Gets a glyph's name, or . + public string? NameOf(int glyphId) => (uint)glyphId < (uint)_names.Length ? _names[glyphId] : null; + + /// Finds the first glyph of a name. + public bool TryGetGlyphId(string name, out int glyphId) + { + Dictionary byName = LazyInitializer.EnsureInitialized(ref _byName, BuildIndex); + return byName.TryGetValue(name, out glyphId); + } + + private Dictionary BuildIndex() + { + var index = new Dictionary(_names.Length, StringComparer.Ordinal); + for (int glyph = 0; glyph < _names.Length; glyph++) + { + if (_names[glyph] is { } name) + { + index.TryAdd(name, glyph); + } + } + + return index; + } + + /// Version 2.0: an index per glyph into the standard order (below 258) or the Pascal strings that follow (258 to 32767). + private static PostTable ReadVersion2(ReadOnlySpan post, int glyphCount, FontProgramContext context) + { + if (post.Length < 34) + { + Report(context, "the version 2.0 table has no glyph count; no glyph has a name"); + return None; + } + + int declared = BinaryPrimitives.ReadUInt16BigEndian(post[32..]); + int count = Math.Min(declared, Math.Min(glyphCount, (post.Length - 34) / 2)); + if (count != declared) + { + Report(context, string.Create(CultureInfo.InvariantCulture, $"the version 2.0 table names {declared} glyphs but the program has {glyphCount} and the table holds indexes for {(post.Length - 34) / 2}; {count} are named")); + } + + // The Pascal strings follow the indexes for all declared glyphs, and are counted, not terminated. + int stringsStart = 34 + (2 * declared); + var strings = new List(); + int position = stringsStart; + while (position < post.Length) + { + int length = post[position]; + if (position + 1 + length > post.Length) + { + Report(context, "a glyph name string runs past the end of the table; it is dropped"); + break; + } + + strings.Add(Encoding.Latin1.GetString(post.Slice(position + 1, length))); + position += 1 + length; + } + + var names = new string?[count]; + bool missing = false; + for (int glyph = 0; glyph < count; glyph++) + { + int index = BinaryPrimitives.ReadUInt16BigEndian(post[(34 + (2 * glyph))..]); + if (index < MacStandardNames.Length) + { + names[glyph] = MacStandardNames[index]; + } + else if (index < 32768) + { + int stringIndex = index - MacStandardNames.Length; + if (stringIndex < strings.Count) + { + names[glyph] = strings[stringIndex]; + } + else + { + missing = true; + } + } + } + + if (missing) + { + Report(context, "some glyph name indexes point past the table's name strings; those glyphs have no name"); + } + + return new PostTable(names); + } + + /// Version 2.5: an offset per glyph into the standard order (FreeType's reading: name = standard[glyph + offset]). + private static PostTable ReadVersion25(ReadOnlySpan post, int glyphCount, FontProgramContext context) + { + if (post.Length < 34) + { + Report(context, "the version 2.5 table has no glyph count; no glyph has a name"); + return None; + } + + int count = Math.Min(BinaryPrimitives.ReadUInt16BigEndian(post[32..]), Math.Min(glyphCount, post.Length - 34)); + var names = new string?[count]; + for (int glyph = 0; glyph < count; glyph++) + { + int index = glyph + (sbyte)post[34 + glyph]; + names[glyph] = index >= 0 && index < MacStandardNames.Length ? MacStandardNames[index] : null; + } + + return new PostTable(names); + } + + private static void Report(FontProgramContext context, string problem) => + context.Report(DiagnosticCodes.FontTableInvalid, DiagnosticSeverity.Warning, $"The font program's \"post\" table deviates from the OpenType specification: {problem}."); +} diff --git a/src/Broadside/Fonts/TrueType/SfntFile.cs b/src/Broadside/Fonts/TrueType/SfntFile.cs new file mode 100644 index 00000000..0018e728 --- /dev/null +++ b/src/Broadside/Fonts/TrueType/SfntFile.cs @@ -0,0 +1,313 @@ +using System.Buffers.Binary; +using System.Globalization; +using System.Text; +using Broadside.Diagnostics; +using Broadside.Parsing; + +namespace Broadside.Fonts.TrueType; + +/// +/// The table directory of one font of an sfnt file (TrueType, OpenType, or one face of a TrueType collection): where each table is. +/// Shared by the TrueType outlines here and the CFF outlines of OpenType programs (#51). +/// +/// +/// OpenType specification, "OpenType font file": table directory and TTC header. Table checksums are not verified (real files carry +/// wrong ones and no reader checks them). Offsets are from the start of the file, also inside a collection. +/// +internal sealed class SfntFile +{ + /// The sfnt version of TrueType outlines (00 01 00 00). + public const uint TrueTypeVersion = 0x00010000; + + /// Apple's sfnt version for TrueType outlines (true). + public const uint AppleTrueTypeVersion = 0x74727565; + + /// The sfnt version of CFF outlines (OTTO). + public const uint OpenTypeVersion = 0x4F54544F; + + /// The tag of a TrueType collection header (ttcf). + public const uint CollectionTag = 0x74746366; + + private readonly Table[] _tables; + + private SfntFile(ReadOnlyMemory data, uint version, Table[] tables) + { + Data = data; + Version = version; + _tables = tables; + } + + /// Gets the whole file. + public ReadOnlyMemory Data { get; } + + /// Gets the font's sfnt version. + public uint Version { get; } + + /// Makes a tag from its four ASCII characters. + public static uint Tag(string tag) => + ((uint)tag[0] << 24) | ((uint)tag[1] << 16) | ((uint)tag[2] << 8) | tag[3]; + + /// Whether a 32-bit value is one of the sfnt versions or the collection tag. + public static bool IsKnownVersion(uint version) => + version is TrueTypeVersion or AppleTrueTypeVersion or OpenTypeVersion or CollectionTag; + + /// Whether the data starts with an sfnt or collection signature and its (first) font has a table of the given tag. + public static bool HasTable(ReadOnlySpan data, uint tag) + { + if (data.Length < 12) + { + return false; + } + + int start = 0; + if (BinaryPrimitives.ReadUInt32BigEndian(data) == CollectionTag) + { + if (data.Length < 16 || BinaryPrimitives.ReadUInt32BigEndian(data[8..]) == 0) + { + return false; + } + + uint first = BinaryPrimitives.ReadUInt32BigEndian(data[12..]); + if (first > (uint)(data.Length - 12)) + { + return false; + } + + start = (int)first; + } + + int count = BinaryPrimitives.ReadUInt16BigEndian(data[(start + 4)..]); + for (int index = 0; index < count; index++) + { + int record = start + 12 + (16 * index); + if (record + 16 > data.Length) + { + return false; + } + + if (BinaryPrimitives.ReadUInt32BigEndian(data[record..]) == tag) + { + return true; + } + } + + return false; + } + + /// Reads the table directory of the font the context selects; reports and returns when there is none. + /// The program. + /// The context: face selection and diagnostics. + /// The directory. + public static SfntFile? Open(ReadOnlyMemory data, FontProgramContext context) + { + ReadOnlySpan span = data.Span; + if (span.Length < 12) + { + context.Report(DiagnosticCodes.FontProgramInvalid, DiagnosticSeverity.Error, "The font program is shorter than an sfnt table directory (OpenType \"Organization of an OpenType font\"); it is not usable."); + return null; + } + + uint version = BinaryPrimitives.ReadUInt32BigEndian(span); + if (version != CollectionTag) + { + if (!IsKnownVersion(version)) + { + context.Report( + DiagnosticCodes.FontTableInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The font program's sfnt version 0x{version:X8} is not 0x00010000, 'true' or 'OTTO'; its table directory is read anyway.")); + } + + return ReadDirectory(data, 0, context); + } + + // TTC header: tag, major, minor, numFonts, offsetTable[numFonts]. + uint fonts = BinaryPrimitives.ReadUInt32BigEndian(span[8..]); + int available = (int)Math.Min(fonts, (uint)((span.Length - 12) / 4)); + if (available == 0) + { + context.Report(DiagnosticCodes.FontProgramInvalid, DiagnosticSeverity.Error, "The font collection lists no fonts; the program is not usable."); + return null; + } + + int chosen = -1; + if (context.FaceName is { } faceName) + { + for (int index = 0; index < available && chosen < 0; index++) + { + uint offset = BinaryPrimitives.ReadUInt32BigEndian(span[(12 + (4 * index))..]); + if (offset < (uint)span.Length && ReadDirectory(data, (int)offset, context: null) is { } face + && string.Equals(face.ReadPostScriptName(), faceName, StringComparison.Ordinal)) + { + chosen = index; + } + } + } + + if (chosen < 0) + { + chosen = context.FaceIndex; + if (chosen < 0 || chosen >= available) + { + context.Report( + DiagnosticCodes.FontTableInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The font collection has {available} fonts; font {context.FaceIndex} does not exist and font 0 is read.")); + chosen = 0; + } + } + + uint start = BinaryPrimitives.ReadUInt32BigEndian(span[(12 + (4 * chosen))..]); + if (start > (uint)(span.Length - 12)) + { + context.Report(DiagnosticCodes.FontProgramInvalid, DiagnosticSeverity.Error, "The font collection's offset to the chosen font lies outside the program; it is not usable."); + return null; + } + + return ReadDirectory(data, (int)start, context); + } + + /// Finds a table: its bytes, clamped to the file; when absent or empty. + public bool TryGetTable(uint tag, out ReadOnlyMemory table) + { + foreach (Table entry in _tables) + { + if (entry.Tag == tag) + { + table = Data.Slice(entry.Offset, entry.Length); + return true; + } + } + + table = default; + return false; + } + + /// Whether the font has a table. + public bool Has(uint tag) => TryGetTable(tag, out _); + + /// Reads the PostScript name (name id 6) from the "name" table: Windows Unicode, then Macintosh Roman, then Unicode platform. + /// The name, or . + public string? ReadPostScriptName() + { + if (!TryGetTable(Tag("name"), out ReadOnlyMemory memory)) + { + return null; + } + + ReadOnlySpan name = memory.Span; + if (name.Length < 6) + { + return null; + } + + int count = BinaryPrimitives.ReadUInt16BigEndian(name[2..]); + int storage = BinaryPrimitives.ReadUInt16BigEndian(name[4..]); + string? best = null; + int bestRank = int.MaxValue; + for (int index = 0; index < count; index++) + { + int record = 6 + (12 * index); + if (record + 12 > name.Length) + { + break; + } + + int platform = BinaryPrimitives.ReadUInt16BigEndian(name[record..]); + int nameId = BinaryPrimitives.ReadUInt16BigEndian(name[(record + 6)..]); + int length = BinaryPrimitives.ReadUInt16BigEndian(name[(record + 8)..]); + int offset = storage + BinaryPrimitives.ReadUInt16BigEndian(name[(record + 10)..]); + int rank = platform switch { 3 => 0, 1 => 1, 0 => 2, _ => int.MaxValue }; + if (nameId != 6 || rank >= bestRank || offset + length > name.Length) + { + continue; + } + + ReadOnlySpan text = name.Slice(offset, length); + best = platform == 1 ? Encoding.Latin1.GetString(text) : Encoding.BigEndianUnicode.GetString(text); + bestRank = rank; + } + + return best; + } + + private static SfntFile? ReadDirectory(ReadOnlyMemory data, int start, FontProgramContext? context) + { + ReadOnlySpan span = data.Span; + if (start + 12 > span.Length) + { + context?.Report(DiagnosticCodes.FontProgramInvalid, DiagnosticSeverity.Error, "The font's table directory lies outside the program; it is not usable."); + return null; + } + + uint version = BinaryPrimitives.ReadUInt32BigEndian(span[start..]); + int declared = BinaryPrimitives.ReadUInt16BigEndian(span[(start + 4)..]); + int count = Math.Min(declared, (span.Length - start - 12) / 16); + if (count < declared) + { + context?.Report( + DiagnosticCodes.FontTableInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The table directory lists {declared} tables but the program holds records for {count}; the others are ignored.")); + } + + var tables = new List(count); + for (int index = 0; index < count; index++) + { + ReadOnlySpan record = span.Slice(start + 12 + (16 * index), 16); + uint tag = BinaryPrimitives.ReadUInt32BigEndian(record); + uint offset = BinaryPrimitives.ReadUInt32BigEndian(record[8..]); + uint length = BinaryPrimitives.ReadUInt32BigEndian(record[12..]); + if (length == 0) + { + continue; + } + + if (offset >= (uint)span.Length) + { + context?.Report( + DiagnosticCodes.FontTableInvalid, + DiagnosticSeverity.Warning, + $"The \"{TagText(tag)}\" table starts past the end of the font program; it is ignored."); + continue; + } + + if (length > (uint)span.Length - offset) + { + context?.Report( + DiagnosticCodes.FontTableInvalid, + DiagnosticSeverity.Warning, + $"The \"{TagText(tag)}\" table runs past the end of the font program; it is read up to the end."); + length = (uint)span.Length - offset; + } + + if (tables.Exists(table => table.Tag == tag)) + { + context?.Report( + DiagnosticCodes.FontTableInvalid, + DiagnosticSeverity.Warning, + $"The table directory lists the \"{TagText(tag)}\" table twice; the first is used."); + continue; + } + + tables.Add(new Table(tag, (int)offset, (int)length)); + } + + return new SfntFile(data, version, [.. tables]); + } + + /// A tag as text, for messages. + public static string TagText(uint tag) + { + Span text = stackalloc char[4]; + for (int index = 0; index < 4; index++) + { + byte value = (byte)(tag >> (24 - (8 * index))); + text[index] = value is >= 0x20 and < 0x7F ? (char)value : '?'; + } + + return new string(text); + } + + private readonly record struct Table(uint Tag, int Offset, int Length); +} diff --git a/src/Broadside/Fonts/TrueType/TrueTypeFontProgram.Glyphs.cs b/src/Broadside/Fonts/TrueType/TrueTypeFontProgram.Glyphs.cs new file mode 100644 index 00000000..064a46e8 --- /dev/null +++ b/src/Broadside/Fonts/TrueType/TrueTypeFontProgram.Glyphs.cs @@ -0,0 +1,559 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.Globalization; + +namespace Broadside.Fonts.TrueType; + +/// Glyph outlines: decoding "glyf" descriptions into points, composing components, and turning contours into a path. +internal sealed partial class TrueTypeFontProgram +{ + /// + /// + /// OpenType "glyf" table. Points are decoded into pooled buffers, composites are assembled with their transforms (offsets are not + /// scaled unless SCALED_COMPONENT_OFFSET alone is set, as on Apple and Microsoft platforms) and point matching, and each contour + /// becomes move, line and quadratic segments, with the implied on-curve point midway between two off-curve points. Nothing is + /// allocated once the buffers are warm. + /// + public override GlyphOutlineStatus GetOutline(int glyphId, GlyphOutline outline) + { + ArgumentNullException.ThrowIfNull(outline); + outline.Clear(); + if (!TryGetGlyphData(glyphId, report: true, out ReadOnlySpan glyph)) + { + return GlyphOutlineStatus.Invalid; + } + + if (glyph.IsEmpty) + { + return GlyphOutlineStatus.Empty; + } + + Span ancestors = stackalloc int[_maxDepth + 1]; + var loader = new GlyphLoader(this, ancestors); + try + { + GlyphOutlineStatus status = loader.Load(glyphId, 0); + if (status != GlyphOutlineStatus.Complete || loader.PointCount == 0) + { + return status == GlyphOutlineStatus.Invalid ? status : GlyphOutlineStatus.Empty; + } + + // Place the outline as rasterizers do: its left edge at the left side bearing from the origin. + double shift = 0; + if (glyph.Length >= 10 && ReadHorizontalMetrics(glyphId) is { Present: true } metrics) + { + shift = metrics.LeftSideBearing - BinaryPrimitives.ReadInt16BigEndian(glyph[2..]); + } + + loader.Emit(outline, shift); + return outline.IsEmpty ? GlyphOutlineStatus.Empty : GlyphOutlineStatus.Complete; + } + finally + { + loader.Dispose(); + } + } + + /// The points of one top-level glyph, components included, in pooled buffers. + private ref struct GlyphLoader + { + private readonly TrueTypeFontProgram _program; + private readonly Span _ancestors; + private double[] _x; + private double[] _y; + private bool[] _onCurve; + private int[] _ends; + private byte[] _flags; + private int _contourCount; + private int _components; + + public GlyphLoader(TrueTypeFontProgram program, Span ancestors) + { + _program = program; + _ancestors = ancestors; + _x = ArrayPool.Shared.Rent(64); + _y = ArrayPool.Shared.Rent(64); + _onCurve = ArrayPool.Shared.Rent(64); + _ends = ArrayPool.Shared.Rent(8); + _flags = ArrayPool.Shared.Rent(64); + } + + public int PointCount { get; private set; } + + public readonly void Dispose() + { + ArrayPool.Shared.Return(_x); + ArrayPool.Shared.Return(_y); + ArrayPool.Shared.Return(_onCurve); + ArrayPool.Shared.Return(_ends); + ArrayPool.Shared.Return(_flags); + } + + /// Appends a glyph's points and contours; on failure, leaves the buffers as they were. + public GlyphOutlineStatus Load(int glyphId, int depth) + { + _ancestors[depth] = glyphId; + if (!_program.TryGetGlyphData(glyphId, report: true, out ReadOnlySpan glyph)) + { + return GlyphOutlineStatus.Invalid; + } + + if (glyph.IsEmpty) + { + return GlyphOutlineStatus.Empty; + } + + if (glyph.Length < 10) + { + _program.ReportGlyph(glyphId, "it is shorter than a glyph header; it is dropped"); + return GlyphOutlineStatus.Invalid; + } + + int contours = BinaryPrimitives.ReadInt16BigEndian(glyph); + if (contours >= 0) + { + return LoadSimple(glyph, contours, glyphId); + } + + if (contours < -1) + { + _program.ReportGlyph(glyphId, string.Create(CultureInfo.InvariantCulture, $"its numberOfContours is {contours}; it is read as a composite glyph")); + } + + return LoadComposite(glyph, glyphId, depth); + } + + /// Writes the contours as a path (implied on-curve midpoints between off-curve points), shifted horizontally. + public readonly void Emit(GlyphOutline outline, double shift) + { + int start = 0; + for (int contour = 0; contour < _contourCount; contour++) + { + int end = _ends[contour]; + if (end > start) + { + EmitContour(outline, start, end, shift); + } + + start = Math.Max(start, end + 1); + } + } + + private readonly void EmitContour(GlyphOutline outline, int first, int last, double shift) + { + // Start on an on-curve point: the first, else the last, else the midpoint between them. + double startX; + double startY; + int from; + int to = last; + if (_onCurve[first]) + { + (startX, startY) = (_x[first], _y[first]); + from = first + 1; + } + else if (_onCurve[last]) + { + (startX, startY) = (_x[last], _y[last]); + from = first; + to = last - 1; + } + else + { + (startX, startY) = ((_x[first] + _x[last]) / 2, (_y[first] + _y[last]) / 2); + from = first; + } + + outline.MoveTo(startX + shift, startY); + bool pending = false; + double controlX = 0; + double controlY = 0; + for (int index = from; index <= to; index++) + { + double x = _x[index]; + double y = _y[index]; + if (_onCurve[index]) + { + if (pending) + { + outline.QuadTo(controlX + shift, controlY, x + shift, y); + pending = false; + } + else + { + outline.LineTo(x + shift, y); + } + } + else + { + if (pending) + { + outline.QuadTo(controlX + shift, controlY, ((controlX + x) / 2) + shift, (controlY + y) / 2); + } + + (controlX, controlY) = (x, y); + pending = true; + } + } + + if (pending) + { + outline.QuadTo(controlX + shift, controlY, startX + shift, startY); + } + + outline.Close(); + } + + /// A simple glyph: contour ends, instructions (skipped), flags, then x and y coordinates as deltas. + private GlyphOutlineStatus LoadSimple(ReadOnlySpan glyph, int contours, int glyphId) + { + if (contours == 0) + { + return GlyphOutlineStatus.Empty; + } + + int basePoint = PointCount; + int baseContour = _contourCount; + int position = 10; + if (position + (2 * contours) + 2 > glyph.Length) + { + return Truncated(glyphId, basePoint, baseContour); + } + + EnsureContours(baseContour + contours); + int previous = -1; + for (int contour = 0; contour < contours; contour++) + { + int end = BinaryPrimitives.ReadUInt16BigEndian(glyph[(position + (2 * contour))..]); + if (end <= previous) + { + _program.ReportGlyph(glyphId, "its contour end points are not in increasing order; it is dropped"); + return GlyphOutlineStatus.Invalid; + } + + _ends[baseContour + contour] = basePoint + end; + previous = end; + } + + int points = previous + 1; + position += 2 * contours; + if (basePoint + points > _program._context.MaxGlyphPoints) + { + _program.ReportGlyph(glyphId, string.Create(CultureInfo.InvariantCulture, $"it has more than {_program._context.MaxGlyphPoints} points with its components; it is dropped")); + return GlyphOutlineStatus.Invalid; + } + + int instructions = BinaryPrimitives.ReadUInt16BigEndian(glyph[position..]); + position += 2 + instructions; + if (position > glyph.Length) + { + return Truncated(glyphId, basePoint, baseContour); + } + + // Flags, with REPEAT runs; a run past the point count is cut short. + EnsurePoints(basePoint + points); + Span flags = _flags.AsSpan(0, points); + int count = 0; + bool clamped = false; + while (count < points) + { + if (position >= glyph.Length) + { + return Truncated(glyphId, basePoint, baseContour); + } + + byte flag = glyph[position++]; + flags[count++] = flag; + if ((flag & 0x08) != 0) + { + if (position >= glyph.Length) + { + return Truncated(glyphId, basePoint, baseContour); + } + + int repeat = glyph[position++]; + if (repeat > points - count) + { + clamped = true; + repeat = points - count; + } + + flags.Slice(count, repeat).Fill(flag); + count += repeat; + } + } + + if (clamped) + { + _program.ReportGlyph(glyphId, "a repeated flag runs past its last point; the run is cut short"); + } + + int xLength = 0; + int yLength = 0; + foreach (byte flag in flags) + { + xLength += (flag & 0x02) != 0 ? 1 : (flag & 0x10) != 0 ? 0 : 2; + yLength += (flag & 0x04) != 0 ? 1 : (flag & 0x20) != 0 ? 0 : 2; + } + + if (position + xLength + yLength > glyph.Length) + { + return Truncated(glyphId, basePoint, baseContour); + } + + // x: SHORT with SAME = positive byte, SHORT alone = negative byte, SAME alone = repeat (no byte), neither = int16 delta. + int xAt = position; + int yAt = position + xLength; + int x = 0; + int y = 0; + for (int index = 0; index < points; index++) + { + byte flag = flags[index]; + switch (flag & 0x12) + { + case 0x02: + x -= glyph[xAt++]; + break; + case 0x12: + x += glyph[xAt++]; + break; + case 0x00: + x += BinaryPrimitives.ReadInt16BigEndian(glyph[xAt..]); + xAt += 2; + break; + } + + switch (flag & 0x24) + { + case 0x04: + y -= glyph[yAt++]; + break; + case 0x24: + y += glyph[yAt++]; + break; + case 0x00: + y += BinaryPrimitives.ReadInt16BigEndian(glyph[yAt..]); + yAt += 2; + break; + } + + _x[basePoint + index] = x; + _y[basePoint + index] = y; + _onCurve[basePoint + index] = (flag & 0x01) != 0; + } + + PointCount = basePoint + points; + _contourCount = baseContour + contours; + return GlyphOutlineStatus.Complete; + } + + /// A composite glyph: components loaded recursively, transformed, then offset or matched to a point. + private GlyphOutlineStatus LoadComposite(ReadOnlySpan glyph, int glyphId, int depth) + { + int basePoint = PointCount; + int position = 10; + int flags; + do + { + if (position + 4 > glyph.Length) + { + _program.ReportGlyph(glyphId, "its component records are truncated; the components before the damage are kept"); + break; + } + + flags = BinaryPrimitives.ReadUInt16BigEndian(glyph[position..]); + int child = BinaryPrimitives.ReadUInt16BigEndian(glyph[(position + 2)..]); + position += 4; + if (position + ComponentArgumentsLength(flags) > glyph.Length) + { + _program.ReportGlyph(glyphId, "its component records are truncated; the components before the damage are kept"); + break; + } + + int argument1; + int argument2; + bool xy = (flags & CompositeFlags.ArgsAreXYValues) != 0; + if ((flags & CompositeFlags.ArgsAreWords) != 0) + { + argument1 = xy ? BinaryPrimitives.ReadInt16BigEndian(glyph[position..]) : BinaryPrimitives.ReadUInt16BigEndian(glyph[position..]); + argument2 = xy ? BinaryPrimitives.ReadInt16BigEndian(glyph[(position + 2)..]) : BinaryPrimitives.ReadUInt16BigEndian(glyph[(position + 2)..]); + position += 4; + } + else + { + argument1 = xy ? (sbyte)glyph[position] : glyph[position]; + argument2 = xy ? (sbyte)glyph[position + 1] : glyph[position + 1]; + position += 2; + } + + // x' = xscale·x + scale10·y; y' = scale01·x + yscale·y (F2Dot14 values). + double xScale = 1; + double scale01 = 0; + double scale10 = 0; + double yScale = 1; + bool transformed = true; + if ((flags & CompositeFlags.HaveScale) != 0) + { + xScale = yScale = F2Dot14(glyph, position); + position += 2; + } + else if ((flags & CompositeFlags.HaveXAndYScale) != 0) + { + xScale = F2Dot14(glyph, position); + yScale = F2Dot14(glyph, position + 2); + position += 4; + } + else if ((flags & CompositeFlags.HaveTwoByTwo) != 0) + { + xScale = F2Dot14(glyph, position); + scale01 = F2Dot14(glyph, position + 2); + scale10 = F2Dot14(glyph, position + 4); + yScale = F2Dot14(glyph, position + 6); + position += 8; + } + else + { + transformed = false; + } + + if (++_components > MaxComponentsPerGlyph) + { + _program.ReportGlyph(glyphId, string.Create(CultureInfo.InvariantCulture, $"it has more than {MaxComponentsPerGlyph} components with its nested components; the rest are skipped")); + break; + } + + if (!CanLoadComponent(glyphId, child, depth)) + { + continue; + } + + int childBase = PointCount; + int childContours = _contourCount; + GlyphOutlineStatus status = Load(child, depth + 1); + if (status == GlyphOutlineStatus.Invalid) + { + PointCount = childBase; + _contourCount = childContours; + continue; + } + + if (transformed) + { + for (int index = childBase; index < PointCount; index++) + { + double px = _x[index]; + double py = _y[index]; + _x[index] = (xScale * px) + (scale10 * py); + _y[index] = (scale01 * px) + (yScale * py); + } + } + + double offsetX; + double offsetY; + if (xy) + { + offsetX = argument1; + offsetY = argument2; + if (transformed && (flags & CompositeFlags.ScaledComponentOffset) != 0 && (flags & CompositeFlags.UnscaledComponentOffset) == 0) + { + offsetX *= Math.Sqrt((xScale * xScale) + (scale10 * scale10)); + offsetY *= Math.Sqrt((yScale * yScale) + (scale01 * scale01)); + } + } + else + { + // Point matching: the component's point argument2 lands on the parent's point argument1. + int parentPoint = basePoint + argument1; + int childPoint = childBase + argument2; + if (parentPoint < childBase && childPoint < PointCount) + { + offsetX = _x[parentPoint] - _x[childPoint]; + offsetY = _y[parentPoint] - _y[childPoint]; + } + else + { + _program.ReportGlyph(glyphId, "a component's matching point numbers are out of range; the component is not moved"); + offsetX = offsetY = 0; + } + } + + if (offsetX != 0 || offsetY != 0) + { + for (int index = childBase; index < PointCount; index++) + { + _x[index] += offsetX; + _y[index] += offsetY; + } + } + } + while ((flags & CompositeFlags.MoreComponents) != 0); + + // WE_HAVE_INSTRUCTIONS: the instructions after the last component are not read. + return GlyphOutlineStatus.Complete; + } + + private readonly bool CanLoadComponent(int glyphId, int child, int depth) + { + if ((uint)child >= (uint)_program._glyphCount) + { + _program.ReportGlyph(glyphId, string.Create(CultureInfo.InvariantCulture, $"a component refers to glyph {child}, past the program's {_program._glyphCount} glyphs; it is skipped")); + return false; + } + + if (_ancestors[..(depth + 1)].Contains(child)) + { + _program.ReportGlyph(glyphId, string.Create(CultureInfo.InvariantCulture, $"a component refers to glyph {child}, which contains this glyph; it is skipped")); + return false; + } + + if (depth + 1 > _program._maxDepth) + { + _program.ReportGlyph(glyphId, string.Create(CultureInfo.InvariantCulture, $"its components nest deeper than {_program._maxDepth} levels; the deeper ones are skipped")); + return false; + } + + return true; + } + + private static double F2Dot14(ReadOnlySpan glyph, int position) => BinaryPrimitives.ReadInt16BigEndian(glyph[position..]) / 16384.0; + + private GlyphOutlineStatus Truncated(int glyphId, int basePoint, int baseContour) + { + PointCount = basePoint; + _contourCount = baseContour; + _program.ReportGlyph(glyphId, "its data ends before its last point; it is dropped"); + return GlyphOutlineStatus.Invalid; + } + + private void EnsurePoints(int count) + { + if (count > _x.Length) + { + Grow(ref _x, count, PointCount); + Grow(ref _y, count, PointCount); + Grow(ref _onCurve, count, PointCount); + } + + if (count > _flags.Length) + { + ArrayPool.Shared.Return(_flags); + _flags = ArrayPool.Shared.Rent(count); + } + } + + private void EnsureContours(int count) + { + if (count > _ends.Length) + { + Grow(ref _ends, count, _contourCount); + } + } + + private static void Grow(ref T[] array, int count, int used) + { + T[] larger = ArrayPool.Shared.Rent(Math.Max(count, array.Length * 2)); + array.AsSpan(0, used).CopyTo(larger); + ArrayPool.Shared.Return(array); + array = larger; + } + } +} diff --git a/src/Broadside/Fonts/TrueType/TrueTypeFontProgram.cs b/src/Broadside/Fonts/TrueType/TrueTypeFontProgram.cs new file mode 100644 index 00000000..a0da1d81 --- /dev/null +++ b/src/Broadside/Fonts/TrueType/TrueTypeFontProgram.cs @@ -0,0 +1,421 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Graphics; +using Broadside.Parsing; + +namespace Broadside.Fonts.TrueType; + +/// +/// A parsed TrueType program: tables located once, glyphs decoded on request from the program's bytes, which it keeps a reference to. +/// +/// +/// Apple TrueType Reference Manual and OpenType specification: "head", "hhea", "hmtx", "maxp", "loca", "glyf", "cmap", "post". +/// ISO 32000-2 §9.6.3, §9.9. Immutable and safe for concurrent use; the "post" names are read on first use. +/// +internal sealed partial class TrueTypeFontProgram : FontProgram +{ + private const int MaxComponentsPerGlyph = 4096; + private const int MaxAncestorDepth = 256; + + private readonly SfntFile _sfnt; + private readonly ReadOnlyMemory _glyf; + private readonly ReadOnlyMemory _loca; + private readonly bool _longOffsets; + private readonly int _glyphCount; + private readonly int _unitsPerEm; + private readonly ReadOnlyMemory? _hmtx; + private readonly int _horizontalMetricCount; + private readonly ReadOnlyMemory? _post; + private readonly CmapSubtable[] _cmaps; + private readonly FontProgramContext _context; + private readonly int _maxDepth; + private PostTable? _postTable; + private string? _postScriptName; + private bool _postScriptNameRead; + + private TrueTypeFontProgram( + SfntFile sfnt, + ReadOnlyMemory glyf, + ReadOnlyMemory loca, + bool longOffsets, + int glyphCount, + int unitsPerEm, + PdfRectangle bbox, + (double Ascender, double Descender, double LineGap) vertical, + ReadOnlyMemory? hmtx, + int horizontalMetricCount, + ReadOnlyMemory? post, + ReadOnlyMemory? cmap, + FontProgramContext context) + { + _sfnt = sfnt; + _glyf = glyf; + _loca = loca; + _longOffsets = longOffsets; + _glyphCount = glyphCount; + _unitsPerEm = unitsPerEm; + FontBBox = bbox; + Ascender = vertical.Ascender; + Descender = vertical.Descender; + LineGap = vertical.LineGap; + _hmtx = hmtx; + _horizontalMetricCount = horizontalMetricCount; + _post = post; + _context = context; + _maxDepth = Math.Clamp(context.MaxCompositeDepth, 0, MaxAncestorDepth - 1); + _cmaps = cmap is { } table ? CmapSubtable.ReadAll(table, glyphCount, context) : []; + FontMatrix = Matrix.CreateScale(1.0 / unitsPerEm, 1.0 / unitsPerEm); + } + + /// + public override FontProgramFormat Format => _sfnt.Version == SfntFile.OpenTypeVersion ? FontProgramFormat.OpenType : FontProgramFormat.TrueType; + + /// + public override int GlyphCount => _glyphCount; + + /// + /// OpenType "head" table: [1/unitsPerEm 0 0 1/unitsPerEm 0 0]. + public override Matrix FontMatrix { get; } + + /// + /// OpenType "head" table, xMin yMin xMax yMax. + public override PdfRectangle FontBBox { get; } + + /// + /// OpenType "hhea" table. + public override double Ascender { get; } + + /// + /// OpenType "hhea" table. + public override double Descender { get; } + + /// + /// OpenType "hhea" table. + public override double LineGap { get; } + + /// + public override IReadOnlyList CharacterMaps => _cmaps; + + /// + /// OpenType "name" table, name id 6. + public override string? PostScriptName + { + get + { + if (!Volatile.Read(ref _postScriptNameRead)) + { + _postScriptName = _sfnt.ReadPostScriptName(); + Volatile.Write(ref _postScriptNameRead, true); + } + + return _postScriptName; + } + } + + /// Gets the units per em, from "head". + internal int UnitsPerEm => _unitsPerEm; + + private PostTable Post => LazyInitializer.EnsureInitialized( + ref _postTable, + () => _post is { } post ? PostTable.Read(post.Span, _glyphCount, _context) : PostTable.None); + + /// Builds the program from its located tables, repairing missing or inconsistent ones with diagnostics. + internal static TrueTypeFontProgram Create( + SfntFile sfnt, + ReadOnlyMemory glyf, + ReadOnlyMemory loca, + FontProgramContext context, + ReadOnlyMemory? head, + ReadOnlyMemory? hhea, + ReadOnlyMemory? hmtx, + ReadOnlyMemory? maxp, + ReadOnlyMemory? cmap, + ReadOnlyMemory? post) + { + // maxp: numGlyphs at offset 4 in every version; the version 1.0 maxima are hints only. + int glyphCount = -1; + if (maxp is { Length: >= 6 } maxpTable) + { + glyphCount = BinaryPrimitives.ReadUInt16BigEndian(maxpTable.Span[4..]); + } + else + { + ReportTable(context, "maxp", "is missing or too short; the glyph count is taken from \"loca\""); + } + + // head: unitsPerEm, the font box and the loca format. + int unitsPerEm = 1000; + var bbox = default(PdfRectangle); + int locaFormat = -1; + if (head is { Length: >= 54 } headTable) + { + ReadOnlySpan span = headTable.Span; + int declared = BinaryPrimitives.ReadUInt16BigEndian(span[18..]); + if (declared is >= 16 and <= 16384) + { + unitsPerEm = declared; + } + else + { + ReportTable(context, "head", string.Create(CultureInfo.InvariantCulture, $"gives unitsPerEm {declared}, outside 16 to 16384; 1000 is used")); + } + + bbox = new PdfRectangle( + BinaryPrimitives.ReadInt16BigEndian(span[36..]), + BinaryPrimitives.ReadInt16BigEndian(span[38..]), + BinaryPrimitives.ReadInt16BigEndian(span[40..]), + BinaryPrimitives.ReadInt16BigEndian(span[42..])); + locaFormat = BinaryPrimitives.ReadInt16BigEndian(span[50..]); + } + else + { + ReportTable(context, "head", "is missing or too short; 1000 units per em are used and the \"loca\" format is inferred from its length"); + } + + if (locaFormat is not (0 or 1)) + { + bool fitsLong = glyphCount >= 0 ? loca.Length >= (glyphCount + 1) * 4 : loca.Length % 4 == 0 && loca.Length >= 8; + bool fitsShort = glyphCount >= 0 && loca.Length == (glyphCount + 1) * 2; + int inferred = fitsShort || !fitsLong ? 0 : 1; + if (head is { Length: >= 54 }) + { + ReportTable(context, "head", string.Create(CultureInfo.InvariantCulture, $"gives indexToLocFormat {locaFormat}, which is neither 0 nor 1; {inferred} is inferred from the \"loca\" length")); + } + + locaFormat = inferred; + } + + bool longOffsets = locaFormat == 1; + int entries = loca.Length / (longOffsets ? 4 : 2); + if (glyphCount < 0) + { + glyphCount = Math.Max(0, entries - 1); + } + else if (entries < glyphCount + 1) + { + ReportTable(context, "loca", string.Create(CultureInfo.InvariantCulture, $"has offsets for {Math.Max(0, entries - 1)} glyphs but \"maxp\" counts {glyphCount}; the glyphs without offsets do not exist")); + glyphCount = Math.Max(0, entries - 1); + } + + // hhea: the vertical metrics and how many hmtx entries carry an advance. + (double, double, double) vertical = default; + int metricCount = 0; + if (hhea is { Length: >= 36 } hheaTable) + { + ReadOnlySpan span = hheaTable.Span; + vertical = (BinaryPrimitives.ReadInt16BigEndian(span[4..]), BinaryPrimitives.ReadInt16BigEndian(span[6..]), BinaryPrimitives.ReadInt16BigEndian(span[8..])); + metricCount = BinaryPrimitives.ReadUInt16BigEndian(span[34..]); + if (metricCount > glyphCount) + { + metricCount = glyphCount; + } + } + else + { + ReportTable(context, "hhea", "is missing or too short; glyph advances are 0"); + } + + if (hmtx is { } hmtxTable && metricCount > 0) + { + if (hmtxTable.Length < (4 * metricCount) + (2 * (glyphCount - metricCount))) + { + ReportTable(context, "hmtx", "is shorter than \"hhea\" and \"maxp\" require; the metrics present are used and the others are 0"); + } + } + else if (hhea is { Length: >= 36 }) + { + ReportTable(context, "hmtx", metricCount == 0 ? "has no advance (numberOfHMetrics is 0); glyph advances are 0" : "is missing; glyph advances are 0"); + metricCount = 0; + } + + if (cmap is null && !context.IsCidFont) + { + ReportTable(context, "cmap", "is missing; a simple TrueType font's program shall have one (ISO 32000-2 §9.9), so glyphs are selected by other means"); + } + + return new TrueTypeFontProgram( + sfnt, + glyf, + loca, + longOffsets, + glyphCount, + unitsPerEm, + bbox, + vertical, + metricCount > 0 ? hmtx : null, + metricCount, + post, + cmap, + context); + } + + /// + public override GlyphMetrics GetMetrics(int glyphId) => GetMetrics(glyphId, 0); + + /// + /// OpenType "post" table. + public override string? GetGlyphName(int glyphId) => Post.NameOf(glyphId); + + /// + /// OpenType "post" table; the first glyph of a name wins when several share it. + public override bool TryGetGlyphId(string glyphName, out int glyphId) + { + ArgumentNullException.ThrowIfNull(glyphName); + if (Post.TryGetGlyphId(glyphName, out glyphId)) + { + return true; + } + + glyphId = 0; + return false; + } + + /// The "hmtx" entry of a glyph: the last advance repeats past numberOfHMetrics; missing data reads as 0. + private (double Advance, double LeftSideBearing, bool Present) ReadHorizontalMetrics(int glyphId) + { + if (_hmtx is not { } hmtx || (uint)glyphId >= (uint)_glyphCount) + { + return (0, 0, false); + } + + ReadOnlySpan span = hmtx.Span; + int advanceIndex = Math.Min(glyphId, _horizontalMetricCount - 1); + int advanceAt = 4 * advanceIndex; + double advance = advanceAt + 2 <= span.Length ? BinaryPrimitives.ReadUInt16BigEndian(span[advanceAt..]) : 0; + int bearingAt = glyphId < _horizontalMetricCount ? (4 * glyphId) + 2 : (4 * _horizontalMetricCount) + (2 * (glyphId - _horizontalMetricCount)); + bool present = bearingAt + 2 <= span.Length; + double bearing = present ? BinaryPrimitives.ReadInt16BigEndian(span[bearingAt..]) : 0; + return (advance, bearing, present); + } + + /// A glyph's metrics; a composite with USE_MY_METRICS takes its component's (OpenType "glyf", composite flags). + private GlyphMetrics GetMetrics(int glyphId, int depth) + { + if (depth <= _maxDepth && TryGetGlyphData(glyphId, report: false, out ReadOnlySpan glyph) + && glyph.Length >= 10 && BinaryPrimitives.ReadInt16BigEndian(glyph) < 0) + { + int position = 10; + int flags; + do + { + if (position + 4 > glyph.Length) + { + break; + } + + flags = BinaryPrimitives.ReadUInt16BigEndian(glyph[position..]); + int child = BinaryPrimitives.ReadUInt16BigEndian(glyph[(position + 2)..]); + if ((flags & CompositeFlags.UseMyMetrics) != 0 && child != glyphId) + { + return GetMetrics(child, depth + 1); + } + + position += 4 + ComponentArgumentsLength(flags); + } + while ((flags & CompositeFlags.MoreComponents) != 0); + } + + (double advance, double bearing, _) = ReadHorizontalMetrics(glyphId); + return new GlyphMetrics(advance, bearing); + } + + /// The bytes of a glyph's description through "loca"; empty for a glyph without an outline. + /// when the glyph id is out of range or its location is unusable (reported when asked). + private bool TryGetGlyphData(int glyphId, bool report, out ReadOnlySpan glyph) + { + glyph = default; + if ((uint)glyphId >= (uint)_glyphCount) + { + return false; + } + + ReadOnlySpan loca = _loca.Span; + long start; + long end; + if (_longOffsets) + { + start = BinaryPrimitives.ReadUInt32BigEndian(loca[(4 * glyphId)..]); + end = BinaryPrimitives.ReadUInt32BigEndian(loca[(4 * (glyphId + 1))..]); + } + else + { + start = BinaryPrimitives.ReadUInt16BigEndian(loca[(2 * glyphId)..]) * 2L; + end = BinaryPrimitives.ReadUInt16BigEndian(loca[(2 * (glyphId + 1))..]) * 2L; + } + + if (start == end) + { + return true; + } + + int length = _glyf.Length; + if (start >= length) + { + if (report) + { + ReportGlyph(glyphId, "its \"loca\" offset lies past the end of \"glyf\"; it has no outline"); + } + + return false; + } + + if (end < start || end > length) + { + if (report) + { + ReportGlyph(glyphId, "its \"loca\" end offset is before its start or past the end of \"glyf\"; its data is bounded by the end of \"glyf\""); + } + + end = length; + } + + glyph = _glyf.Span[(int)start..(int)end]; + return true; + } + + private void ReportGlyph(int glyphId, string problem) => _context.Report( + DiagnosticCodes.FontGlyphInvalid, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"Glyph {glyphId} of the TrueType program deviates from the OpenType \"glyf\" table format: {problem}.")); + + private static void ReportTable(FontProgramContext context, string table, string problem) => context.Report( + DiagnosticCodes.FontTableInvalid, + DiagnosticSeverity.Warning, + $"The TrueType program's \"{table}\" table {problem}."); + + /// The length of a component record after its flags and glyph index: arguments and transform. + private static int ComponentArgumentsLength(int flags) + { + int length = (flags & CompositeFlags.ArgsAreWords) != 0 ? 4 : 2; + if ((flags & CompositeFlags.HaveScale) != 0) + { + length += 2; + } + else if ((flags & CompositeFlags.HaveXAndYScale) != 0) + { + length += 4; + } + else if ((flags & CompositeFlags.HaveTwoByTwo) != 0) + { + length += 8; + } + + return length; + } + + /// The component flags of a composite glyph description (OpenType "glyf" table). + private static class CompositeFlags + { + public const int ArgsAreWords = 0x0001; + public const int ArgsAreXYValues = 0x0002; + public const int HaveScale = 0x0008; + public const int MoreComponents = 0x0020; + public const int HaveXAndYScale = 0x0040; + public const int HaveTwoByTwo = 0x0080; + public const int UseMyMetrics = 0x0200; + public const int ScaledComponentOffset = 0x0800; + public const int UnscaledComponentOffset = 0x1000; + } +} diff --git a/src/Broadside/Fonts/TrueType/TrueTypeFontProgramParser.cs b/src/Broadside/Fonts/TrueType/TrueTypeFontProgramParser.cs new file mode 100644 index 00000000..2be25372 --- /dev/null +++ b/src/Broadside/Fonts/TrueType/TrueTypeFontProgramParser.cs @@ -0,0 +1,97 @@ +using System.Buffers.Binary; +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Parsing; + +namespace Broadside.Fonts.TrueType; + +/// +/// The managed default parser for TrueType programs: FontFile2 streams, and FontFile3 streams of subtype +/// OpenType whose outlines are "glyf" data. The first default of the font program parser extension point. +/// +/// +/// +/// ISO 32000-2 §9.6.3 and §9.9 (Tables 124 and 125); Apple TrueType Reference Manual and the OpenType specification for the tables: +/// "head", "hhea", "hmtx", "maxp", "loca", "glyf" (simple and composite glyphs), "cmap" (formats 0, 2, 4, 6, 12, 13) and "post". A +/// TrueType collection is read too, the font chosen by or +/// . +/// +/// +/// Outlines are quadratic, unhinted: glyph instructions, "fpgm", "prep" and "cvt " are skipped, never executed, so glyphs whose +/// components only assemble through instructions (a few CJK fonts) draw scrambled. Each outline is translated by the difference +/// between its "hmtx" left side bearing and its bounding box's left edge, as TrueType rasterizers place glyphs. +/// +/// +/// Leniency follows ADR 0005: a missing "head", "hhea", "hmtx" or "maxp" is replaced by defaults with a diagnostic; only a program +/// without "glyf" and "loca" is unusable. A damaged glyph is dropped (), never drawn in part. +/// +/// +public sealed class TrueTypeFontProgramParser : IFontProgramParser +{ + private static readonly uint Glyf = SfntFile.Tag("glyf"); + private static readonly uint Loca = SfntFile.Tag("loca"); + private static readonly uint Head = SfntFile.Tag("head"); + private static readonly uint Hhea = SfntFile.Tag("hhea"); + private static readonly uint Hmtx = SfntFile.Tag("hmtx"); + private static readonly uint Maxp = SfntFile.Tag("maxp"); + private static readonly uint Cmap = SfntFile.Tag("cmap"); + private static readonly uint Post = SfntFile.Tag("post"); + private static readonly uint Cff = SfntFile.Tag("CFF "); + + /// + public IReadOnlyList Formats { get; } = [FontProgramFormat.TrueType]; + + /// + /// + /// Accepts the TrueType sfnt versions 00 01 00 00 and true, a TrueType collection (ttcf), and an OpenType + /// program (OTTO) only when it has a "glyf" table: ISO 32000-2 Table 124 allows "glyf" outlines in OpenType streams. + /// + public bool CanParse(ReadOnlySpan data) + { + if (data.Length < 12) + { + return false; + } + + uint version = BinaryPrimitives.ReadUInt32BigEndian(data); + return version switch + { + SfntFile.TrueTypeVersion or SfntFile.AppleTrueTypeVersion or SfntFile.CollectionTag => SfntFile.HasTable(data, Glyf) || !SfntFile.HasTable(data, Cff), + SfntFile.OpenTypeVersion => SfntFile.HasTable(data, Glyf), + _ => false, + }; + } + + /// + public FontProgram? Parse(ReadOnlyMemory data, FontProgramContext context) + { + ArgumentNullException.ThrowIfNull(context); + if (context.Length1 is { } length1 && length1 > data.Length) + { + context.Report( + DiagnosticCodes.FontProgramTruncated, + DiagnosticSeverity.Warning, + string.Create(CultureInfo.InvariantCulture, $"The font file stream's Length1 is {length1}, but its data is {data.Length} bytes (ISO 32000-2 §9.9, Table 125); the bytes present are read.")); + } + + if (SfntFile.Open(data, context) is not { } sfnt) + { + return null; + } + + if (!sfnt.TryGetTable(Glyf, out ReadOnlyMemory glyf) || !sfnt.TryGetTable(Loca, out ReadOnlyMemory loca)) + { + context.Report( + DiagnosticCodes.FontProgramInvalid, + DiagnosticSeverity.Error, + sfnt.Has(Cff) + ? "The font program has CFF outlines, not the \"glyf\" and \"loca\" tables of TrueType outlines (ISO 32000-2 §9.9, Table 124); it is not usable as TrueType." + : "The font program has no \"glyf\" or no \"loca\" table, which a TrueType program shall have (ISO 32000-2 §9.9, Table 124); it is not usable."); + return null; + } + + return TrueTypeFontProgram.Create(sfnt, glyf, loca, context, Read(sfnt, Head), Read(sfnt, Hhea), Read(sfnt, Hmtx), Read(sfnt, Maxp), Read(sfnt, Cmap), Read(sfnt, Post)); + } + + private static ReadOnlyMemory? Read(SfntFile sfnt, uint tag) => sfnt.TryGetTable(tag, out ReadOnlyMemory table) ? table : default(ReadOnlyMemory?); +} diff --git a/src/Broadside/Fonts/TrueTypeGlyphSelector.cs b/src/Broadside/Fonts/TrueTypeGlyphSelector.cs new file mode 100644 index 00000000..f6bd62a0 --- /dev/null +++ b/src/Broadside/Fonts/TrueTypeGlyphSelector.cs @@ -0,0 +1,234 @@ +using System.Globalization; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Fonts; + +/// +/// The glyph id of each character code of a simple TrueType font, chosen as ISO 32000-2 §9.6.5.4 describes, through the font +/// program's "cmap" subtables and "post" names. Each code is worked out on first use and kept. +/// +/// +/// +/// §9.6.5.4: when the encoding is MacRomanEncoding or WinAnsiEncoding, or the font is nonsymbolic, a code becomes a +/// glyph name through the encoding, then a Unicode value through the Adobe Glyph List and a glyph through the (3, 1) subtable; or, +/// without one, a Mac OS Roman code (MacRomanEncoding plus Table 113) and a glyph through the (1, 0) subtable; failing both, the +/// glyph of that name in "post". When the font has no encoding or is symbolic, the code itself selects the glyph: through the (3, 0) +/// subtable with the high byte 0x00, 0xF0, 0xF1 or 0xF2 (§9.6.5.4 allows those four ranges), else through the (1, 0) subtable. +/// +/// +/// When the prescribed route finds nothing, "a PDF processor may supply a mapping of its choosing" (§9.6.5.4, last paragraph): +/// the other route, then the code as a Unicode value in a Unicode subtable (as pdf.js and PDFBox do for symbolic fonts that carry +/// a Unicode "cmap"), then, for a symbolic font whose program has no usable "cmap", the code as the glyph id (as pdf.js does). +/// Each such choice is recorded as an information diagnostic. The (0, 3), (0, 0), (0, 1), (3, 10) and (0, 4) subtables stand in +/// for (3, 1) as Unicode subtables. +/// +/// +internal sealed class TrueTypeGlyphSelector +{ + private static readonly (int Platform, int Encoding)[] UnicodeSubtables = [(3, 1), (0, 3), (0, 0), (0, 1), (3, 10), (0, 4)]; + + private readonly PdfTrueTypeFont _font; + private readonly int[] _glyphs = new int[256]; + private readonly FontCharacterMap[] _unicode; + private readonly FontCharacterMap? _symbol; + private readonly FontCharacterMap? _macintosh; + private readonly bool _byName; + private readonly bool _encodingGiven; + + public TrueTypeGlyphSelector(PdfTrueTypeFont font, SimpleFontMetrics metrics, FontProgram? program) + { + _font = font; + Metrics = metrics; + Program = program; + Array.Fill(_glyphs, -1); + IReadOnlyList maps = program?.CharacterMaps ?? []; + _unicode = [.. UnicodeSubtables.Select(id => Find(maps, id.Platform, id.Encoding)).OfType()]; + _symbol = Find(maps, 3, 0); + _macintosh = Find(maps, 1, 0); + + CosObject? encoding = font.Get(FontNames.Encoding); + bool winOrMac = FontNames.WinAnsiEncoding.Equals(encoding) || FontNames.MacRomanEncoding.Equals(encoding); + bool dictionary = encoding is CosDictionary; + _encodingGiven = winOrMac || dictionary; + + // §9.8.2: a processor checks the Symbolic flag. Without Flags, a font with no encoding is taken as symbolic (PDFBox). + CosDictionary? descriptor = font.DescriptorDictionary; + bool hasFlags = descriptor is not null && font.GetFrom(descriptor, FontNames.Flags) is CosInteger; + PdfFontFlags flags = descriptor is null ? PdfFontFlags.None : PdfFontDescriptor.ReadFlags(descriptor, font.Document); + bool symbolic = hasFlags ? flags.HasFlag(PdfFontFlags.Symbolic) : encoding is null; + if (symbolic && flags.HasFlag(PdfFontFlags.Nonsymbolic) && encoding is CosDictionary encodingDictionary + && font.GetFrom(encodingDictionary, FontNames.Differences) is CosArray) + { + // Both flags and a Differences array: the producer meant the names (pdf.js and PDFBox read it as nonsymbolic). + symbolic = false; + font.Report( + DiagnosticCodes.FontGlyphMappingFallback, + DiagnosticSeverity.Information, + "The font descriptor sets both the Symbolic and Nonsymbolic flags (ISO 32000-2 §9.8.2, Table 121) and the encoding has a Differences array; glyphs are selected by name as for a nonsymbolic font."); + } + + _byName = !symbolic && (winOrMac || dictionary || flags.HasFlag(PdfFontFlags.Nonsymbolic)); + } + + /// Gets the names and widths the selector was built from: a new set means the font changed. + public SimpleFontMetrics Metrics { get; } + + /// Gets the program the selector was built from. + public FontProgram? Program { get; } + + /// Gets the glyph id of a character code; 0 (the missing glyph) when none applies. + public int GetGlyphId(byte code) + { + int glyph = Volatile.Read(ref _glyphs[code]); + if (glyph < 0) + { + glyph = Program is null ? 0 : Select(code); + Volatile.Write(ref _glyphs[code], glyph); + } + + return glyph; + } + + private static FontCharacterMap? Find(IReadOnlyList maps, int platform, int encoding) + { + foreach (FontCharacterMap map in maps) + { + if (map.PlatformId == platform && map.EncodingId == encoding) + { + return map; + } + } + + return null; + } + + private int Select(byte code) + { + if (_byName) + { + int glyph = ByName(code); + if (glyph == 0 && (glyph = ByCode(code)) != 0) + { + ReportFallback(code, "its glyph name selects no glyph, so the code itself is looked up in the (3, 0) or (1, 0) \"cmap\" subtable"); + } + + return glyph; + } + + int selected = ByCode(code); + if (selected != 0) + { + return selected; + } + + if (_encodingGiven && (selected = ByName(code)) != 0) + { + ReportFallback(code, "the code selects no glyph through the (3, 0) or (1, 0) \"cmap\" subtable, so its glyph name from the encoding is used"); + return selected; + } + + foreach (FontCharacterMap map in _unicode) + { + if ((selected = map.GetGlyphId(code)) != 0) + { + ReportFallback(code, string.Create(CultureInfo.InvariantCulture, $"the code selects no glyph through the (3, 0) or (1, 0) \"cmap\" subtable, so it is looked up as a Unicode value in the ({map.PlatformId}, {map.EncodingId}) subtable")); + return selected; + } + } + + if (_symbol is null && _macintosh is null && _unicode.Length == 0 && code < Program!.GlyphCount) + { + ReportFallback(code, "the font program has no usable \"cmap\" subtable, so the code is used as the glyph id"); + return code; + } + + return 0; + } + + /// The name route: encoding name, then (3, 1) by Unicode or (1, 0) by Mac OS Roman code, then "post". + private int ByName(byte code) + { + string name = Metrics.Names[code]; + if (name == GlyphNameTable.NotDef) + { + return 0; + } + + int glyph; + if (_unicode.Length > 0) + { + if (AdobeGlyphList.TryGetScalar(name, zapfDingbats: false, out int scalar)) + { + foreach (FontCharacterMap map in _unicode) + { + if ((glyph = map.GetGlyphId(scalar)) != 0) + { + return glyph; + } + } + } + } + else if (_macintosh is not null && MacOSRomanCode(name) is >= 0 and var macCode && (glyph = _macintosh.GetGlyphId(macCode)) != 0) + { + return glyph; + } + + return Program!.TryGetGlyphId(name, out glyph) ? glyph : 0; + } + + /// The code route: (3, 0) with each of the four high bytes, then (1, 0). + private int ByCode(byte code) + { + int glyph; + if (_symbol is not null) + { + foreach (int high in (ReadOnlySpan)[0x00, 0xF0, 0xF1, 0xF2]) + { + if ((glyph = _symbol.GetGlyphId((high << 8) | code)) != 0) + { + return glyph; + } + } + } + + if (_macintosh is null || (glyph = _macintosh.GetGlyphId(code)) == 0) + { + return 0; + } + + if (_symbol is not null) + { + ReportFallback(code, "the (3, 0) \"cmap\" subtable does not map the code, so the (1, 0) subtable is used"); + } + + return glyph; + } + + /// The Mac OS Roman code of a glyph name: MacRomanEncoding with the Table 113 additions (§9.6.5.4). + private static int MacOSRomanCode(string name) + { + int index = GlyphNameTable.IndexOf(name); + if (index < 0) + { + return -1; + } + + ReadOnlySpan table = GlyphNameTable.Table(BuiltInEncoding.MacOSRoman); + for (int code = 0; code < table.Length; code++) + { + if (table[code] == index) + { + return code; + } + } + + return -1; + } + + private void ReportFallback(byte code, string what) => _font.Report( + DiagnosticCodes.FontGlyphMappingFallback, + DiagnosticSeverity.Information, + string.Create(CultureInfo.InvariantCulture, $"Character code {code} of the TrueType font: {what} (ISO 32000-2 §9.6.5.4 lets a processor choose a mapping).")); +} diff --git a/src/Broadside/Parsing/DiagnosticCodes.Fonts.cs b/src/Broadside/Parsing/DiagnosticCodes.Fonts.cs index 18abb043..03f346f1 100644 --- a/src/Broadside/Parsing/DiagnosticCodes.Fonts.cs +++ b/src/Broadside/Parsing/DiagnosticCodes.Fonts.cs @@ -18,4 +18,16 @@ internal static partial class DiagnosticCodes public const string FontDifferencesInvalid = nameof(FontDifferencesInvalid); public const string FontBuiltInEncodingUnavailable = nameof(FontBuiltInEncodingUnavailable); public const string FontGlyphMissing = nameof(FontGlyphMissing); + + // Font programs and the font program parser extension point (§9.9; issue #50). + public const string FontProgramUnsupported = nameof(FontProgramUnsupported); + public const string FontProgramFormatMismatch = nameof(FontProgramFormatMismatch); + public const string FontProgramInvalid = nameof(FontProgramInvalid); + public const string FontProgramTruncated = nameof(FontProgramTruncated); + public const string FontTableInvalid = nameof(FontTableInvalid); + public const string FontGlyphInvalid = nameof(FontGlyphInvalid); + public const string FontCmapInvalid = nameof(FontCmapInvalid); + + // Character code to glyph id for TrueType fonts (§9.6.5.4; issue #50). + public const string FontGlyphMappingFallback = nameof(FontGlyphMappingFallback); } diff --git a/src/Broadside/PdfDocument.Fonts.cs b/src/Broadside/PdfDocument.Fonts.cs new file mode 100644 index 00000000..51ecf26c --- /dev/null +++ b/src/Broadside/PdfDocument.Fonts.cs @@ -0,0 +1,33 @@ +using Broadside.Fonts; +using Broadside.Objects; + +namespace Broadside; + +/// Font programs (issue #50): parsing embedded programs through the engine's font program parsers. +public sealed partial class PdfDocument +{ + /// Decodes a font file stream and hands it to the parser the engine picks (ISO 32000-2 §9.9, Tables 124 and 125). + private FontProgram? ParseFontProgram(CosStream stream, CosReference? reference, FontProgramSource source, bool isCidFont, string? faceName) + { + CosDictionary dictionary = stream.Dictionary; + var context = new FontProgramContext(_diagnostics, reference) + { + Source = source, + Subtype = Resolve(dictionary.TryGetValue(FontNames.Subtype, out CosObject? subtype) ? subtype : null) as CosName, + Length1 = ReadLength(dictionary, FontNames.Length1), + Length2 = ReadLength(dictionary, FontNames.Length2), + Length3 = ReadLength(dictionary, FontNames.Length3), + IsCidFont = isCidFont, + FaceName = faceName, + }; + + ReadOnlyMemory data = _streams.Decode(stream); + return _fontProgramParsers.Parse(data, context); + } + + private long? ReadLength(CosDictionary dictionary, CosName key) => + dictionary.TryGetValue(key, out CosObject? value) && Resolve(value) is CosInteger length ? length.Value : null; + + /// A font file stream at one version: a changed stream is parsed again. + private readonly record struct FontFileKey(CosStream Stream, int Version); +} diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index ebfe5f58..bbd9fd41 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -1,5 +1,6 @@ using System.Buffers; using System.Runtime.CompilerServices; +using Broadside.Caching; using Broadside.Diagnostics; using Broadside.Filters; using Broadside.Fonts; @@ -60,6 +61,8 @@ public sealed partial class PdfDocument : IDisposable private readonly ObjectLoader _loader; private readonly StreamDecoder _streams; private readonly ConditionalWeakTable _fonts = []; + private readonly FontProgramParserRegistry _fontProgramParsers; + private readonly OnceCache _fontPrograms = new(); private readonly ConditionalWeakTable _nameTrees = []; private readonly ConditionalWeakTable _numberTrees = []; private StructureContext? _structure; @@ -72,8 +75,10 @@ private PdfDocument( CosDictionary catalog, IReadOnlyList revisions, PdfLinearization? linearization, - PdfSecurity? security) + PdfSecurity? security, + FontProgramParserRegistry fontProgramParsers) { + _fontProgramParsers = fontProgramParsers; Security = security; _source = source; _diagnostics = diagnostics; @@ -686,6 +691,24 @@ public void DecodeStream(CosStream stream, IBufferWriter output) /// public void Dispose() => _source.Dispose(); + /// + /// Returns the parsed program of a font file stream, parsing it on first use with the engine's font program parsers (issue #50): + /// once per stream however many fonts and threads ask, again only after the stream changes. + /// + /// The font file stream. + /// The reference it was reached through, which its diagnostics carry. + /// The font descriptor entry it comes from. + /// Whether it belongs to a CIDFont. + /// The font asking, whose BaseFont picks the font of a font collection. + /// The program, or when no parser reads it. + /// ISO 32000-2 §9.9. + internal FontProgram? GetFontProgram(CosStream stream, CosReference? reference, FontProgramSource source, bool isCidFont, PdfFont font) => + _fontPrograms.GetOrCreate( + new FontFileKey(stream, stream.Version), + (Document: this, Reference: reference, Source: source, IsCidFont: isCidFont, Font: font), + static (key, state) => new Created(state.Document.ParseFontProgram(key.Stream, state.Reference, state.Source, state.IsCidFont, state.Font.FaceName)), + static (_, _) => null); + /// Gets the document's functions, compiled once each (issue #78): the seam colour spaces, graphics states and shadings use. internal FunctionCache Functions { get; } @@ -811,7 +834,7 @@ internal static PdfDocument Read(PdfSource source, EngineConfiguration configura } PdfLinearization? linearization = LinearizationReader.Read(source, loader, diagnostics); - var document = new PdfDocument(source, diagnostics, loader, streams, catalog, revisions, linearization, security); + var document = new PdfDocument(source, diagnostics, loader, streams, catalog, revisions, linearization, security, configuration.FontProgramParsers); // Table 15: ID is "required in PDF 2.0 or if an Encrypt entry is present" (the latter is the security handler's // EncryptionIdMissing). diff --git a/src/Broadside/PdfOptions.cs b/src/Broadside/PdfOptions.cs index 84fa3fef..4b8bcd7f 100644 --- a/src/Broadside/PdfOptions.cs +++ b/src/Broadside/PdfOptions.cs @@ -1,4 +1,5 @@ using Broadside.Filters; +using Broadside.Fonts; using Broadside.Objects; using Broadside.Security; using Microsoft.Extensions.Logging; @@ -23,6 +24,7 @@ public sealed class PdfOptions private readonly List _filters = []; private readonly List _securityHandlers = []; + private readonly List _fontProgramParsers = []; private long _maxDecodedStreamLength = DefaultMaxDecodedStreamLength; private long _streamBufferLimit = DefaultStreamBufferLimit; @@ -190,6 +192,25 @@ public PdfOptions WithPassword(string? password) return this; } + /// Gets the font program parsers registered with , in registration order. + /// ISO 32000-2 §9.9. Not public, so configuration binding never sees it; parsers are code. + internal IReadOnlyList FontProgramParsers => _fontProgramParsers; + + /// + /// Uses for embedded font programs, tried before the managed defaults and before parsers registered + /// earlier: the first parser whose accepts a program's bytes reads it, so a parser for a + /// format the defaults read replaces them, and a parser for a new format adds it. + /// + /// The parser. Shared by every document and thread of the engine: it must keep no state between calls. + /// These options. + /// ISO 32000-2 §9.9. The font program parser extension point (ADR 0001); the managed default reads TrueType programs. + public PdfOptions UseFontProgramParser(IFontProgramParser parser) + { + ArgumentNullException.ThrowIfNull(parser); + _fontProgramParsers.Add(parser); + return this; + } + /// Offers to every encrypted document opened without credentials of its own. /// The credentials, or for none. /// These options. diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index efdc0966..11d6c395 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -1,4 +1,12 @@ #nullable enable +abstract Broadside.Fonts.FontCharacterMap.EncodingId.get -> int +abstract Broadside.Fonts.FontCharacterMap.Format.get -> int +abstract Broadside.Fonts.FontCharacterMap.GetGlyphId(int code) -> int +abstract Broadside.Fonts.FontCharacterMap.PlatformId.get -> int +abstract Broadside.Fonts.FontProgram.FontMatrix.get -> Broadside.Graphics.Matrix +abstract Broadside.Fonts.FontProgram.Format.get -> Broadside.Fonts.FontProgramFormat +abstract Broadside.Fonts.FontProgram.GetOutline(int glyphId, Broadside.Fonts.GlyphOutline! outline) -> Broadside.Fonts.GlyphOutlineStatus +abstract Broadside.Fonts.FontProgram.GlyphCount.get -> int abstract Broadside.Objects.CosNumber.ToDouble() -> double Broadside.Content.ClipEvent Broadside.Content.ClipEvent.ClipEvent() -> void @@ -265,6 +273,78 @@ Broadside.Content.ShadingEvent.IsHidden.get -> bool Broadside.Content.ShadingEvent.ResourceName.get -> System.ReadOnlySpan Broadside.Content.ShadingEvent.Shading.get -> Broadside.Objects.CosObject? Broadside.Content.ShadingEvent.ShadingEvent() -> void +Broadside.Fonts.FontCharacterMap +Broadside.Fonts.FontCharacterMap.FontCharacterMap() -> void +Broadside.Fonts.FontProgram +Broadside.Fonts.FontProgram.FontProgram() -> void +Broadside.Fonts.FontProgramContext +Broadside.Fonts.FontProgramContext.Diagnostics.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Fonts.FontProgramContext.FaceIndex.get -> int +Broadside.Fonts.FontProgramContext.FaceIndex.init -> void +Broadside.Fonts.FontProgramContext.FaceName.get -> string? +Broadside.Fonts.FontProgramContext.FaceName.init -> void +Broadside.Fonts.FontProgramContext.FontProgramContext() -> void +Broadside.Fonts.FontProgramContext.IsCidFont.get -> bool +Broadside.Fonts.FontProgramContext.IsCidFont.init -> void +Broadside.Fonts.FontProgramContext.Length1.get -> long? +Broadside.Fonts.FontProgramContext.Length1.init -> void +Broadside.Fonts.FontProgramContext.Length2.get -> long? +Broadside.Fonts.FontProgramContext.Length2.init -> void +Broadside.Fonts.FontProgramContext.Length3.get -> long? +Broadside.Fonts.FontProgramContext.Length3.init -> void +Broadside.Fonts.FontProgramContext.MaxCompositeDepth.get -> int +Broadside.Fonts.FontProgramContext.MaxCompositeDepth.init -> void +Broadside.Fonts.FontProgramContext.MaxGlyphPoints.get -> int +Broadside.Fonts.FontProgramContext.MaxGlyphPoints.init -> void +Broadside.Fonts.FontProgramContext.ReadingMode.get -> Broadside.PdfReadingMode +Broadside.Fonts.FontProgramContext.ReadingMode.init -> void +Broadside.Fonts.FontProgramContext.Report(string! code, Broadside.Diagnostics.DiagnosticSeverity severity, string! message) -> void +Broadside.Fonts.FontProgramContext.Source.get -> Broadside.Fonts.FontProgramSource +Broadside.Fonts.FontProgramContext.Source.init -> void +Broadside.Fonts.FontProgramContext.Subtype.get -> Broadside.Objects.CosName? +Broadside.Fonts.FontProgramContext.Subtype.init -> void +Broadside.Fonts.FontProgramFormat +Broadside.Fonts.FontProgramFormat.Cff = 2 -> Broadside.Fonts.FontProgramFormat +Broadside.Fonts.FontProgramFormat.OpenType = 1 -> Broadside.Fonts.FontProgramFormat +Broadside.Fonts.FontProgramFormat.TrueType = 0 -> Broadside.Fonts.FontProgramFormat +Broadside.Fonts.FontProgramFormat.Type1 = 3 -> Broadside.Fonts.FontProgramFormat +Broadside.Fonts.FontProgramSource +Broadside.Fonts.FontProgramSource.FontFile = 1 -> Broadside.Fonts.FontProgramSource +Broadside.Fonts.FontProgramSource.FontFile2 = 2 -> Broadside.Fonts.FontProgramSource +Broadside.Fonts.FontProgramSource.FontFile3 = 3 -> Broadside.Fonts.FontProgramSource +Broadside.Fonts.FontProgramSource.Unspecified = 0 -> Broadside.Fonts.FontProgramSource +Broadside.Fonts.GlyphMetrics +Broadside.Fonts.GlyphMetrics.AdvanceWidth.get -> double +Broadside.Fonts.GlyphMetrics.AdvanceWidth.init -> void +Broadside.Fonts.GlyphMetrics.GlyphMetrics() -> void +Broadside.Fonts.GlyphMetrics.GlyphMetrics(double AdvanceWidth, double LeftSideBearing) -> void +Broadside.Fonts.GlyphMetrics.LeftSideBearing.get -> double +Broadside.Fonts.GlyphMetrics.LeftSideBearing.init -> void +Broadside.Fonts.GlyphOutline +Broadside.Fonts.GlyphOutline.Clear() -> void +Broadside.Fonts.GlyphOutline.Close() -> void +Broadside.Fonts.GlyphOutline.CubicTo(double control1X, double control1Y, double control2X, double control2Y, double x, double y) -> void +Broadside.Fonts.GlyphOutline.GlyphOutline() -> void +Broadside.Fonts.GlyphOutline.IsEmpty.get -> bool +Broadside.Fonts.GlyphOutline.LineTo(double x, double y) -> void +Broadside.Fonts.GlyphOutline.MoveTo(double x, double y) -> void +Broadside.Fonts.GlyphOutline.Path.get -> Broadside.Graphics.PathView +Broadside.Fonts.GlyphOutline.QuadTo(double controlX, double controlY, double x, double y) -> void +Broadside.Fonts.GlyphOutlineStatus +Broadside.Fonts.GlyphOutlineStatus.Complete = 0 -> Broadside.Fonts.GlyphOutlineStatus +Broadside.Fonts.GlyphOutlineStatus.Empty = 1 -> Broadside.Fonts.GlyphOutlineStatus +Broadside.Fonts.GlyphOutlineStatus.Invalid = 2 -> Broadside.Fonts.GlyphOutlineStatus +Broadside.Fonts.IFontProgramParser +Broadside.Fonts.IFontProgramParser.CanParse(System.ReadOnlySpan data) -> bool +Broadside.Fonts.IFontProgramParser.Formats.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Fonts.IFontProgramParser.Parse(System.ReadOnlyMemory data, Broadside.Fonts.FontProgramContext! context) -> Broadside.Fonts.FontProgram? +Broadside.Fonts.PdfFont.Program.get -> Broadside.Fonts.FontProgram? +Broadside.Fonts.PdfTrueTypeFont.GetGlyphId(byte code) -> int +Broadside.Fonts.TrueType.TrueTypeFontProgramParser +Broadside.Fonts.TrueType.TrueTypeFontProgramParser.CanParse(System.ReadOnlySpan data) -> bool +Broadside.Fonts.TrueType.TrueTypeFontProgramParser.Formats.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Fonts.TrueType.TrueTypeFontProgramParser.Parse(System.ReadOnlyMemory data, Broadside.Fonts.FontProgramContext! context) -> Broadside.Fonts.FontProgram? +Broadside.Fonts.TrueType.TrueTypeFontProgramParser.TrueTypeFontProgramParser() -> void Broadside.Graphics.BlendMode Broadside.Graphics.BlendMode.Color = 14 -> Broadside.Graphics.BlendMode Broadside.Graphics.BlendMode.ColorBurn = 7 -> Broadside.Graphics.BlendMode @@ -437,11 +517,14 @@ Broadside.Objects.CosString.CosString(System.ReadOnlySpan bytes, bool hexa Broadside.Objects.CosString.DecodeText() -> string! Broadside.Objects.CosString.Equals(Broadside.Objects.CosString? other) -> bool Broadside.Objects.CosString.IsHexadecimal.get -> bool +Broadside.PdfOptions.UseFontProgramParser(Broadside.Fonts.IFontProgramParser! parser) -> Broadside.PdfOptions! Broadside.PdfPage.ProcessContent(Broadside.Content.ContentProcessor! processor) -> void Broadside.PdfPage.ProcessContent(Broadside.Content.ContentProcessor! processor, Broadside.Content.ContentOptions! options) -> void const Broadside.Content.ContentOptions.DefaultMaxNestingDepth = 50 -> int const Broadside.Content.ContentOptions.DefaultMaxOperands = 65536 -> int const Broadside.Content.ContentOptions.DefaultMaxSaveDepth = 4096 -> int +const Broadside.Fonts.FontProgramContext.DefaultMaxCompositeDepth = 16 -> int +const Broadside.Fonts.FontProgramContext.DefaultMaxGlyphPoints = 65536 -> int const Broadside.Objects.CosReference.MaxGeneration = 65535 -> int override Broadside.Content.CompositeContentProcessor.BeginForm(in Broadside.Content.FormEvent form, Broadside.Content.ContentContext! context) -> Broadside.Content.ContentVisit override Broadside.Content.CompositeContentProcessor.BeginMarkedContent(in Broadside.Content.MarkedContentEvent mc, Broadside.Content.ContentContext! context) -> void @@ -518,6 +601,15 @@ virtual Broadside.Content.ContentProcessor.RestoreState(Broadside.Content.Conten virtual Broadside.Content.ContentProcessor.SaveState(Broadside.Content.ContentContext! context) -> void virtual Broadside.Content.ContentProcessor.ShowGlyph(in Broadside.Content.GlyphEvent glyph, Broadside.Content.ContentContext! context) -> void virtual Broadside.Content.ContentProcessor.VisitOperator(in Broadside.Content.ContentOperator op, Broadside.Content.ContentContext! context) -> void +virtual Broadside.Fonts.FontProgram.Ascender.get -> double +virtual Broadside.Fonts.FontProgram.CharacterMaps.get -> System.Collections.Generic.IReadOnlyList! +virtual Broadside.Fonts.FontProgram.Descender.get -> double +virtual Broadside.Fonts.FontProgram.FontBBox.get -> Broadside.PdfRectangle +virtual Broadside.Fonts.FontProgram.GetGlyphName(int glyphId) -> string? +virtual Broadside.Fonts.FontProgram.GetMetrics(int glyphId) -> Broadside.Fonts.GlyphMetrics +virtual Broadside.Fonts.FontProgram.LineGap.get -> double +virtual Broadside.Fonts.FontProgram.PostScriptName.get -> string? +virtual Broadside.Fonts.FontProgram.TryGetGlyphId(string! glyphName, out int glyphId) -> bool virtual Broadside.Objects.CosObject.IsDirty.get -> bool Broadside.Diagnostics.Diagnostic Broadside.Diagnostics.Diagnostic.Code.get -> string! diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 1e234565..0c937f7f 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -3,6 +3,7 @@ using Broadside.Diagnostics; using Broadside.Filters; using Broadside.Fonts; +using Broadside.Fonts.TrueType; using Broadside.Graphics; using Broadside.IO; using Broadside.Objects; @@ -47,6 +48,7 @@ internal static class FuzzTargets ["structure-tree"] = StructureTree.Target, ["function-type4"] = FunctionType4, ["function-sampled"] = FunctionSampled, + ["font-truetype"] = FontTrueType, }; private static readonly CosName ContentsKey = new("Contents"); @@ -201,6 +203,127 @@ private static void ReadFonts(PdfDocument document, PdfPage page) } } } + + if (font is PdfTrueTypeFont trueType && trueType.Program is { } program) + { + var outline = new GlyphOutline(); + for (int code = 0; code < 256; code++) + { + int glyph = trueType.GetGlyphId((byte)code); + if (glyph < 0 || (glyph > 0 && glyph >= program.GlyphCount)) + { + throw new InvalidOperationException($"Code {code} of font {entry.Key.Value} selects glyph {glyph} of {program.GlyphCount}."); + } + + CheckOutline(program.GetOutline(glyph, outline), outline); + } + } + } + } + + /// + /// Parses the input as a TrueType program (issue #50) and reads all of it: every glyph's outline (up to 4,096 glyphs) and metrics, + /// every "cmap" subtable for the codes 0 to 0x1FF and 0xF000 to 0xF0FF, every "post" name and its reverse lookup. An input that + /// starts with %PDF- is read from its first 00 01 00 00, so the TrueType corpus files seed the target with their + /// unfiltered programs. Every outline must be well formed (each contour a moveto ... close, as many points as its verbs take, + /// finite coordinates, empty exactly when not ) and every glyph id inside the program. + /// + /// ISO 32000-2 §9.9 and §9.6.5.4; OpenType "glyf", "loca", "cmap", "post", "hmtx" tables. + private static void FontTrueType(ReadOnlySpan data) + { + if (data.StartsWith("%PDF-"u8)) + { + int start = data.IndexOf((ReadOnlySpan)[0, 1, 0, 0]); + if (start < 0) + { + return; + } + + data = data[start..]; + } + + byte[] bytes = data.ToArray(); + var parser = new TrueTypeFontProgramParser(); + _ = parser.CanParse(bytes); + if (parser.Parse(bytes, new FontProgramContext()) is not { } program) + { + return; + } + + _ = (program.FontBBox, program.Ascender, program.Descender, program.LineGap, program.PostScriptName, program.FontMatrix); + var outline = new GlyphOutline(); + int glyphs = Math.Min(program.GlyphCount, 4096); + for (int glyph = -1; glyph <= glyphs; glyph++) + { + CheckOutline(program.GetOutline(glyph, outline), outline); + GlyphMetrics metrics = program.GetMetrics(glyph); + if (!double.IsFinite(metrics.AdvanceWidth) || !double.IsFinite(metrics.LeftSideBearing)) + { + throw new InvalidOperationException($"Glyph {glyph} has metrics that are not finite."); + } + + if (program.GetGlyphName(glyph) is { } name && (!program.TryGetGlyphId(name, out int named) || named > glyph)) + { + throw new InvalidOperationException($"Glyph {glyph} is named {name}, but the name finds glyph {named}."); + } + } + + foreach (FontCharacterMap map in program.CharacterMaps) + { + for (int code = 0; code < 0x200; code++) + { + CheckGlyphId(map, code, program.GlyphCount); + } + + for (int code = 0xF000; code < 0xF100; code++) + { + CheckGlyphId(map, code, program.GlyphCount); + } + } + } + + private static void CheckGlyphId(FontCharacterMap map, int code, int glyphCount) + { + int glyph = map.GetGlyphId(code); + if (glyph < 0 || (glyph > 0 && glyph >= glyphCount)) + { + throw new InvalidOperationException($"The ({map.PlatformId}, {map.EncodingId}) subtable maps code {code} to glyph {glyph} of {glyphCount}."); + } + } + + /// A glyph outline must be contours of moveto, segments and close, with the points its verbs take, all finite. + private static void CheckOutline(GlyphOutlineStatus status, GlyphOutline outline) + { + PathView path = outline.Path; + if ((status == GlyphOutlineStatus.Complete) == path.IsEmpty) + { + throw new InvalidOperationException($"Status {status} with {path.Verbs.Length} verbs."); + } + + int points = 0; + bool open = false; + foreach (PathVerb verb in path.Verbs) + { + if (open == (verb == PathVerb.MoveTo) || (!open && verb == PathVerb.Close)) + { + throw new InvalidOperationException($"A {verb} where a contour is {(open ? "open" : "not open")}."); + } + + open = verb != PathVerb.Close; + points += verb switch { PathVerb.MoveTo or PathVerb.LineTo => 1, PathVerb.QuadTo => 2, PathVerb.CubicTo => 3, _ => 0 }; + } + + if (open || points != path.Points.Length) + { + throw new InvalidOperationException($"The outline ends inside a contour or has {path.Points.Length} points for verbs taking {points}."); + } + + foreach (PathPoint point in path.Points) + { + if (!double.IsFinite(point.X) || !double.IsFinite(point.Y)) + { + throw new InvalidOperationException($"Point {point} is not finite."); + } } } diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index db4781d3..c24fce31 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters, and reads every font of each page's resources through the font model (each simple font's 256 glyph names and widths, which must be non-empty and finite, and its descriptor); a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. `xmp` reads the input as an XMP packet (ISO 16684-1) through the reader the document uses, and again from its first `> /RoleMap << /A /B /B /A >>` followed by `<< /S /A /P 4 0 R /Pg 3 0 R /K [0 5 0 R] /A [1 << /O /Layout >> 2] >>`. `content-lexer` reads the input as decoded content stream bytes with the content reader (ISO 32000-2 §7.8.2, #55): every operator must lie inside the input, after the previous one, with a keyword of at least one byte, and every operand, nested arrays and dictionaries included, must be readable; `content-interpreter` runs the input as a page's content through the interpreter with a processor that asks for every event and checks that path verbs and points agree, that clip handles chain back to the initial clip and that the state stack is balanced at the end; `document` now also interprets every page with that processor. Whole files are weak seeds for the two content targets; for libFuzzer and AFL seed them with decoded content streams (`qpdf --show-object=4 --filtered-stream-data tests/Corpus/filter-chain.pdf`) and with `ContentSamples.PathHeavy` output. `function-type4` compiles the input after its first byte as a Type 4 (PostScript calculator) program (byte 0 picks 1 to 4 inputs and 1 to 4 outputs) and `function-sampled` builds a Type 0 (sampled) function whose Size, BitsPerSample, Order and Encode come from bytes 0 to 4 and whose samples are the rest (ISO 32000-2 §7.10); both evaluate at fixed points inside and outside the domain, require every output inside the range, and require warm evaluations to allocate nothing. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters, and reads every font of each page's resources through the font model (each simple font's 256 glyph names and widths, which must be non-empty and finite, and its descriptor); a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. `xmp` reads the input as an XMP packet (ISO 16684-1) through the reader the document uses, and again from its first `> /RoleMap << /A /B /B /A >>` followed by `<< /S /A /P 4 0 R /Pg 3 0 R /K [0 5 0 R] /A [1 << /O /Layout >> 2] >>`. `content-lexer` reads the input as decoded content stream bytes with the content reader (ISO 32000-2 §7.8.2, #55): every operator must lie inside the input, after the previous one, with a keyword of at least one byte, and every operand, nested arrays and dictionaries included, must be readable; `content-interpreter` runs the input as a page's content through the interpreter with a processor that asks for every event and checks that path verbs and points agree, that clip handles chain back to the initial clip and that the state stack is balanced at the end; `document` now also interprets every page with that processor. Whole files are weak seeds for the two content targets; for libFuzzer and AFL seed them with decoded content streams (`qpdf --show-object=4 --filtered-stream-data tests/Corpus/filter-chain.pdf`) and with `ContentSamples.PathHeavy` output. `function-type4` compiles the input after its first byte as a Type 4 (PostScript calculator) program (byte 0 picks 1 to 4 inputs and 1 to 4 outputs) and `function-sampled` builds a Type 0 (sampled) function whose Size, BitsPerSample, Order and Encode come from bytes 0 to 4 and whose samples are the rest (ISO 32000-2 §7.10); both evaluate at fixed points inside and outside the domain, require every output inside the range, and require warm evaluations to allocate nothing. `font-truetype` parses the input as a TrueType program (ISO 32000-2 §9.9, #50) and reads all of it: every glyph's outline (up to 4,096) and metrics, every "cmap" subtable for codes 0 to 0x1FF and 0xF000 to 0xF0FF, every "post" name and its reverse lookup; outlines must be well-formed contours with finite points and every glyph id inside the program. An input starting with `%PDF-` is read from its first `00 01 00 00`, so the five TrueType corpus files (unfiltered programs) seed it in smoke mode; `document` also selects and outlines the glyph of every code of each page's TrueType fonts. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. @@ -44,6 +44,8 @@ mkdir -p artifacts/fuzz/seeds-xref-stream artifacts/fuzz/seeds-object-stream `function-type4` and `function-sampled` take control bytes and a raw program or sample table; for libFuzzer and AFL seed them from `functions.pdf`: `{ printf '\014'; qpdf --show-object=17 --filtered-stream-data tests/Corpus/functions.pdf; } > artifacts/fuzz/seeds-type4/logo-green.bin` (1 input, 4 outputs) and `{ printf '\014\003\002\000\000'; qpdf --show-object=11 --filtered-stream-data tests/Corpus/functions.pdf; } > artifacts/fuzz/seeds-sampled/sampled.bin` (1 input, 4 outputs, 8 bits, Size 3). +`font-truetype` takes a bare program: for libFuzzer and AFL seed it with the programs of the TrueType corpus files (`qpdf --show-object=7 --filtered-stream-data tests/Corpus/text-truetype-composite.pdf > artifacts/fuzz/seeds-truetype/composite.ttf`, likewise `text-truetype-embedded`, `-symbolic`, `-macroman`, `-loca-long`) and with real programs from the fetched corpora. + For the `filter-*` targets whole files are weak seeds too (a whole PDF as a stream body); for real fuzzing extract stream bodies, for example `qpdf --show-object=4 --raw-stream-data tests/Corpus/lzw-stream.pdf > artifacts/fuzz/seeds/lzw.bin`. Smoke mode is a regression net, not a fuzzer: it has no coverage feedback and finds only shallow bugs. Use a real fuzzer for anything that parses. diff --git a/tests/Broadside.TestSupport/Corpus.cs b/tests/Broadside.TestSupport/Corpus.cs index a4473ae7..30f936b0 100644 --- a/tests/Broadside.TestSupport/Corpus.cs +++ b/tests/Broadside.TestSupport/Corpus.cs @@ -21,6 +21,10 @@ public static class Corpus "text-standard14-widths.pdf", "text-standard14-alias.pdf", "text-type1-symbolic-noencoding.pdf", + "text-truetype-composite.pdf", + "text-truetype-symbolic.pdf", + "text-truetype-macroman.pdf", + "text-truetype-loca-long.pdf", "xref-stream.pdf", "object-stream.pdf", "incremental-update.pdf", diff --git a/tests/Broadside.TestSupport/TrueTypeBuilder.cs b/tests/Broadside.TestSupport/TrueTypeBuilder.cs new file mode 100644 index 00000000..32165aa0 --- /dev/null +++ b/tests/Broadside.TestSupport/TrueTypeBuilder.cs @@ -0,0 +1,530 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Broadside.TestSupport; + +/// +/// Builds TrueType programs in memory for tests of the font program contract: glyphs, metrics and tables are given explicitly so a +/// test can make any of them malformed. Coordinates are written as int16 deltas, flags one per point; nothing is optimized. +/// +/// OpenType specification: table directory, "head", "hhea", "hmtx", "maxp", "loca", "glyf", "cmap", "post". +public sealed class TrueTypeBuilder +{ + /// Gets the glyph descriptions, by glyph id (empty for a glyph without outline). + public List Glyphs { get; } = []; + + /// Gets or sets the advance and left side bearing per glyph; default 500 and the glyph's xMin. + public IReadOnlyList<(ushort Advance, short LeftSideBearing)>? Metrics { get; set; } + + /// Gets or sets hhea's numberOfHMetrics; default the glyph count. + public int? HorizontalMetricCount { get; set; } + + /// Gets or sets a value indicating whether "loca" uses 32-bit offsets. + public bool LongOffsets { get; set; } + + /// Gets or sets the "cmap" table; default one (3, 1) format 4 subtable mapping nothing. + public byte[]? Cmap { get; set; } + + /// Gets or sets the "post" table; default version 3.0. + public byte[]? Post { get; set; } + + /// Gets or sets the PostScript name in "name". + public string Name { get; set; } = "BroadsideTest"; + + /// Gets the tables to replace (a value) or leave out () after the others are built. + public Dictionary Overrides { get; } = []; + + /// Gets or sets the sfnt version. + public uint Version { get; set; } = 0x00010000; + + /// A simple glyph from contours of points (x, y, on-curve); int16 deltas, no instructions. + public static byte[] Simple(params (int X, int Y, bool On)[][] contours) + { + (int X, int Y, bool On)[] points = [.. contours.SelectMany(contour => contour)]; + var bytes = new List(); + Header(bytes, contours.Length, points.Select(p => (p.X, p.Y))); + int end = -1; + foreach ((int X, int Y, bool On)[] contour in contours) + { + end += contour.Length; + U16(bytes, end); + } + + U16(bytes, 0); + bytes.AddRange(points.Select(p => (byte)(p.On ? 1 : 0))); + int previous = 0; + foreach ((int x, _, _) in points) + { + I16(bytes, x - previous); + previous = x; + } + + previous = 0; + foreach ((_, int y, _) in points) + { + I16(bytes, y - previous); + previous = y; + } + + return [.. bytes]; + } + + /// A rectangle glyph, on-curve points clockwise from the bottom left. + public static byte[] Rectangle(int x0, int y0, int x1, int y1) => Simple([(x0, y0, true), (x0, y1, true), (x1, y1, true), (x1, y0, true)]); + + /// + /// A composite glyph from component records: flags (MORE_COMPONENTS is added), glyph, two arguments, and the transform bytes; the + /// arguments are words when flag 0x0001 is set. The header box is the given one. + /// + public static byte[] Composite((int XMin, int YMin, int XMax, int YMax) box, params (int Flags, int Glyph, int Argument1, int Argument2, byte[] Transform)[] components) + { + var bytes = new List(); + I16(bytes, -1); + I16(bytes, box.XMin); + I16(bytes, box.YMin); + I16(bytes, box.XMax); + I16(bytes, box.YMax); + for (int index = 0; index < components.Length; index++) + { + (int flags, int glyph, int argument1, int argument2, byte[] transform) = components[index]; + flags |= index < components.Length - 1 ? 0x0020 : 0; + U16(bytes, flags); + U16(bytes, glyph); + if ((flags & 0x0001) != 0) + { + I16(bytes, argument1); + I16(bytes, argument2); + } + else + { + bytes.Add(unchecked((byte)argument1)); + bytes.Add(unchecked((byte)argument2)); + } + + bytes.AddRange(transform); + } + + return [.. bytes]; + } + + /// F2Dot14 values, big-endian. + public static byte[] F2Dot14(params double[] values) + { + var bytes = new List(); + foreach (double value in values) + { + I16(bytes, (int)Math.Round(value * 16384)); + } + + return [.. bytes]; + } + + /// A "cmap" table from (platform, encoding, subtable) records. + public static byte[] CmapTable(params (int Platform, int Encoding, byte[] Subtable)[] subtables) + { + var bytes = new List(); + U16(bytes, 0); + U16(bytes, subtables.Length); + int offset = 4 + (8 * subtables.Length); + foreach ((int platform, int encoding, byte[] subtable) in subtables) + { + U16(bytes, platform); + U16(bytes, encoding); + U32(bytes, (uint)offset); + offset += subtable.Length; + } + + foreach ((_, _, byte[] subtable) in subtables) + { + bytes.AddRange(subtable); + } + + return [.. bytes]; + } + + /// A format 0 subtable. + public static byte[] Format0(IReadOnlyDictionary map) + { + var bytes = new List(); + U16(bytes, 0); + U16(bytes, 262); + U16(bytes, 0); + for (int code = 0; code < 256; code++) + { + bytes.Add((byte)map.GetValueOrDefault(code)); + } + + return [.. bytes]; + } + + /// A format 4 subtable from (start, end, idDelta) segments, written in the order given, with idRangeOffset 0; a final 0xFFFF segment is added. + public static byte[] Format4(params (int Start, int End, int Delta)[] segments) + { + (int Start, int End, int Delta)[] all = [.. segments, (0xFFFF, 0xFFFF, 1)]; + var bytes = new List(); + U16(bytes, 4); + U16(bytes, 16 + (8 * all.Length)); + U16(bytes, 0); + U16(bytes, 2 * all.Length); + U16(bytes, 0); + U16(bytes, 0); + U16(bytes, 0); + foreach ((_, int end, _) in all) + { + U16(bytes, end); + } + + U16(bytes, 0); + foreach ((int start, _, _) in all) + { + U16(bytes, start); + } + + foreach ((_, _, int delta) in all) + { + U16(bytes, delta & 0xFFFF); + } + + foreach (var unused in all) + { + U16(bytes, 0); + } + + return [.. bytes]; + } + + /// A format 12 (or 13) subtable from (start, end, glyph) groups. + public static byte[] Format12(int format, params (int Start, int End, int Glyph)[] groups) + { + var bytes = new List(); + U16(bytes, format); + U16(bytes, 0); + U32(bytes, (uint)(16 + (12 * groups.Length))); + U32(bytes, 0); + U32(bytes, (uint)groups.Length); + foreach ((int start, int end, int glyph) in groups) + { + U32(bytes, (uint)start); + U32(bytes, (uint)end); + U32(bytes, (uint)glyph); + } + + return [.. bytes]; + } + + /// + /// A format 2 subtable: single-byte codes map through subheader 0 (first code 0, all 256), and each high byte given maps its low + /// bytes from First through its own subheader to the given glyphs. + /// + public static byte[] Format2(int[] singleByteGlyphs, params (int High, int First, int[] Glyphs)[] twoByte) + { + var keys = new int[256]; + for (int index = 0; index < twoByte.Length; index++) + { + keys[twoByte[index].High] = (index + 1) * 8; + } + + int subHeaderCount = twoByte.Length + 1; + var arrays = new List { singleByteGlyphs }; + arrays.AddRange(twoByte.Select(entry => entry.Glyphs)); + var bytes = new List(); + U16(bytes, 2); + U16(bytes, 0); + U16(bytes, 0); + foreach (int key in keys) + { + U16(bytes, key); + } + + int subHeaderStart = bytes.Count; + int arrayStart = subHeaderStart + (8 * subHeaderCount); + int arrayOffset = arrayStart; + for (int index = 0; index < subHeaderCount; index++) + { + int first = index == 0 ? 0 : twoByte[index - 1].First; + int rangeOffsetPosition = subHeaderStart + (8 * index) + 6; + U16(bytes, first); + U16(bytes, arrays[index].Length); + U16(bytes, 0); + U16(bytes, arrayOffset - rangeOffsetPosition); + arrayOffset += 2 * arrays[index].Length; + } + + foreach (int[] array in arrays) + { + foreach (int glyph in array) + { + U16(bytes, glyph); + } + } + + byte[] result = [.. bytes]; + BinaryPrimitives.WriteUInt16BigEndian(result.AsSpan(2), (ushort)result.Length); + return result; + } + + /// A "post" table of version 2.0 (names are standard Macintosh names when they are one, else strings) or 2.5 (offsets). + public static byte[] Post2(int declaredCount, params string?[] names) + { + string[] standard = MacStandardNames; + var bytes = new List(); + U32(bytes, 0x00020000); + bytes.AddRange(new byte[28]); + U16(bytes, declaredCount); + var strings = new List(); + foreach (string? name in names) + { + int index = name is null ? 0 : Array.IndexOf(standard, name); + if (index < 0) + { + index = 258 + strings.Count; + strings.Add(name!); + } + + U16(bytes, index); + } + + foreach (string text in strings) + { + bytes.Add((byte)text.Length); + bytes.AddRange(Encoding.ASCII.GetBytes(text)); + } + + return [.. bytes]; + } + + /// A "post" table of version 2.5: one signed offset per glyph into the standard order. + public static byte[] Post25(params sbyte[] offsets) + { + var bytes = new List(); + U32(bytes, 0x00025000); + bytes.AddRange(new byte[28]); + U16(bytes, offsets.Length); + bytes.AddRange(offsets.Select(offset => unchecked((byte)offset))); + return [.. bytes]; + } + + /// A "post" table of version 1.0, 3.0 or another, header only. + public static byte[] PostHeader(uint version) + { + var bytes = new List(); + U32(bytes, version); + bytes.AddRange(new byte[28]); + return [.. bytes]; + } + + /// A TrueType collection of whole fonts: each font's table offsets are moved to where it lands. + public static byte[] Collection(params byte[][] fonts) + { + int header = 12 + (4 * fonts.Length); + var result = new List(); + U32(result, 0x74746366); + U16(result, 1); + U16(result, 0); + U32(result, (uint)fonts.Length); + int position = header; + foreach (byte[] font in fonts) + { + U32(result, (uint)position); + position += font.Length; + } + + position = header; + foreach (byte[] font in fonts) + { + byte[] moved = (byte[])font.Clone(); + int count = BinaryPrimitives.ReadUInt16BigEndian(moved.AsSpan(4)); + for (int index = 0; index < count; index++) + { + Span offset = moved.AsSpan(12 + (16 * index) + 8, 4); + BinaryPrimitives.WriteUInt32BigEndian(offset, BinaryPrimitives.ReadUInt32BigEndian(offset) + (uint)position); + } + + result.AddRange(moved); + position += font.Length; + } + + return [.. result]; + } + + /// Builds the program. + public byte[] Build() + { + int count = Glyphs.Count; + var glyf = new List(); + var offsets = new List(); + foreach (byte[] glyph in Glyphs) + { + offsets.Add(glyf.Count); + glyf.AddRange(glyph); + while (glyf.Count % 4 != 0) + { + glyf.Add(0); + } + } + + offsets.Add(glyf.Count); + var loca = new List(); + foreach (int offset in offsets) + { + if (LongOffsets) + { + U32(loca, (uint)offset); + } + else + { + U16(loca, offset / 2); + } + } + + IReadOnlyList<(ushort Advance, short LeftSideBearing)> metrics = Metrics + ?? [.. Glyphs.Select(glyph => ((ushort)500, glyph.Length >= 10 ? BinaryPrimitives.ReadInt16BigEndian(glyph.AsSpan(2)) : (short)0))]; + int horizontal = HorizontalMetricCount ?? count; + var hmtx = new List(); + for (int index = 0; index < metrics.Count; index++) + { + if (index < horizontal) + { + U16(hmtx, metrics[index].Advance); + } + + I16(hmtx, metrics[index].LeftSideBearing); + } + + var head = new List(); + U32(head, 0x00010000); + U32(head, 0x00010000); + U32(head, 0); + U32(head, 0x5F0F3CF5); + U16(head, 0x000B); + U16(head, 1000); + head.AddRange(new byte[16]); + I16(head, 0); + I16(head, 0); + I16(head, 1000); + I16(head, 1000); + U16(head, 0); + U16(head, 8); + I16(head, 2); + I16(head, LongOffsets ? 1 : 0); + I16(head, 0); + + var hhea = new List(); + U32(hhea, 0x00010000); + I16(hhea, 800); + I16(hhea, -200); + I16(hhea, 0); + U16(hhea, 1000); + hhea.AddRange(new byte[22]); + U16(hhea, horizontal); + + var maxp = new List(); + U32(maxp, 0x00005000); + U16(maxp, count); + + var name = new List(); + byte[] text = Encoding.BigEndianUnicode.GetBytes(Name); + U16(name, 0); + U16(name, 1); + U16(name, 18); + U16(name, 3); + U16(name, 1); + U16(name, 0x409); + U16(name, 6); + U16(name, text.Length); + U16(name, 0); + name.AddRange(text); + + var tables = new Dictionary + { + ["cmap"] = Cmap ?? CmapTable((3, 1, Format4())), + ["glyf"] = [.. glyf], + ["head"] = [.. head], + ["hhea"] = [.. hhea], + ["hmtx"] = [.. hmtx], + ["loca"] = [.. loca], + ["maxp"] = [.. maxp], + ["name"] = [.. name], + ["post"] = Post ?? PostHeader(0x00030000), + }; + foreach ((string tag, byte[]? table) in Overrides) + { + if (table is null) + { + tables.Remove(tag); + } + else + { + tables[tag] = table; + } + } + + return Sfnt(tables, Version); + } + + /// An sfnt file from tables, in tag order, each padded to four bytes; checksums are left 0. + public static byte[] Sfnt(IReadOnlyDictionary tables, uint version = 0x00010000) + { + string[] tags = [.. tables.Keys.Order(StringComparer.Ordinal)]; + var result = new List(); + U32(result, version); + U16(result, tags.Length); + U16(result, 0); + U16(result, 0); + U16(result, 0); + int offset = 12 + (16 * tags.Length); + foreach (string tag in tags) + { + result.AddRange(Encoding.ASCII.GetBytes(tag)); + U32(result, 0); + U32(result, (uint)offset); + U32(result, (uint)tables[tag].Length); + offset += (tables[tag].Length + 3) & ~3; + } + + foreach (string tag in tags) + { + result.AddRange(tables[tag]); + while (result.Count % 4 != 0) + { + result.Add(0); + } + } + + return [.. result]; + } + + private static readonly string[] MacStandardNames = + [ + ".notdef", ".null", "nonmarkingreturn", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", + "quotesingle", "parenleft", "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", "zero", "one", "two", + "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", "equal", "greater", "question", "at", + "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", + ]; + + private static void Header(List bytes, int contours, IEnumerable<(int X, int Y)> points) + { + (int X, int Y)[] all = [.. points]; + I16(bytes, contours); + I16(bytes, all.Length == 0 ? 0 : all.Min(p => p.X)); + I16(bytes, all.Length == 0 ? 0 : all.Min(p => p.Y)); + I16(bytes, all.Length == 0 ? 0 : all.Max(p => p.X)); + I16(bytes, all.Length == 0 ? 0 : all.Max(p => p.Y)); + } + + private static void U16(List bytes, int value) + { + bytes.Add((byte)(value >> 8)); + bytes.Add((byte)value); + } + + private static void I16(List bytes, int value) => U16(bytes, value & 0xFFFF); + + private static void U32(List bytes, uint value) + { + bytes.Add((byte)(value >> 24)); + bytes.Add((byte)(value >> 16)); + bytes.Add((byte)(value >> 8)); + bytes.Add((byte)value); + } +} diff --git a/tests/Broadside.Tests/Fonts/FontProgramParserRegistrationTests.cs b/tests/Broadside.Tests/Fonts/FontProgramParserRegistrationTests.cs new file mode 100644 index 00000000..6ce81de7 --- /dev/null +++ b/tests/Broadside.Tests/Fonts/FontProgramParserRegistrationTests.cs @@ -0,0 +1,152 @@ +using Broadside.Diagnostics; +using Broadside.Fonts; +using Broadside.Fonts.TrueType; +using Broadside.Graphics; +using Broadside.TestSupport; + +namespace Broadside.Tests.Fonts; + +/// +/// The font program parser extension point: parsers registered through come before +/// the managed TrueType default, per engine, with no static state. ISO 32000-2 §9.9; ADR 0001. +/// +public class FontProgramParserRegistrationTests +{ + private const string Expected = "M 100,0 L 100,700 L 300,700 L 300,0 Z"; + + [Fact] + public void A_decorated_default_parser_parses_the_program_once_and_gives_the_same_outlines() + { + var counting = new CountingParser(new TrueTypeFontProgramParser()); + using PdfDocument document = TrueTypeCorpusTests.Open("text-truetype-embedded.pdf", new PdfOptions().UseFontProgramParser(counting)); + PdfTrueTypeFont font = TrueTypeCorpusTests.Font(document, "F1"); + + Assert.Equal(Expected, OutlineText.Of(font.Program!, font.GetGlyphId(0x49))); + Assert.Equal(2, font.GetGlyphId(0x49)); + Assert.Equal(1, font.GetGlyphId(0x48)); + Assert.Same(font.Program, document.GetFont(font.Reference)!.Program); + Parallel.For(0, 64, _ => Assert.Equal(Expected, OutlineText.Of(font.Program!, 2))); + Assert.Equal(1, counting.Count); + } + + [Fact] + public void A_registered_parser_replaces_the_default_for_the_programs_it_accepts() + { + using PdfDocument document = TrueTypeCorpusTests.Open("text-truetype-embedded.pdf", new PdfOptions().UseFontProgramParser(new SquareParser())); + PdfTrueTypeFont font = TrueTypeCorpusTests.Font(document, "F1"); + + Assert.IsType(font.Program); + Assert.Equal("M 0,0 L 1,0 L 1,1 L 0,1 Z", OutlineText.Of(font.Program!, font.GetGlyphId(0x48))); + Assert.Equal("M 0,0 L 1,0 L 1,1 L 0,1 Z", OutlineText.Of(font.Program!, font.GetGlyphId(0x49))); + } + + [Fact] + public void Another_engine_without_the_registration_still_uses_the_default() + { + using PdfDocument replaced = new PdfEngine(new PdfOptions().UseFontProgramParser(new SquareParser())).Open(Corpus.Bytes("text-truetype-embedded.pdf")); + using PdfDocument standard = new PdfEngine().Open(Corpus.Bytes("text-truetype-embedded.pdf")); + + Assert.IsType(TrueTypeCorpusTests.Font(replaced, "F1").Program); + PdfTrueTypeFont font = TrueTypeCorpusTests.Font(standard, "F1"); + Assert.Equal(Expected, OutlineText.Of(font.Program!, font.GetGlyphId(0x49))); + } + + [Fact] + public void A_parser_that_throws_leaves_the_font_without_a_program_and_a_diagnostic() + { + using PdfDocument document = TrueTypeCorpusTests.Open("text-truetype-embedded.pdf", new PdfOptions().UseFontProgramParser(new ThrowingParser())); + PdfTrueTypeFont font = TrueTypeCorpusTests.Font(document, "F1"); + + Assert.Null(font.Program); + Assert.Equal(0, font.GetGlyphId(0x48)); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal("FontProgramInvalid", diagnostic.Code); + Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity); + } + + [Fact] + public void A_program_no_parser_reads_is_reported_as_unsupported_information() + { + using PdfDocument document = FontPdf.Open( + "<< /Type /Font /Subtype /Type1 /BaseFont /Embedded /FirstChar 65 /LastChar 65 /Widths [500] /FontDescriptor 5 0 R >>", + "<< /Type /FontDescriptor /FontName /Embedded /Flags 32 /FontBBox [0 0 1 1] /ItalicAngle 0 /Ascent 1 /Descent 0 /StemV 1 /FontFile 6 0 R >>", + "<< /Length 12 /Length1 12 >>\nstream\n%!PS-AdobeFo\nendstream"); + + Assert.Null(FontPdf.Font(document).Program); + Assert.Contains(document.Diagnostics, d => d.Code == "FontProgramUnsupported" && d.Severity == DiagnosticSeverity.Information); + } + + [Fact] + public void Registering_a_null_parser_throws() + { + Assert.Throws(() => new PdfOptions().UseFontProgramParser(null!)); + } + + private sealed class CountingParser(IFontProgramParser inner) : IFontProgramParser + { + private int _count; + + public int Count => _count; + + public IReadOnlyList Formats => inner.Formats; + + public bool CanParse(ReadOnlySpan data) => inner.CanParse(data); + + public FontProgram? Parse(ReadOnlyMemory data, FontProgramContext context) + { + Interlocked.Increment(ref _count); + return inner.Parse(data, context); + } + } + + private sealed class SquareParser : IFontProgramParser + { + public IReadOnlyList Formats { get; } = [FontProgramFormat.TrueType]; + + public bool CanParse(ReadOnlySpan data) => true; + + public FontProgram? Parse(ReadOnlyMemory data, FontProgramContext context) => new SquareProgram(); + } + + private sealed class SquareProgram : FontProgram + { + public override FontProgramFormat Format => FontProgramFormat.TrueType; + + public override int GlyphCount => 3; + + public override Matrix FontMatrix => Matrix.Identity; + + public override IReadOnlyList CharacterMaps { get; } = [new IdentityMap()]; + + public override GlyphOutlineStatus GetOutline(int glyphId, GlyphOutline outline) + { + outline.Clear(); + outline.MoveTo(0, 0); + outline.LineTo(1, 0); + outline.LineTo(1, 1); + outline.LineTo(0, 1); + outline.Close(); + return GlyphOutlineStatus.Complete; + } + } + + private sealed class IdentityMap : FontCharacterMap + { + public override int PlatformId => 3; + + public override int EncodingId => 1; + + public override int Format => 4; + + public override int GetGlyphId(int code) => code is 'H' or 'I' ? code - 'G' : 0; + } + + private sealed class ThrowingParser : IFontProgramParser + { + public IReadOnlyList Formats { get; } = [FontProgramFormat.TrueType]; + + public bool CanParse(ReadOnlySpan data) => true; + + public FontProgram? Parse(ReadOnlyMemory data, FontProgramContext context) => throw new InvalidOperationException("broken parser"); + } +} diff --git a/tests/Broadside.Tests/Fonts/OutlineText.cs b/tests/Broadside.Tests/Fonts/OutlineText.cs new file mode 100644 index 00000000..98cb4152 --- /dev/null +++ b/tests/Broadside.Tests/Fonts/OutlineText.cs @@ -0,0 +1,44 @@ +using System.Globalization; +using System.Text; +using Broadside.Fonts; +using Broadside.Graphics; + +namespace Broadside.Tests.Fonts; + +/// Writes a glyph outline as compact path text (M x,y L x,y Q cx,cy x,y C … Z) so tests compare whole outlines. +internal static class OutlineText +{ + /// The outline of one glyph of a program, as text; the status first when it is not . + public static string Of(FontProgram program, int glyphId) + { + var outline = new GlyphOutline(); + GlyphOutlineStatus status = program.GetOutline(glyphId, outline); + return status == GlyphOutlineStatus.Complete ? Of(outline.Path) : status.ToString(); + } + + /// A path as text. + public static string Of(PathView path) + { + var text = new StringBuilder(); + int point = 0; + foreach (PathVerb verb in path.Verbs) + { + if (text.Length > 0) + { + text.Append(' '); + } + + int count = verb switch { PathVerb.MoveTo or PathVerb.LineTo => 1, PathVerb.QuadTo => 2, PathVerb.CubicTo => 3, _ => 0 }; + text.Append(verb switch { PathVerb.MoveTo => 'M', PathVerb.LineTo => 'L', PathVerb.QuadTo => 'Q', PathVerb.CubicTo => 'C', _ => 'Z' }); + for (int index = 0; index < count; index++) + { + PathPoint p = path.Points[point++]; + text.Append(' ').Append(Number(p.X)).Append(',').Append(Number(p.Y)); + } + } + + return text.ToString(); + } + + private static string Number(double value) => Math.Round(value, 4).ToString(CultureInfo.InvariantCulture); +} diff --git a/tests/Broadside.Tests/Fonts/RealWorldTrueTypeTests.cs b/tests/Broadside.Tests/Fonts/RealWorldTrueTypeTests.cs new file mode 100644 index 00000000..bc6d7dbc --- /dev/null +++ b/tests/Broadside.Tests/Fonts/RealWorldTrueTypeTests.cs @@ -0,0 +1,113 @@ +using Broadside.Fonts; +using Broadside.Objects; +using Broadside.Security; +using Broadside.Tests.Document; +using Broadside.TestSupport; + +namespace Broadside.Tests.Fonts; + +/// +/// Every embedded TrueType program of a simple font in the fetched real-world corpora parses leniently, every code selects a glyph +/// id inside the program, and every glyph's outline is extracted without an exception. Skips when the corpora are not fetched. +/// ISO 32000-2 §9.6.3, §9.6.5.4, §9.9. +/// +[Trait("Category", "Corpus")] +public class RealWorldTrueTypeTests(ITestOutputHelper output) +{ + private const int MaxGlyphsPerProgram = 4096; + + public static TheoryData CorpusIds => new(RealWorldCorpusTests.CorpusIds); + + [Theory] + [MemberData(nameof(CorpusIds))] + public void Every_embedded_TrueType_program_of_a_real_world_corpus_outlines_every_glyph(string corpusId) + { + IReadOnlyList files = RealWorldCorpus.Files(corpusId); + if (files.Count == 0) + { + Assert.Skip($"Corpus '{corpusId}' not fetched; run tools/CorpusFetcher (or set {RealWorldCorpus.EnvironmentVariable})."); + } + + int programs = 0; + int unusable = 0; + int glyphs = 0; + int invalid = 0; + var outline = new GlyphOutline(); + foreach (string file in files) + { + if (RealWorldCorpusTests.Unreadable.ContainsKey(file)) + { + continue; + } + + using PdfDocument? document = OpenOrNull(file); + if (document is null) + { + continue; + } + + var seen = new HashSet(ReferenceEqualityComparer.Instance); + foreach (PdfPage page in document.Pages) + { + if (page.Resources is not { } resources + || !resources.TryGetValue(new CosName("Font"), out CosObject? value) + || document.Resolve(value) is not CosDictionary fontResources) + { + continue; + } + + foreach (KeyValuePair entry in fontResources) + { + if (document.GetFont(entry.Value) is not PdfTrueTypeFont font || !seen.Add(font.Dictionary) || font.Descriptor?.FontFile2 is null) + { + continue; + } + + if (font.Program is not { } program) + { + unusable++; + continue; + } + + programs++; + for (int code = 0; code < 256; code++) + { + int glyph = font.GetGlyphId((byte)code); + Assert.InRange(glyph, 0, Math.Max(0, program.GlyphCount - 1)); + } + + for (int glyph = 0; glyph < Math.Min(program.GlyphCount, MaxGlyphsPerProgram); glyph++) + { + glyphs++; + if (program.GetOutline(glyph, outline) == GlyphOutlineStatus.Invalid) + { + invalid++; + } + + foreach (Broadside.Graphics.PathPoint point in outline.Path.Points) + { + Assert.True(double.IsFinite(point.X) && double.IsFinite(point.Y), file); + } + + _ = program.GetMetrics(glyph); + _ = program.GetGlyphName(glyph); + } + } + } + } + + output.WriteLine($"{corpusId}: {programs} TrueType programs, {unusable} unusable, {glyphs} glyphs outlined, {invalid} damaged."); + } + + private static PdfDocument? OpenOrNull(string file) + { + try + { + return PdfDocument.Open(File.ReadAllBytes(RealWorldCorpus.PathOf(file))); + } + catch (Exception exception) when (exception is PdfPasswordException or PdfCertificateException or NotSupportedException) + { + return null; + } + } +} diff --git a/tests/Broadside.Tests/Fonts/TrueTypeCorpusTests.cs b/tests/Broadside.Tests/Fonts/TrueTypeCorpusTests.cs new file mode 100644 index 00000000..eb04cf6a --- /dev/null +++ b/tests/Broadside.Tests/Fonts/TrueTypeCorpusTests.cs @@ -0,0 +1,191 @@ +using Broadside.Diagnostics; +using Broadside.Fonts; +using Broadside.TestSupport; + +namespace Broadside.Tests.Fonts; + +/// +/// Glyph outlines and glyph selection of the embedded TrueType corpus files, through the public document API. Expected values +/// are the coordinates and tables tests/Corpus/generate.py writes. ISO 32000-2 §9.6.3, §9.6.5.4, §9.9. +/// +public class TrueTypeCorpusTests +{ + [Fact] + public void Every_code_of_the_embedded_TrueType_page_has_its_quadratic_outline() + { + using PdfDocument document = Open("text-truetype-embedded.pdf"); + PdfTrueTypeFont font = Font(document, "F1"); + FontProgram program = Assert.IsAssignableFrom(font.Program); + + Assert.Equal(FontProgramFormat.TrueType, program.Format); + Assert.Equal(3, program.GlyphCount); + Assert.Equal(1.0 / 1000, program.FontMatrix.A); + Assert.Equal(1, font.GetGlyphId(0x48)); + Assert.Equal(2, font.GetGlyphId(0x49)); + Assert.Equal( + "M 100,0 L 100,700 L 300,700 L 300,400 L 500,400 L 500,700 L 700,700 L 700,0 L 500,0 L 500,300 L 300,300 L 300,0 Z", + OutlineText.Of(program, font.GetGlyphId(0x48))); + Assert.Equal("M 100,0 L 100,700 L 300,700 L 300,0 Z", OutlineText.Of(program, font.GetGlyphId(0x49))); + Assert.Equal("Empty", OutlineText.Of(program, 0)); + Assert.Equal(new GlyphMetrics(800, 100), program.GetMetrics(1)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Simple_glyphs_start_contours_on_curve_and_imply_midpoints_between_off_curve_points() + { + using PdfDocument document = Open("text-truetype-composite.pdf"); + PdfTrueTypeFont font = Font(document, "F1"); + FontProgram program = font.Program!; + + Assert.Equal([1, 2, 3], Glyphs(font, "Ioc")); + Assert.Equal("M 100,0 L 100,700 L 300,700 L 300,0 Z", OutlineText.Of(program, 1)); + Assert.Equal("M 125,125 Q 250,0 375,125 Q 500,250 375,375 Q 250,500 125,375 Q 0,250 125,125 Z", OutlineText.Of(program, 2)); + Assert.Equal("M 0,200 Q 0,0 200,0 L 200,200 Z", OutlineText.Of(program, 3)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Composite_glyphs_apply_offsets_transforms_point_matching_and_nesting() + { + using PdfDocument document = Open("text-truetype-composite.pdf"); + PdfTrueTypeFont font = Font(document, "F1"); + FontProgram program = font.Program!; + + Assert.Equal([4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], Glyphs(font, "0123456789:")); + string[] expected = + [ + "M 500,300 L 500,1000 L 700,1000 L 700,300 Z", // word offset (400, 300) + "M 110,20 L 110,720 L 310,720 L 310,20 Z", // byte offset (10, 20) + "M 100,20 L 100,370 L 200,370 L 200,20 Z", // scale 0.5, SCALED_COMPONENT_OFFSET: offset (50, 20) + "M 150,40 L 150,390 L 250,390 L 250,40 Z", // scale 0.5, UNSCALED_COMPONENT_OFFSET: offset (100, 40) + "M 150,40 L 150,390 L 250,390 L 250,40 Z", // neither flag: unscaled, as on Apple and Microsoft platforms + "M 300,0 L 300,700 L 100,700 L 100,0 Z", // x scale -1, offset (400, 0) + "M 700,100 L 0,100 L 0,300 L 700,300 Z", // 2x2 (0 1 -1 0): x' = -y, y' = x, offset (700, 0) + "M 100,0 L 100,700 L 300,700 L 300,0 Z M 300,700 L 300,1400 L 500,1400 L 500,700 Z", // point 0 onto point 2 + "M 110,120 L 110,820 L 310,820 L 310,120 Z", // glyph 5 moved by (0, 100) + "M 50,200 Q 50,0 250,0 L 250,200 Z", // glyph 3 moved by (50, 0) + "M 125,125 Q 250,0 375,125 Q 500,250 375,375 Q 250,500 125,375 Q 0,250 125,125 Z", // with instructions + ]; + Assert.Equal(expected, Enumerable.Range(4, 11).Select(glyph => OutlineText.Of(program, glyph)).ToArray()); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Advances_past_the_last_hmtx_advance_repeat_it_and_USE_MY_METRICS_takes_the_component_metrics() + { + using PdfDocument document = Open("text-truetype-composite.pdf"); + FontProgram program = Font(document, "F1").Program!; + + Assert.Equal(new GlyphMetrics(600, 100), program.GetMetrics(11)); + Assert.Equal(new GlyphMetrics(600, 110), program.GetMetrics(12)); + Assert.Equal(new GlyphMetrics(300, 0), program.GetMetrics(13)); + Assert.Equal(new GlyphMetrics(600, 150), program.GetMetrics(15)); + Assert.Equal(new GlyphMetrics(0, 0), program.GetMetrics(16)); + } + + [Fact] + public void An_outline_is_placed_at_its_left_side_bearing() + { + using PdfDocument document = Open("text-truetype-composite.pdf"); + PdfTrueTypeFont font = Font(document, "F1"); + + Assert.Equal(15, font.GetGlyphId((byte)'<')); + Assert.Equal("M 150,0 L 150,700 L 350,700 L 350,0 Z", OutlineText.Of(font.Program!, 15)); + } + + [Fact] + public void A_format_4_glyph_id_array_entry_of_0_stays_the_missing_glyph() + { + using PdfDocument document = Open("text-truetype-composite.pdf"); + PdfTrueTypeFont font = Font(document, "F1"); + FontCharacterMap map = Assert.Single(font.Program!.CharacterMaps); + + Assert.Equal((3, 1, 4), (map.PlatformId, map.EncodingId, map.Format)); + Assert.Equal(0, map.GetGlyphId(';')); + Assert.Equal(0, font.GetGlyphId((byte)';')); + Assert.Equal(1, map.GetGlyphId('I')); + Assert.Equal(0, map.GetGlyphId('J')); + Assert.Equal(0, map.GetGlyphId(0x10000)); + } + + [Fact] + public void A_symbolic_font_selects_glyphs_by_code_through_3_0_with_the_F0_high_byte_before_1_0() + { + using PdfDocument document = Open("text-truetype-symbolic.pdf"); + PdfTrueTypeFont font = Font(document, "F1"); + + Assert.Equal([1, 2, 3, 2], Glyphs(font, "ABCD")); + Assert.Equal(0, font.GetGlyphId((byte)'E')); + Assert.All(document.Diagnostics, diagnostic => Assert.Equal(DiagnosticSeverity.Information, diagnostic.Severity)); + Assert.Equal(["FontBuiltInEncodingUnavailable", "FontGlyphMappingFallback"], document.Diagnostics.Select(diagnostic => diagnostic.Code).Order().ToArray()); + } + + [Fact] + public void A_nonsymbolic_font_with_only_a_1_0_cmap_maps_names_through_Mac_OS_Roman_and_then_post() + { + using PdfDocument document = Open("text-truetype-macroman.pdf"); + PdfTrueTypeFont font = Font(document, "F1"); + FontProgram program = font.Program!; + + Assert.Equal(["Euro", "eacute", "brds.alt"], [font.GetGlyphName(0x80), font.GetGlyphName(0xE9), font.GetGlyphName(0x81)]); + Assert.Equal([1, 2, 3], [font.GetGlyphId(0x80), font.GetGlyphId(0xE9), font.GetGlyphId(0x81)]); + Assert.Equal(6, Assert.Single(program.CharacterMaps).Format); + Assert.Equal([".notdef", "Euro", "eacute", "brds.alt"], [.. Enumerable.Range(0, 4).Select(program.GetGlyphName)]); + Assert.True(program.TryGetGlyphId("brds.alt", out int glyph)); + Assert.Equal(3, glyph); + Assert.False(program.TryGetGlyphId("Aring", out _)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Long_loca_offsets_and_a_3_10_format_12_cmap_select_the_glyphs() + { + using PdfDocument document = Open("text-truetype-loca-long.pdf"); + PdfTrueTypeFont font = Font(document, "F1"); + FontProgram program = font.Program!; + FontCharacterMap map = Assert.Single(program.CharacterMaps); + + Assert.Equal((3, 10, 12), (map.PlatformId, map.EncodingId, map.Format)); + Assert.Equal(2, map.GetGlyphId(0x1F600)); + Assert.Equal([1, 2], Glyphs(font, "HI")); + Assert.Equal( + "M 100,0 L 100,700 L 300,700 L 300,400 L 500,400 L 500,700 L 700,700 L 700,0 L 500,0 L 500,300 L 300,300 L 300,0 Z", + OutlineText.Of(program, 1)); + Assert.Equal("M 100,0 L 100,700 L 300,700 L 300,0 Z", OutlineText.Of(program, 2)); + Assert.Equal(".null", program.GetGlyphName(1)); + Assert.Equal("BroadsideLongLoca", program.PostScriptName); + Assert.Empty(document.Diagnostics); + } + + [Theory] + [InlineData("text-truetype-embedded.pdf")] + [InlineData("text-truetype-composite.pdf")] + [InlineData("text-truetype-macroman.pdf")] + [InlineData("text-truetype-loca-long.pdf")] + public void Strict_mode_reads_every_glyph_of_the_well_formed_TrueType_files(string name) + { + using PdfDocument document = Open(name, new PdfOptions().UseStrict()); + PdfTrueTypeFont font = Font(document, "F1"); + var outline = new GlyphOutline(); + for (int code = 0; code < 256; code++) + { + _ = font.GetGlyphId((byte)code); + } + + for (int glyph = 0; glyph < font.Program!.GlyphCount; glyph++) + { + Assert.NotEqual(GlyphOutlineStatus.Invalid, font.Program.GetOutline(glyph, outline)); + } + + Assert.DoesNotContain(document.Diagnostics, diagnostic => diagnostic.Severity > DiagnosticSeverity.Information); + } + + internal static PdfDocument Open(string name, PdfOptions? options = null) => + PdfDocument.Open(Path.Combine(Corpus.Directory, name), options ?? new PdfOptions()); + + internal static PdfTrueTypeFont Font(PdfDocument document, string resource) => + Assert.IsType(Assert.Single(document.Pages).GetFont(resource)); + + private static int[] Glyphs(PdfTrueTypeFont font, string codes) => [.. codes.Select(code => font.GetGlyphId((byte)code))]; +} diff --git a/tests/Broadside.Tests/Fonts/TrueTypeGlyphSelectionTests.cs b/tests/Broadside.Tests/Fonts/TrueTypeGlyphSelectionTests.cs new file mode 100644 index 00000000..84d2596b --- /dev/null +++ b/tests/Broadside.Tests/Fonts/TrueTypeGlyphSelectionTests.cs @@ -0,0 +1,173 @@ +using System.Text; +using Broadside.Diagnostics; +using Broadside.Fonts; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Fonts; + +/// +/// Character code to glyph id for simple TrueType fonts (ISO 32000-2 §9.6.5.4) in the cases the corpus files do not cover, and the +/// font program as a document-level object: parsed from the font file stream, diagnostics on that stream, reparsed after a change. +/// +public class TrueTypeGlyphSelectionTests +{ + private static readonly byte[] None = []; + + [Fact] + public void A_symbolic_font_whose_program_has_no_cmap_uses_the_code_as_the_glyph_id() + { + var builder = new TrueTypeBuilder { Glyphs = { None, Rectangle(1), Rectangle(2), Rectangle(3) } }; + builder.Overrides["cmap"] = null; + using PdfDocument document = Open(builder.Build(), flags: 4, encoding: null); + PdfTrueTypeFont font = Assert.IsType(FontPdf.Font(document)); + + Assert.Equal([1, 2, 3, 0], [font.GetGlyphId(1), font.GetGlyphId(2), font.GetGlyphId(3), font.GetGlyphId(4)]); + Assert.Equal( + [("FontBuiltInEncodingUnavailable", new CosReference(4, 0)), ("FontGlyphMappingFallback", new CosReference(4, 0)), ("FontTableInvalid", new CosReference(6, 0))], + document.Diagnostics.Select(d => (d.Code, d.ObjectReference)).Order()); + } + + [Fact] + public void A_symbolic_font_with_WinAnsiEncoding_and_only_a_unicode_cmap_falls_back_to_glyph_names() + { + var builder = new TrueTypeBuilder + { + Glyphs = { None, Rectangle(1), Rectangle(2) }, + Cmap = TrueTypeBuilder.CmapTable((3, 1, TrueTypeBuilder.Format4((0x41, 0x41, 2 - 0x41), (0x20AC, 0x20AC, 1 - 0x20AC)))), + }; + using PdfDocument document = Open(builder.Build(), flags: 4, encoding: "/WinAnsiEncoding"); + PdfTrueTypeFont font = Assert.IsType(FontPdf.Font(document)); + + Assert.Equal([1, 2], [font.GetGlyphId(0x80), font.GetGlyphId(0x41)]); + Assert.All(document.Diagnostics, d => Assert.Equal(DiagnosticSeverity.Information, d.Severity)); + } + + [Fact] + public void Both_flags_with_a_Differences_array_select_by_name_as_for_a_nonsymbolic_font() + { + var builder = new TrueTypeBuilder + { + Glyphs = { None, Rectangle(1), Rectangle(2) }, + Cmap = TrueTypeBuilder.CmapTable((3, 0, TrueTypeBuilder.Format4((0xF041, 0xF041, 1 - 0xF041))), (3, 1, TrueTypeBuilder.Format4((0x42, 0x42, 2 - 0x42)))), + }; + using PdfDocument document = Open(builder.Build(), flags: 4 | 32, encoding: "<< /Differences [65 /B] >>"); + PdfTrueTypeFont font = Assert.IsType(FontPdf.Font(document)); + + Assert.Equal(2, font.GetGlyphId(0x41)); + Assert.Contains(document.Diagnostics, d => d.Code == "FontGlyphMappingFallback"); + } + + [Fact] + public void A_nonsymbolic_font_without_an_encoding_reads_names_from_StandardEncoding() + { + var builder = new TrueTypeBuilder + { + Glyphs = { None, Rectangle(1) }, + Cmap = TrueTypeBuilder.CmapTable((3, 1, TrueTypeBuilder.Format4((0x2019, 0x2019, 1 - 0x2019)))), + }; + using PdfDocument document = Open(builder.Build(), flags: 32, encoding: null); + PdfTrueTypeFont font = Assert.IsType(FontPdf.Font(document)); + + // StandardEncoding 0x27 is quoteright (U+2019); WinAnsiEncoding would give quotesingle. + Assert.Equal(1, font.GetGlyphId(0x27)); + } + + [Fact] + public void A_font_without_a_program_selects_no_glyph() + { + using PdfDocument document = FontPdf.Open("<< /Type /Font /Subtype /TrueType /BaseFont /Arial >>"); + PdfTrueTypeFont font = Assert.IsType(FontPdf.Font(document)); + + Assert.Null(font.Program); + Assert.Equal(0, font.GetGlyphId(0x41)); + } + + [Fact] + public void Diagnostics_of_the_program_are_recorded_against_the_font_file_stream() + { + byte[] program = new TrueTypeBuilder { Glyphs = { None, Rectangle(1) } }.Build(); + using PdfDocument document = Open(program, flags: 32, encoding: "/WinAnsiEncoding", length1: program.Length + 10); + FontProgram parsed = FontPdf.Font(document).Program!; + + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal(("FontProgramTruncated", new CosReference(6, 0)), (diagnostic.Code, diagnostic.ObjectReference)); + Assert.Equal(2, parsed.GlyphCount); + } + + [Fact] + public void Strict_mode_throws_from_the_call_that_meets_a_damaged_glyph() + { + byte[] program = new TrueTypeBuilder { Glyphs = { None, TrueTypeBuilder.Rectangle(0, 0, 10, 10)[..^3] } }.Build(); + using PdfDocument document = Open(program, flags: 32, encoding: "/WinAnsiEncoding", options: new PdfOptions().UseStrict()); + FontProgram parsed = FontPdf.Font(document).Program!; + + Assert.Equal("FontGlyphInvalid", Assert.Throws(() => parsed.GetOutline(1, new GlyphOutline())).Diagnostic.Code); + } + + [Fact] + public void A_CFF_OpenType_program_is_unsupported_until_a_parser_reads_it() + { + byte[] program = TrueTypeBuilder.Sfnt(new Dictionary { ["CFF "] = [1, 0, 4, 1] }, 0x4F54544F); + using PdfDocument document = Open(program, flags: 32, encoding: "/WinAnsiEncoding", key: "FontFile3", subtype: "/OpenType"); + + Assert.Null(FontPdf.Font(document).Program); + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal(("FontProgramUnsupported", DiagnosticSeverity.Information), (diagnostic.Code, diagnostic.Severity)); + } + + [Fact] + public void A_TrueType_program_in_a_FontFile3_OpenType_stream_is_read() + { + byte[] program = new TrueTypeBuilder { Glyphs = { None, Rectangle(1) }, Version = 0x4F54544F }.Build(); + using PdfDocument document = Open(program, flags: 32, encoding: "/WinAnsiEncoding", key: "FontFile3", subtype: "/OpenType"); + + Assert.Equal(FontProgramFormat.OpenType, FontPdf.Font(document).Program!.Format); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Data_of_another_format_than_declared_is_read_by_its_parser_with_a_diagnostic() + { + byte[] program = new TrueTypeBuilder { Glyphs = { None, Rectangle(1) } }.Build(); + using PdfDocument document = Open(program, flags: 32, encoding: "/WinAnsiEncoding", key: "FontFile3", subtype: "/Type1C"); + + Assert.NotNull(FontPdf.Font(document).Program); + Assert.Equal("FontProgramFormatMismatch", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_changed_font_file_stream_is_parsed_again() + { + byte[] first = new TrueTypeBuilder { Glyphs = { None, Rectangle(1) } }.Build(); + byte[] second = new TrueTypeBuilder { Glyphs = { None, Rectangle(1), Rectangle(2) } }.Build(); + using PdfDocument document = Open(first, flags: 32, encoding: "/WinAnsiEncoding"); + PdfFont font = FontPdf.Font(document); + FontProgram before = font.Program!; + + font.Descriptor!.FontFile2!.EncodedData = second; + + Assert.Equal(2, before.GlyphCount); + Assert.Equal(3, font.Program!.GlyphCount); + } + + private static byte[] Rectangle(int size) => TrueTypeBuilder.Rectangle(0, 0, 100 * size, 100); + + private static PdfDocument Open( + byte[] program, + int flags, + string? encoding, + long? length1 = null, + string key = "FontFile2", + string? subtype = null, + PdfOptions? options = null) + { + string encodingEntry = encoding is null ? string.Empty : $" /Encoding {encoding}"; + string subtypeEntry = subtype is null ? string.Empty : $" /Subtype {subtype}"; + return FontPdf.Open( + $"<< /Type /Font /Subtype /TrueType /BaseFont /Test /FirstChar 0 /LastChar 0 /Widths [500]{encodingEntry} /FontDescriptor 5 0 R >>", + options ?? new PdfOptions(), + $"<< /Type /FontDescriptor /FontName /Test /Flags {flags} /FontBBox [0 0 1000 1000] /ItalicAngle 0 /Ascent 800 /Descent -200 /StemV 80 /{key} 6 0 R >>", + $"<< /Length {program.Length} /Length1 {length1 ?? program.Length}{subtypeEntry} >>\nstream\n{Encoding.Latin1.GetString(program)}\nendstream"); + } +} diff --git a/tests/Broadside.Tests/Fonts/TrueTypeProgramTests.cs b/tests/Broadside.Tests/Fonts/TrueTypeProgramTests.cs new file mode 100644 index 00000000..9232aac5 --- /dev/null +++ b/tests/Broadside.Tests/Fonts/TrueTypeProgramTests.cs @@ -0,0 +1,399 @@ +using Broadside.Diagnostics; +using Broadside.Fonts; +using Broadside.Fonts.TrueType; +using Broadside.TestSupport; + +namespace Broadside.Tests.Fonts; + +/// +/// The TrueType parser through the font program contract: bytes in, glyph outlines, metrics and lookups out, with programs built +/// in memory so each table can be made malformed. Vectors follow the OpenType "glyf", "cmap" and "post" table specifications and +/// fontTools' composite tests (offset, SCALED/UNSCALED offsets, point matching with a rotation). ISO 32000-2 §9.9. +/// +public class TrueTypeProgramTests +{ + private static readonly byte[] None = []; + private static readonly byte[] Square = TrueTypeBuilder.Rectangle(0, 0, 100, 100); + + [Theory] + [InlineData(0x1000, "M 10,20 L 10,70 L 60,70 L 60,20 Z")] + [InlineData(0x0800, "M 5,10 L 5,60 L 55,60 L 55,10 Z")] + [InlineData(0x0000, "M 10,20 L 10,70 L 60,70 L 60,20 Z")] + public void A_scaled_component_offset_is_scaled_only_with_SCALED_COMPONENT_OFFSET(int offsetFlag, string expected) + { + FontProgram program = Parse(new TrueTypeBuilder + { + Glyphs = { None, Square, TrueTypeBuilder.Composite((0, 0, 60, 70), (0x0002 | 0x0008 | offsetFlag, 1, 10, 20, TrueTypeBuilder.F2Dot14(0.5))) }, + Metrics = [(500, 0), (500, 0), (500, 0)], + }); + + Assert.Equal(expected, OutlineText.Of(program, 2)); + } + + [Fact] + public void Point_matching_moves_a_rotated_component_onto_a_point_of_the_glyph_so_far() + { + // Component 2 is the square rotated by 45 degrees (cos = sin = 11585/16384) with its point 0 matched onto point 2. + FontProgram program = Parse(new TrueTypeBuilder + { + Glyphs = + { + None, + Square, + TrueTypeBuilder.Composite( + (0, 0, 171, 242), + (0x0002, 1, 0, 0, []), + (0x0080, 1, 2, 0, TrueTypeBuilder.F2Dot14(Math.Sqrt(0.5), Math.Sqrt(0.5), -Math.Sqrt(0.5), Math.Sqrt(0.5)))), + }, + Metrics = [(500, 0), (500, 0), (500, 0)], + }); + + Assert.Equal( + "M 0,0 L 0,100 L 100,100 L 100,0 Z M 100,100 L 29.2908,170.7092 L 100,241.4185 L 170.7092,170.7092 Z", + OutlineText.Of(program, 2)); + } + + [Fact] + public void A_composite_that_contains_itself_skips_the_component_with_a_diagnostic() + { + var context = new FontProgramContext(); + FontProgram program = Parse( + new TrueTypeBuilder + { + Glyphs = + { + None, + Square, + TrueTypeBuilder.Composite((0, 0, 100, 100), (0x0002, 1, 0, 0, []), (0x0002, 3, 0, 0, [])), + TrueTypeBuilder.Composite((0, 0, 100, 100), (0x0002, 2, 0, 0, [])), + }, + Metrics = [(500, 0), (500, 0), (500, 0), (500, 0)], + }, + context); + + Assert.Equal("M 0,0 L 0,100 L 100,100 L 100,0 Z", OutlineText.Of(program, 2)); + Assert.Equal("M 0,0 L 0,100 L 100,100 L 100,0 Z", OutlineText.Of(program, 3)); + Assert.Equal("FontGlyphInvalid", Assert.Single(context.Diagnostics).Code); + } + + [Fact] + public void Components_nested_deeper_than_the_limit_are_skipped() + { + var context = new FontProgramContext { MaxCompositeDepth = 2 }; + FontProgram program = Parse( + new TrueTypeBuilder + { + Glyphs = + { + None, + Square, + TrueTypeBuilder.Composite((0, 0, 100, 100), (0x0002, 1, 0, 0, [])), + TrueTypeBuilder.Composite((0, 0, 100, 100), (0x0002, 2, 0, 0, [])), + TrueTypeBuilder.Composite((0, 0, 100, 100), (0x0002, 3, 0, 0, [])), + }, + Metrics = [(500, 0), (500, 0), (500, 0), (500, 0), (500, 0)], + }, + context); + + Assert.Equal("M 0,0 L 0,100 L 100,100 L 100,0 Z", OutlineText.Of(program, 3)); + Assert.Empty(context.Diagnostics); + Assert.Equal("Empty", OutlineText.Of(program, 4)); + Assert.Equal("FontGlyphInvalid", Assert.Single(context.Diagnostics).Code); + } + + [Fact] + public void A_glyph_with_more_points_than_the_limit_is_dropped() + { + var context = new FontProgramContext { MaxGlyphPoints = 6 }; + FontProgram program = Parse( + new TrueTypeBuilder + { + Glyphs = { None, Square, TrueTypeBuilder.Composite((0, 0, 100, 100), (0x0002, 1, 0, 0, []), (0x0002, 1, 0, 0, [])) }, + }, + context); + + Assert.Equal("M 0,0 L 0,100 L 100,100 L 100,0 Z", OutlineText.Of(program, 1)); + Assert.Equal("M 0,0 L 0,100 L 100,100 L 100,0 Z", OutlineText.Of(program, 2)); + Assert.Equal("FontGlyphInvalid", Assert.Single(context.Diagnostics).Code); + } + + [Fact] + public void Decreasing_contour_end_points_drop_the_glyph() + { + byte[] glyph = TrueTypeBuilder.Simple([(0, 0, true), (0, 10, true)], [(5, 5, true), (5, 6, true)]); + glyph[10] = 0; + glyph[11] = 3; + var context = new FontProgramContext(); + FontProgram program = Parse(new TrueTypeBuilder { Glyphs = { None, glyph } }, context); + + Assert.Equal("Invalid", OutlineText.Of(program, 1)); + Assert.Equal("FontGlyphInvalid", Assert.Single(context.Diagnostics).Code); + } + + [Fact] + public void A_glyph_whose_coordinates_are_cut_short_is_dropped_and_the_others_still_draw() + { + byte[] glyph = Square[..^3]; + var context = new FontProgramContext(); + FontProgram program = Parse(new TrueTypeBuilder { Glyphs = { None, glyph, Square } }, context); + + Assert.Equal("Invalid", OutlineText.Of(program, 1)); + Assert.Equal("M 0,0 L 0,100 L 100,100 L 100,0 Z", OutlineText.Of(program, 2)); + Assert.Equal("FontGlyphInvalid", Assert.Single(context.Diagnostics).Code); + } + + [Fact] + public void A_flag_repeated_past_the_last_point_is_cut_short() + { + // Two on-curve points with x and y as positive bytes: one flag 0x37 repeated 5 times instead of 1. + byte[] glyph = [0, 1, 0, 0, 0, 0, 0, 10, 0, 10, 0, 1, 0, 0, 0x3F, 5, 0, 10, 10, 0]; + var context = new FontProgramContext(); + FontProgram program = Parse(new TrueTypeBuilder { Glyphs = { None, glyph } }, context); + + Assert.Equal("M 0,10 L 10,10 Z", OutlineText.Of(program, 1)); + Assert.Equal("FontGlyphInvalid", Assert.Single(context.Diagnostics).Code); + } + + [Fact] + public void Short_coordinates_take_their_sign_from_the_same_flag_and_same_without_short_repeats() + { + // Flags: point 0 x short positive (0x12), y short negative (0x04); point 1 x same (0x10), y int16; all on-curve. + byte[] glyph = [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0x17, 0x11, 50, 20, 0x01, 0x2C]; + FontProgram program = Parse(new TrueTypeBuilder { Glyphs = { None, glyph }, Metrics = [(500, 0), (500, 0)] }); + + Assert.Equal("M 50,-20 L 50,280 Z", OutlineText.Of(program, 1)); + } + + [Fact] + public void Bad_loca_offsets_are_bounded_by_the_glyph_table() + { + byte[] font = new TrueTypeBuilder { Glyphs = { None, Square, Square }, LongOffsets = true }.Build(); + int loca = TableOffset(font, "loca"); + WriteUInt32(font, loca + 4, 0x7FFF0000); + WriteUInt32(font, loca + 8, 0); + var context = new FontProgramContext(); + FontProgram program = Parse(font, context); + + Assert.Equal("Invalid", OutlineText.Of(program, 1)); + Assert.Equal("FontGlyphInvalid", Assert.Single(context.Diagnostics).Code); + Assert.Equal(GlyphOutlineStatus.Invalid, program.GetOutline(99, new GlyphOutline())); + Assert.Equal(GlyphOutlineStatus.Invalid, program.GetOutline(-1, new GlyphOutline())); + } + + [Fact] + public void Missing_head_hhea_and_maxp_are_replaced_by_defaults_with_diagnostics() + { + var builder = new TrueTypeBuilder { Glyphs = { None, Square } }; + builder.Overrides["head"] = null; + builder.Overrides["hhea"] = null; + builder.Overrides["maxp"] = null; + var context = new FontProgramContext(); + FontProgram program = Parse(builder, context); + + Assert.Equal(2, program.GlyphCount); + Assert.Equal(1.0 / 1000, program.FontMatrix.A); + Assert.Equal(default, program.GetMetrics(1)); + Assert.Equal("M 0,0 L 0,100 L 100,100 L 100,0 Z", OutlineText.Of(program, 1)); + Assert.Equal(["FontTableInvalid"], context.Diagnostics.Select(diagnostic => diagnostic.Code).Distinct()); + } + + [Fact] + public void A_program_without_glyf_is_not_usable() + { + var builder = new TrueTypeBuilder { Glyphs = { None, Square } }; + builder.Overrides["glyf"] = null; + var context = new FontProgramContext(); + + Assert.Null(new TrueTypeFontProgramParser().Parse(builder.Build(), context)); + Diagnostic diagnostic = Assert.Single(context.Diagnostics); + Assert.Equal(("FontProgramInvalid", DiagnosticSeverity.Error), (diagnostic.Code, diagnostic.Severity)); + } + + [Fact] + public void A_Length1_longer_than_the_data_is_reported_and_the_program_read() + { + byte[] font = new TrueTypeBuilder { Glyphs = { None, Square } }.Build(); + var context = new FontProgramContext { Length1 = font.Length + 100 }; + FontProgram program = Parse(font, context); + + Assert.Equal("M 0,0 L 0,100 L 100,100 L 100,0 Z", OutlineText.Of(program, 1)); + Assert.Equal("FontProgramTruncated", Assert.Single(context.Diagnostics).Code); + } + + [Fact] + public void Strict_mode_throws_for_a_damaged_glyph_when_its_outline_is_asked_for() + { + FontProgram program = Parse(new TrueTypeBuilder { Glyphs = { None, Square[..^3] } }, new FontProgramContext { ReadingMode = PdfReadingMode.Strict }); + + DiagnosticException exception = Assert.Throws(() => program.GetOutline(1, new GlyphOutline())); + Assert.Equal("FontGlyphInvalid", exception.Diagnostic.Code); + } + + [Fact] + public void Signatures_select_the_parser() + { + var parser = new TrueTypeFontProgramParser(); + byte[] font = new TrueTypeBuilder { Glyphs = { None, Square } }.Build(); + byte[] openTypeWithGlyf = new TrueTypeBuilder { Glyphs = { None, Square }, Version = 0x4F54544F }.Build(); + byte[] openTypeCff = TrueTypeBuilder.Sfnt(new Dictionary { ["CFF "] = [1, 0, 4, 1], ["head"] = new byte[54] }, 0x4F54544F); + + Assert.True(parser.CanParse(font)); + Assert.True(parser.CanParse(TrueTypeBuilder.Collection(font))); + Assert.True(parser.CanParse(openTypeWithGlyf)); + Assert.False(parser.CanParse(openTypeCff)); + Assert.False(parser.CanParse("%!PS-AdobeFont-1.0"u8)); + Assert.False(parser.CanParse([0, 1, 0])); + Assert.Equal(FontProgramFormat.OpenType, Parse(openTypeWithGlyf).Format); + } + + [Fact] + public void A_collection_font_is_chosen_by_PostScript_name_then_by_index() + { + byte[] first = new TrueTypeBuilder { Glyphs = { None, Square }, Name = "First" }.Build(); + byte[] second = new TrueTypeBuilder { Glyphs = { None, Square, Square }, Name = "Second" }.Build(); + byte[] collection = TrueTypeBuilder.Collection(first, second); + + Assert.Equal(("Second", 3), Describe(Parse(collection, new FontProgramContext { FaceName = "Second" }))); + Assert.Equal(("Second", 3), Describe(Parse(collection, new FontProgramContext { FaceIndex = 1 }))); + Assert.Equal(("First", 2), Describe(Parse(collection, new FontProgramContext { FaceName = "Other" }))); + var context = new FontProgramContext { FaceIndex = 5 }; + Assert.Equal(("First", 2), Describe(Parse(collection, context))); + Assert.Equal("FontTableInvalid", Assert.Single(context.Diagnostics).Code); + Assert.Equal("M 0,0 L 0,100 L 100,100 L 100,0 Z", OutlineText.Of(Parse(collection, new FontProgramContext { FaceIndex = 1 }), 2)); + + static (string?, int) Describe(FontProgram program) => (program.PostScriptName, program.GlyphCount); + } + + [Fact] + public void Cmap_formats_0_2_4_6_12_and_13_map_codes_to_glyphs() + { + byte[] cmap = TrueTypeBuilder.CmapTable( + (1, 0, TrueTypeBuilder.Format0(new Dictionary { [0x41] = 2 })), + (3, 1, TrueTypeBuilder.Format4((0x20, 0x22, 1 - 0x20))), + (3, 3, TrueTypeBuilder.Format2([0, 1, 2], (0x81, 0x40, [3, 0, 1]))), + (3, 10, TrueTypeBuilder.Format12(12, (0x10000, 0x10002, 1))), + (0, 6, TrueTypeBuilder.Format12(13, (0x4E00, 0x4EFF, 3)))); + FontProgram program = Parse(new TrueTypeBuilder { Glyphs = { None, Square, Square, Square }, Cmap = cmap }); + IReadOnlyList maps = program.CharacterMaps; + + Assert.Equal([(1, 0, 0), (3, 1, 4), (3, 3, 2), (3, 10, 12), (0, 6, 13)], maps.Select(map => (map.PlatformId, map.EncodingId, map.Format))); + Assert.Equal([2, 0, 0], [maps[0].GetGlyphId(0x41), maps[0].GetGlyphId(0x42), maps[0].GetGlyphId(0x141)]); + Assert.Equal([1, 3, 0], [maps[1].GetGlyphId(0x20), maps[1].GetGlyphId(0x22), maps[1].GetGlyphId(0x23)]); + Assert.Equal([1, 2, 3, 0, 1, 0, 0], [maps[2].GetGlyphId(1), maps[2].GetGlyphId(2), maps[2].GetGlyphId(0x8140), maps[2].GetGlyphId(0x8141), maps[2].GetGlyphId(0x8142), maps[2].GetGlyphId(0x8143), maps[2].GetGlyphId(0x81)]); + Assert.Equal([1, 3, 0], [maps[3].GetGlyphId(0x10000), maps[3].GetGlyphId(0x10002), maps[3].GetGlyphId(0x10003)]); + Assert.Equal([3, 3, 0], [maps[4].GetGlyphId(0x4E00), maps[4].GetGlyphId(0x4E80), maps[4].GetGlyphId(0x4F00)]); + } + + [Fact] + public void Format_4_segments_out_of_order_are_searched_in_order_and_glyphs_past_the_program_read_as_0() + { + byte[] cmap = TrueTypeBuilder.CmapTable((3, 1, TrueTypeBuilder.Format4((0x60, 0x61, 1 - 0x60), (0x41, 0x42, 50 - 0x41)))); + var context = new FontProgramContext(); + FontProgram program = Parse(new TrueTypeBuilder { Glyphs = { None, Square, Square }, Cmap = cmap }, context); + FontCharacterMap map = Assert.Single(program.CharacterMaps); + + Assert.Equal([1, 2, 0], [map.GetGlyphId(0x60), map.GetGlyphId(0x61), map.GetGlyphId(0x41)]); + Assert.Equal(["FontCmapInvalid"], context.Diagnostics.Select(diagnostic => diagnostic.Code)); + } + + [Fact] + public void Unknown_and_unsupported_cmap_formats_are_left_out_with_a_diagnostic() + { + byte[] format8 = [0, 8, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0]; + byte[] format14 = [0, 14, 0, 0, 0, 10, 0, 0, 0, 0]; + byte[] cmap = TrueTypeBuilder.CmapTable((3, 1, format8), (0, 5, format14), (3, 0, [0, 99, 0, 6, 0, 0])); + var context = new FontProgramContext(); + FontProgram program = Parse(new TrueTypeBuilder { Glyphs = { None, Square }, Cmap = cmap }, context); + + Assert.Empty(program.CharacterMaps); + Assert.Equal(["FontCmapInvalid"], context.Diagnostics.Select(diagnostic => diagnostic.Code)); + } + + [Fact] + public void Post_names_come_from_versions_1_2_and_2_5_and_the_first_glyph_of_a_name_wins() + { + FontProgram version2 = Parse(new TrueTypeBuilder { Glyphs = { None, Square, Square, Square }, Post = TrueTypeBuilder.Post2(4, ".notdef", "A", "custom", "A") }); + FontProgram version25 = Parse(new TrueTypeBuilder { Glyphs = { None, Square, Square }, Post = TrueTypeBuilder.Post25(0, 35, 35) }); + FontProgram version1 = Parse(new TrueTypeBuilder { Glyphs = { None, Square, Square }, Post = TrueTypeBuilder.PostHeader(0x00010000) }); + + Assert.Equal([".notdef", "A", "custom", "A"], Enumerable.Range(0, 4).Select(version2.GetGlyphName)); + Assert.True(version2.TryGetGlyphId("A", out int glyph)); + Assert.Equal(1, glyph); + Assert.Equal([".notdef", "A", "B"], Enumerable.Range(0, 3).Select(version25.GetGlyphName)); + Assert.Equal([".notdef", ".null", "nonmarkingreturn"], Enumerable.Range(0, 3).Select(version1.GetGlyphName)); + Assert.Null(version1.GetGlyphName(3)); + } + + [Fact] + public void A_post_table_naming_more_glyphs_than_the_program_has_is_cut_to_the_program() + { + var context = new FontProgramContext(); + FontProgram program = Parse(new TrueTypeBuilder { Glyphs = { None, Square }, Post = TrueTypeBuilder.Post2(3, ".notdef", "A", "B") }, context); + + Assert.Equal([".notdef", "A", null], Enumerable.Range(0, 3).Select(program.GetGlyphName)); + Assert.Equal("FontTableInvalid", Assert.Single(context.Diagnostics).Code); + } + + [Fact] + public void Extracting_outlines_allocates_nothing_once_warm() + { + byte[] composite = TrueTypeBuilder.Composite((0, 0, 200, 200), (0x0002 | 0x0008, 1, 10, 20, TrueTypeBuilder.F2Dot14(0.5)), (0x0002, 2, 0, 0, [])); + byte[] curve = TrueTypeBuilder.Simple([(0, 0, false), (100, 0, true), (100, 100, false), (0, 100, false)]); + FontProgram program = Parse(new TrueTypeBuilder { Glyphs = { None, Square, curve, composite } }); + var outline = new GlyphOutline(); + for (int warm = 0; warm < 50; warm++) + { + Outline(program, outline); + } + + long before = GC.GetAllocatedBytesForCurrentThread(); + int segments = Outline(program, outline); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.True(segments > 1_000); + Assert.Equal(0, allocated); + + static int Outline(FontProgram program, GlyphOutline outline) + { + int segments = 0; + for (int pass = 0; pass < 100; pass++) + { + for (int glyph = 0; glyph < program.GlyphCount; glyph++) + { + program.GetOutline(glyph, outline); + segments += outline.Path.Verbs.Length; + } + } + + return segments; + } + } + + private static FontProgram Parse(TrueTypeBuilder builder, FontProgramContext? context = null) => Parse(builder.Build(), context); + + private static FontProgram Parse(byte[] font, FontProgramContext? context = null) => + Assert.IsAssignableFrom(new TrueTypeFontProgramParser().Parse(font, context ?? new FontProgramContext())); + + private static int TableOffset(byte[] font, string tag) + { + int count = (font[4] << 8) | font[5]; + for (int index = 0; index < count; index++) + { + int record = 12 + (16 * index); + if (System.Text.Encoding.ASCII.GetString(font, record, 4) == tag) + { + return (font[record + 8] << 24) | (font[record + 9] << 16) | (font[record + 10] << 8) | font[record + 11]; + } + } + + throw new InvalidOperationException(tag); + } + + private static void WriteUInt32(byte[] bytes, int offset, uint value) + { + bytes[offset] = (byte)(value >> 24); + bytes[offset + 1] = (byte)(value >> 16); + bytes[offset + 2] = (byte)(value >> 8); + bytes[offset + 3] = (byte)value; + } +} diff --git a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt index 5c8d21a5..c6acd0ae 100644 --- a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt +++ b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt @@ -58,7 +58,11 @@ text-standard14-winansi-quirks.pdf, text-standard14-zapfdingbats.pdf, text-standard14.pdf, + text-truetype-composite.pdf, text-truetype-embedded.pdf, + text-truetype-loca-long.pdf, + text-truetype-macroman.pdf, + text-truetype-symbolic.pdf, text-type1-symbolic-noencoding.pdf, viewer-preferences.pdf, wrong-stream-length.pdf, diff --git a/tests/Corpus/README.md b/tests/Corpus/README.md index b6daf94e..9082d909 100644 --- a/tests/Corpus/README.md +++ b/tests/Corpus/README.md @@ -45,6 +45,10 @@ Verification was run with qpdf 12.4.2 (`qpdf --check`), poppler (`pdfinfo`, `pdf | `text-standard14-widths.pdf` | Non-embedded Courier with all four of `/FirstChar 65 /LastChar 66 /Widths [500 700]` and a font descriptor with `/MissingWidth 777`, showing `ABC`. Expected: A 500, B 700, C 777 (not Courier's 600). | 9.6.2.1 Table 109, 9.8.1 Table 120 | `pdftotext` prints `ABC` | clean | | `text-standard14-alias.pdf` | Non-embedded `/TrueType` font `/BaseFont /Arial,Bold` with `/WinAnsiEncoding`, no widths, no font descriptor, showing `Hi!`. Expected: Helvetica-Bold metrics H 722, i 278, exclam 333. | 9.6.2.2, 9.6.3 | `pdftotext` prints `Hi!`; `pdffonts` shows `Arial,Bold TrueType WinAnsi emb=no` | clean | | `text-type1-symbolic-noencoding.pdf` | Non-embedded Type 1 font `/BroadsideSymbolic` (not a standard 14 font), descriptor `/Flags 4` (Symbolic), `/Widths [600 650 700]` for 65-67, no `/Encoding`, showing `ABC`. Expected: widths 600 650 700; glyph names A B C from StandardEncoding, standing in for the unknown built-in encoding, with a diagnostic. | 9.6.5.1, 9.8.2 Table 121 | `pdftotext` prints `ABC`; `pdffonts` shows `Type 1 Standard emb=no` | clean | +| `text-truetype-composite.pdf` | Embedded TrueType font `/BroadsideComposite` (`/Flags 32`, `/WinAnsiEncoding`) showing `Ioc0123456789:;<`. Glyphs (gid): 1 `I` rectangle (100,0)-(300,700); 2 `o` four off-curve points only (250,0) (500,250) (250,500) (0,250); 3 `c` starting off-curve (0,0) then on-curve (200,0) (200,200) (0,200); composites of glyph 1: 4 word offset (400,300), 5 byte offset (10,20), 6/7/8 scale 0.5 with offset (100,40) and SCALED_COMPONENT_OFFSET / UNSCALED_COMPONENT_OFFSET / neither, 9 x-and-y scale (-1,1) offset (400,0), 10 2x2 (0 1 -1 0) offset (700,0), 11 glyph 1 plus glyph 1 matched point 0 onto point 2, 12 glyph 5 offset (0,100), 13 glyph 3 offset (50,0) with USE_MY_METRICS, 14 glyph 2 with instructions; 15 `I` with lsb 150 (xMin 100). Simple glyphs use short, same and repeated flags. `hmtx` has 12 advances for 16 glyphs. One (3,1) format 4 cmap: 0x30-0x3C through glyphIdArray (idDelta 1, `;` stored as 0), `I` `c` `o` with negative idDelta; `post` 3.0. | 9.6.3, 9.6.5.4, 9.9 Table 125 | `qpdf --check` clean; `pdftotext` prints `Ioc0123456789:;<`; `pdffonts` shows `TrueType WinAnsi emb=yes`; `pdftoppm` (FreeType) renders the composites as described (raised, scaled, mirrored, rotated to a horizontal bar, stacked) and nothing for `;` | clean | +| `text-truetype-symbolic.pdf` | Embedded TrueType font `/BroadsideSymbolic`, `/Flags 4` (Symbolic), no `/Encoding`, showing `ABCD`. cmap (1,0) format 0 maps 0x41-0x44 to glyphs 3 2 1 2; (3,0) format 4 maps 0xF041-0xF043 to glyphs 1 2 3. Expected glyphs 1 2 3 2: (3,0) with the 0xF0 high byte first; `D`, which (3,0) does not map, through (1,0) as a mapping of the processor's choosing (PDFBox does the same), with an information diagnostic. | 9.6.5.4, 9.8.2 Table 121 | `qpdf --check` clean; `pdftotext` prints `ABCD`; `pdffonts` shows `TrueType WinAnsi emb=yes`; `pdftoppm` renders glyphs 1 2 3 for `ABC` and nothing for `D` (poppler uses only (3,0) when present) | clean | +| `text-truetype-macroman.pdf` | Embedded TrueType font `/BroadsideMacRoman`, `/Flags 32`, encoding `<< /BaseEncoding /WinAnsiEncoding /Differences [129 /brds.alt] >>`, showing bytes 0x80 0xE9 0x81. The program has only a (1,0) cmap, format 6 from 0x8E: 0x8E to glyph 2, 0xDB to glyph 1; `post` 2.0 names glyphs `.notdef Euro eacute brds.alt`. Expected glyphs 1 (Euro, Mac OS Roman 219 per Table 113), 2 (eacute, Mac 0x8E), 3 (brds.alt through `post`). | 9.6.5.4 Table 113 | `qpdf --check` clean; `pdftotext` prints `€é` and U+0081; `pdffonts` shows `TrueType Custom emb=yes` | clean | +| `text-truetype-loca-long.pdf` | Embedded TrueType font `/BroadsideLongLoca` (`/Flags 32`, `/WinAnsiEncoding`) showing `HI`: `indexToLocFormat` 1 with glyph `H` 75 bytes long and unpadded, so glyph `I` starts at an odd offset; the only cmap is (3,10) format 12 (0x48-0x49 to glyphs 1-2, U+1F600 to glyph 2); `post` 1.0. | 9.6.5.4, 9.9 Table 125 | `qpdf --check` clean; `pdftotext` prints `HI`; `pdffonts` shows `TrueType WinAnsi emb=yes`; `pdftoppm` renders the H and I blocks | clean | | `xref-stream.pdf` | Cross-reference stream (`/Type /XRef`, `/W [1 2 1]`, uncompressed), no classic table, no `trailer` keyword. | 7.5.8.2, 7.5.8.3 | `qpdf --check`; `qpdf --qdf --object-streams=disable` | clean | | `object-stream.pdf` | Catalog, page tree and page stored in an object stream (`/Type /ObjStm`, `/N 3`, `/First`), located through type 2 entries in a cross-reference stream. | 7.5.7, 7.5.8.3 Table 18 | `qpdf --qdf --object-streams=disable` lists objects 1-3 as ordinary objects | clean | | `incremental-update.pdf` | `empty-page.pdf` followed by one update section that replaces object 3 with an A4 `/MediaBox`; update trailer carries `/Prev`. | 7.5.6 | `pdfinfo` shows `595 x 842 pts (A4)` | clean | diff --git a/tests/Corpus/generate.py b/tests/Corpus/generate.py index 31d74449..438f21f0 100644 --- a/tests/Corpus/generate.py +++ b/tests/Corpus/generate.py @@ -654,6 +654,262 @@ def minimal_truetype() -> tuple[bytes, dict[int, int]]: return bytes(font), {c: advances[g] for c, g in chars.items()} +# The standard Macintosh glyph order of the 'post' table (Apple TrueType Reference Manual, "The 'post' table"). +MAC_STANDARD_NAMES = ( + ".notdef .null nonmarkingreturn space exclam quotedbl numbersign dollar percent ampersand quotesingle parenleft " + "parenright asterisk plus comma hyphen period slash zero one two three four five six seven eight nine colon " + "semicolon less equal greater question at A B C D E F G H I J K L M N O P Q R S T U V W X Y Z bracketleft " + "backslash bracketright asciicircum underscore grave a b c d e f g h i j k l m n o p q r s t u v w x y z " + "braceleft bar braceright asciitilde Adieresis Aring Ccedilla Eacute Ntilde Odieresis Udieresis aacute agrave " + "acircumflex adieresis atilde aring ccedilla eacute egrave ecircumflex edieresis iacute igrave icircumflex " + "idieresis ntilde oacute ograve ocircumflex odieresis otilde uacute ugrave ucircumflex udieresis dagger degree " + "cent sterling section bullet paragraph germandbls registered copyright trademark acute dieresis notequal AE " + "Oslash infinity plusminus lessequal greaterequal yen mu partialdiff summation product pi integral ordfeminine " + "ordmasculine Omega ae oslash questiondown exclamdown logicalnot radical florin approxequal Delta guillemotleft " + "guillemotright ellipsis nonbreakingspace Agrave Atilde Otilde OE oe endash emdash quotedblleft quotedblright " + "quoteleft quoteright divide lozenge ydieresis Ydieresis fraction currency guilsinglleft guilsinglright fi fl " + "daggerdbl periodcentered quotesinglbase quotedblbase perthousand Acircumflex Ecircumflex Aacute Edieresis Egrave " + "Iacute Icircumflex Idieresis Igrave Oacute Ocircumflex apple Ograve Uacute Ucircumflex Ugrave dotlessi " + "circumflex tilde macron breve dotaccent ring cedilla hungarumlaut ogonek caron Lslash lslash Scaron scaron " + "Zcaron zcaron brokenbar Eth eth Yacute yacute Thorn thorn minus multiply onesuperior twosuperior threesuperior " + "onehalf onequarter threequarters franc Gbreve gbreve Idotaccent Scedilla scedilla Cacute cacute Ccaron ccaron " + "dcroat").split() +assert len(MAC_STANDARD_NAMES) == 258 + +# Composite glyph component flags (OpenType 'glyf' table). +ARG_WORDS, ARGS_XY, HAVE_SCALE, MORE_COMPONENTS = 0x0001, 0x0002, 0x0008, 0x0020 +HAVE_X_AND_Y_SCALE, HAVE_TWO_BY_TWO, HAVE_INSTRUCTIONS, USE_MY_METRICS = 0x0040, 0x0080, 0x0100, 0x0200 +SCALED_OFFSET, UNSCALED_OFFSET = 0x0800, 0x1000 + + +def f2dot14(value: float) -> bytes: + return struct.pack(">h", round(value * 16384)) + + +class TtfGlyph: + """A glyph of a synthesized TrueType font: simple (points with on-curve flags) or composite (component records).""" + + def __init__(self, contours=None, components=None, instructions: bytes = b""): + self.contours = contours or [] # [[(x, y, on_curve), ...], ...] + self.components = components or [] # [(flags, glyph, arg1, arg2, transform), ...] + self.instructions = instructions + + +def _f2(data: bytes) -> list[float]: + return [v / 16384 for v in struct.unpack(">%dh" % (len(data) // 2), data)] + + +def _glyph_points(glyphs: list[TtfGlyph], gid: int) -> list[tuple[float, float]]: + """The points of a glyph with composites applied (only to compute the header bounding boxes).""" + g = glyphs[gid] + if not g.components: + return [(x, y) for c in g.contours for x, y, _ in c] + points: list[tuple[float, float]] = [] + for flags, child, a1, a2, transform in g.components: + pts = _glyph_points(glyphs, child) + m = [1.0, 0.0, 0.0, 1.0] # xscale, scale01, scale10, yscale + if flags & HAVE_SCALE: + s = _f2(transform)[0] + m = [s, 0.0, 0.0, s] + elif flags & HAVE_X_AND_Y_SCALE: + sx, sy = _f2(transform) + m = [sx, 0.0, 0.0, sy] + elif flags & HAVE_TWO_BY_TWO: + m = _f2(transform) + pts = [(m[0] * x + m[2] * y, m[1] * x + m[3] * y) for x, y in pts] + if flags & ARGS_XY: + dx, dy = a1, a2 + if transform and flags & SCALED_OFFSET and not flags & UNSCALED_OFFSET: + dx, dy = dx * (m[0] ** 2 + m[2] ** 2) ** 0.5, dy * (m[3] ** 2 + m[1] ** 2) ** 0.5 + else: + dx, dy = points[a1][0] - pts[a2][0], points[a1][1] - pts[a2][1] + points += [(x + dx, y + dy) for x, y in pts] + return points + + +def _glyph_bbox(glyphs: list[TtfGlyph], gid: int) -> tuple[int, int, int, int]: + pts = _glyph_points(glyphs, gid) + if not pts: + return (0, 0, 0, 0) + xs, ys = [p[0] for p in pts], [p[1] for p in pts] + return (int(min(xs)), int(min(ys)), int(max(xs)), int(max(ys))) + + +def _encode_glyph(glyphs: list[TtfGlyph], gid: int) -> bytes: + """Encodes a glyph description: simple glyphs with short and same coordinates and repeated flags where they fit.""" + g = glyphs[gid] + if not g.contours and not g.components: + return b"" + bbox = _glyph_bbox(glyphs, gid) + if g.components: + out = struct.pack(">hhhhh", -1, *bbox) + for i, (flags, child, a1, a2, transform) in enumerate(g.components): + last = i == len(g.components) - 1 + flags |= 0 if last else MORE_COMPONENTS + if last and g.instructions: + flags |= HAVE_INSTRUCTIONS + out += struct.pack(">HH", flags, child) + fmt = (">hh" if flags & ARGS_XY else ">HH") if flags & ARG_WORDS else (">bb" if flags & ARGS_XY else ">BB") + out += struct.pack(fmt, a1, a2) + transform + if g.instructions: + out += struct.pack(">H", len(g.instructions)) + g.instructions + return out + pts = [p for c in g.contours for p in c] + out = struct.pack(">hhhhh", len(g.contours), *bbox) + end = -1 + for c in g.contours: + end += len(c) + out += struct.pack(">H", end) + out += struct.pack(">H", len(g.instructions)) + g.instructions + flags, xs, ys = [], b"", b"" + px = py = 0 + for x, y, on in pts: + dx, dy = x - px, y - py + px, py = x, y + f = 0x01 if on else 0x00 + if dx == 0: + f |= 0x10 + elif -255 <= dx <= 255: + f |= 0x02 | (0x10 if dx > 0 else 0) + xs += bytes([abs(dx)]) + else: + xs += struct.pack(">h", dx) + if dy == 0: + f |= 0x20 + elif -255 <= dy <= 255: + f |= 0x04 | (0x20 if dy > 0 else 0) + ys += bytes([abs(dy)]) + else: + ys += struct.pack(">h", dy) + flags.append(f) + packed = b"" + i = 0 + while i < len(flags): # a run of equal flags is written once with REPEAT (0x08) and a count + run = 1 + while i + run < len(flags) and flags[i + run] == flags[i] and run < 256: + run += 1 + packed += bytes([flags[i] | 0x08, run - 1]) if run > 1 else bytes([flags[i]]) + i += run + return out + packed + xs + ys + + +def cmap_format0(mapping: dict[int, int]) -> bytes: + return struct.pack(">HHH", 0, 262, 0) + bytes(mapping.get(c, 0) for c in range(256)) + + +def cmap_format4(segments: list[tuple[int, int, int, list[int] | None]]) -> bytes: + """Segments (start, end, idDelta, glyph ids or None); glyph ids go through idRangeOffset into glyphIdArray.""" + segments = segments + [(0xFFFF, 0xFFFF, 1, None)] + n = len(segments) + ends = b"".join(struct.pack(">H", e) for _, e, _, _ in segments) + starts = b"".join(struct.pack(">H", s) for s, _, _, _ in segments) + deltas = b"".join(struct.pack(">H", d & 0xFFFF) for _, _, d, _ in segments) + offsets, array = b"", b"" + for i, (_, _, _, ids) in enumerate(segments): + if ids is None: + offsets += struct.pack(">H", 0) + else: + offsets += struct.pack(">H", 2 * (n - i) + len(array)) + array += b"".join(struct.pack(">H", g) for g in ids) + es = n.bit_length() - 1 + body = struct.pack(">HHHH", 2 * n, 2 * (1 << es), es, 2 * n - 2 * (1 << es)) + ends + b"\0\0" + starts + deltas + offsets + array + return struct.pack(">HHH", 4, 6 + len(body), 0) + body + + +def cmap_format6(first: int, ids: list[int]) -> bytes: + return struct.pack(">HHHHH", 6, 10 + 2 * len(ids), 0, first, len(ids)) + b"".join(struct.pack(">H", g) for g in ids) + + +def cmap_format12(groups: list[tuple[int, int, int]]) -> bytes: + body = b"".join(struct.pack(">III", s, e, g) for s, e, g in groups) + return struct.pack(">HHIII", 12, 0, 16 + len(body), 0, len(groups)) + body + + +def cmap_table(subtables: list[tuple[int, int, bytes]]) -> bytes: + subtables = sorted(subtables, key=lambda t: (t[0], t[1])) + out = struct.pack(">HH", 0, len(subtables)) + offset = 4 + 8 * len(subtables) + data = b"" + for platform, encoding, sub in subtables: + out += struct.pack(">HHI", platform, encoding, offset + len(data)) + data += sub + return out + data + + +def post_table(version: int, names: list[str] | None = None) -> bytes: + """'post' version 0x00010000, 0x00020000 (names: index into the standard order or Pascal strings) or 0x00030000.""" + out = struct.pack(">IiHHIIIII", version, 0, 0, 0, 0, 0, 0, 0, 0) + if version == 0x00020000: + indexes, strings = [], b"" + custom: list[str] = [] + for name in names or []: + if name in MAC_STANDARD_NAMES: + indexes.append(MAC_STANDARD_NAMES.index(name)) + else: + indexes.append(258 + len(custom)) + custom.append(name) + strings += bytes([len(name)]) + name.encode("ascii") + out += struct.pack(">H", len(indexes)) + b"".join(struct.pack(">H", i) for i in indexes) + strings + return out + + +def ttf_font(glyphs: list[TtfGlyph], metrics: list[tuple[int, int]], n_hmetrics: int, cmap: bytes, post: bytes, + ps_name: str, long_loca: bool = False, pad: bool = True) -> bytes: + """A TrueType program from glyphs, (advance, lsb) per glyph (advances past n_hmetrics are dropped), cmap and post. + + Tables: head, hhea, maxp, hmtx, loca, glyf, cmap, name, post (the ones ISO 32000-2 Table 124 and 9.9 require, plus + name and post). Glyphs are padded to 4 bytes unless ``pad`` is false (long loca permits odd offsets).""" + upem = 1000 + glyf = bytearray() + loca = [] + for gid in range(len(glyphs)): + loca.append(len(glyf)) + data = _encode_glyph(glyphs, gid) + glyf += data + (bytes((-len(data)) % 4) if pad else b"") + loca.append(len(glyf)) + loca_tbl = b"".join(struct.pack(">I", o) if long_loca else struct.pack(">H", o // 2) for o in loca) + boxes = [_glyph_bbox(glyphs, g) for g in range(len(glyphs)) if glyphs[g].contours or glyphs[g].components] + bbox = (min(b[0] for b in boxes), min(b[1] for b in boxes), max(b[2] for b in boxes), max(b[3] for b in boxes)) + hmtx = b"".join(struct.pack(">Hh", a, l) for a, l in metrics[:n_hmetrics]) + hmtx += b"".join(struct.pack(">h", l) for _, l in metrics[n_hmetrics:]) + head = struct.pack(">IIIIHHqqhhhhHHhhh", 0x00010000, 0x00010000, 0, 0x5F0F3CF5, 0x000B, upem, 0, 0, + *bbox, 0, 8, 2, 1 if long_loca else 0, 0) + hhea = struct.pack(">IhhhHhhhhhhhhhhhH", 0x00010000, 800, -200, 0, max(a for a, _ in metrics), 0, 0, bbox[2], + 1, 0, 0, 0, 0, 0, 0, 0, n_hmetrics) + maxp = struct.pack(">IHHHHHHHHHHHHHH", 0x00010000, len(glyphs), 64, 4, 64, 4, 2, 0, 0, 0, 0, 0, 0, 4, 2) + names = [(1, ps_name), (2, "Regular"), (4, ps_name), (6, ps_name)] + name_data, recs = b"", b"" + for nid, text in names: + enc = text.encode("utf-16-be") + recs += struct.pack(">HHHHHH", 3, 1, 0x409, nid, len(enc), len(name_data)) + name_data += enc + name = struct.pack(">HHH", 0, len(names), 6 + 12 * len(names)) + recs + name_data + tables = {b"cmap": cmap, b"glyf": bytes(glyf), b"head": head, b"hhea": hhea, b"hmtx": hmtx, b"loca": loca_tbl, + b"maxp": maxp, b"name": name, b"post": post} + tags = sorted(tables) + n = len(tags) + es = n.bit_length() - 1 + sr = (1 << es) * 16 + font = bytearray(struct.pack(">IHHHH", 0x00010000, n, sr, es, n * 16 - sr)) + offset = 12 + 16 * n + body = bytearray() + head_off = 0 + for tag in tags: + data = tables[tag] + if tag == b"head": + head_off = offset + len(body) + font += tag + struct.pack(">III", _checksum(data), offset + len(body), len(data)) + body += data + bytes((-len(data)) % 4) + font += body + adj = (0xB1B0AFBA - _checksum(bytes(font))) & 0xFFFFFFFF + font[head_off + 8:head_off + 12] = struct.pack(">I", adj) + return bytes(font) + + +def ttf_rect(x0: int, y0: int, x1: int, y1: int) -> TtfGlyph: + return TtfGlyph([[(x0, y0, True), (x0, y1, True), (x1, y1, True), (x1, y0, True)]]) + + # --------------------------------------------------------------------------- # The corpus # --------------------------------------------------------------------------- @@ -794,6 +1050,117 @@ def gen_text_type1_symbolic_noencoding() -> bytes: return font_file([font], [b"ABC"], [(6, descriptor)]) +def truetype_file(font: bytes, base_font: bytes, flags: int, first: int, widths: list[int], encoding: bytes | None, + codes: bytes) -> bytes: + """A page showing ``codes`` in an embedded TrueType font (9.6.3, 9.8, 9.9 Table 125: Length1 is the program length).""" + enc = b" /Encoding " + encoding if encoding is not None else b"" + w = b" ".join(b"%d" % x for x in widths) + return simple_file([ + (1, catalog()), + (2, pages()), + (3, b"<< /Type /Page /Parent 2 0 R /MediaBox %s /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>" % LETTER), + (4, stream(b"", codes_content([("F1", codes)]))), + (5, b"<< /Type /Font /Subtype /TrueType /BaseFont /%s /FirstChar %d /LastChar %d /Widths [%s]%s " + b"/FontDescriptor 6 0 R >>" % (base_font, first, first + len(widths) - 1, w, enc)), + (6, b"<< /Type /FontDescriptor /FontName /%s /Flags %d /FontBBox [-300 0 700 1400] /ItalicAngle 0 /Ascent 800 " + b"/Descent -200 /CapHeight 700 /StemV 200 /FontFile2 7 0 R >>" % (base_font, flags)), + (7, stream(b"/Length1 %d" % len(font), font)), + ], binary=True) + + +def gen_text_truetype_composite() -> bytes: + """9.6.3, 9.6.5.4, 9.9: simple glyphs with off-curve points (an all-off-curve contour, a contour starting off-curve), + short, same and repeated coordinate flags, and composite glyphs with every argument and transform form of the + OpenType 'glyf' table (word and byte offsets, scale with SCALED/UNSCALED/neither offset flag, x-and-y scale, 2x2, + point matching, nesting, USE_MY_METRICS, instructions). hmtx has fewer advances than glyphs; the (3,1) format 4 + cmap has a glyphIdArray segment (with a 0 entry that stays 0) and negative deltas. Glyph 15 has lsb != xMin.""" + I = ttf_rect(100, 0, 300, 700) + glyphs = [ + TtfGlyph(), # 0 .notdef + I, # 1 'I' + TtfGlyph([[(250, 0, False), (500, 250, False), (250, 500, False), (0, 250, False)]]), # 2 'o': all off-curve + TtfGlyph([[(0, 0, False), (200, 0, True), (200, 200, True), (0, 200, True)]]), # 3 'c': starts off-curve + TtfGlyph(components=[(ARG_WORDS | ARGS_XY, 1, 400, 300, b"")]), # 4 word offset + TtfGlyph(components=[(ARGS_XY, 1, 10, 20, b"")]), # 5 byte offset + TtfGlyph(components=[(ARGS_XY | HAVE_SCALE | SCALED_OFFSET, 1, 100, 40, f2dot14(0.5))]), # 6 + TtfGlyph(components=[(ARGS_XY | HAVE_SCALE | UNSCALED_OFFSET, 1, 100, 40, f2dot14(0.5))]), # 7 + TtfGlyph(components=[(ARGS_XY | HAVE_SCALE, 1, 100, 40, f2dot14(0.5))]), # 8 + TtfGlyph(components=[(ARG_WORDS | ARGS_XY | HAVE_X_AND_Y_SCALE, 1, 400, 0, + f2dot14(-1) + f2dot14(1))]), # 9 mirror + TtfGlyph(components=[(ARG_WORDS | ARGS_XY | HAVE_TWO_BY_TWO, 1, 700, 0, + f2dot14(0) + f2dot14(1) + f2dot14(-1) + f2dot14(0))]), # 10 rotation by 90 + TtfGlyph(components=[(ARGS_XY, 1, 0, 0, b""), (0, 1, 2, 0, b"")]), # 11 point matching + TtfGlyph(components=[(ARGS_XY, 5, 0, 100, b"")]), # 12 nested + TtfGlyph(components=[(ARGS_XY | USE_MY_METRICS, 3, 50, 0, b"")]), # 13 USE_MY_METRICS + TtfGlyph(components=[(ARGS_XY, 2, 0, 0, b"")], instructions=b"\x00\x01\x02"), # 14 instructions + ttf_rect(100, 0, 300, 700), # 15 lsb 150, xMin 100 + ] + advances = [500, 400, 500, 300, 700, 400, 400, 400, 400, 400, 700, 600] + metrics = [] + for gid in range(len(glyphs)): + lsb = _glyph_bbox(glyphs, gid)[0] + (50 if gid == 15 else 0) + metrics.append((advances[min(gid, len(advances) - 1)], lsb)) + cmap = cmap_table([(3, 1, cmap_format4([ + (0x30, 0x3C, 1, [g - 1 for g in range(4, 15)] + [0, 14]), # '0'..':' -> 4..14, ';' -> 0, '<' -> 15 + (0x49, 0x49, 1 - 0x49, None), + (0x63, 0x63, 3 - 0x63, None), + (0x6F, 0x6F, 2 - 0x6F, None), + ]))]) + font = ttf_font(glyphs, metrics, len(advances), cmap, post_table(0x00030000), "BroadsideComposite") + codes = b"Ioc0123456789:;<" + gids = {0x49: 1, 0x6F: 2, 0x63: 3, 0x3B: 0, 0x3C: 15} + gids.update({0x30 + i: 4 + i for i in range(11)}) + widths = [metrics[gids[c]][0] if c in gids else 0 for c in range(0x30, 0x70)] + return truetype_file(font, b"BroadsideComposite", 32, 0x30, widths, b"/WinAnsiEncoding", codes) + + +def gen_text_truetype_symbolic() -> bytes: + """9.6.5.4: a symbolic font (Flags 4) without Encoding selects glyphs by code: the (3,0) subtable at 0xF000 + code + comes before the (1,0) subtable, which maps the same codes to other glyphs; code 0x44 is only in (1,0).""" + glyphs = [TtfGlyph(), ttf_rect(100, 0, 300, 700), ttf_rect(100, 0, 500, 500), ttf_rect(100, 0, 700, 300)] + metrics = [(500, 0), (400, 100), (600, 100), (800, 100)] + cmap = cmap_table([ + (1, 0, cmap_format0({0x41: 3, 0x42: 2, 0x43: 1, 0x44: 2})), + (3, 0, cmap_format4([(0xF041, 0xF043, 1 - 0xF041, None)])), + ]) + font = ttf_font(glyphs, metrics, len(metrics), cmap, post_table(0x00030000), "BroadsideSymbolic") + return truetype_file(font, b"BroadsideSymbolic", 4, 0x41, [400, 600, 800, 600], None, b"ABCD") + + +def gen_text_truetype_macroman() -> bytes: + """9.6.5.4 and Table 113: a nonsymbolic font whose program has only a (1,0) cmap (format 6): names from the encoding + (WinAnsi base with Differences) map to Mac OS Roman codes (Euro is 219, eacute 0x8E); a name with no Mac OS Roman code + (brds.alt) is found through the 'post' format 2 names.""" + glyphs = [TtfGlyph(), ttf_rect(100, 0, 300, 700), ttf_rect(100, 0, 500, 500), ttf_rect(100, 0, 700, 300)] + metrics = [(500, 0), (400, 100), (600, 100), (800, 100)] + ids = [0] * (0xDB - 0x8E + 1) + ids[0] = 2 # 0x8E eacute + ids[0xDB - 0x8E] = 1 # 0xDB Euro (Table 113) + cmap = cmap_table([(1, 0, cmap_format6(0x8E, ids))]) + post = post_table(0x00020000, [".notdef", "Euro", "eacute", "brds.alt"]) + font = ttf_font(glyphs, metrics, len(metrics), cmap, post, "BroadsideMacRoman") + widths = [0] * (0xE9 - 0x80 + 1) + widths[0], widths[1], widths[0xE9 - 0x80] = 400, 800, 600 + return truetype_file(font, b"BroadsideMacRoman", 32, 0x80, widths, + b"<< /Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences [129 /brds.alt] >>", + b"\x80\xe9\x81") + + +def gen_text_truetype_loca_long() -> bytes: + """9.6.5.4 and the OpenType 'loca' table: long offsets (indexToLocFormat 1) with an odd-length, unpadded glyph; the + only cmap is (3,10) format 12, a Unicode subtable that stands in for (3,1); 'post' version 1.0.""" + H = TtfGlyph([[(x, y, True) for x, y in [(100, 0), (100, 700), (300, 700), (300, 400), (500, 400), (500, 700), + (700, 700), (700, 0), (500, 0), (500, 300), (300, 300), (300, 0)]]], + instructions=b"\x00") + glyphs = [TtfGlyph(), H, ttf_rect(100, 0, 300, 700)] + metrics = [(500, 0), (800, 100), (400, 100)] + cmap = cmap_table([(3, 10, cmap_format12([(0x48, 0x49, 1), (0x1F600, 0x1F600, 2)]))]) + font = ttf_font(glyphs, metrics, len(metrics), cmap, post_table(0x00010000), "BroadsideLongLoca", + long_loca=True, pad=False) + assert len(_encode_glyph(glyphs, 1)) % 2 == 1 + return truetype_file(font, b"BroadsideLongLoca", 32, 0x48, [800, 400], b"/WinAnsiEncoding", b"HI") + + def gen_xref_stream() -> bytes: f = File("1.5", binary=True) f.add(1, catalog()) @@ -1678,6 +2045,10 @@ def gen_functions() -> bytes: "text-standard14-widths.pdf": gen_text_standard14_widths, "text-standard14-alias.pdf": gen_text_standard14_alias, "text-type1-symbolic-noencoding.pdf": gen_text_type1_symbolic_noencoding, + "text-truetype-composite.pdf": gen_text_truetype_composite, + "text-truetype-symbolic.pdf": gen_text_truetype_symbolic, + "text-truetype-macroman.pdf": gen_text_truetype_macroman, + "text-truetype-loca-long.pdf": gen_text_truetype_loca_long, "xref-stream.pdf": gen_xref_stream, "object-stream.pdf": gen_object_stream, "incremental-update.pdf": gen_incremental_update, diff --git a/tests/Corpus/text-truetype-composite.pdf b/tests/Corpus/text-truetype-composite.pdf new file mode 100644 index 0000000000000000000000000000000000000000..7c810cc38f6e89a6eb1d3cbc1c978a7c5f22ecd0 GIT binary patch literal 2179 zcmb7GL2nyX5T0E-q1mR8N)ZS|rKgfqJv3eKK6~S!5H)scwW2_kSSeCf(8jy5x3YJw z-Hqg;9*{ts5UPX}ap2GcKLBy+AqNf|d_V$;3*x|mN{Am2E)mFl^VW4zC!q3HZ}-jj zX6Boj9q;q}&9&Nsb$QX4|LyS)KN*%Nh-mAsvAitI`n|3%%&MEZ?Wiftn{Lxjgbjst zv9eq$O=BWl@%-BNt^^F3D9{k<}GZzbmfR zxjaKp!$NT!Pv@(mG&gp(QdQ`ByyIsjuegbyZC2vQ^^(Bzt5K&LB|(Z8QVZfFt+w1) z6w8R+9SW9Z3G-Iqr7e`5qb;5=8F$8JX()4nPrBI8|G(tFT7eHQ@M_qIydXqh-3r3h zFbNI;PJPW!8gbA~qgXg#KiY9DA1~w)1NHjfb~~umiS=u{%|u8$YmE2U&i_`BJEns zcRlx)+8rW&4VcpcF!8Gn5Bhz`bFEI=d-0oz-yuJQTy94VSN~2AA^!~de8=r|=^T9w z8U9FwDCC)!&b>;M!=$g#hAHB}$bHZIm>Oh`aGLV8j;BGVNXNBI*Qr6#U;wNzT5E$x zgNK99VPOEzMh=z}G)d3Fatioq_&S5F=P@<%aJ!`MF{?Z)&w71*@9#CmNZP)(&$#Ve zm^{b^d*o<{`na%Hkfqo9{XT%f0Q&Hh`-3Ca9%z>sqmX7bNBM4r9}zK=*lCKy++$3yWUkBJ_gAI7ce z86Hwkb8(D(m5XV5 zg)X2!%2c5nv`JgkrTgf=Pw5N#3L4BdgL387R4Im-KGEl literal 0 HcmV?d00001 diff --git a/tests/Corpus/text-truetype-loca-long.pdf b/tests/Corpus/text-truetype-loca-long.pdf new file mode 100644 index 0000000000000000000000000000000000000000..ede8668bc6f18bab637064bc6ff938925386d204 GIT binary patch literal 1626 zcma)7L2nyX5T3O|)ovq5IC0=GY6;?yu)AK{aiz#2P8_wug($J;p+)Fr_hr46y=(2R zrIb?-`~ZFcr-~CNen5UeZy-^w9N^LeN8r}NH*f7Yv60}d-h1=S%$u1vvpc(SxPP$a zeYkCJ{QBDuKiM9;oSr(LSZR;cyMZs4OlzPs` zahUT%U(`Q`m2{F6>|Hu2lI4TqCeu(Y{W$k^7^_Zt#t&WSH@zBf->DgUNddK->*9c& zBb}#{EI@z~`9TT`hVZyy6xwaLzT{nwO}(?z(@9he*l&nJUSwL0>`otMJg(Kbf6Ci% z>$=atX)lTqoxR(x?M1G=1cn$t7%AtyK_7S1@>6j{Q`H0Ik+49Qp?&0-`gWV(= zY6zU&JdpBA_>OoIuvHVZr^a`691RL{+Bq)t=rcAFF@F#bHL9?11HrQ!lvVV&={GM* zD)hXjWD(H~dP-GV3r1>8Z~y)?INxB_qv4a&;Qq4&^pBX`fmY#3d+!;M^$u`z0LB}? zR2~5z0>3vH6=&DJrRTr}@ahnS!=3>@#lALDXJcBUuYkV><^)+>_1?V>{5|k@<1{Z! zJR~-WF)hSpV_(H1;{&r2Rj}X1yoYI#^%qu5;ae19JFlG6P0;>&`P^Q=y&gW7Q8|D8 z!rFYbZ*9JQQ7T)TP_B~E4IzKEFP0=Pn639;-umLLoj>Vj^`)?{jF~5*>&CMPai+?D zw`3Iv(_-oJs9Jv*X^1Sq!o}DE)iv5x`iNG{lzYy{3cL^`O@wQ$+<@*a;F7M;n?NPK z0?M7z*FYap2USQ(!Cy`>R!u$Ngd(#CkQ{**(S(Mev;U$0-xkXp&ZA$VmYc;{rcZ5` zTef>KxY=l+3!U->&qGU*!O5K0MDtqUc{Mcd1zxR=uVaDd`)IohyoTFa;%&R=zcale oQ~3BY^G`UAztr49zfDtV=hJ^dUZ|`v_rXVBvo|)npB~u%07}~9I&}30-3S{LYEs2Lq@(LDtvK5 z!86|q{ge+}ML)zU@g&OFJ~vTWE>Bc$5(#SI$J~{ED4OvxA6Vd5ZHH@{PQG50ftGSb zIbgFZ(|D422v9}76Jv#3uz4dVG#YSy&byj6_0HzoG77Q*yER2fvqXxK(d=Ovo1F^x z`dous%i^BTTXn0mS+^V9yT_fLO2U*sO^5P!aaVaP=Kka;%hTCQCbCFuQ>3ymHj`NR zY3R#c;dSGYh~PR*(yTQQ3ENH`5sE2tT$jx|p`Q(q+zMi<`sV1^fHSF(AoT|{yAP#F@8ga!63_9(A>}D=r-pT)jT`lP@*{(cA)Ut4vOZsac-)!PFM20 z)k!0wtMmbt=$bbYW4f)ip!pcj*TL|9zw_wVTSVF(@ZLZQ|ESUW4ER&v>Hvyoe$Wqr zzXyJ0Fv^aX9&2mBkAbfZV^2_pUL?|&fsK(k9@7ea2>b#tN66yx>o5HVTnGMg9H-gR zJMGVbe+E`MEsu|AnXb?mz#q{~(((V_94eO@`FO4AC&(zdEAEQ_jehb+d#XRxP7D3@ z6<>R(ojy^CDQx-)GMCSRO@CKgd-7djQ+9gqt54p)`~24L^la%DrM@uWQ9pr4qNQ1O zFsH1)UnzxnOWFnUV2No2DS{*^pa~6ul7GSf=M}MeMEA5& z#&&fYYo&5$lEh1AAB@Xi_~S(O4SaVEYc{yLvEgoTpJzH7_kbE4&2?4WISV@5!F{`+ zb1FE!3py98FY0Rb%RJmnb6%DRd>oSeD&G$uNX9+Vjbn8SPp|Ma6G@iu$F5gwV|BH2 HYsdHtO3S1^ literal 0 HcmV?d00001 diff --git a/tests/Corpus/text-truetype-symbolic.pdf b/tests/Corpus/text-truetype-symbolic.pdf new file mode 100644 index 0000000000000000000000000000000000000000..1d4b2962b89d3a23ec1016e224ea7ccd24f9aedd GIT binary patch literal 1882 zcmc&#zmFS56n?v2qGUOdoJ0i_1LC99D1KSm45qEFeo14Pv9F3K5S~8PS+!xNC?5k8%AlMg;hOI^c3mKnv z$aT)gVUUXJ9?NeaN<0~5!ae24mPJQSlPE~@JkF;o2xT)q6xYkp*W8L&->B$#qYScC z_?$pE`znnmNe=~b<-0K==!Gk)TF_`9^{MRaR%92>Cu-Es2EyB5L7F8>4((K`_k1o?MXM&4ecZomAAGjQ9cV3I=B@ z?eTGPi4G@XuvTHzlH(6m*dJut+i7QNcui;v?_xKM6uLgQ0micpeAct-D0#W#HNX#4C@? z8^B)yzdIOahv)w`R)N0(z7)khNj|*+{5`Nel!s$lCfLj$fyD?-T>9>p5>AmT^uqFE^D;!+g02|F5^DyJL~X{rRIconqdaPA}ds`h_-8 zfN9k{=FWM`-g5AhdHm0I!Jil>Isf)@VB9fIo-FZxw2yg=6VyJinO_*IPaftrw$rz_ z-@NtZ#m&Fy)zWVZEkH)|7#WGqyw*MRc1g;lv&pTl~env_sX61h?eF)M1*5e=ye zHUiUwMp2(8KoZ&)>tC$k%KmdKUX+K4IBo>D}noFKaTl1E8fC1lS!uc PaP71^}c2= literal 0 HcmV?d00001 From 2e799f59899b47fc10962b8aee5745a648623a24 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:54:25 -0500 Subject: [PATCH 047/152] fix(fuzz): page labels keep their whole prefix; bound the label by it (#48) libFuzzer (scheduled workflow trial run) reported four inputs whose page label prefixes were 8 KB long: the document target assumed prefixes under 4 KB, but Table 161 sets no length on P. The invariant is now the longest prefix of the ranges plus MaxNumeralLength; the library was right. PageLabelTests.A_long_prefix_is_kept_whole pins the contract. Co-Authored-By: Claude Opus 5.5 --- tests/Broadside.Fuzz/FuzzTargets.cs | 4 +++- tests/Broadside.Tests/Document/PageLabelTests.cs | 12 ++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 7889de56..24804b12 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -966,8 +966,10 @@ private static void ReadCatalogEssentials(PdfDocument document) if (document.PageLabels is { } labels) { + // A label is its range's prefix (any length, Table 161) and a number of at most MaxNumeralLength characters. IReadOnlyList all = labels.GetLabels(); - if (all.Count != document.Pages.Count || all.Any(label => label.Length > PdfPageLabelRange.MaxNumeralLength + 4096)) + int longestPrefix = labels.Ranges.Select(range => range.Prefix.Length).DefaultIfEmpty(0).Max(); + if (all.Count != document.Pages.Count || all.Any(label => label.Length > longestPrefix + PdfPageLabelRange.MaxNumeralLength)) { throw new InvalidOperationException("Page labels must give one bounded label per page."); } diff --git a/tests/Broadside.Tests/Document/PageLabelTests.cs b/tests/Broadside.Tests/Document/PageLabelTests.cs index 320327bd..bacc35c2 100644 --- a/tests/Broadside.Tests/Document/PageLabelTests.cs +++ b/tests/Broadside.Tests/Document/PageLabelTests.cs @@ -137,6 +137,18 @@ public void A_malformed_page_label_is_repaired_with_a_warning(string entries, st Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); } + // The fuzz harness assumed prefixes under 4 KB and reported an 8 KB one as a finding (issue #48): Table 161 sets no length on P, + // so the label is the whole prefix followed by the number. + [Fact] + public void A_long_prefix_is_kept_whole() + { + string prefix = new('x', 8192); + using PdfDocument document = OnePageLabelled($"/S /D /P ({prefix}) /St 7"); + + Assert.Equal(prefix + "7", document.PageLabels!.GetLabel(0)); + Assert.Empty(document.Diagnostics); + } + [Fact] public void Pages_before_the_first_range_are_numbered_in_decimal_with_a_warning() { From ba29aa1a14208287cb2a301b6e24903c2d901c5d Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:55:09 -0500 Subject: [PATCH 048/152] feat(graphics): colour spaces and the colour-management extension point (#77) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every colour set by content resolves to a typed colour in a typed colour space (ISO 32000-2 §8.6), and conversion to device colour goes through a replaceable colour-management contract (§10.3, §10.4). - Colour spaces: PdfColorSpace views for all eleven families (device singletons, CalGray, CalRGB, Lab, ICCBased with its profile header, Indexed, Separation with All/None, DeviceN with NChannel attributes, Pattern with and without an underlying space), cached per document object, live over COS, repaired leniently with diagnostics (cycles and unusable spaces read as DeviceGray), strict mode throws. - PdfColor value (inline components, pattern name, object and matrix) in GraphicsState.StrokeColor/FillColor; CS cs SC SCN sc scn G g RG rg K k in the interpreter, allocation-free once warm. - Default colour spaces at paint time (ContentContext.DefaultColorSpaces), including Indexed bases, Pattern underlying spaces and Separation/DeviceN alternates, never remapped twice. - IColorManagement/IColorConverter with ManagedColorManagement (§10.4.2 formulas, CIE spaces through XYZ/Bradford/sRGB with black point compensation, ICCBased through its alternate or as Lab) behind PdfOptions.UseColorManagement; PdfColorConverter expands Indexed, Separation, DeviceN and Pattern and converts floats or 8-bit rows. - DeviceCMYK to RGB defaults to a cubic fitted to the CGATS TR 001 (SWOP) measurements (tools/CmykFit/fit.py); ManagedColorManagement.Classic keeps the §10.4.2.5 formula. - Corpus: colorspace-families.pdf (with generated ICC v2 RGB and GRAY profiles), color-operators.pdf, default-colorspaces.pdf, separation-special.pdf. Fuzz target colorspace; ColorConversionBenchmarks. - Conformance: 8.6 split into 8.6.1-8.6.8; 10.3 partial, 10.4 done. Co-Authored-By: Claude Opus 5.5 --- .../ColorConversionBenchmarks.cs | 74 ++++ docs/conformance/iso-32000-2.md | 17 +- src/Broadside/Content/ContentContext.cs | 85 ++++ .../Content/ContentInterpreter.Color.cs | 177 +++++++- src/Broadside/Content/ContentInterpreter.cs | 1 + src/Broadside/Content/ContentIssue.cs | 19 +- src/Broadside/EngineConfiguration.cs | 5 + .../Graphics/BlackPointCompensation.cs | 19 + src/Broadside/Graphics/CieXyz.cs | 15 + src/Broadside/Graphics/CmykConversion.cs | 18 + src/Broadside/Graphics/ColorConversion.cs | 44 ++ src/Broadside/Graphics/Colors/CieChecks.cs | 44 ++ src/Broadside/Graphics/Colors/CieConverter.cs | 135 ++++++ .../Graphics/Colors/CmykCharacterization.cs | 115 +++++ src/Broadside/Graphics/Colors/ColorEntries.cs | 79 ++++ src/Broadside/Graphics/Colors/ColorMath.cs | 162 +++++++ .../Graphics/Colors/ColorPipeline.cs | 120 +++++ .../Graphics/Colors/ColorPipelines.cs | 270 +++++++++++ .../Graphics/Colors/ColorSpaceCache.cs | 419 ++++++++++++++++++ .../Graphics/Colors/ColorSpaceNames.cs | 51 +++ .../Graphics/Colors/DeviceConverter.cs | 104 +++++ .../Graphics/Colors/IccAlternateConverter.cs | 53 +++ src/Broadside/Graphics/Colors/TintSpaces.cs | 71 +++ src/Broadside/Graphics/ComponentRange.cs | 13 + src/Broadside/Graphics/DeviceColorModel.cs | 15 + src/Broadside/Graphics/GraphicsState.cs | 42 +- src/Broadside/Graphics/IColorConverter.cs | 21 + src/Broadside/Graphics/IColorManagement.cs | 30 ++ src/Broadside/Graphics/IccProfileHeader.cs | 121 +++++ .../Graphics/ManagedColorManagement.cs | 61 +++ .../Graphics/PdfCalGrayColorSpace.cs | 67 +++ src/Broadside/Graphics/PdfCalRgbColorSpace.cs | 81 ++++ src/Broadside/Graphics/PdfColor.cs | 142 ++++++ src/Broadside/Graphics/PdfColorConverter.cs | 183 ++++++++ src/Broadside/Graphics/PdfColorSpace.cs | 180 ++++++++ src/Broadside/Graphics/PdfColorSpaceFamily.cs | 39 ++ .../Graphics/PdfDefaultColorSpaces.cs | 60 +++ .../Graphics/PdfDeviceCmykColorSpace.cs | 28 ++ .../Graphics/PdfDeviceGrayColorSpace.cs | 22 + .../Graphics/PdfDeviceNAttributes.cs | 79 ++++ .../Graphics/PdfDeviceNColorSpace.cs | 149 +++++++ .../Graphics/PdfDeviceNMixingHints.cs | 73 +++ src/Broadside/Graphics/PdfDeviceNProcess.cs | 32 ++ .../Graphics/PdfDeviceRgbColorSpace.cs | 22 + .../Graphics/PdfIccBasedColorSpace.cs | 227 ++++++++++ .../Graphics/PdfIndexedColorSpace.cs | 116 +++++ src/Broadside/Graphics/PdfLabColorSpace.cs | 88 ++++ .../Graphics/PdfPatternColorSpace.cs | 68 +++ .../Graphics/PdfSeparationColorSpace.cs | 73 +++ .../Parsing/DiagnosticCodes.Color.cs | 27 ++ src/Broadside/PdfDocument.cs | 64 ++- src/Broadside/PdfOptions.cs | 19 + src/Broadside/PublicAPI.Unshipped.txt | 224 ++++++++++ tests/Broadside.Fuzz/FuzzTargets.cs | 114 +++++ tests/Broadside.Fuzz/README.md | 2 +- tests/Broadside.TestSupport/Corpus.cs | 4 + .../Colors/ColorAllocationTests.cs | 106 +++++ .../Colors/ColorConversionTests.cs | 240 ++++++++++ .../Colors/ColorManagementTests.cs | 112 +++++ .../Colors/ColorOperatorTests.cs | 146 ++++++ .../Colors/ColorRepairTests.cs | 60 +++ .../Colors/ColorSpaceFamilyTests.cs | 311 +++++++++++++ tests/Broadside.Tests/Colors/ColorTesting.cs | 108 +++++ .../Colors/CorpusColorTests.cs | 138 ++++++ .../Colors/DefaultColorSpaceTests.cs | 94 ++++ tests/Broadside.Tests/Colors/IccProfiles.cs | 34 ++ ...pus_file_names_match_snapshot.verified.txt | 4 + tests/Corpus/README.md | 4 + tests/Corpus/color-operators.pdf | Bin 0 -> 1297 bytes tests/Corpus/colorspace-families.pdf | Bin 0 -> 2934 bytes tests/Corpus/default-colorspaces.pdf | Bin 0 -> 1345 bytes tests/Corpus/generate.py | 199 +++++++++ tests/Corpus/separation-special.pdf | Bin 0 -> 954 bytes tools/CmykFit/__pycache__/fit.cpython-314.pyc | Bin 0 -> 14933 bytes tools/CmykFit/fit.py | 140 ++++++ 75 files changed, 6261 insertions(+), 18 deletions(-) create mode 100644 bench/Broadside.Benchmarks/ColorConversionBenchmarks.cs create mode 100644 src/Broadside/Graphics/BlackPointCompensation.cs create mode 100644 src/Broadside/Graphics/CieXyz.cs create mode 100644 src/Broadside/Graphics/CmykConversion.cs create mode 100644 src/Broadside/Graphics/ColorConversion.cs create mode 100644 src/Broadside/Graphics/Colors/CieChecks.cs create mode 100644 src/Broadside/Graphics/Colors/CieConverter.cs create mode 100644 src/Broadside/Graphics/Colors/CmykCharacterization.cs create mode 100644 src/Broadside/Graphics/Colors/ColorEntries.cs create mode 100644 src/Broadside/Graphics/Colors/ColorMath.cs create mode 100644 src/Broadside/Graphics/Colors/ColorPipeline.cs create mode 100644 src/Broadside/Graphics/Colors/ColorPipelines.cs create mode 100644 src/Broadside/Graphics/Colors/ColorSpaceCache.cs create mode 100644 src/Broadside/Graphics/Colors/ColorSpaceNames.cs create mode 100644 src/Broadside/Graphics/Colors/DeviceConverter.cs create mode 100644 src/Broadside/Graphics/Colors/IccAlternateConverter.cs create mode 100644 src/Broadside/Graphics/Colors/TintSpaces.cs create mode 100644 src/Broadside/Graphics/ComponentRange.cs create mode 100644 src/Broadside/Graphics/DeviceColorModel.cs create mode 100644 src/Broadside/Graphics/IColorConverter.cs create mode 100644 src/Broadside/Graphics/IColorManagement.cs create mode 100644 src/Broadside/Graphics/IccProfileHeader.cs create mode 100644 src/Broadside/Graphics/ManagedColorManagement.cs create mode 100644 src/Broadside/Graphics/PdfCalGrayColorSpace.cs create mode 100644 src/Broadside/Graphics/PdfCalRgbColorSpace.cs create mode 100644 src/Broadside/Graphics/PdfColor.cs create mode 100644 src/Broadside/Graphics/PdfColorConverter.cs create mode 100644 src/Broadside/Graphics/PdfColorSpace.cs create mode 100644 src/Broadside/Graphics/PdfColorSpaceFamily.cs create mode 100644 src/Broadside/Graphics/PdfDefaultColorSpaces.cs create mode 100644 src/Broadside/Graphics/PdfDeviceCmykColorSpace.cs create mode 100644 src/Broadside/Graphics/PdfDeviceGrayColorSpace.cs create mode 100644 src/Broadside/Graphics/PdfDeviceNAttributes.cs create mode 100644 src/Broadside/Graphics/PdfDeviceNColorSpace.cs create mode 100644 src/Broadside/Graphics/PdfDeviceNMixingHints.cs create mode 100644 src/Broadside/Graphics/PdfDeviceNProcess.cs create mode 100644 src/Broadside/Graphics/PdfDeviceRgbColorSpace.cs create mode 100644 src/Broadside/Graphics/PdfIccBasedColorSpace.cs create mode 100644 src/Broadside/Graphics/PdfIndexedColorSpace.cs create mode 100644 src/Broadside/Graphics/PdfLabColorSpace.cs create mode 100644 src/Broadside/Graphics/PdfPatternColorSpace.cs create mode 100644 src/Broadside/Graphics/PdfSeparationColorSpace.cs create mode 100644 src/Broadside/Parsing/DiagnosticCodes.Color.cs create mode 100644 tests/Broadside.Tests/Colors/ColorAllocationTests.cs create mode 100644 tests/Broadside.Tests/Colors/ColorConversionTests.cs create mode 100644 tests/Broadside.Tests/Colors/ColorManagementTests.cs create mode 100644 tests/Broadside.Tests/Colors/ColorOperatorTests.cs create mode 100644 tests/Broadside.Tests/Colors/ColorRepairTests.cs create mode 100644 tests/Broadside.Tests/Colors/ColorSpaceFamilyTests.cs create mode 100644 tests/Broadside.Tests/Colors/ColorTesting.cs create mode 100644 tests/Broadside.Tests/Colors/CorpusColorTests.cs create mode 100644 tests/Broadside.Tests/Colors/DefaultColorSpaceTests.cs create mode 100644 tests/Broadside.Tests/Colors/IccProfiles.cs create mode 100644 tests/Corpus/color-operators.pdf create mode 100644 tests/Corpus/colorspace-families.pdf create mode 100644 tests/Corpus/default-colorspaces.pdf create mode 100644 tests/Corpus/separation-special.pdf create mode 100644 tools/CmykFit/__pycache__/fit.cpython-314.pyc create mode 100644 tools/CmykFit/fit.py diff --git a/bench/Broadside.Benchmarks/ColorConversionBenchmarks.cs b/bench/Broadside.Benchmarks/ColorConversionBenchmarks.cs new file mode 100644 index 00000000..3b1053d1 --- /dev/null +++ b/bench/Broadside.Benchmarks/ColorConversionBenchmarks.cs @@ -0,0 +1,74 @@ +using System.Text; +using BenchmarkDotNet.Attributes; +using Broadside.Graphics; +using Broadside.Objects; + +namespace Broadside.Benchmarks; + +/// +/// Converts a 1-megapixel image's worth of colours (ISO 32000-2 §8.6, §10.4) through , as an image +/// decoder converts rows: 8-bit DeviceCMYK through the SWOP characterisation, an 8-bit Separation through its 256-entry table, +/// 8-bit Indexed through its palette, and Lab from floats through XYZ to sRGB. Conversion is a hot path: Allocated must +/// read -; Broadside.Tests.Colors.ColorAllocationTests fails the build if it does not. +/// +[MemoryDiagnoser] +public class ColorConversionBenchmarks +{ + private const int Pixels = 1 << 20; + + private static readonly Dictionary Spaces = new() + { + ["Cmyk"] = "/DeviceCMYK", + ["Separation"] = "[/Separation /Spot /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0.4 1 0] /N 1 >>]", + ["Indexed"] = "[/Indexed /DeviceRGB 255 <" + string.Concat(Enumerable.Range(0, 256).Select(static i => $"{i:X2}{255 - i:X2}{(i * 7) & 255:X2}")) + ">]", + ["Lab"] = "[/Lab << /WhitePoint [0.9642 1 0.8249] /Range [-128 127 -128 127] >>]", + }; + + private PdfDocument? _document; + private PdfColorConverter? _converter; + private byte[] _samples = []; + private byte[] _bytes = []; + private float[] _components = []; + private float[] _colors = []; + + /// The source colour space. + [Params("Cmyk", "Separation", "Indexed", "Lab")] + public string Space { get; set; } = ""; + + [GlobalSetup] + public void Setup() + { + _document = PdfDocument.Create(); + PdfColorSpace space = _document.GetColorSpace(CosObject.Parse(Encoding.ASCII.GetBytes(Spaces[Space]))); + _converter = _document.GetColorConverter(space); + if (_document.Diagnostics.Count > 0) + { + throw new InvalidOperationException($"{Space} does not read cleanly."); + } + + // Deterministic pseudo-random samples (a multiplicative hash), so every run converts the same data. + _samples = new byte[Pixels * _converter.InputCount]; + _components = new float[Pixels * _converter.InputCount]; + for (int i = 0; i < _samples.Length; i++) + { + uint hash = unchecked((uint)i * 2654435761u); + _samples[i] = (byte)(hash >> 24); + _components[i] = (hash >> 8) / (float)(1 << 24) * 200 - 100; + } + + _bytes = new byte[Pixels * 3]; + + _colors = new float[Pixels * 3]; + } + + [GlobalCleanup] + public void Cleanup() => _document?.Dispose(); + + /// A megapixel of 8-bit samples to 8-bit RGB (the Lab samples map 0..255 onto L* 0..100 and a*, b* -128..127). + [Benchmark] + public void ConvertBytes() => _converter!.Convert(_samples, _bytes, Pixels); + + /// A megapixel of float components to float RGB. + [Benchmark] + public void ConvertFloats() => _converter!.Convert(_components, _colors, Pixels); +} diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index 72fa46c0..542cc7a5 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -52,7 +52,7 @@ Clause numbers at the second level; split rows to the third level as clauses are | 7.7.4 | Name dictionary | partial | `PdfNameDictionary`, `PdfDocument` | `Broadside.Tests.Navigation.NameTreeTests.Name_tree_dests_pdf_maps_its_three_keys_to_their_destination_arrays_with_no_diagnostics`, `Broadside.Tests.Navigation.NameTreeTests.A_tree_root_that_is_not_a_dictionary_reads_as_absent_with_a_diagnostic` | `PdfDocument.Names`; every Table 32 entry is reachable as a name tree through `PdfNameDictionary.GetTree`; `Dests` values are typed as destinations through `PdfDocument.GetNamedDestination` (12.3.2.4); EmbeddedFiles (#76) and JavaScript (#73) arrive with their features | | 7.8.1 | General | n/a | | | Introductory text: content streams and resource dictionaries are specified in 7.8.2 and 7.8.3 | | 7.8.2 | Content streams | done | `ContentReader`, `OperandArena`, `OperatorTable`, `ContentInterpreter`, `ContentProcessor`, `ContentOperator`, `ContentOperand`, `ContentOperands`, `ContentOperatorCode`, `PdfPage` | `Broadside.Tests.Content.ContentSyntaxTests`, `Broadside.Tests.Content.CorpusContentTests`, `Broadside.Tests.Content.ContentRunTests.A_contents_array_reads_as_its_parts_joined_by_white_space`, `Broadside.Tests.Content.ContentRunTests.A_contents_array_element_that_is_not_a_stream_is_skipped`, `Broadside.Tests.Content.ContentAllocationTests` | Issue #55. Operands are read in place (no object per operand, no string per keyword; zero allocation proven by `ContentAllocationTests` and `bench/Broadside.Benchmarks/ContentLexerBenchmarks.cs`); all 73 operators of Annex A recognised; glued keywords (`q1`, `0cm`, `Qq`) split when they decompose wholly into operators and numbers (`ContentGluedTokens`, Information); Table 33 BX/EX nest and silence unknown operators; outside them an unknown operator and its operands are ignored (`ContentUnknownOperator`); too few operands or wrong types skip the operator, too many use the last ones, leftovers at the end are dropped (`ContentOperandCount`, `ContentOperandType`); an inline image is read whole (BI dictionary, data to EI by L/Length or the pdf.js heuristic) and never tokenized. A Contents array is one stream with a line feed between parts (Table 31). Fuzz targets `content-lexer`, `content-interpreter`; `document` now runs every page. | -| 7.8.3 | Resource dictionaries | partial | `ContentContext` | `Broadside.Tests.Content.ContentRunTests.The_context_describes_the_page_run` | The page's (inherited) Resources are the run's `ContentContext.Resources`; looking names up in ExtGState, Font, XObject, Properties (#56), ColorSpace (#77), Pattern and Shading (#79) arrives with those operators; forms without Resources inheriting the page's is #56. | +| 7.8.3 | Resource dictionaries | partial | `ContentContext` | `Broadside.Tests.Content.ContentRunTests.The_context_describes_the_page_run` | The page's (inherited) Resources are the run's `ContentContext.Resources`; ColorSpace and Pattern names are looked up by the colour operators (#77, `ColorSpaceCache.FindResource`, allocation-free); ExtGState, Font, XObject, Properties (#56) and Shading (#79) arrive with those operators; forms without Resources inheriting the page's is #56. | | 7.9.1 | General | not started | | | | | 7.9.2 | String object types | partial | `CosString` | `Broadside.Tests.Objects.TextStringTests` | Text strings decode (PDFDocEncoding, UTF-16BE, UTF-8, language escapes removed); encoding text into a string pending | | 7.9.3 | Text streams | not started | | | | @@ -78,7 +78,7 @@ Clause numbers at the second level; split rows to the third level as clauses are | 8.3.2 | Coordinate spaces | partial | `Matrix`, `GraphicsState`, `ContentContext` | `Broadside.Tests.Content.GraphicsStateTests.Cm_premultiplies_the_ctm`, `Broadside.Tests.Content.PathTests.A_stroked_polyline_is_reported_in_user_space_with_the_identity_ctm`, `Broadside.Tests.Content.ContentRunTests.The_context_describes_the_page_run` | 8.3.2.1 to 8.3.2.5. Geometry is reported in user space with the CTM to the run's default user space, which starts at the identity: device space, page rotation, crop and UserUnit are the consumer's (Phase 3). `ContentContext.StreamBaseMatrix` is the base for pattern space (#77/#79). Form space (#56), text and glyph space (#56), image space (#56/#60) arrive with their operators. | | 8.3.3 | Common transformations | done | `Matrix` | `Broadside.Tests.Content.MatrixTests.The_product_applies_the_first_matrix_first`, `Broadside.Tests.Content.GraphicsStateTests.Cm_premultiplies_the_ctm` | Translation and scaling factories; rotation and skew are any six numbers given to `cm`. | | 8.3.4 | Transformation matrices | done | `Matrix` | `Broadside.Tests.Content.MatrixTests`, `Broadside.Tests.Content.GraphicsStateTests.Cm_premultiplies_the_ctm`, `Broadside.Tests.Content.GraphicsStateTests.A_singular_matrix_is_concatenated_as_given` | Row-vector convention, premultiplication (M′ = Mcm × CTM), inverse when one exists; singular matrices are legal and kept as given; elements and coordinates are doubles. | -| 8.4.1 | General | partial | `GraphicsState` | `Broadside.Tests.Content.GraphicsStateTests.A_path_is_painted_with_the_initial_state_of_tables_51_and_52` | Tables 51 and 52 initial values for the CTM, clip, line parameters, rendering intent, flatness, stroke adjustment, blend mode, alpha, alpha source, text knockout, overprint and the text state numbers; the CTM starts at the identity (default user space). Still to come: colour spaces and colours (#77), font, soft mask, transfer, halftone, black generation, undercolour removal, smoothness and black point compensation (#56). Out-of-range numbers are clipped into range with `ContentGraphicsStateRange`. | +| 8.4.1 | General | partial | `GraphicsState` | `Broadside.Tests.Content.GraphicsStateTests.A_path_is_painted_with_the_initial_state_of_tables_51_and_52` | Tables 51 and 52 initial values for the CTM, clip, line parameters, rendering intent, flatness, stroke adjustment, blend mode, alpha, alpha source, text knockout, overprint and the text state numbers; the CTM starts at the identity (default user space). Colour spaces and colours (both DeviceGray black) and black point compensation (Default) since #77. Still to come: font, soft mask, transfer, halftone, black generation, undercolour removal and smoothness (#56). Out-of-range numbers are clipped into range with `ContentGraphicsStateRange`. | | 8.4.2 | Graphics state stack | done | `ContentInterpreter`, `GraphicsState` | `Broadside.Tests.Content.GraphicsStateTests.Q_restores_the_whole_state_saved_by_q`, `Broadside.Tests.Content.GraphicsStateTests.State_stack_events_follow_q_and_q_with_the_depth_after_each`, `Broadside.Tests.Content.GraphicsStateTests.Q_without_q_is_ignored_and_recorded`, `Broadside.Tests.Content.GraphicsStateTests.Unbalanced_q_at_the_end_is_restored_with_implicit_restore_events`, `Broadside.Tests.Content.GraphicsStateTests.A_contents_array_is_one_stream_for_q_and_q`, `Broadside.Tests.Content.GraphicsStateTests.A_q_beyond_the_depth_limit_is_ignored_with_its_q`, `Broadside.Tests.Content.PathTests.The_current_path_survives_q_and_q_does_not_save_it` | q copies the state struct into a pooled stack slot, Q pops to the running stream's floor (`ContentStackUnderflow` below it); unbalanced q at the end is closed with implicit restore events (`ContentUnbalancedSave`); a q beyond `ContentOptions.MaxSaveDepth` (default 4,096) is ignored with its Q (`ContentStackOverflow`). | | 8.4.3 | Details of graphics state parameters | done | `GraphicsState`, `LineCap`, `LineJoin` | `Broadside.Tests.Content.GraphicsStateTests.Each_operator_of_table_56_sets_its_parameter`, `Broadside.Tests.Content.GraphicsStateTests.Dash_patterns_are_normalized_as_8_4_3_6_says`, `Broadside.Tests.Content.GraphicsStateTests.A_negative_line_width_uses_its_absolute_value`, `Broadside.Tests.Content.GraphicsStateTests.Out_of_range_caps_joins_miter_limits_and_flatness_are_clipped_into_range` | 8.4.3.1 to 8.4.3.6 as the interpreter holds them: a negative line width takes its absolute value (as viewers do), a cap or join other than 0 to 2 reads as 0, a miter limit below 1 as 1, a dash array with a negative element or only zeros as solid, a negative dash phase is incremented by twice the sum. Stroking with these parameters (caps, joins, miters, dashes) is the rasterizer's (Phase 3). | | 8.4.4 | Graphics state operators | partial | `ContentInterpreter`, `GraphicsState` | `Broadside.Tests.Content.GraphicsStateTests` | Table 56: q, Q, cm, w, J, j, M, d, ri, i done (an unrecognised intent selects RelativeColorimetric, §8.6.5.8); gs is read and checked but applied from #56. | @@ -87,7 +87,14 @@ Clause numbers at the second level; split rows to the third level as clauses are | 8.5.2 | Path construction operators | done | `PathBuilder`, `PathView`, `PathVerb`, `PathPoint` | `Broadside.Tests.Content.PathTests.A_rectangle_is_a_moveto_three_lines_and_a_close_keeping_the_signs_of_its_size`, `Broadside.Tests.Content.PathTests.The_v_and_y_curves_replicate_the_current_point_and_the_end_point`, `Broadside.Tests.Content.PathTests.A_moveto_after_a_moveto_replaces_it`, `Broadside.Tests.Content.PathTests.A_segment_after_a_close_starts_a_new_subpath_at_the_closed_subpaths_first_point`, `Broadside.Tests.Content.PathTests.A_lineto_without_a_current_point_begins_a_subpath_at_its_end_point`, `Broadside.Tests.Content.PathTests.Coordinates_keep_double_precision` | 8.5.2.1 and 8.5.2.2. Normalized to MoveTo, LineTo, CubicTo, Close (QuadTo is reserved for glyph outlines); re keeps the signs of its size; a segment with no current point begins a subpath at its end point (`ContentNoCurrentPoint`); doubles throughout; no geometry is stored when no processor wants paths or clips. | | 8.5.3 | Path-painting operators | done | `ContentInterpreter`, `PathEvent`, `PathPaint`, `FillRule` | `Broadside.Tests.Content.PathTests.Each_painting_operator_reports_how_it_paints`, `Broadside.Tests.Content.PathTests.Painting_without_a_path_paints_nothing_and_is_recorded`, `Broadside.Tests.Content.PathTests.A_trailing_lone_moveto_is_kept_for_the_renderer_to_ignore`, `Broadside.Tests.Content.PathTests.A_path_left_unpainted_at_the_end_is_discarded_with_an_information_diagnostic` | 8.5.3.1 to 8.5.3.3: Table 59 operators (F read as f), the closing segment of s, b and b* in the path; the path is passed exactly as built: the degenerate-subpath, lone-moveto and implicit-close rules of 8.5.3.2 and 8.5.3.3 are the renderer's (Phase 3). Painting with no path is `ContentNoCurrentPath`. | | 8.5.4 | Clipping path operators | done | `ContentInterpreter`, `ClipArena`, `ClipEvent`, `ClipView`, `ClipKind` | `Broadside.Tests.Content.ClipTests` | W and W* take effect after the painting operator of their path object (`IntersectClip` follows `PaintPath`, so W S is not clipped by its own path); W n only clips; clips are arena nodes chained to their parents by handle, so q/Q restore them by copying an int; W without a path is ignored (`ContentNoCurrentPath`). Text clips (Tr 4-7, at ET) are #56. | -| 8.6 | Colour spaces | not started | | | | +| 8.6.1 | General | done | `PdfColorSpace`, `PdfColor`, `PdfColorConverter` | `Broadside.Tests.Colors.ColorOperatorTests`, `Broadside.Tests.Colors.ColorSpaceFamilyTests` | Colour spaces are live views over their name or array, one shared instance per colour space object (`ColorSpaceCache`); colours are `PdfColor` values (space + up to 32 inline components). | +| 8.6.2 | Colour values | done | `PdfColor`, `ComponentRange` | `Broadside.Tests.Colors.ColorConversionTests.Components_are_clipped_into_their_ranges_before_conversion`, `Broadside.Tests.Colors.ColorSpaceFamilyTests.Lab_ranges_bound_its_components_and_its_initial_colour` | Components are kept as the content stream gives them and clipped into each component's range on conversion. | +| 8.6.3 | Colour space families | done | `PdfColorSpaceFamily`, `PdfColorSpace`, `ColorSpaceCache` | `Broadside.Tests.Colors.ColorSpaceFamilyTests`, `Broadside.Tests.Colors.CorpusColorTests.Every_family_of_colorspace_families_pdf_is_typed_and_painted` | Table 61, every family typed (`colorspace-families.pdf`); names DeviceGray/RGB/CMYK and Pattern never refer to resources; a value that is not a colour space, an unknown family or a space that contains itself reads as DeviceGray (`ColorSpaceInvalid`, `ColorSpaceCycle`, `ColorSpaceTooDeep`); `[/DeviceRGB]` is read with `ColorSpaceEntryInvalid`; minimum versions per family (`MinimumVersion`). | +| 8.6.4 | Device colour spaces | done | `PdfDeviceGrayColorSpace`, `PdfDeviceRgbColorSpace`, `PdfDeviceCmykColorSpace`, `DeviceConverter` | `Broadside.Tests.Colors.ColorOperatorTests.G_g_RG_rg_K_k_select_the_device_space_and_set_the_colour`, `Broadside.Tests.Colors.ColorConversionTests.Gray_and_RGB_convert_by_the_formulas_of_10_4_2_2` | 8.6.4.1 to 8.6.4.4; initial colours 0, 0 0 0, 0 0 0 1. | +| 8.6.5 | CIE-Based colour spaces | partial | `PdfCalGrayColorSpace`, `PdfCalRgbColorSpace`, `PdfLabColorSpace`, `PdfIccBasedColorSpace`, `IccProfileHeader`, `PdfDefaultColorSpaces`, `CieConverter`, `IccAlternateConverter`, `ColorConversion`, `BlackPointCompensation`, `RenderingIntent` | `Broadside.Tests.Colors.ColorSpaceFamilyTests`, `Broadside.Tests.Colors.ColorConversionTests.CalRGB_with_the_sRGB_primaries_and_gamma_1_reproduces_sRGB`, `Broadside.Tests.Colors.ColorConversionTests.Lab_with_a_D50_white_is_adapted_to_the_sRGB_white`, `Broadside.Tests.Colors.ColorConversionTests.Black_point_compensation_maps_the_source_black_point_to_black_unless_it_is_off`, `Broadside.Tests.Colors.ColorConversionTests.An_ICC_Lab_profile_converts_as_Lab_and_another_profile_through_its_alternate`, `Broadside.Tests.Colors.DefaultColorSpaceTests`, `Broadside.Tests.Colors.CorpusColorTests.Default_colour_spaces_of_default_colorspaces_pdf_apply_at_paint_time` | 8.6.5.1-8.6.5.4 done (CalCMYK read as DeviceCMYK; XYZ, Bradford to D65, sRGB); 8.6.5.5 partial: the profile header is read (Tables 66-67), colours convert through the alternate (or as Lab for a Lab profile) until the ICC engine (Phase 3C); 8.6.5.6 done (defaults at paint time from the current resources, nested bases and alternates, never remapped twice, invalid defaults `DefaultColorSpaceInvalid`); 8.6.5.7 informative; 8.6.5.8 intents carried to conversion (absolute colorimetric skips white adaptation), the ICC intents themselves are Phase 3C; 8.6.5.9 black point compensation for CIE spaces, on by default, off under AbsoluteColorimetric (UseBlackPtComp is set by #56). | +| 8.6.6 | Special colour spaces | partial | `PdfPatternColorSpace`, `PdfIndexedColorSpace`, `PdfSeparationColorSpace`, `PdfDeviceNColorSpace`, `PdfDeviceNAttributes`, `PdfDeviceNProcess`, `PdfDeviceNMixingHints`, `TintPipeline`, `IndexedPipeline` | `Broadside.Tests.Colors.ColorSpaceFamilyTests`, `Broadside.Tests.Colors.ColorConversionTests.Indexed_colours_come_from_the_table_scaled_to_the_base_ranges`, `Broadside.Tests.Colors.ColorConversionTests.Separation_tints_go_through_the_tint_transform_to_the_alternate`, `Broadside.Tests.Colors.ColorConversionTests.All_marks_every_colourant_and_None_paints_nothing`, `Broadside.Tests.Colors.CorpusColorTests.All_paints_every_colourant_and_None_paints_nothing_in_separation_special_pdf`, `Broadside.Tests.Colors.ColorRepairTests` | 8.6.6.2-8.6.6.5 read and converted as a display does (always through the alternate; All = 1 - tint, None and all-None DeviceN paint nothing); Indexed tables scale to the base ranges, short tables read zeros; missing tint transforms convert as subtractive ink. NChannel Colorants, Process and MixingHints are read and exposed but not used for blending (separation output, not needed on a display). 8.6.6.6 is examples. | +| 8.6.7 | Overprint control | not started | | | OP, op and OPM are held in `GraphicsState` with their initial values and set through gs by #56; simulating overprint is output-device work. | +| 8.6.8 | Colour operators | done | `ContentInterpreter`, `GraphicsState`, `ContentContext`, `PdfColor` | `Broadside.Tests.Colors.ColorOperatorTests`, `Broadside.Tests.Colors.CorpusColorTests.The_twelve_operators_of_color_operators_pdf_set_fill_and_stroke_colours`, `Broadside.Tests.Colors.CorpusColorTests.Inline_image_colour_spaces_resolve_abbreviations_and_the_abbreviated_Indexed_space`, `Broadside.Tests.Colors.ColorRepairTests`, `Broadside.Tests.Colors.ColorAllocationTests.Setting_colours_in_every_kind_of_space_allocates_nothing_once_warm` | Table 73: CS/cs set the initial colour; SC/sc accepted for ICCBased, Separation and DeviceN with `ContentColorOperatorMismatch`; scn names a pattern (resolved from the current resources, with the stream's base matrix); too few components skip the operator, too many use the last (`ContentColorOperandCount`). Colour operators in d1 glyphs and uncoloured patterns are ignored once #57/#79 set `ContentInterpreter.IgnoresColorOperators`. Allocation-free once warm. | | 8.7 | Patterns | not started | | | | | 8.8 | External objects | not started | | | | | 8.9 | Images | not started | | | | @@ -116,8 +123,8 @@ Clause numbers at the second level; split rows to the third level as clauses are | 9.10 | Extraction of text content | not started | | | | | 10.1 | Rendering: General | not started | | | | | 10.2 | Raster output device native colour | not started | | | | -| 10.3 | CIE-based colour to device colour | not started | | | | -| 10.4 | Conversions among device colour spaces | not started | | | | +| 10.3 | CIE-based colour to device colour | partial | `IColorManagement`, `IColorConverter`, `ManagedColorManagement`, `CieConverter` | `Broadside.Tests.Colors.ColorManagementTests`, `Broadside.Tests.Colors.ColorConversionTests.CalRGB_with_the_sRGB_primaries_and_gamma_1_reproduces_sRGB` | The colour-management extension point (`PdfOptions.UseColorManagement`); the managed default converts CalGray, CalRGB and Lab through XYZ to sRGB and ICCBased through the alternate; conversion through ICC.1:2010 profiles is the Phase 3C engine. | +| 10.4 | Conversions among device colour spaces | done | `DeviceConverter`, `ColorMath`, `CmykCharacterization`, `CmykConversion`, `ColorConversion` | `Broadside.Tests.Colors.ColorConversionTests.Gray_and_RGB_convert_by_the_formulas_of_10_4_2_2`, `Broadside.Tests.Colors.ColorConversionTests.RGB_to_CMYK_follows_the_example_of_10_4_2_3_before_black_generation_and_undercolour_removal`, `Broadside.Tests.Colors.ColorConversionTests.Gray_and_CMYK_convert_by_the_formulas_of_10_4_2_4`, `Broadside.Tests.Colors.ColorConversionTests.Classic_CMYK_to_RGB_is_the_formula_of_10_4_2_5`, `Broadside.Tests.Colors.ColorConversionTests.The_default_CMYK_conversion_approximates_SWOP_printing` | 10.4.2.1-10.4.2.5. BG/UCR from the request (default BG(k) = k, UCR(k) = k); CMYK to RGB by default through a polynomial fitted to CGATS TR 001 (`tools/CmykFit/fit.py`; §10.4.2.1 allows it), the exact 10.4.2.5 formula with `ManagedColorManagement.Classic`. | | 10.5 | Transfer functions | not started | | | | | 10.6 | Halftones | not started | | | | | 10.7 | Scan conversion details | not started | | | | diff --git a/src/Broadside/Content/ContentContext.cs b/src/Broadside/Content/ContentContext.cs index 0f4e17d0..3eddafa8 100644 --- a/src/Broadside/Content/ContentContext.cs +++ b/src/Broadside/Content/ContentContext.cs @@ -1,5 +1,8 @@ +using Broadside.Diagnostics; using Broadside.Graphics; +using Broadside.Graphics.Colors; using Broadside.Objects; +using Broadside.Parsing; namespace Broadside.Content; @@ -61,9 +64,91 @@ public sealed class ContentContext /// Gets the token that cancels the run. public CancellationToken CancellationToken { get; internal set; } + /// + /// Gets the default colour spaces of the current resources, which replace the device spaces of what is painted now: pass them to + /// with the colour being painted. + /// + /// + /// ISO 32000-2 §8.6.5.6: the look-up uses the resources current when the object is painted, so inside a form XObject the form's + /// own defaults apply. The initial DeviceGray colour is remapped too. + /// + public PdfDefaultColorSpaces DefaultColorSpaces => Document.ColorSpaces.GetDefaults(Resources); + + /// Returns the colour space a value names in the running content stream. + /// + /// A name, as the operand of CS and cs (DeviceGray, DeviceRGB, DeviceCMYK and Pattern name those spaces; any other + /// name is looked up in the ColorSpace subdictionary of ), or a colour space array. + /// + /// The space; DeviceGray, with a diagnostic, when the value names none. + /// ISO 32000-2 §8.6.8, Table 73; §7.8.3. + public PdfColorSpace GetColorSpace(CosObject colorSpace) + { + ArgumentNullException.ThrowIfNull(colorSpace); + CosReference? owner = CurrentStream ?? Page?.Reference; + if (Document.Resolve(colorSpace) is not CosName name) + { + return Document.ColorSpaces.Get(colorSpace, owner); + } + + PdfColorSpace? space = Document.ColorSpaces.FindNamed(Resources, name.Bytes, owner, out NamedLookup lookup); + ReportLookup(lookup, name); + return space ?? PdfDeviceGrayColorSpace.Instance; + } + + /// Returns the colour space of an inline image's ColorSpace (or CS) entry. + /// The entry's value, such as from . + /// The space; DeviceGray, with a diagnostic, when the value names none. + /// + /// ISO 32000-2 §8.9.7, Tables 91 and 92: the abbreviations G, RGB, CMYK and I (Indexed, whose base may be abbreviated and whose + /// lookup table is a string) are allowed, and the full device names; G, RGB, CMYK and the device names never refer to resources, + /// any other name is a key of the ColorSpace subdictionary of the current resources (PDF 1.2). + /// + public PdfColorSpace GetInlineImageColorSpace(CosObject colorSpace) + { + ArgumentNullException.ThrowIfNull(colorSpace); + CosReference? owner = CurrentStream ?? Page?.Reference; + if (Document.ColorSpaces.FindInline(colorSpace, owner) is { } space) + { + return space; + } + + if (colorSpace is CosName name) + { + PdfColorSpace? named = Document.ColorSpaces.FindNamed(Resources, name.Bytes, owner, out NamedLookup lookup); + ReportLookup(lookup == NamedLookup.Abbreviation ? NamedLookup.Family : lookup, name); + return named ?? PdfDeviceGrayColorSpace.Instance; + } + + Document.ColorSpaces.ReportFailure(owner, ColorSpaceFailure.Invalid, "an inline image's colour space"); + return PdfDeviceGrayColorSpace.Instance; + } + /// Returns the clip node a clip handle refers to, such as . /// The handle; 0 for the run's initial clipping path. /// The node; a node of kind for 0 and for a handle this run did not issue. /// ISO 32000-2 §8.5.4. public ClipView GetClip(int handle) => _interpreter.Clips.Get(handle); + + private void ReportLookup(NamedLookup lookup, CosName name) + { + CosReference? owner = CurrentStream ?? Page?.Reference; + if (lookup == NamedLookup.Missing) + { + Document.DiagnosticSink.Report( + DiagnosticCodes.ContentColorSpaceMissing, + DiagnosticSeverity.Warning, + $"The colour space /{name.Value} is not in the resources' ColorSpace dictionary; DeviceGray is used.", + offset: null, + owner); + } + else if (lookup == NamedLookup.Abbreviation) + { + Document.DiagnosticSink.Report( + DiagnosticCodes.ContentColorSpaceAbbreviated, + DiagnosticSeverity.Warning, + $"The colour space /{name.Value} is an inline image abbreviation used outside an inline image; it is read as the device space.", + offset: null, + owner); + } + } } diff --git a/src/Broadside/Content/ContentInterpreter.Color.cs b/src/Broadside/Content/ContentInterpreter.Color.cs index db6ae25b..b553764b 100644 --- a/src/Broadside/Content/ContentInterpreter.Color.cs +++ b/src/Broadside/Content/ContentInterpreter.Color.cs @@ -1,16 +1,181 @@ +using Broadside.Graphics; +using Broadside.Graphics.Colors; +using Broadside.Objects; + namespace Broadside.Content; /// The colour operators of Table 73: CS cs SC SCN sc scn G g RG rg K k. /// -/// ISO 32000-2 §8.6.8. Operands are checked by the core; colour spaces and colour values are resolved into the graphics state from -/// issue #77. +/// +/// ISO 32000-2 §8.6.8. CS/cs select a colour space and its initial colour; the device names and Pattern name those +/// spaces, any other name is looked up in the current resources' ColorSpace subdictionary. SC/sc take one +/// number per component; SCN/scn also accept Pattern (the pattern's name last, after the underlying space's +/// components for an uncoloured pattern), Separation, DeviceN and ICCBased. G g RG rg K k select DeviceGray, DeviceRGB or +/// DeviceCMYK and set the colour. The graphics state keeps the space the operator selected; default colour spaces apply when painting. +/// +/// +/// Repairs, each recorded once per run: a name not in the resources reads as DeviceGray (an abbreviation G, RGB or CMYK as the +/// device space); too few components skip the operator, too many use the last ones; sc in a Pattern space, scn with a +/// name in another space and scn without a name in a Pattern space are skipped; SC/sc in a space that wants +/// SCN/scn is accepted. Allocates nothing once the spaces are cached. +/// /// internal sealed partial class ContentInterpreter { - private static void ExecuteColor(ContentOperatorCode code, ContentOperands operands, int offset) + private readonly float[] _colorScratch = new float[PdfColor.MaxComponents]; + + /// + /// Gets or sets a value indicating whether colour operators are ignored, as inside a Type 3 glyph described with d1 or an + /// uncoloured tiling pattern (§8.6.8: PDF 2.0 ignores them there). Set by the nested runs of issues #57 and #79. + /// + internal bool IgnoresColorOperators { get; set; } + + private void ExecuteColor(ContentOperatorCode code, ContentOperands operands, int offset) + { + if (IgnoresColorOperators) + { + Report(ContentIssue.ColorOperatorIgnored, offset, "A colour operator inside a d1 glyph or an uncoloured pattern, where colours shall not be specified; ignored."); + return; + } + + switch (code) + { + case ContentOperatorCode.SetStrokeColorSpace or ContentOperatorCode.SetFillColorSpace: + SetColorSpace(code == ContentOperatorCode.SetStrokeColorSpace, operands[0].Bytes, offset); + break; + case ContentOperatorCode.SetStrokeGray or ContentOperatorCode.SetFillGray: + SetDeviceColor(code == ContentOperatorCode.SetStrokeGray, PdfDeviceGrayColorSpace.Instance, operands); + break; + case ContentOperatorCode.SetStrokeRgb or ContentOperatorCode.SetFillRgb: + SetDeviceColor(code == ContentOperatorCode.SetStrokeRgb, PdfDeviceRgbColorSpace.Instance, operands); + break; + case ContentOperatorCode.SetStrokeCmyk or ContentOperatorCode.SetFillCmyk: + SetDeviceColor(code == ContentOperatorCode.SetStrokeCmyk, PdfDeviceCmykColorSpace.Instance, operands); + break; + case ContentOperatorCode.SetStrokeColor or ContentOperatorCode.SetFillColor: + SetColor(code == ContentOperatorCode.SetStrokeColor, operands, extended: false, offset); + break; + default: + SetColor(code == ContentOperatorCode.SetStrokeColorExtended, operands, extended: true, offset); + break; + } + } + + /// CS/cs: selects the space and its initial colour (Table 73). + private void SetColorSpace(bool stroke, ReadOnlySpan name, int offset) + { + ColorSpaceCache spaces = _context.Document.ColorSpaces; + PdfColorSpace? space = spaces.FindNamed(_context.Resources, name, CurrentStream ?? _fallbackReference, out NamedLookup lookup); + if (lookup == NamedLookup.Missing) + { + Report(ContentIssue.ColorSpaceMissing, offset, "A colour space name that is neither a family name nor in the resources' ColorSpace dictionary; DeviceGray is used."); + } + else if (lookup == NamedLookup.Abbreviation) + { + Report(ContentIssue.ColorSpaceAbbreviated, offset, "An inline image abbreviation (G, RGB or CMYK) names a colour space outside an inline image; it is read as the device space."); + } + + space ??= PdfDeviceGrayColorSpace.Instance; + if (space.ComponentCount > PdfColor.MaxComponents && space is PdfDeviceNColorSpace deviceN) + { + Report(ContentIssue.ColorComponentLimit, offset, "A DeviceN colour space has more than 32 colourants; colours are set in its alternate space."); + space = deviceN.Alternate; + } + + State.SetColor(stroke, space.GetInitialColor()); + } + + /// G g RG rg K k: the operands were checked against the operator's fixed count. + private void SetDeviceColor(bool stroke, PdfColorSpace space, ContentOperands operands) + { + Span components = stackalloc float[4]; + int count = space.ComponentCount; + for (int i = 0; i < count; i++) + { + components[i] = Component(operands[i].Number); + } + + State.SetColor(stroke, new PdfColor(space, components[..count])); + } + + /// SC sc SCN scn. + private void SetColor(bool stroke, ContentOperands operands, bool extended, int offset) { - _ = code; - _ = operands; - _ = offset; + PdfColorSpace space = stroke ? State.StrokeColor.ColorSpace : State.FillColor.ColorSpace; + int count = operands.Count; + bool named = operands[count - 1].Kind == ContentOperandKind.Name; + int numbers = named ? count - 1 : count; + if (space is PdfPatternColorSpace pattern) + { + if (!extended || !named) + { + Report(ContentIssue.ColorOperatorInvalid, offset, "In a Pattern colour space only scn and SCN with a pattern name set the colour; the operator is skipped."); + return; + } + + if (TakeComponents(operands, numbers, pattern.ComponentCount, offset, out Span components)) + { + SetPattern(stroke, pattern, components, operands[count - 1].Bytes, offset); + } + + return; + } + + if (named) + { + Report(ContentIssue.ColorOperatorInvalid, offset, "scn or SCN with a name in a colour space that is not Pattern; the operator is skipped."); + return; + } + + if (!extended && space.Family is PdfColorSpaceFamily.IccBased or PdfColorSpaceFamily.Separation or PdfColorSpaceFamily.DeviceN) + { + Report(ContentIssue.ColorOperatorMismatch, offset, "sc or SC in an ICCBased, Separation or DeviceN colour space, which take scn and SCN; the colour is set anyway."); + } + + if (TakeComponents(operands, numbers, Math.Min(space.ComponentCount, PdfColor.MaxComponents), offset, out Span values)) + { + State.SetColor(stroke, new PdfColor(space, values)); + } + } + + /// Reads the last numbers; too few skip the operator, too many are reported. + private bool TakeComponents(ContentOperands operands, int numbers, int expected, int offset, out Span components) + { + components = default; + if (numbers < expected) + { + Report(ContentIssue.ColorOperandCount, offset, "A colour operator has fewer components than its colour space; the operator is skipped."); + return false; + } + + if (numbers > expected) + { + Report(ContentIssue.ColorOperandCount, offset, "A colour operator has more components than its colour space; the last ones are used."); + } + + components = _colorScratch.AsSpan(0, expected); + for (int i = 0; i < expected; i++) + { + components[i] = Component(operands[numbers - expected + i].Number); + } + + return true; + } + + /// Sets a Pattern colour: the pattern from the current resources and the matrix of the stream that names it (§8.7.2). + private void SetPattern(bool stroke, PdfPatternColorSpace space, ReadOnlySpan components, ReadOnlySpan name, int offset) + { + ColorSpaceCache spaces = _context.Document.ColorSpaces; + CosObject? value = spaces.FindResource(_context.Resources, ColorSpaceNames.Pattern, name, out CosName? key); + if (value is null) + { + Report(ContentIssue.PatternMissing, offset, "scn names a pattern that is not in the resources' Pattern dictionary; the colour paints nothing."); + } + + CosObject? pattern = value is null ? null : spaces.Resolve(value); + State.SetColor(stroke, new PdfColor(space, components, key, pattern, _context.StreamBaseMatrix)); } + + /// A component as stored: the operand's value, kept within the float range. + private static float Component(double value) => (float)Math.Clamp(value, -float.MaxValue, float.MaxValue); } diff --git a/src/Broadside/Content/ContentInterpreter.cs b/src/Broadside/Content/ContentInterpreter.cs index fb872fc4..f73085cd 100644 --- a/src/Broadside/Content/ContentInterpreter.cs +++ b/src/Broadside/Content/ContentInterpreter.cs @@ -219,6 +219,7 @@ private void Begin(PdfDocument document, PdfPage? page, ContentProcessor process _part = 0; _inText = false; _pendingClip = null; + IgnoresColorOperators = false; _maxSaveDepth = options.MaxSaveDepth; _arena.Limit = options.MaxOperands; _path.Accumulate = (_events & (ContentEvents.Paths | ContentEvents.Clips)) != 0; diff --git a/src/Broadside/Content/ContentIssue.cs b/src/Broadside/Content/ContentIssue.cs index cb8b8eb9..9b93f257 100644 --- a/src/Broadside/Content/ContentIssue.cs +++ b/src/Broadside/Content/ContentIssue.cs @@ -29,6 +29,14 @@ internal enum ContentIssue CompatibilityUnbalanced, TextObjectUnbalanced, InlineImageInvalid, + ColorSpaceMissing, + ColorSpaceAbbreviated, + ColorOperandCount, + ColorOperatorMismatch, + ColorOperatorInvalid, + ColorOperatorIgnored, + PatternMissing, + ColorComponentLimit, } /// The code and severity of each . @@ -53,12 +61,21 @@ internal static class ContentIssues ContentIssue.GraphicsStateRange => DiagnosticCodes.ContentGraphicsStateRange, ContentIssue.CompatibilityUnbalanced => DiagnosticCodes.ContentCompatibilityUnbalanced, ContentIssue.TextObjectUnbalanced => DiagnosticCodes.ContentTextObjectUnbalanced, + ContentIssue.ColorSpaceMissing => DiagnosticCodes.ContentColorSpaceMissing, + ContentIssue.ColorSpaceAbbreviated => DiagnosticCodes.ContentColorSpaceAbbreviated, + ContentIssue.ColorOperandCount => DiagnosticCodes.ContentColorOperandCount, + ContentIssue.ColorOperatorMismatch => DiagnosticCodes.ContentColorOperatorMismatch, + ContentIssue.ColorOperatorInvalid => DiagnosticCodes.ContentColorOperatorInvalid, + ContentIssue.ColorOperatorIgnored => DiagnosticCodes.ContentColorOperatorIgnored, + ContentIssue.PatternMissing => DiagnosticCodes.ContentPatternMissing, + ContentIssue.ColorComponentLimit => DiagnosticCodes.ColorComponentLimitExceeded, _ => DiagnosticCodes.ContentInlineImageInvalid, }; public static DiagnosticSeverity Severity(ContentIssue issue) => issue switch { - ContentIssue.GluedTokens or ContentIssue.OperatorOutOfContext or ContentIssue.PathNotPainted => DiagnosticSeverity.Information, + ContentIssue.GluedTokens or ContentIssue.OperatorOutOfContext or ContentIssue.PathNotPainted or ContentIssue.ColorComponentLimit + => DiagnosticSeverity.Information, _ => DiagnosticSeverity.Warning, }; } diff --git a/src/Broadside/EngineConfiguration.cs b/src/Broadside/EngineConfiguration.cs index 0a451b27..8d996988 100644 --- a/src/Broadside/EngineConfiguration.cs +++ b/src/Broadside/EngineConfiguration.cs @@ -1,5 +1,6 @@ using Broadside.Diagnostics; using Broadside.Filters; +using Broadside.Graphics; using Broadside.Security; using Microsoft.Extensions.Logging; @@ -42,6 +43,9 @@ internal sealed class EngineConfiguration /// Gets the credentials offered to encrypted documents opened without their own (issue #42). public PdfCredentials? Credentials { get; private init; } + /// Gets the colour management colours are converted through (issue #77). + public IColorManagement ColorManagement { get; private init; } = ManagedColorManagement.Default; + /// Gets how many bytes of a non-seekable stream are copied into memory before a temporary file is used (issue #45). public long StreamBufferLimit { get; private init; } = PdfOptions.DefaultStreamBufferLimit; @@ -58,5 +62,6 @@ internal sealed class EngineConfiguration SecurityHandlers = options.SecurityHandlers.Count == 0 ? SecurityHandlerRegistry.Default : SecurityHandlerRegistry.Create(options.SecurityHandlers), Credentials = options.Credentials, StreamBufferLimit = options.StreamBufferLimit, + ColorManagement = options.ColorManagement, }; } diff --git a/src/Broadside/Graphics/BlackPointCompensation.cs b/src/Broadside/Graphics/BlackPointCompensation.cs new file mode 100644 index 00000000..d62efffc --- /dev/null +++ b/src/Broadside/Graphics/BlackPointCompensation.cs @@ -0,0 +1,19 @@ +namespace Broadside.Graphics; + +/// Whether conversions between colour spaces compensate for the difference between their black points. +/// +/// ISO 32000-2 §8.6.5.9 and Table 57 (UseBlackPtComp, PDF 2.0): ON, OFF or Default, which leaves it to +/// the processor; Broadside's managed colour management compensates by default. With the AbsoluteColorimetric intent black +/// point compensation is never applied. +/// +public enum BlackPointCompensation +{ + /// Default, the initial value (Table 52): the processor decides. + Default, + + /// ON. + On, + + /// OFF. + Off, +} diff --git a/src/Broadside/Graphics/CieXyz.cs b/src/Broadside/Graphics/CieXyz.cs new file mode 100644 index 00000000..14ef4351 --- /dev/null +++ b/src/Broadside/Graphics/CieXyz.cs @@ -0,0 +1,15 @@ +namespace Broadside.Graphics; + +/// A CIE 1931 XYZ tristimulus value, such as the white or black point of a CIE-based colour space. +/// X. +/// Y. +/// Z. +/// ISO 32000-2 §8.6.5.1 and Tables 62 to 64 (WhitePoint, BlackPoint). +public readonly record struct CieXyz(double X, double Y, double Z) +{ + /// Gets the CIE standard illuminant D65, the white of sRGB (IEC 61966-2-1), used when a white point is unusable. + public static CieXyz D65 { get; } = new(0.95047, 1.0, 1.08883); + + /// Gets the CIE standard illuminant D50, the white of the ICC profile connection space (ICC.1:2022 §6.3.2). + public static CieXyz D50 { get; } = new(0.9642, 1.0, 0.8249); +} diff --git a/src/Broadside/Graphics/CmykConversion.cs b/src/Broadside/Graphics/CmykConversion.cs new file mode 100644 index 00000000..815507d2 --- /dev/null +++ b/src/Broadside/Graphics/CmykConversion.cs @@ -0,0 +1,18 @@ +namespace Broadside.Graphics; + +/// How converts DeviceCMYK to RGB and gray. +/// ISO 32000-2 §10.4.2.4 and §10.4.2.5. +public enum CmykConversion +{ + /// + /// The default: a polynomial fitted to the CGATS TR 001 (SWOP) characterisation data, close to what viewers using a SWOP + /// profile show (100 % cyan is about (0, 0.69, 0.94), not (0, 1, 1)); gray is then 0.3 r + 0.59 g + 0.11 b of that colour. + /// + Characterized, + + /// + /// The formulas of §10.4.2: red = 1 − min(1, c + k), green = 1 − min(1, m + k), blue = 1 − min(1, y + k), and gray = + /// 1 − min(1, 0.3 c + 0.59 m + 0.11 y + k), which §10.4.2.1 calls crude approximations. + /// + Classic, +} diff --git a/src/Broadside/Graphics/ColorConversion.cs b/src/Broadside/Graphics/ColorConversion.cs new file mode 100644 index 00000000..be88dd7c --- /dev/null +++ b/src/Broadside/Graphics/ColorConversion.cs @@ -0,0 +1,44 @@ +namespace Broadside.Graphics; + +/// What a colour is converted to and how: the device colour model, the rendering intent and the device-dependent controls. +/// +/// ISO 32000-2 §8.6.5.8 (rendering intents), §8.6.5.9 (black point compensation) and §10.4.2.3 (black generation and undercolour +/// removal, used only when converting to CMYK). The default value converts to RGB with the relative colorimetric intent and the +/// processor's choice of black point compensation. +/// +public readonly record struct ColorConversion +{ + /// Gets the device colour model converted to. + public DeviceColorModel Target { get; init; } + + /// Gets the rendering intent. + /// ISO 32000-2 §8.6.5.8, Table 69. + public RenderingIntent Intent { get; init; } + + /// Gets whether black point compensation is applied. + /// ISO 32000-2 §8.6.5.9. + public BlackPointCompensation BlackPointCompensation { get; init; } + + /// Gets the black-generation function (one input k, one output 0 to 1), or for the default BG(k) = k. + /// ISO 32000-2 §10.4.2.3 and Table 57 (BG, BG2). Used only when converting RGB to CMYK. + public PdfFunction? BlackGeneration { get; init; } + + /// Gets the undercolour-removal function (one input k, one output −1 to 1), or for the default UCR(k) = k. + /// ISO 32000-2 §10.4.2.3 and Table 57 (UCR, UCR2). Used only when converting RGB to CMYK. + public PdfFunction? UndercolorRemoval { get; init; } + + /// Gets a value indicating whether black point compensation applies: on unless it is off or the intent is absolute colorimetric. + /// ISO 32000-2 §8.6.5.9: with AbsoluteColorimetric "black point compensation shall not be used". + public bool CompensatesBlackPoint => BlackPointCompensation != BlackPointCompensation.Off && Intent != RenderingIntent.AbsoluteColorimetric; + + /// Returns the conversion the graphics state asks for: its rendering intent and black point compensation. + /// The graphics state. + /// The device colour model converted to. + /// The conversion. + public static ColorConversion FromState(in GraphicsState state, DeviceColorModel target) => new() + { + Target = target, + Intent = state.RenderingIntent, + BlackPointCompensation = state.BlackPointCompensation, + }; +} diff --git a/src/Broadside/Graphics/Colors/CieChecks.cs b/src/Broadside/Graphics/Colors/CieChecks.cs new file mode 100644 index 00000000..02eae92c --- /dev/null +++ b/src/Broadside/Graphics/Colors/CieChecks.cs @@ -0,0 +1,44 @@ +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Graphics.Colors; + +/// The checks the CIE dictionaries share (ISO 32000-2 Tables 62 to 64). +internal static class CieChecks +{ + /// Records a missing or invalid WhitePoint and an invalid BlackPoint. + /// The space reporting. + /// The document's colour spaces. + /// The CIE dictionary. + /// The family name, for the message. + public static void WhiteAndBlack(PdfColorSpace space, ColorSpaceCache cache, CosDictionary dictionary, string family) + { + if (ColorEntries.WhitePoint(cache, dictionary) is null) + { + space.Report( + DiagnosticCodes.ColorSpaceEntryInvalid, + $"A {family} WhitePoint is missing or invalid (it shall be three numbers with X and Z positive and Y 1.0); D65 is used."); + } + + if (ColorEntries.BlackPoint(cache, dictionary, out bool present) is null && present) + { + space.Report(DiagnosticCodes.ColorSpaceEntryInvalid, $"A {family} BlackPoint is not three non-negative numbers; [0 0 0] is used."); + } + } + + /// Returns the dictionary at element 1 of a CIE space array, reporting when it is missing. + /// The space. + /// The resolved element 1. + /// The family name, for the message. + /// The dictionary, or . + public static CosDictionary? Dictionary(PdfColorSpace space, CosObject value, string family) + { + if (value is CosDictionary dictionary) + { + return dictionary; + } + + space.Report(DiagnosticCodes.ColorSpaceEntryInvalid, $"A {family} colour space has no dictionary; its entries take their defaults and D65 is used as the white point."); + return null; + } +} diff --git a/src/Broadside/Graphics/Colors/CieConverter.cs b/src/Broadside/Graphics/Colors/CieConverter.cs new file mode 100644 index 00000000..5213b107 --- /dev/null +++ b/src/Broadside/Graphics/Colors/CieConverter.cs @@ -0,0 +1,135 @@ +namespace Broadside.Graphics.Colors; + +/// Converts CalGray, CalRGB and Lab colours (and Lab-based ICC profiles) through CIE XYZ to sRGB, then to the target model. +/// +/// +/// ISO 32000-2 §8.6.5.2 to §8.6.5.4 give XYZ relative to the space's white point; §10.3 leaves the CIE to device step to colour +/// management. The pipeline: clip the components into range; compute XYZ; with black point compensation (§8.6.5.9), scale each +/// tristimulus value, normalised to the white, so the black point maps to zero; adapt from the white point to D65 with the Bradford +/// transform (none for the absolute colorimetric intent); take XYZ to linear sRGB and encode it (IEC 61966-2-1); RGB then goes to +/// gray or CMYK by §10.4.2. +/// +/// +/// pdf.js approximates CalGray and Lab differently, so renders differ slightly from it; this is the colorimetric result. +/// +/// +internal sealed class CieConverter : IColorConverter +{ + private readonly PdfColorSpaceFamily _family; + private readonly ColorConversion _conversion; + private readonly CieXyz _white; + private readonly double[] _black; + private readonly bool _compensate; + private readonly double[] _gamma; + private readonly double[] _matrix; + private readonly double[] _ranges; + private readonly double[] _toSrgb; + + private CieConverter(PdfColorSpaceFamily family, ColorConversion conversion, CieXyz white, CieXyz black, double[] gamma, double[] matrix, double[] ranges) + { + _family = family; + _conversion = conversion; + _white = white; + _black = [black.X / white.X, black.Y / white.Y, black.Z / white.Z]; + _compensate = conversion.CompensatesBlackPoint && (black.X > 0 || black.Y > 0 || black.Z > 0) && _black.All(static b => b < 1); + _gamma = gamma; + _matrix = matrix; + _ranges = ranges; + _toSrgb = ColorMath.XyzToLinearSrgb(conversion.Intent == RenderingIntent.AbsoluteColorimetric ? null : white); + InputCount = family == PdfColorSpaceFamily.CalGray ? 1 : 3; + OutputCount = DeviceConverter.Outputs(conversion.Target); + } + + /// + public int InputCount { get; } + + /// + public int OutputCount { get; } + + /// Creates the converter for a CalGray space. + public static CieConverter ForCalGray(PdfCalGrayColorSpace space, ColorConversion conversion) => + new(PdfColorSpaceFamily.CalGray, conversion, space.WhitePoint, space.BlackPoint, [space.Gamma], [], []); + + /// Creates the converter for a CalRGB space. + public static CieConverter ForCalRgb(PdfCalRgbColorSpace space, ColorConversion conversion) => + new(PdfColorSpaceFamily.CalRgb, conversion, space.WhitePoint, space.BlackPoint, [.. space.Gamma], [.. space.Matrix], []); + + /// Creates the converter for a Lab space. + public static CieConverter ForLab(PdfLabColorSpace space, ColorConversion conversion) => + new(PdfColorSpaceFamily.Lab, conversion, space.WhitePoint, space.BlackPoint, [], [], [0, 100, .. space.Range]); + + /// Creates the converter for an ICC profile whose data colour space is Lab: D50 white (the PCS), ranges from the space. + public static CieConverter ForIccLab(PdfIccBasedColorSpace space, ColorConversion conversion) => + new(PdfColorSpaceFamily.Lab, conversion, CieXyz.D50, default, [], [], [.. space.Range]); + + /// + public void Convert(ReadOnlySpan source, Span destination, int count) + { + int inputs = InputCount; + int outputs = OutputCount; + Span xyz = stackalloc double[3]; + Span rgb = stackalloc double[3]; + for (int i = 0; i < count; i++) + { + ToXyz(source.Slice(i * inputs, inputs), xyz); + if (_compensate) + { + Compensate(xyz); + } + + ColorMath.Apply(_toSrgb, xyz[0], xyz[1], xyz[2], rgb); + ColorMath.FromRgb( + ColorMath.EncodeSrgb(rgb[0]), + ColorMath.EncodeSrgb(rgb[1]), + ColorMath.EncodeSrgb(rgb[2]), + destination.Slice(i * outputs, outputs), + _conversion); + } + } + + private void ToXyz(ReadOnlySpan input, Span xyz) + { + switch (_family) + { + case PdfColorSpaceFamily.CalGray: + // §8.6.5.2: X = XW·A^G, Y = YW·A^G, Z = ZW·A^G. + double a = Math.Pow(ColorMath.Clamp01(input[0]), _gamma[0]); + xyz[0] = _white.X * a; + xyz[1] = _white.Y * a; + xyz[2] = _white.Z * a; + break; + case PdfColorSpaceFamily.CalRgb: + // §8.6.5.3: X = XA·A^GR + XB·B^GG + XC·C^GB, likewise Y and Z; Matrix = [XA YA ZA XB YB ZB XC YC ZC]. + double ag = Math.Pow(ColorMath.Clamp01(input[0]), _gamma[0]); + double bg = Math.Pow(ColorMath.Clamp01(input[1]), _gamma[1]); + double cg = Math.Pow(ColorMath.Clamp01(input[2]), _gamma[2]); + xyz[0] = (_matrix[0] * ag) + (_matrix[3] * bg) + (_matrix[6] * cg); + xyz[1] = (_matrix[1] * ag) + (_matrix[4] * bg) + (_matrix[7] * cg); + xyz[2] = (_matrix[2] * ag) + (_matrix[5] * bg) + (_matrix[8] * cg); + break; + default: + // §8.6.5.4: M = (L* + 16) / 116, L = M + a* / 500, N = M − b* / 200; X = XW·g(L), Y = YW·g(M), Z = ZW·g(N). + double lightness = Clip(input[0], _ranges[0], _ranges[1]); + double astar = Clip(input[1], _ranges[2], _ranges[3]); + double bstar = Clip(input[2], _ranges[4], _ranges[5]); + double mid = (lightness + 16) / 116; + xyz[0] = _white.X * ColorMath.LabG(mid + (astar / 500)); + xyz[1] = _white.Y * ColorMath.LabG(mid); + xyz[2] = _white.Z * ColorMath.LabG(mid - (bstar / 200)); + break; + } + } + + /// + /// Black point compensation with a black destination: each tristimulus value, relative to the white, is scaled so the source + /// black point lands on zero while the white stays (ISO 32000-2 §8.6.5.9; Adobe's algorithm with the sRGB black of 0). + /// + private void Compensate(Span xyz) + { + xyz[0] = _white.X * (((xyz[0] / _white.X) - _black[0]) / (1 - _black[0])); + xyz[1] = _white.Y * (((xyz[1] / _white.Y) - _black[1]) / (1 - _black[1])); + xyz[2] = _white.Z * (((xyz[2] / _white.Z) - _black[2]) / (1 - _black[2])); + } + + private static double Clip(double value, double minimum, double maximum) => value >= minimum ? Math.Min(value, maximum) : minimum; +} diff --git a/src/Broadside/Graphics/Colors/CmykCharacterization.cs b/src/Broadside/Graphics/Colors/CmykCharacterization.cs new file mode 100644 index 00000000..9babd854 --- /dev/null +++ b/src/Broadside/Graphics/Colors/CmykCharacterization.cs @@ -0,0 +1,115 @@ +namespace Broadside.Graphics.Colors; + +/// +/// DeviceCMYK to sRGB through a cubic polynomial per channel fitted to the CGATS TR 001 (SWOP) characterisation data: what +/// uses until the ICC engine (Phase 3) converts through a real CMYK profile. +/// +/// +/// +/// ISO 32000-2 §10.4.2.1 allows any conversion where the formulas of §10.4.2.4 and §10.4.2.5 are "crude approximations". The +/// coefficients come from tools/CmykFit/fit.py: the 928 IT8.7/3 patches of ANSI CGATS TR 001-1995 (TR001CLR.AVG, CIELAB +/// D50), media-relative to the paper, Bradford-adapted to D65, encoded as sRGB, clipped, then a least-squares fit of 1 plus the 34 +/// monomials c^i m^j y^l k^n of degree 1 to 3 per channel. The constant 1 keeps 0 0 0 0 exactly white. Fit error: RMS 3.8, maximum +/// 59 (in a cyan region where sRGB clips) in 8-bit units. +/// +/// +/// No black point compensation is built in: 0 0 0 1 is the measured SWOP black, about (54, 53, 54) in 8-bit sRGB. +/// +/// +internal static class CmykCharacterization +{ + // Term order after the constant 1 (exponents of c, m, y, k): + // k, y, m, c, k², yk, y², mk, my, m², ck, cy, cm, c², k³, yk², y²k, y³, mk², myk, my², m²k, m²y, m³, + // ck², cyk, cy², cmk, cmy, cm², c²k, c²y, c²m, c³. + private static readonly double[] Red = + [ + -0.803180, 0.071494, -0.068862, -1.101559, -0.056887, + -0.114768, -0.113958, 0.142824, -0.079101, 0.028996, + 0.966668, 0.277752, 0.360922, 0.026293, 0.091580, + 0.051949, 0.033237, 0.064307, -0.012075, 0.040213, + 0.027756, -0.050177, 0.015752, -0.039471, -0.069774, + -0.059045, -0.050329, -0.316786, -0.033123, 0.063312, + 0.010640, -0.156283, -0.008079, -0.027286, + ]; + + private static readonly double[] Green = + [ + -0.803683, -0.066935, -0.805601, -0.399815, 0.034791, + 0.046780, -0.000014, 0.649890, 0.080141, 0.133329, + 0.382238, 0.049054, 0.403126, 0.093551, -0.008413, + -0.001591, -0.008639, 0.013069, 0.016473, -0.045031, + -0.027600, 0.034470, 0.036746, -0.153136, -0.040624, + -0.002809, -0.011811, -0.358493, -0.040933, 0.070848, + -0.059523, -0.009579, -0.089144, -0.006788, + ]; + + private static readonly double[] Blue = + [ + -0.757823, -0.806179, -0.468566, -0.066118, 0.014424, + 0.632180, 0.072745, 0.359828, 0.496836, 0.028606, + 0.039023, 0.208200, 0.038686, 0.004309, -0.023342, + 0.013525, 0.042963, -0.086250, 0.009252, -0.357426, + 0.035014, -0.024201, -0.066334, 0.005588, 0.005169, + -0.166013, 0.079875, -0.001326, -0.157697, 0.019153, + 0.013494, -0.060840, 0.020458, -0.002912, + ]; + + /// Converts one CMYK colour (each 0 to 1, already clipped) to encoded sRGB, each 0 to 1. + /// Cyan. + /// Magenta. + /// Yellow. + /// Black. + /// Three values. + public static void ToRgb(double c, double m, double y, double k, Span rgb) + { + Span terms = stackalloc double[34]; + terms[0] = k; + terms[1] = y; + terms[2] = m; + terms[3] = c; + terms[4] = k * k; + terms[5] = y * k; + terms[6] = y * y; + terms[7] = m * k; + terms[8] = m * y; + terms[9] = m * m; + terms[10] = c * k; + terms[11] = c * y; + terms[12] = c * m; + terms[13] = c * c; + terms[14] = k * k * k; + terms[15] = y * k * k; + terms[16] = y * y * k; + terms[17] = y * y * y; + terms[18] = m * k * k; + terms[19] = m * y * k; + terms[20] = m * y * y; + terms[21] = m * m * k; + terms[22] = m * m * y; + terms[23] = m * m * m; + terms[24] = c * k * k; + terms[25] = c * y * k; + terms[26] = c * y * y; + terms[27] = c * m * k; + terms[28] = c * m * y; + terms[29] = c * m * m; + terms[30] = c * c * k; + terms[31] = c * c * y; + terms[32] = c * c * m; + terms[33] = c * c * c; + rgb[0] = ColorMath.Clamp01(1 + Dot(Red, terms)); + rgb[1] = ColorMath.Clamp01(1 + Dot(Green, terms)); + rgb[2] = ColorMath.Clamp01(1 + Dot(Blue, terms)); + } + + private static double Dot(ReadOnlySpan coefficients, ReadOnlySpan terms) + { + double sum = 0; + for (int i = 0; i < coefficients.Length; i++) + { + sum += coefficients[i] * terms[i]; + } + + return sum; + } +} diff --git a/src/Broadside/Graphics/Colors/ColorEntries.cs b/src/Broadside/Graphics/Colors/ColorEntries.cs new file mode 100644 index 00000000..6a5e969e --- /dev/null +++ b/src/Broadside/Graphics/Colors/ColorEntries.cs @@ -0,0 +1,79 @@ +using Broadside.Objects; + +namespace Broadside.Graphics.Colors; + +/// Reads the numeric entries of colour space dictionaries (ISO 32000-2 Tables 62 to 72) as they are now. +internal static class ColorEntries +{ + /// Reads an array of numbers. + /// The document's colour spaces, for resolving. + /// The dictionary, or . + /// The key. + /// The numbers; when absent, not an array or holding something that is not a finite number. + public static double[]? Numbers(ColorSpaceCache cache, CosDictionary? dictionary, CosName key) => + dictionary is not null && dictionary.TryGetValue(key, out CosObject? value) ? Numbers(cache, value) : null; + + /// Reads an array of numbers. + /// The document's colour spaces, for resolving. + /// The value. + /// The numbers; when not an array of finite numbers. + public static double[]? Numbers(ColorSpaceCache cache, CosObject? value) + { + if (cache.Resolve(value) is not CosArray array) + { + return null; + } + + double[] numbers = new double[array.Count]; + for (int i = 0; i < numbers.Length; i++) + { + if (cache.Resolve(array[i]) is not CosNumber number || !double.IsFinite(number.ToDouble())) + { + return null; + } + + numbers[i] = number.ToDouble(); + } + + return numbers; + } + + /// Reads a number. + /// The document's colour spaces, for resolving. + /// The value. + /// The number; when not a finite number. + public static double? Number(ColorSpaceCache cache, CosObject? value) => + cache.Resolve(value) is CosNumber number && double.IsFinite(number.ToDouble()) ? number.ToDouble() : null; + + /// Reads a number entry. + /// The document's colour spaces, for resolving. + /// The dictionary, or . + /// The key. + /// The number; when absent or not a finite number. + public static double? Number(ColorSpaceCache cache, CosDictionary? dictionary, CosName key) => + dictionary is not null && dictionary.TryGetValue(key, out CosObject? value) ? Number(cache, value) : null; + + /// Reads a white point: three numbers, X and Z positive, Y 1. + /// The document's colour spaces. + /// The CIE dictionary. + /// The white point; when absent or invalid. + /// ISO 32000-2 Tables 62 to 64: "XW and ZW shall be positive, and YW shall be equal to 1.0". + public static CieXyz? WhitePoint(ColorSpaceCache cache, CosDictionary? dictionary) => + Numbers(cache, dictionary, ColorSpaceNames.WhitePoint) is [double x, double y, double z] && x > 0 && z > 0 && Math.Abs(y - 1) < 1e-3 + ? new CieXyz(x, 1, z) + : null; + + /// Reads a black point: three non-negative numbers. + /// The document's colour spaces. + /// The CIE dictionary. + /// Whether the entry is there at all. + /// The black point; when absent or invalid. + /// ISO 32000-2 Tables 62 to 64: default [0 0 0]; "all three of these numbers shall be non-negative". + public static CieXyz? BlackPoint(ColorSpaceCache cache, CosDictionary? dictionary, out bool present) + { + present = dictionary is not null && dictionary.ContainsKey(ColorSpaceNames.BlackPoint); + return Numbers(cache, dictionary, ColorSpaceNames.BlackPoint) is [double x, double y, double z] && x >= 0 && y >= 0 && z >= 0 + ? new CieXyz(x, y, z) + : null; + } +} diff --git a/src/Broadside/Graphics/Colors/ColorMath.cs b/src/Broadside/Graphics/Colors/ColorMath.cs new file mode 100644 index 00000000..085d3fc8 --- /dev/null +++ b/src/Broadside/Graphics/Colors/ColorMath.cs @@ -0,0 +1,162 @@ +namespace Broadside.Graphics.Colors; + +/// The colorimetry the managed colour management is built from: chromatic adaptation, XYZ to sRGB and the device formulas. +/// +/// ISO 32000-2 §8.6.5 (CIE-based spaces), §10.4.2 (conversions among device spaces). The Bradford transform and the sRGB primaries +/// and encoding are those of IEC 61966-2-1 and ICC.1:2022 Annex E; all arithmetic is in double precision. +/// +internal static class ColorMath +{ + /// The Bradford cone response matrix, row-major. + private static readonly double[] Bradford = [0.8951, 0.2664, -0.1614, -0.7502, 1.7135, 0.0367, 0.0389, -0.0685, 1.0296]; + + /// The inverse of . + private static readonly double[] BradfordInverse = [0.9869929, -0.1470543, 0.1599627, 0.4323053, 0.5183603, 0.0492912, -0.0085287, 0.0400428, 0.9684867]; + + /// XYZ (D65) to linear sRGB (IEC 61966-2-1). + private static readonly double[] XyzToSrgb = [3.2404542, -1.5371385, -0.4985314, -0.9692660, 1.8760108, 0.0415560, 0.0556434, -0.2040259, 1.0572252]; + + /// Returns the matrix taking XYZ under white to XYZ under D65 and then to linear sRGB. + /// The source white, or to skip adaptation (absolute colorimetric). + /// A row-major 3 × 3 matrix. + public static double[] XyzToLinearSrgb(CieXyz? source) + { + if (source is not { } white) + { + return XyzToSrgb; + } + + Span sourceCone = stackalloc double[3]; + Span targetCone = stackalloc double[3]; + Apply(Bradford, white.X, white.Y, white.Z, sourceCone); + CieXyz d65 = CieXyz.D65; + Apply(Bradford, d65.X, d65.Y, d65.Z, targetCone); + double[] scaled = new double[9]; + for (int row = 0; row < 3; row++) + { + double factor = targetCone[row] / sourceCone[row]; + for (int column = 0; column < 3; column++) + { + scaled[(3 * row) + column] = factor * Bradford[(3 * row) + column]; + } + } + + return Multiply(XyzToSrgb, Multiply(BradfordInverse, scaled)); + } + + /// The sRGB transfer function, linear to encoded, clipped to 0..1. + /// The linear value. + /// The encoded value. + public static double EncodeSrgb(double linear) + { + if (!(linear > 0.0031308)) + { + return linear > 0 ? 12.92 * linear : 0; + } + + return linear >= 1 ? 1 : (1.055 * Math.Pow(linear, 1 / 2.4)) - 0.055; + } + + /// The inverse of the Lab companding function: g(x) = x³ for x ≥ 6/29, else 108/841·(x − 4/29). + /// The value. + /// g(x). + /// ISO 32000-2 §8.6.5.4. + public static double LabG(double x) => x >= 6.0 / 29 ? x * x * x : 108.0 / 841 * (x - (4.0 / 29)); + + /// Writes an RGB colour (each 0 to 1) in the target model. + /// Red. + /// Green. + /// Blue. + /// One, three or four values. + /// The target and, for CMYK, the black generation and undercolour removal. + /// ISO 32000-2 §10.4.2.2 (RGB to gray) and §10.4.2.3 (RGB to CMYK). + public static void FromRgb(double r, double g, double b, Span destination, in ColorConversion conversion) + { + switch (conversion.Target) + { + case DeviceColorModel.Gray: + destination[0] = (float)Clamp01((0.3 * r) + (0.59 * g) + (0.11 * b)); + break; + case DeviceColorModel.Cmyk: + RgbToCmyk(r, g, b, destination, conversion); + break; + default: + destination[0] = (float)Clamp01(r); + destination[1] = (float)Clamp01(g); + destination[2] = (float)Clamp01(b); + break; + } + } + + /// RGB to CMYK: c = 1 − r, m = 1 − g, y = 1 − b, k = min(c, m, y); then UCR(k) is removed from each and BG(k) is black. + /// Red. + /// Green. + /// Blue. + /// Four values. + /// The black generation and undercolour removal functions; null for BG(k) = k and UCR(k) = k. + /// + /// ISO 32000-2 §10.4.2.3. BG and UCR are device-dependent; without them Broadside removes all of the undercolour and replaces it + /// by black (BG(k) = k, UCR(k) = k). + /// + public static void RgbToCmyk(double r, double g, double b, Span destination, in ColorConversion conversion) + { + double c = 1 - Clamp01(r); + double m = 1 - Clamp01(g); + double y = 1 - Clamp01(b); + double k = Math.Min(c, Math.Min(m, y)); + double black = k; + double undercolor = k; + Span io = stackalloc float[2]; + if (conversion.BlackGeneration is { } generation) + { + io[0] = (float)k; + generation.Evaluate(io[..1], io[1..]); + black = io[1]; + } + + if (conversion.UndercolorRemoval is { } removal) + { + io[0] = (float)k; + removal.Evaluate(io[..1], io[1..]); + undercolor = io[1]; + } + + destination[0] = (float)Clamp01(c - undercolor); + destination[1] = (float)Clamp01(m - undercolor); + destination[2] = (float)Clamp01(y - undercolor); + destination[3] = (float)Clamp01(black); + } + + /// Clips to 0..1; NaN becomes 0. + /// The value. + /// The clipped value. + public static double Clamp01(double value) => value > 0 ? Math.Min(value, 1) : 0; + + /// Multiplies a row-major 3 × 3 matrix by a vector. + public static void Apply(ReadOnlySpan matrix, double x, double y, double z, Span result) + { + result[0] = (matrix[0] * x) + (matrix[1] * y) + (matrix[2] * z); + result[1] = (matrix[3] * x) + (matrix[4] * y) + (matrix[5] * z); + result[2] = (matrix[6] * x) + (matrix[7] * y) + (matrix[8] * z); + } + + private static double[] Multiply(double[] left, double[] right) + { + double[] product = new double[9]; + for (int row = 0; row < 3; row++) + { + for (int column = 0; column < 3; column++) + { + double sum = 0; + for (int k = 0; k < 3; k++) + { + sum += left[(3 * row) + k] * right[(3 * k) + column]; + } + + product[(3 * row) + column] = sum; + } + } + + return product; + } +} diff --git a/src/Broadside/Graphics/Colors/ColorPipeline.cs b/src/Broadside/Graphics/Colors/ColorPipeline.cs new file mode 100644 index 00000000..47233fe4 --- /dev/null +++ b/src/Broadside/Graphics/Colors/ColorPipeline.cs @@ -0,0 +1,120 @@ +namespace Broadside.Graphics.Colors; + +/// +/// One step of a colour conversion as runs it: from a colour space's components to device colours. +/// Immutable after construction (the 8-bit table is built once, lazily) and safe to run from several threads at once. +/// +/// +/// ISO 32000-2 §8.6.6: the special spaces are expanded here (an Indexed table, a tint transform, All and None), and the device, +/// CIE-based and ICCBased spaces go to the colour-management extension point. Runs of colours go through one call; nothing is +/// allocated per colour. +/// +internal abstract class ColorPipeline +{ + /// How many colours are converted per batch through stack scratch space. + protected const int Chunk = 64; + + /// The most input components per batch held on the stack. + protected const int ScratchLength = Chunk * PdfColor.MaxComponents; + + private readonly ComponentRange[] _ranges; + private byte[]? _byteTable; + + /// Initializes the shared part of a pipeline. + /// The range of each input component: what 8-bit samples 0 to 255 map onto. + /// The number of device components. + protected ColorPipeline(ComponentRange[] ranges, int outputs) + { + _ranges = ranges; + OutputCount = outputs; + } + + /// Gets the number of input components. + public int InputCount => _ranges.Length; + + /// Gets the number of device components. + public int OutputCount { get; } + + /// Gets a value indicating whether colours in this space paint nothing (Separation None, an all-None DeviceN). + public virtual bool PaintsNothing => false; + + /// Converts colours of components. + /// The components, colour after colour. + /// Receives the device colours, colour after colour. + /// The number of colours. + public abstract void Convert(ReadOnlySpan source, Span destination, int count); + + /// Converts 8-bit samples: each byte maps linearly from 0..255 onto its component's range. + /// The samples, colour after colour. + /// Receives 8-bit device colours. + /// The number of colours. + public virtual void Convert(ReadOnlySpan source, Span destination, int count) + { + int inputs = InputCount; + int outputs = OutputCount; + if (inputs == 1) + { + ReadOnlySpan table = ByteTable(); + for (int i = 0; i < count; i++) + { + table.Slice(source[i] * outputs, outputs).CopyTo(destination.Slice(i * outputs, outputs)); + } + + return; + } + + // A DeviceN space may have many colourants: the batch shrinks so the scratch space stays bounded. + int chunk = Math.Clamp(ScratchLength / inputs, 1, Chunk); + Span components = stackalloc float[ScratchLength]; + Span colors = stackalloc float[Chunk * 4]; + for (int start = 0; start < count; start += chunk) + { + int n = Math.Min(chunk, count - start); + ReadOnlySpan samples = source.Slice(start * inputs, n * inputs); + for (int i = 0; i < samples.Length; i++) + { + ComponentRange range = _ranges[i % inputs]; + components[i] = (float)(range.Minimum + (samples[i] * (range.Maximum - range.Minimum) / 255)); + } + + Convert(components[..(n * inputs)], colors, n); + ToBytes(colors[..(n * outputs)], destination.Slice(start * outputs, n * outputs)); + } + } + + /// Converts device colours 0..1 to bytes, rounding to nearest. + /// The colours. + /// The bytes. + protected static void ToBytes(ReadOnlySpan colors, Span destination) + { + for (int i = 0; i < colors.Length; i++) + { + destination[i] = (byte)((ColorMath.Clamp01(colors[i]) * 255) + 0.5); + } + } + + /// Returns the 256 device colours of a one-component space, built on first use. + /// 256 × bytes. + private byte[] ByteTable() + { + byte[]? table = Volatile.Read(ref _byteTable); + if (table is not null) + { + return table; + } + + ComponentRange range = _ranges[0]; + float[] components = new float[256]; + for (int b = 0; b < 256; b++) + { + components[b] = (float)(range.Minimum + (b * (range.Maximum - range.Minimum) / 255)); + } + + float[] colors = new float[256 * OutputCount]; + Convert(components, colors, 256); + table = new byte[colors.Length]; + ToBytes(colors, table); + Volatile.Write(ref _byteTable, table); + return table; + } +} diff --git a/src/Broadside/Graphics/Colors/ColorPipelines.cs b/src/Broadside/Graphics/Colors/ColorPipelines.cs new file mode 100644 index 00000000..51fae766 --- /dev/null +++ b/src/Broadside/Graphics/Colors/ColorPipelines.cs @@ -0,0 +1,270 @@ +namespace Broadside.Graphics.Colors; + +/// A device, CIE-based or ICCBased space, converted by the colour-management extension point after clipping into range. +/// ISO 32000-2 §8.6.4, §8.6.5; §8.6.5.6: out-of-range values are clipped to the nearest valid value. +internal sealed class ManagedPipeline : ColorPipeline +{ + private readonly IColorConverter _converter; + private readonly ComponentRange[] _clip; + + public ManagedPipeline(PdfColorSpace space, IColorConverter converter, int outputs) + : base(Ranges(space), outputs) + { + if (converter.InputCount != space.ComponentCount || converter.OutputCount != outputs) + { + throw new InvalidOperationException( + $"The colour management converter for {space.Family} takes {converter.InputCount} and gives {converter.OutputCount} components; {space.ComponentCount} and {outputs} are needed."); + } + + _converter = converter; + _clip = Ranges(space); + } + + /// The component ranges of a space. + public static ComponentRange[] Ranges(PdfColorSpace space) + { + var ranges = new ComponentRange[space.ComponentCount]; + for (int i = 0; i < ranges.Length; i++) + { + ranges[i] = space.GetComponentRange(i); + } + + return ranges; + } + + /// + public override void Convert(ReadOnlySpan source, Span destination, int count) + { + int inputs = InputCount; + Span clipped = stackalloc float[Chunk * 4]; + for (int start = 0; start < count; start += Chunk) + { + int n = Math.Min(Chunk, count - start); + ReadOnlySpan batch = source.Slice(start * inputs, n * inputs); + for (int i = 0; i < batch.Length; i++) + { + clipped[i] = (float)_clip[i % inputs].Clamp(batch[i]); + } + + _converter.Convert(clipped[..batch.Length], destination[(start * OutputCount)..], n); + } + } +} + +/// An Indexed space: the table of colours is converted once; indices pick from it. +/// +/// ISO 32000-2 §8.6.6.3: table byte b of component j is minj + b × (maxj − minj) / 255 in the base space; an index is rounded and +/// clipped to 0..hival. A short table reads as zeros past its end. +/// +internal sealed class IndexedPipeline : ColorPipeline +{ + private readonly float[] _palette; + private readonly byte[] _bytes; + private readonly int _high; + + public IndexedPipeline(PdfIndexedColorSpace space, ColorPipeline basePipeline) + : base([new ComponentRange(0, space.HighValue)], basePipeline.OutputCount) + { + _high = space.HighValue; + int m = basePipeline.InputCount; + int entries = _high + 1; + ReadOnlySpan lookup = space.GetLookup().Span; + PdfColorSpace baseSpace = space.Base; + float[] components = new float[entries * m]; + for (int i = 0; i < components.Length; i++) + { + byte b = i < lookup.Length ? lookup[i] : (byte)0; + ComponentRange range = baseSpace.GetComponentRange(i % m); + components[i] = (float)(range.Minimum + (b * (range.Maximum - range.Minimum) / 255)); + } + + _palette = new float[entries * OutputCount]; + basePipeline.Convert(components, _palette, entries); + _bytes = new byte[_palette.Length]; + ToBytes(_palette, _bytes); + } + + /// + public override void Convert(ReadOnlySpan source, Span destination, int count) + { + int outputs = OutputCount; + for (int i = 0; i < count; i++) + { + float value = source[i]; + int index = value >= 0 ? (int)Math.Min(Math.Floor(value + 0.5), _high) : 0; + _palette.AsSpan(index * outputs, outputs).CopyTo(destination.Slice(i * outputs, outputs)); + } + } + + /// + /// Here a byte is the index itself (Table 88: the default Decode of an Indexed image is [0 2^bpc − 1]). + public override void Convert(ReadOnlySpan source, Span destination, int count) + { + int outputs = OutputCount; + for (int i = 0; i < count; i++) + { + int index = Math.Min(source[i], _high); + _bytes.AsSpan(index * outputs, outputs).CopyTo(destination.Slice(i * outputs, outputs)); + } + } +} + +/// A Separation or DeviceN space painted through its alternate: tints go through the tint transform. +/// +/// ISO 32000-2 §8.6.6.4 and §8.6.6.5. Without a usable tint transform the tints are treated as subtractive ink: the largest tint t +/// gives gray 1 − t, RGB (1 − t) × 3, CMYK (0, 0, 0, t), and 0 in every other alternate. Outputs the transform does not give are 0. +/// +internal sealed class TintPipeline : ColorPipeline +{ + private readonly PdfFunction? _function; + private readonly ColorPipeline _alternate; + private readonly PdfColorSpaceFamily _alternateFamily; + + public TintPipeline(int inputs, PdfFunction? function, PdfColorSpace alternate, ColorPipeline alternatePipeline) + : base(Unit(inputs), alternatePipeline.OutputCount) + { + _function = function is { IsValid: true } && function.InputCount <= PdfColor.MaxComponents ? function : null; + _alternate = alternatePipeline; + _alternateFamily = alternate.Family; + } + + /// + public override void Convert(ReadOnlySpan source, Span destination, int count) + { + int inputs = InputCount; + int m = _alternate.InputCount; + int chunk = Math.Clamp(ScratchLength / Math.Max(inputs, m), 1, Chunk); + Span components = stackalloc float[ScratchLength]; + Span input = stackalloc float[PdfColor.MaxComponents]; + Span output = stackalloc float[PdfColor.MaxComponents]; + for (int start = 0; start < count; start += chunk) + { + int n = Math.Min(chunk, count - start); + Span alternate = components[..(n * m)]; + for (int i = 0; i < n; i++) + { + ReadOnlySpan tints = source.Slice((start + i) * inputs, inputs); + Span target = alternate.Slice(i * m, m); + if (_function is { } function) + { + // The function takes its own number of inputs (it clips them to its domain) and its outputs fill the alternate. + int k = function.InputCount; + input[..k].Clear(); + tints[..Math.Min(k, inputs)].CopyTo(input); + function.Evaluate(input[..k], output); + target.Clear(); + output[..Math.Min(function.OutputCount, m)].CopyTo(target); + } + else + { + Subtractive(tints, target); + } + } + + _alternate.Convert(alternate, destination.Slice(start * OutputCount, n * OutputCount), n); + } + } + + private static ComponentRange[] Unit(int count) + { + var ranges = new ComponentRange[count]; + Array.Fill(ranges, new ComponentRange(0, 1)); + return ranges; + } + + private void Subtractive(ReadOnlySpan tints, Span target) + { + float tint = 0; + foreach (float value in tints) + { + tint = Math.Max(tint, Math.Clamp(value, 0, 1)); + } + + target.Clear(); + switch (_alternateFamily) + { + case PdfColorSpaceFamily.DeviceGray or PdfColorSpaceFamily.CalGray: + target[0] = 1 - tint; + break; + case PdfColorSpaceFamily.DeviceRgb or PdfColorSpaceFamily.CalRgb: + target[0] = target[1] = target[2] = 1 - tint; + break; + case PdfColorSpaceFamily.DeviceCmyk: + target[3] = tint; + break; + } + } +} + +/// Separation All: every colourant at the tint; on an additive device, 1 − tint on every component. +/// ISO 32000-2 §8.6.6.4. +internal sealed class AllColorantsPipeline(DeviceColorModel target, int outputs) : ColorPipeline([new ComponentRange(0, 1)], outputs) +{ + /// + public override void Convert(ReadOnlySpan source, Span destination, int count) + { + int outputs = OutputCount; + for (int i = 0; i < count; i++) + { + float tint = (float)ColorMath.Clamp01(source[i]); + destination.Slice(i * outputs, outputs).Fill(target == DeviceColorModel.Cmyk ? tint : 1 - tint); + } + } +} + +/// Separation None, or DeviceN whose colourants are all None: nothing is painted. +/// ISO 32000-2 §8.6.6.4 and §8.6.6.5. The colour written is no ink (white, or CMYK 0 0 0 0); painters check . +internal sealed class NoColorantPipeline(int inputs, DeviceColorModel target, int outputs) : ColorPipeline(Unit(inputs), outputs) +{ + /// + public override bool PaintsNothing => true; + + /// + public override void Convert(ReadOnlySpan source, Span destination, int count) => + destination[..(count * OutputCount)].Fill(target == DeviceColorModel.Cmyk ? 0 : 1); + + /// + public override void Convert(ReadOnlySpan source, Span destination, int count) => + destination[..(count * OutputCount)].Fill(target == DeviceColorModel.Cmyk ? (byte)0 : (byte)255); + + private static ComponentRange[] Unit(int count) + { + var ranges = new ComponentRange[count]; + Array.Fill(ranges, new ComponentRange(0, 1)); + return ranges; + } +} + +/// A Pattern space without an underlying space: its colours have no components; the pattern itself paints (§8.7). +/// ISO 32000-2 §8.6.6.2. The colour written is black. +internal sealed class PatternPipeline(DeviceColorModel target, int outputs) : ColorPipeline([], outputs) +{ + /// + public override void Convert(ReadOnlySpan source, Span destination, int count) + { + for (int i = 0; i < count; i++) + { + Black(destination.Slice(i * OutputCount, OutputCount)); + } + } + + /// + public override void Convert(ReadOnlySpan source, Span destination, int count) + { + Span black = stackalloc float[OutputCount]; + Black(black); + for (int i = 0; i < count; i++) + { + ToBytes(black, destination.Slice(i * OutputCount, OutputCount)); + } + } + + private void Black(Span color) + { + color.Clear(); + if (target == DeviceColorModel.Cmyk) + { + color[3] = 1; + } + } +} diff --git a/src/Broadside/Graphics/Colors/ColorSpaceCache.cs b/src/Broadside/Graphics/Colors/ColorSpaceCache.cs new file mode 100644 index 00000000..69530240 --- /dev/null +++ b/src/Broadside/Graphics/Colors/ColorSpaceCache.cs @@ -0,0 +1,419 @@ +using System.Collections.Concurrent; +using Broadside.Caching; +using Broadside.Diagnostics; +using Broadside.Graphics.Functions; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Graphics.Colors; + +/// Why a colour space value could not be read. +internal enum ColorSpaceFailure +{ + /// Nothing went wrong. + None, + + /// The value is not a colour space name or array. + Invalid, + + /// The value refers back to a space that is being read. + Cycle, + + /// Spaces nest more deeply than . + TooDeep, +} + +/// How a colour space name in a content stream was resolved. +internal enum NamedLookup +{ + /// A family name: DeviceGray, DeviceRGB, DeviceCMYK or Pattern. + Family, + + /// A key of the ColorSpace subdictionary of the current resources. + Resource, + + /// Not a resource, but an inline image abbreviation (G, RGB, CMYK), read as the device space. + Abbreviation, + + /// Not found. + Missing, +} + +/// +/// A document's colour spaces: one view per colour space object, the default colour spaces per resource dictionary, and the +/// converters built from them, all created once and shared by every thread. +/// +/// +/// +/// ISO 32000-2 §8.6. Spaces are keyed by the indirect reference they were reached through, else by the direct array, and by the +/// array's version, so a space whose array changes is read again (ADR 0004). Built through : +/// concurrent first reads create one view, and a space that contains itself (an Indexed base referring to the Indexed space) is +/// detected as a cycle. Names (/CS0) are never keys: the same name means different spaces in different resources. +/// +/// +/// Converters are keyed by source space, conversion and default spaces, and rebuilt when any container they were built from has +/// changed. +/// +/// +internal sealed class ColorSpaceCache +{ + /// How deeply colour spaces may nest (an Indexed base that is a Separation whose alternate is ICCBased is 3). + public const int MaxDepth = 8; + + [ThreadStatic] + private static int _depth; + + private readonly OnceCache _spaces = new(); + private readonly OnceCache _defaults = new(); + private readonly ConcurrentDictionary _converters = new(); + + /// Initializes a new instance of the class. + /// The document. + /// The document's diagnostics. + /// The colour management converters come from. + public ColorSpaceCache(PdfDocument document, DiagnosticSink diagnostics, IColorManagement management) + { + Document = document; + Diagnostics = diagnostics; + Management = management; + } + + /// Gets the document. + public PdfDocument Document { get; } + + /// Gets the document's diagnostics. + public DiagnosticSink Diagnostics { get; } + + /// Gets the colour management of the document's engine. + public IColorManagement Management { get; } + + /// Resolves an object through the document. + /// The object. + /// The direct object; the null object for . + public CosObject Resolve(CosObject? value) => Document.Resolve(value); + + /// Returns the colour space a value describes; DeviceGray, with a diagnostic, when it describes none. + /// A family name, a colour space array, or a reference to one. + /// The nearest indirect object the value was found in, for diagnostics. + /// The space. + /// ISO 32000-2 §8.6.3. + public PdfColorSpace Get(CosObject? value, CosReference? owner = null) + { + PdfColorSpace? space = Find(value, owner, inline: false, out ColorSpaceFailure failure); + if (space is null) + { + ReportFailure(value as CosReference ?? owner, failure, "a colour space"); + } + + return space ?? PdfDeviceGrayColorSpace.Instance; + } + + /// Returns the colour space of an inline image's ColorSpace entry (§8.9.7): abbreviations allowed, nothing cached. + /// The entry. + /// The content stream, for diagnostics. + /// The space; when the value describes none. + public PdfColorSpace? FindInline(CosObject value, CosReference? owner) => Find(value, owner, inline: true, out _); + + /// Returns the colour space a value describes, without recording anything when it describes none. + /// A family name, a colour space array, or a reference to one. + /// The nearest indirect object the value was found in, for diagnostics recorded while reading it. + /// Whether inline image abbreviations (G, RGB, CMYK, I) are allowed. + /// Why there is no space. + /// The space; for a value that is not a colour space, a cycle, or nesting too deep. + public PdfColorSpace? Find(CosObject? value, CosReference? owner, bool inline, out ColorSpaceFailure failure) + { + failure = ColorSpaceFailure.None; + var reference = value as CosReference; + switch (Resolve(value)) + { + case CosName name: + PdfColorSpace? named = FromName(name, inline); + failure = named is null ? ColorSpaceFailure.Invalid : ColorSpaceFailure.None; + return named; + case CosArray array: + if (_depth >= MaxDepth) + { + failure = ColorSpaceFailure.TooDeep; + return null; + } + + if (inline) + { + return Create(array, reference, owner, inline: true); + } + + var key = new Key((object?)reference ?? array, array.Version); + PdfColorSpace? space = _spaces.GetOrCreate( + key, + (Cache: this, Array: array, Reference: reference, Owner: owner), + static (_, state) => new Created(state.Cache.Create(state.Array, state.Reference, state.Owner, inline: false)), + static (_, _) => null); + failure = space is null ? ColorSpaceFailure.Cycle : ColorSpaceFailure.None; + return space; + default: + failure = ColorSpaceFailure.Invalid; + return null; + } + } + + /// Looks a name up in a subdictionary of a resource dictionary without allocating. + /// The resource dictionary, or . + /// The subdictionary's key, such as ColorSpace or Pattern. + /// The name's bytes. + /// The name as stored in the dictionary. + /// The value as stored (possibly a reference); when absent. + /// ISO 32000-2 §7.8.3, Table 34. + public CosObject? FindResource(CosDictionary? resources, CosName category, ReadOnlySpan name, out CosName? key) + { + key = null; + if (resources is null || !resources.TryGetValue(category, out CosObject? entry) || Resolve(entry) is not CosDictionary dictionary) + { + return null; + } + + for (int i = 0; i < dictionary.Count; i++) + { + KeyValuePair pair = dictionary.GetAt(i); + if (pair.Key.Bytes.SequenceEqual(name)) + { + key = pair.Key; + return pair.Value; + } + } + + return null; + } + + /// Returns the colour space a name operand of CS or cs names, without allocating once the space is cached. + /// The current resource dictionary, or . + /// The name's bytes. + /// The content stream, for diagnostics recorded while reading the space. + /// How the name was resolved. + /// The space; when the name is neither a family name nor a resource. + /// + /// ISO 32000-2 §8.6.8, Table 73: DeviceGray, DeviceRGB, DeviceCMYK and Pattern always name those spaces and never resources; any + /// other name is a key of the ColorSpace subdictionary of the current resources. The inline image abbreviations G, RGB and + /// CMYK are accepted as a last resort (pdf.js does), after the resources. + /// + public PdfColorSpace? FindNamed(CosDictionary? resources, ReadOnlySpan name, CosReference? owner, out NamedLookup lookup) + { + lookup = NamedLookup.Family; + if (name.SequenceEqual("DeviceGray"u8)) + { + return PdfDeviceGrayColorSpace.Instance; + } + + if (name.SequenceEqual("DeviceRGB"u8)) + { + return PdfDeviceRgbColorSpace.Instance; + } + + if (name.SequenceEqual("DeviceCMYK"u8)) + { + return PdfDeviceCmykColorSpace.Instance; + } + + if (name.SequenceEqual("Pattern"u8)) + { + return PdfPatternColorSpace.Colored; + } + + if (FindResource(resources, ColorSpaceNames.ColorSpace, name, out _) is { } value) + { + lookup = NamedLookup.Resource; + return Get(value, value as CosReference ?? owner); + } + + lookup = NamedLookup.Abbreviation; + if (name.SequenceEqual("G"u8)) + { + return PdfDeviceGrayColorSpace.Instance; + } + + if (name.SequenceEqual("RGB"u8)) + { + return PdfDeviceRgbColorSpace.Instance; + } + + if (name.SequenceEqual("CMYK"u8)) + { + return PdfDeviceCmykColorSpace.Instance; + } + + lookup = NamedLookup.Missing; + return null; + } + + /// Returns the default colour spaces of a resource dictionary. + /// The resource dictionary, or . + /// The defaults; when it has none. + /// ISO 32000-2 §8.6.5.6. + public PdfDefaultColorSpaces GetDefaults(CosDictionary? resources) + { + if (resources is null + || !resources.TryGetValue(ColorSpaceNames.ColorSpace, out CosObject? entry) + || Resolve(entry) is not CosDictionary spaces + || !(spaces.ContainsKey(ColorSpaceNames.DefaultGray) || spaces.ContainsKey(ColorSpaceNames.DefaultRgb) || spaces.ContainsKey(ColorSpaceNames.DefaultCmyk))) + { + return PdfDefaultColorSpaces.None; + } + + return _defaults.GetOrCreate( + new Key(spaces, spaces.Version), + (Cache: this, Spaces: spaces, Owner: entry as CosReference), + static (_, state) => new Created(state.Cache.CreateDefaults(state.Spaces, state.Owner)), + static (_, _) => PdfDefaultColorSpaces.None); + } + + /// Returns the converter from under with . + /// The source space. + /// The conversion. + /// The default colour spaces in effect. + /// The converter, built once and rebuilt when what it was built from changes. + public PdfColorConverter GetConverter(PdfColorSpace source, ColorConversion conversion, PdfDefaultColorSpaces defaults) + { + var key = new ConverterKey(source, conversion, defaults); + if (_converters.TryGetValue(key, out PdfColorConverter? converter) && converter.IsCurrent) + { + return converter; + } + + converter = PdfColorConverter.Create(this, source, conversion, defaults); + _converters[key] = converter; + return converter; + } + + /// Records why a nested or top-level value is not a colour space. + /// The space that holds the value. + /// What went wrong. + /// What the value was meant to be, for the message. + public static void ReportFailure(PdfColorSpace space, ColorSpaceFailure failure, string what) => + space.Cache!.ReportFailure(space.DiagnosticReference, failure, what); + + /// Records why a value is not a colour space, against . + /// The object to record it against. + /// What went wrong. + /// What the value was meant to be, for the message. + public void ReportFailure(CosReference? reference, ColorSpaceFailure failure, string what) + { + (string code, DiagnosticSeverity severity, string message) = failure switch + { + ColorSpaceFailure.Cycle => (DiagnosticCodes.ColorSpaceCycle, DiagnosticSeverity.Error, $"The value of {what} refers back to the colour space being read; DeviceGray is used."), + ColorSpaceFailure.TooDeep => (DiagnosticCodes.ColorSpaceTooDeep, DiagnosticSeverity.Error, $"Colour spaces nest more than {MaxDepth} deep at {what}; DeviceGray is used."), + _ => (DiagnosticCodes.ColorSpaceInvalid, DiagnosticSeverity.Warning, $"The value of {what} is not a colour space name or array; DeviceGray is used."), + }; + Diagnostics.Report(code, severity, message, offset: null, reference); + } + + /// Returns the space a family name stands for, or for a name that is not one. + private static PdfColorSpace? FromName(CosName name, bool inline) + { + if (name.Equals(ColorSpaceNames.DeviceGray) || (inline && name.Equals(ColorSpaceNames.G))) + { + return PdfDeviceGrayColorSpace.Instance; + } + + if (name.Equals(ColorSpaceNames.DeviceRgb) || (inline && name.Equals(ColorSpaceNames.Rgb))) + { + return PdfDeviceRgbColorSpace.Instance; + } + + if (name.Equals(ColorSpaceNames.DeviceCmyk) || name.Equals(ColorSpaceNames.CalCmyk) || (inline && name.Equals(ColorSpaceNames.Cmyk))) + { + return PdfDeviceCmykColorSpace.Instance; + } + + return name.Equals(ColorSpaceNames.Pattern) && !inline ? PdfPatternColorSpace.Colored : null; + } + + /// Reads a colour space array into its view, checks it, and repairs it to DeviceGray when it cannot be used. + private PdfColorSpace Create(CosArray array, CosReference? reference, CosReference? owner, bool inline) + { + _depth++; + try + { + CosReference? diagnostics = reference ?? owner; + if (array.Count == 0 || Resolve(array[0]) is not CosName family) + { + Diagnostics.Report(DiagnosticCodes.ColorSpaceInvalid, DiagnosticSeverity.Warning, "A colour space array is empty or does not start with a family name; DeviceGray is used.", offset: null, diagnostics); + return PdfDeviceGrayColorSpace.Instance; + } + + if (FromName(family, inline) is { } device && family.Equals(ColorSpaceNames.Pattern) is false) + { + // §8.6.3: a family with no parameters is named alone; [/DeviceRGB] is read anyway (CalCMYK, §8.6.5.1, silently). + if (!family.Equals(ColorSpaceNames.CalCmyk)) + { + Diagnostics.Report(DiagnosticCodes.ColorSpaceEntryInvalid, DiagnosticSeverity.Warning, $"The device colour space {family.Value} is written as an array; it is read as the name.", offset: null, diagnostics); + } + + return device; + } + + PdfColorSpace? space = family switch + { + _ when family.Equals(ColorSpaceNames.CalGray) => new PdfCalGrayColorSpace(this, array, reference) { OwnerReference = owner, IsInline = inline }, + _ when family.Equals(ColorSpaceNames.CalRgb) => new PdfCalRgbColorSpace(this, array, reference) { OwnerReference = owner, IsInline = inline }, + _ when family.Equals(ColorSpaceNames.Lab) => new PdfLabColorSpace(this, array, reference) { OwnerReference = owner, IsInline = inline }, + _ when family.Equals(ColorSpaceNames.IccBased) && array.Count > 1 && Resolve(array[1]) is CosStream => + new PdfIccBasedColorSpace(this, array, reference) { OwnerReference = owner, IsInline = inline }, + _ when family.Equals(ColorSpaceNames.Indexed) || (inline && family.Equals(ColorSpaceNames.I)) => + new PdfIndexedColorSpace(this, array, reference) { OwnerReference = owner, IsInline = inline }, + _ when family.Equals(ColorSpaceNames.Separation) => new PdfSeparationColorSpace(this, array, reference) { OwnerReference = owner, IsInline = inline }, + _ when family.Equals(ColorSpaceNames.DeviceN) => new PdfDeviceNColorSpace(this, array, reference) { OwnerReference = owner, IsInline = inline }, + _ when family.Equals(ColorSpaceNames.Pattern) => array.Count == 1 + ? PdfPatternColorSpace.Colored + : new PdfPatternColorSpace(this, array, reference) { OwnerReference = owner, IsInline = inline }, + _ => null, + }; + + if (space is null) + { + Diagnostics.Report(DiagnosticCodes.ColorSpaceInvalid, DiagnosticSeverity.Warning, $"The colour space family {family.Value} is unknown, or its parameters are missing; DeviceGray is used.", offset: null, diagnostics); + return PdfDeviceGrayColorSpace.Instance; + } + + return space.Cache is null || space.Validate() ? space : PdfDeviceGrayColorSpace.Instance; + } + finally + { + _depth--; + } + } + + private PdfDefaultColorSpaces CreateDefaults(CosDictionary spaces, CosReference? owner) + { + return new PdfDefaultColorSpaces( + Default(ColorSpaceNames.DefaultGray, 1), + Default(ColorSpaceNames.DefaultRgb, 3), + Default(ColorSpaceNames.DefaultCmyk, 4)); + + PdfColorSpace? Default(CosName key, int components) + { + if (!spaces.TryGetValue(key, out CosObject? value)) + { + return null; + } + + PdfColorSpace space = Get(value, owner); + if (space.ComponentCount == components && space.Family is not (PdfColorSpaceFamily.Lab or PdfColorSpaceFamily.Indexed or PdfColorSpaceFamily.Pattern)) + { + return space; + } + + Diagnostics.Report( + DiagnosticCodes.DefaultColorSpaceInvalid, + DiagnosticSeverity.Warning, + $"{key.Value} is a {space.Family} space of {space.ComponentCount} components; a default colour space shall have {components} and not be Lab, Indexed or Pattern. It is ignored.", + offset: null, + value as CosReference ?? owner); + return null; + } + } + + /// A colour space object's identity (its reference, else the direct container) and the container's version. + private readonly record struct Key(object Identity, int Version); + + /// What a converter is built from. + private readonly record struct ConverterKey(PdfColorSpace Source, ColorConversion Conversion, PdfDefaultColorSpaces Defaults); +} diff --git a/src/Broadside/Graphics/Colors/ColorSpaceNames.cs b/src/Broadside/Graphics/Colors/ColorSpaceNames.cs new file mode 100644 index 00000000..4c55750a --- /dev/null +++ b/src/Broadside/Graphics/Colors/ColorSpaceNames.cs @@ -0,0 +1,51 @@ +using Broadside.Objects; + +namespace Broadside.Graphics.Colors; + +/// The names colour spaces and their dictionaries use (ISO 32000-2 §8.6, Tables 61 to 72), created once. +/// Kept out of so that the content tickets editing it in parallel do not collide. +internal static class ColorSpaceNames +{ + public static readonly CosName DeviceGray = new("DeviceGray"); + public static readonly CosName DeviceRgb = new("DeviceRGB"); + public static readonly CosName DeviceCmyk = new("DeviceCMYK"); + public static readonly CosName CalGray = new("CalGray"); + public static readonly CosName CalRgb = new("CalRGB"); + public static readonly CosName CalCmyk = new("CalCMYK"); + public static readonly CosName Lab = new("Lab"); + public static readonly CosName IccBased = new("ICCBased"); + public static readonly CosName Indexed = new("Indexed"); + public static readonly CosName Pattern = new("Pattern"); + public static readonly CosName Separation = new("Separation"); + public static readonly CosName DeviceN = new("DeviceN"); + + // Inline image abbreviations (§8.9.7, Table 92). + public static readonly CosName G = new("G"); + public static readonly CosName Rgb = new("RGB"); + public static readonly CosName Cmyk = new("CMYK"); + public static readonly CosName I = new("I"); + + public static readonly CosName WhitePoint = new("WhitePoint"); + public static readonly CosName BlackPoint = new("BlackPoint"); + public static readonly CosName Gamma = new("Gamma"); + public static readonly CosName Matrix = new("Matrix"); + public static readonly CosName Range = new("Range"); + public static readonly CosName N = new("N"); + public static readonly CosName Alternate = new("Alternate"); + public static readonly CosName Metadata = new("Metadata"); + public static readonly CosName All = new("All"); + public static readonly CosName None = new("None"); + public static readonly CosName Subtype = new("Subtype"); + public static readonly CosName NChannel = new("NChannel"); + public static readonly CosName Colorants = new("Colorants"); + public static readonly CosName Process = new("Process"); + public static readonly CosName ColorSpace = new("ColorSpace"); + public static readonly CosName Components = new("Components"); + public static readonly CosName MixingHints = new("MixingHints"); + public static readonly CosName Solidities = new("Solidities"); + public static readonly CosName PrintingOrder = new("PrintingOrder"); + public static readonly CosName DotGain = new("DotGain"); + public static readonly CosName DefaultGray = new("DefaultGray"); + public static readonly CosName DefaultRgb = new("DefaultRGB"); + public static readonly CosName DefaultCmyk = new("DefaultCMYK"); +} diff --git a/src/Broadside/Graphics/Colors/DeviceConverter.cs b/src/Broadside/Graphics/Colors/DeviceConverter.cs new file mode 100644 index 00000000..32d9db15 --- /dev/null +++ b/src/Broadside/Graphics/Colors/DeviceConverter.cs @@ -0,0 +1,104 @@ +namespace Broadside.Graphics.Colors; + +/// Converts DeviceGray, DeviceRGB or DeviceCMYK colours to a device colour model. +/// +/// ISO 32000-2 §10.4.2: gray to RGB r = g = b = gray (§10.4.2.2); RGB to gray 0.3 r + 0.59 g + 0.11 b; gray to CMYK (0, 0, 0, +/// 1 − gray) and CMYK to gray 1 − min(1, 0.3 c + 0.59 m + 0.11 y + k) (§10.4.2.4); RGB to CMYK with black generation and +/// undercolour removal (§10.4.2.3); CMYK to RGB either by §10.4.2.5 or by the SWOP characterisation (). +/// +internal sealed class DeviceConverter(PdfColorSpaceFamily source, ColorConversion conversion, CmykConversion cmyk) : IColorConverter +{ + /// + public int InputCount { get; } = source switch + { + PdfColorSpaceFamily.DeviceRgb => 3, + PdfColorSpaceFamily.DeviceCmyk => 4, + _ => 1, + }; + + /// + public int OutputCount { get; } = Outputs(conversion.Target); + + /// The number of components of a device colour model. + /// The model. + /// 1, 3 or 4. + public static int Outputs(DeviceColorModel target) => target switch + { + DeviceColorModel.Gray => 1, + DeviceColorModel.Cmyk => 4, + _ => 3, + }; + + /// + public void Convert(ReadOnlySpan source, Span destination, int count) + { + int inputs = InputCount; + int outputs = OutputCount; + for (int i = 0; i < count; i++) + { + ConvertOne(source.Slice(i * inputs, inputs), destination.Slice(i * outputs, outputs)); + } + } + + private void ConvertOne(ReadOnlySpan input, Span output) + { + switch (source) + { + case PdfColorSpaceFamily.DeviceGray: + double gray = ColorMath.Clamp01(input[0]); + if (conversion.Target == DeviceColorModel.Cmyk) + { + output[0] = output[1] = output[2] = 0; + output[3] = (float)(1 - gray); + } + else + { + ColorMath.FromRgb(gray, gray, gray, output, conversion); + } + + break; + case PdfColorSpaceFamily.DeviceRgb: + ColorMath.FromRgb(input[0], input[1], input[2], output, conversion); + break; + default: + ConvertCmyk(input, output); + break; + } + } + + private void ConvertCmyk(ReadOnlySpan input, Span output) + { + double c = ColorMath.Clamp01(input[0]); + double m = ColorMath.Clamp01(input[1]); + double y = ColorMath.Clamp01(input[2]); + double k = ColorMath.Clamp01(input[3]); + if (conversion.Target == DeviceColorModel.Cmyk) + { + output[0] = (float)c; + output[1] = (float)m; + output[2] = (float)y; + output[3] = (float)k; + return; + } + + if (cmyk == CmykConversion.Classic) + { + if (conversion.Target == DeviceColorModel.Gray) + { + output[0] = (float)(1 - Math.Min(1, (0.3 * c) + (0.59 * m) + (0.11 * y) + k)); + } + else + { + output[0] = (float)(1 - Math.Min(1, c + k)); + output[1] = (float)(1 - Math.Min(1, m + k)); + output[2] = (float)(1 - Math.Min(1, y + k)); + } + + return; + } + + Span rgb = stackalloc double[3]; + CmykCharacterization.ToRgb(c, m, y, k, rgb); + ColorMath.FromRgb(rgb[0], rgb[1], rgb[2], output, conversion); + } +} diff --git a/src/Broadside/Graphics/Colors/IccAlternateConverter.cs b/src/Broadside/Graphics/Colors/IccAlternateConverter.cs new file mode 100644 index 00000000..7f0ccc73 --- /dev/null +++ b/src/Broadside/Graphics/Colors/IccAlternateConverter.cs @@ -0,0 +1,53 @@ +namespace Broadside.Graphics.Colors; + +/// Converts ICCBased colours through the alternate space: clipped into the ICC range, then into the alternate's ranges. +/// +/// ISO 32000-2 §8.6.5.5, Table 65: the alternate is used "without any intermediate conversion"; colour values are constrained to the +/// ICC Range and then clipped into the alternate's ranges. The alternate conversion comes from the same colour management. +/// +internal sealed class IccAlternateConverter : IColorConverter +{ + private const int Chunk = 64; + + private readonly IColorConverter _alternate; + private readonly ComponentRange[] _ranges; + + public IccAlternateConverter(PdfIccBasedColorSpace space, PdfColorSpace alternate, IColorConverter converter) + { + _alternate = converter; + InputCount = space.ComponentCount; + OutputCount = converter.OutputCount; + _ranges = new ComponentRange[InputCount]; + for (int i = 0; i < InputCount; i++) + { + ComponentRange icc = space.GetComponentRange(i); + ComponentRange target = alternate.GetComponentRange(i); + _ranges[i] = new ComponentRange( + Math.Max(icc.Minimum, target.Minimum), + Math.Max(Math.Max(icc.Minimum, target.Minimum), Math.Min(icc.Maximum, target.Maximum))); + } + } + + /// + public int InputCount { get; } + + /// + public int OutputCount { get; } + + /// + public void Convert(ReadOnlySpan source, Span destination, int count) + { + int inputs = InputCount; + Span clipped = stackalloc float[Chunk * 4]; + for (int start = 0; start < count; start += Chunk) + { + int n = Math.Min(Chunk, count - start); + for (int i = 0; i < n * inputs; i++) + { + clipped[i] = (float)_ranges[i % inputs].Clamp(source[(start * inputs) + i]); + } + + _alternate.Convert(clipped[..(n * inputs)], destination[(start * OutputCount)..], n); + } + } +} diff --git a/src/Broadside/Graphics/Colors/TintSpaces.cs b/src/Broadside/Graphics/Colors/TintSpaces.cs new file mode 100644 index 00000000..bb589102 --- /dev/null +++ b/src/Broadside/Graphics/Colors/TintSpaces.cs @@ -0,0 +1,71 @@ +using System.Globalization; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Graphics.Colors; + +/// What Separation and DeviceN spaces share: an alternate space and a tint transform (ISO 32000-2 §8.6.6.4, §8.6.6.5). +internal static class TintSpaces +{ + /// Returns whether may be the alternate of a Separation or DeviceN space: a device or CIE-based space. + /// The space. + /// for DeviceGray, DeviceRGB, DeviceCMYK, CalGray, CalRGB, Lab and ICCBased. + public static bool IsAlternateFamily(PdfColorSpace space) => space.Family <= PdfColorSpaceFamily.IccBased; + + /// Returns the alternate to use: the given one when it may be an alternate, else DeviceGray. + /// The space the entry reads as, or . + /// The alternate. + public static PdfColorSpace Alternate(PdfColorSpace? space) => + space is not null && IsAlternateFamily(space) ? space : PdfDeviceGrayColorSpace.Instance; + + /// Returns the tint transform's view, without recording anything when the entry is not a function. + /// The document's colour spaces. + /// The entry as stored. + /// The number of colourants. + /// The number of alternate components. + /// The function, or . + public static PdfFunction? Function(ColorSpaceCache cache, CosObject value, int inputs, int outputs) => + cache.Resolve(value) is CosDictionary or CosStream ? cache.Document.Functions.Get(value, inputs, outputs) : null; + + /// Records what is wrong with the alternate and the tint transform. + /// The Separation or DeviceN space. + /// The alternate entry as stored. + /// The tint transform entry as stored. + /// The number of colourants. + /// Whether the colourants are All or None, for which both are ignored (but shall still be valid). + /// : the space stays usable. + public static bool Check(PdfColorSpace space, CosObject alternate, CosObject tint, int inputs, bool special) + { + ColorSpaceCache cache = space.Cache!; + PdfColorSpace? found = cache.Find(alternate, space.DiagnosticReference, space.IsInline, out ColorSpaceFailure failure); + if (found is null) + { + ColorSpaceCache.ReportFailure(space, failure, "an alternate colour space"); + } + else if (!IsAlternateFamily(found)) + { + space.Report(DiagnosticCodes.ColorSpaceEntryInvalid, "An alternate colour space shall be a device or CIE-based space; DeviceGray is used."); + } + + int outputs = Alternate(found).ComponentCount; + PdfFunction? function = Function(cache, tint, inputs, outputs); + if (function is not { IsValid: true }) + { + space.Report( + DiagnosticCodes.TintTransformInvalid, + special + ? "The tint transform is not a usable function; it is not needed for the colourants All and None." + : "The tint transform is not a usable function; tints are converted as subtractive ink on the alternate space instead."); + } + else if (function.InputCount != inputs || function.OutputCount < outputs) + { + space.Report( + DiagnosticCodes.TintTransformInvalid, + string.Create( + CultureInfo.InvariantCulture, + $"The tint transform takes {function.InputCount} inputs and gives {function.OutputCount} outputs where {inputs} and {outputs} are needed; missing outputs read as 0.")); + } + + return true; + } +} diff --git a/src/Broadside/Graphics/ComponentRange.cs b/src/Broadside/Graphics/ComponentRange.cs new file mode 100644 index 00000000..45893760 --- /dev/null +++ b/src/Broadside/Graphics/ComponentRange.cs @@ -0,0 +1,13 @@ +namespace Broadside.Graphics; + +/// The interval a colour component's values lie in. +/// The smallest value. +/// The largest value. +/// ISO 32000-2 §8.6.2: a colour value is one number per component, each within the range its colour space defines. +public readonly record struct ComponentRange(double Minimum, double Maximum) +{ + /// Returns clipped into the range; NaN becomes . + /// The value. + /// The nearest value in the range. + public double Clamp(double value) => value >= Minimum ? Math.Min(value, Maximum) : Minimum; +} diff --git a/src/Broadside/Graphics/DeviceColorModel.cs b/src/Broadside/Graphics/DeviceColorModel.cs new file mode 100644 index 00000000..0225a2e0 --- /dev/null +++ b/src/Broadside/Graphics/DeviceColorModel.cs @@ -0,0 +1,15 @@ +namespace Broadside.Graphics; + +/// The device colour model a colour is converted to. +/// ISO 32000-2 §10.2 and §10.4: an output device's native colour space is gray, RGB or CMYK. +public enum DeviceColorModel +{ + /// Additive red, green and blue, as for a display (three components, 0 to 1); the default. + Rgb, + + /// A single gray level (one component, 0 black to 1 white). + Gray, + + /// Subtractive cyan, magenta, yellow and black (four components, 0 to 1). + Cmyk, +} diff --git a/src/Broadside/Graphics/GraphicsState.cs b/src/Broadside/Graphics/GraphicsState.cs index 6488f412..bf240481 100644 --- a/src/Broadside/Graphics/GraphicsState.cs +++ b/src/Broadside/Graphics/GraphicsState.cs @@ -15,9 +15,9 @@ namespace Broadside.Graphics; /// path and the text matrices are not part of it (§8.5.2.1, §9.4.1). /// /// -/// Parameters set by operators that later issues implement (the gs parameters of §8.4.5, colours of §8.6, text state of -/// §9.3) hold their initial values until then; members for parameters whose values are document-model objects (font, colours, -/// soft mask, transfer functions, halftone) are added with those objects. Numeric parameters are always within their valid ranges: +/// Parameters set by operators that later issues implement (the gs parameters of §8.4.5, text state of §9.3) hold their +/// initial values until then; members for parameters whose values are document-model objects (font, soft mask, transfer +/// functions, halftone) are added with those objects. The colours (§8.6) are values. Numeric parameters are always within their valid ranges: /// the interpreter clips out-of-range operands and records a diagnostic (§8.4.1). /// /// @@ -27,6 +27,8 @@ public struct GraphicsState private DashBuffer _dash; private double[]? _dashOverflow; private int _dashCount; + private PdfColor _strokeColor; + private PdfColor _fillColor; /// Gets the current transformation matrix: user space to the run's default user space. /// ISO 32000-2 §8.3.2.3, Table 51. Changed by cm (Table 56). @@ -64,6 +66,23 @@ public struct GraphicsState /// ISO 32000-2 §8.4.3.6: a negative phase is incremented by twice the sum of the dash array until it is not negative. public double DashPhase { readonly get; internal set; } + /// Gets the colour used for stroking: its colour space and values. Initially DeviceGray black (0). + /// + /// ISO 32000-2 §8.6.8, Tables 51 and 73. Set by CS SC SCN G RG K. The space is the one the operator selected; a default + /// colour space replaces a device space when painting (§8.6.5.6, ). + /// + [UnscopedRef] + public readonly ref readonly PdfColor StrokeColor => ref _strokeColor; + + /// Gets the colour used for all other painting: its colour space and values. Initially DeviceGray black (0). + /// ISO 32000-2 §8.6.8, Tables 51 and 73. Set by cs sc scn g rg k; see . + [UnscopedRef] + public readonly ref readonly PdfColor FillColor => ref _fillColor; + + /// Gets whether colour conversions compensate for black points. Initially . + /// ISO 32000-2 §8.6.5.9, Table 52. Set through gs (UseBlackPtComp, PDF 2.0). + public BlackPointCompensation BlackPointCompensation { readonly get; internal set; } + /// Gets the colour rendering intent. Initially . /// ISO 32000-2 §8.6.5.8, Table 52. Set by ri (Table 56). public RenderingIntent RenderingIntent { readonly get; internal set; } @@ -147,8 +166,25 @@ public struct GraphicsState FillAlpha = 1.0, TextKnockout = true, HorizontalScaling = 1.0, + _strokeColor = PdfDeviceGrayColorSpace.Instance.GetInitialColor(), + _fillColor = PdfDeviceGrayColorSpace.Instance.GetInitialColor(), }; + /// Sets the stroking or the non-stroking colour. + /// Whether the stroking colour is set. + /// The colour. + internal void SetColor(bool stroke, in PdfColor color) + { + if (stroke) + { + _strokeColor = color; + } + else + { + _fillColor = color; + } + } + /// Sets the dash pattern; the elements are copied. A pattern longer than the inline storage gets its own array. internal void SetDash(ReadOnlySpan array, double phase) { diff --git a/src/Broadside/Graphics/IColorConverter.cs b/src/Broadside/Graphics/IColorConverter.cs new file mode 100644 index 00000000..d67479bb --- /dev/null +++ b/src/Broadside/Graphics/IColorConverter.cs @@ -0,0 +1,21 @@ +namespace Broadside.Graphics; + +/// Converts colours from one source space to a device colour model; made by an . +/// +/// ISO 32000-2 §10.3 and §10.4. Implementations are immutable and thread-safe, and should not allocate per call: the library calls +/// once per run of colours (an image row, a batch of tints), never per pixel. +/// +public interface IColorConverter +{ + /// Gets the number of components of a source colour. + int InputCount { get; } + + /// Gets the number of components of a device colour: 1 for gray, 3 for RGB, 4 for CMYK, each 0 to 1. + int OutputCount { get; } + + /// Converts colours stored one after the other. + /// At least × component values, each within its range. + /// At least × values; receives the device colours. + /// The number of colours. + void Convert(ReadOnlySpan source, Span destination, int count); +} diff --git a/src/Broadside/Graphics/IColorManagement.cs b/src/Broadside/Graphics/IColorManagement.cs new file mode 100644 index 00000000..9e70abf1 --- /dev/null +++ b/src/Broadside/Graphics/IColorManagement.cs @@ -0,0 +1,30 @@ +namespace Broadside.Graphics; + +/// +/// The colour-management extension point: creates the converters that turn colours of device, CIE-based and ICCBased spaces into +/// device colours. The managed default is ; replace it with +/// , for instance with an ICC engine or a decorator over the default. +/// +/// +/// +/// ISO 32000-2 §8.6.5 (CIE-based spaces and ICC profiles), §10.3 (CIE-based to device colour, per ICC.1:2010) and §10.4 (device to +/// device). The library expands the special spaces itself before calling an implementation: an Indexed colour becomes its base +/// colour, a Separation or DeviceN tint goes through its tint transform to the alternate space, default colour spaces replace device +/// spaces. An implementation therefore only ever receives a source of the families DeviceGray, DeviceRGB, DeviceCMYK, CalGray, +/// CalRGB, Lab and ICCBased, with every component already clipped into its range. +/// +/// +/// Converters are requested once per document, source space and conversion, and then used from any number of threads at once. +/// +/// +public interface IColorManagement +{ + /// Creates a converter from to the device colour model of . + /// The source space: a device, CIE-based or ICCBased space. + /// The target model, rendering intent and device controls. + /// + /// A converter taking values per colour and giving 1, 3 or 4 (gray, RGB, CMYK); immutable + /// and safe to use from several threads at once. + /// + IColorConverter CreateConverter(PdfColorSpace source, ColorConversion conversion); +} diff --git a/src/Broadside/Graphics/IccProfileHeader.cs b/src/Broadside/Graphics/IccProfileHeader.cs new file mode 100644 index 00000000..5edf43ac --- /dev/null +++ b/src/Broadside/Graphics/IccProfileHeader.cs @@ -0,0 +1,121 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Broadside.Graphics; + +/// The 128-byte header of an ICC colour profile: its version, class, colour spaces and rendering intent. +/// +/// +/// ICC.1:2022 §7.2, Tables 17 to 19, as ISO 32000-2 §8.6.5.5 (Tables 66 and 67) needs it to decide whether a profile can be used +/// in PDF. Signatures are kept as their four characters, trailing spaces included ("RGB ", "Lab "). Only the header +/// is read; the profile's tags are the colour-management engine's business. +/// +/// +public sealed class IccProfileHeader +{ + /// The length of the header, which is also the offset of the tag table. + public const int Length = 128; + + private IccProfileHeader() + { + } + + /// Gets the profile size the header states, in bytes. + /// ICC.1:2022 §7.2.2. + public long ProfileSize { get; private init; } + + /// Gets the preferred CMM type signature; empty when zero. + /// ICC.1:2022 §7.2.3. + public string PreferredCmm { get; private init; } = string.Empty; + + /// Gets the profile version: major, minor and bug-fix numbers (for instance 2.1.0 or 4.4.0). + /// ICC.1:2022 §7.2.4. + public Version Version { get; private init; } = new(0, 0, 0); + + /// Gets the profile/device class signature: scnr, mntr, prtr, link, spac, abst or nmcl. + /// ICC.1:2022 §7.2.5, Table 18. + public string DeviceClass { get; private init; } = string.Empty; + + /// Gets the data colour space signature, such as "GRAY", "RGB ", "CMYK" or "Lab ". + /// ICC.1:2022 §7.2.6, Table 19. + public string DataColorSpace { get; private init; } = string.Empty; + + /// Gets the profile connection space signature: "XYZ " or "Lab ". + /// ICC.1:2022 §7.2.7. + public string ConnectionSpace { get; private init; } = string.Empty; + + /// Gets the number of components of the data colour space; 0 when the signature is not one Table 19 lists. + /// ICC.1:2022 Table 19. + public int ComponentCount { get; private init; } + + /// Gets the rendering intent the header records (which PDF ignores, §8.6.5.5). + /// ICC.1:2022 §7.2.15. + public RenderingIntent RenderingIntent { get; private init; } + + /// Gets the illuminant of the profile connection space, D50 in conforming profiles. + /// ICC.1:2022 §7.2.16. + public CieXyz Illuminant { get; private init; } + + /// + /// Gets a value indicating whether PDF allows the profile in an ICCBased colour space: a scanner, monitor, printer or colour space + /// class profile of a gray, RGB, CMYK or Lab data colour space, version 2 to 4. + /// + /// + /// ISO 32000-2 §8.6.5.5, Table 67 (classes and spaces) and Table 66 (versions: a reader shall support ICC.1:2010, version 4, and + /// shall use the alternate for later versions it cannot process). + /// + public bool IsSupportedForPdf => + DeviceClass is "scnr" or "mntr" or "prtr" or "spac" + && DataColorSpace is "GRAY" or "RGB " or "CMYK" or "Lab " + && Version.Major is >= 2 and <= 4; + + /// Reads the header at the start of a profile. + /// The profile's bytes (at least the first 128). + /// The header; when there are fewer than 128 bytes or the acsp signature is missing. + /// ICC.1:2022 §7.2.9: bytes 36 to 39 are the profile file signature acsp. + public static IccProfileHeader? Parse(ReadOnlySpan profile) + { + if (profile.Length < Length || !profile.Slice(36, 4).SequenceEqual("acsp"u8)) + { + return null; + } + + string space = Signature(profile.Slice(16, 4)); + uint intent = BinaryPrimitives.ReadUInt32BigEndian(profile.Slice(64, 4)); + return new IccProfileHeader + { + ProfileSize = BinaryPrimitives.ReadUInt32BigEndian(profile), + PreferredCmm = Signature(profile.Slice(4, 4)), + Version = new Version(profile[8], profile[9] >> 4, profile[9] & 0xF), + DeviceClass = Signature(profile.Slice(12, 4)), + DataColorSpace = space, + ConnectionSpace = Signature(profile.Slice(20, 4)), + ComponentCount = ComponentsOf(space), + RenderingIntent = intent switch + { + 0 => RenderingIntent.Perceptual, + 2 => RenderingIntent.Saturation, + 3 => RenderingIntent.AbsoluteColorimetric, + _ => RenderingIntent.RelativeColorimetric, + }, + Illuminant = new CieXyz(Fixed(profile[68..]), Fixed(profile[72..]), Fixed(profile[76..])), + }; + } + + /// The number of components of a data colour space signature (ICC.1:2022 Table 19); 0 when unknown. + private static int ComponentsOf(string signature) => signature switch + { + "GRAY" => 1, + "XYZ " or "Lab " or "Luv " or "YCbr" or "Yxy " or "RGB " or "HSV " or "HLS " or "CMY " => 3, + "CMYK" => 4, + [char digit, 'C', 'L', 'R'] when digit is >= '2' and <= '9' => digit - '0', + [char letter, 'C', 'L', 'R'] when letter is >= 'A' and <= 'F' => letter - 'A' + 10, + _ => 0, + }; + + private static string Signature(ReadOnlySpan bytes) => + BinaryPrimitives.ReadUInt32BigEndian(bytes) == 0 ? string.Empty : Encoding.Latin1.GetString(bytes); + + /// An s15Fixed16Number (ICC.1:2022 §4.6). + private static double Fixed(ReadOnlySpan bytes) => BinaryPrimitives.ReadInt32BigEndian(bytes) / 65536.0; +} diff --git a/src/Broadside/Graphics/ManagedColorManagement.cs b/src/Broadside/Graphics/ManagedColorManagement.cs new file mode 100644 index 00000000..f6e29e2a --- /dev/null +++ b/src/Broadside/Graphics/ManagedColorManagement.cs @@ -0,0 +1,61 @@ +using Broadside.Graphics.Colors; + +namespace Broadside.Graphics; + +/// +/// The managed default of the colour-management extension point: the device formulas of §10.4.2, the CIE equations of §8.6.5 to +/// sRGB, and ICCBased colours through their alternate space, until the ICC engine arrives (Phase 3). +/// +/// +/// +/// ISO 32000-2 §10.3 and §10.4. Device to device conversions follow §10.4.2, except DeviceCMYK to RGB, which by default uses a +/// characterisation of SWOP printing () because the formula of §10.4.2.5 turns 100 % cyan +/// into (0, 1, 1) where every viewer shows about (0, 0.68, 0.94); keeps the formula. RGB to CMYK uses the +/// graphics state's black generation and undercolour removal, or BG(k) = k and UCR(k) = k when it has none. +/// +/// +/// CalGray, CalRGB and Lab go through XYZ, Bradford adaptation to D65 and the sRGB primaries, with black point compensation unless +/// it is off. An ICCBased space whose profile is a Lab profile is converted as Lab (its values would be meaningless to an RGB +/// alternate); any other converts through . +/// +/// +public sealed class ManagedColorManagement : IColorManagement +{ + /// Initializes a new instance of the class. + /// How DeviceCMYK converts to RGB and gray. + public ManagedColorManagement(CmykConversion cmykConversion = CmykConversion.Characterized) => CmykConversion = cmykConversion; + + /// Gets the default instance, with the characterised CMYK conversion. + public static ManagedColorManagement Default { get; } = new(); + + /// Gets an instance that converts DeviceCMYK by the formulas of §10.4.2 exactly. + public static ManagedColorManagement Classic { get; } = new(CmykConversion.Classic); + + /// Gets how DeviceCMYK converts to RGB and gray. + public CmykConversion CmykConversion { get; } + + /// + /// is an Indexed, Pattern, Separation or DeviceN space. + public IColorConverter CreateConverter(PdfColorSpace source, ColorConversion conversion) + { + ArgumentNullException.ThrowIfNull(source); + switch (source) + { + case PdfDeviceGrayColorSpace or PdfDeviceRgbColorSpace or PdfDeviceCmykColorSpace: + return new DeviceConverter(source.Family, conversion, CmykConversion); + case PdfCalGrayColorSpace calGray: + return CieConverter.ForCalGray(calGray, conversion); + case PdfCalRgbColorSpace calRgb: + return CieConverter.ForCalRgb(calRgb, conversion); + case PdfLabColorSpace lab: + return CieConverter.ForLab(lab, conversion); + case PdfIccBasedColorSpace icc when icc.IsLabProfile: + return CieConverter.ForIccLab(icc, conversion); + case PdfIccBasedColorSpace icc: + PdfColorSpace alternate = icc.Alternate; + return new IccAlternateConverter(icc, alternate, CreateConverter(alternate, conversion)); + default: + throw new ArgumentException($"Colour management converts device, CIE-based and ICCBased spaces, not {source.Family}.", nameof(source)); + } + } +} diff --git a/src/Broadside/Graphics/PdfCalGrayColorSpace.cs b/src/Broadside/Graphics/PdfCalGrayColorSpace.cs new file mode 100644 index 00000000..de34fbfb --- /dev/null +++ b/src/Broadside/Graphics/PdfCalGrayColorSpace.cs @@ -0,0 +1,67 @@ +using Broadside.Graphics.Colors; +using Broadside.Graphics.Functions; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Graphics; + +/// A CalGray colour space: one component A, 0 to 1, calibrated by a white point and a gamma. +/// +/// ISO 32000-2 §8.6.5.2, Table 62: [/CalGray dictionary]. A maps to X = XW·A^G, Y = YW·A^G, Z = ZW·A^G. A missing or +/// invalid white point reads as D65, a negative black point as [0 0 0] and a gamma that is not positive as 1, each recorded once. +/// +public sealed class PdfCalGrayColorSpace : PdfColorSpace +{ + internal PdfCalGrayColorSpace(ColorSpaceCache cache, CosArray array, CosReference? reference) + : base(cache, array, reference) + { + } + + /// + public override PdfColorSpaceFamily Family => PdfColorSpaceFamily.CalGray; + + /// + public override int ComponentCount => 1; + + /// Gets the CalGray dictionary; empty when the array has none. + public CosDictionary Dictionary => Element(1) as CosDictionary ?? []; + + /// Gets the diffuse white point, WhitePoint; D65 when missing or invalid. + /// ISO 32000-2 Table 62 (required). + public CieXyz WhitePoint => ColorEntries.WhitePoint(Cache!, Dictionary) ?? CieXyz.D65; + + /// Gets the diffuse black point, BlackPoint; [0 0 0] when missing or invalid. + /// ISO 32000-2 Table 62. + public CieXyz BlackPoint => ColorEntries.BlackPoint(Cache!, Dictionary, out _) ?? default; + + /// Gets the gamma G, Gamma; 1 when missing or not positive. + /// ISO 32000-2 Table 62. + public double Gamma => ColorEntries.Number(Cache!, Dictionary, ColorSpaceNames.Gamma) is > 0 and double gamma ? gamma : 1; + + /// + internal override bool Validate() + { + if (CieChecks.Dictionary(this, Element(1), "CalGray") is not { } dictionary) + { + return true; + } + + CieChecks.WhiteAndBlack(this, Cache!, dictionary, "CalGray"); + if (dictionary.ContainsKey(ColorSpaceNames.Gamma) && ColorEntries.Number(Cache!, dictionary, ColorSpaceNames.Gamma) is not > 0) + { + Report(DiagnosticCodes.ColorSpaceEntryInvalid, "A CalGray Gamma is not a positive number; 1 is used."); + } + + return true; + } + + /// + internal override void AddDependencies(List dependencies) + { + base.AddDependencies(dependencies); + if (Element(1) is CosDictionary dictionary) + { + dependencies.Add(new FunctionDependency(dictionary, dictionary.Version)); + } + } +} diff --git a/src/Broadside/Graphics/PdfCalRgbColorSpace.cs b/src/Broadside/Graphics/PdfCalRgbColorSpace.cs new file mode 100644 index 00000000..a2465f77 --- /dev/null +++ b/src/Broadside/Graphics/PdfCalRgbColorSpace.cs @@ -0,0 +1,81 @@ +using Broadside.Graphics.Colors; +using Broadside.Graphics.Functions; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Graphics; + +/// A CalRGB colour space: components A, B and C, each 0 to 1, calibrated by a white point, gammas and a matrix. +/// +/// ISO 32000-2 §8.6.5.3, Table 63: [/CalRGB dictionary]. X = XA·A^GR + XB·B^GG + XC·C^GB, and likewise Y and Z, with +/// Matrix = [XA YA ZA XB YB ZB XC YC ZC]. Missing or invalid entries read as their defaults (a white point as D65), each +/// recorded once. +/// +public sealed class PdfCalRgbColorSpace : PdfColorSpace +{ + private static readonly double[] IdentityMatrix = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + + internal PdfCalRgbColorSpace(ColorSpaceCache cache, CosArray array, CosReference? reference) + : base(cache, array, reference) + { + } + + /// + public override PdfColorSpaceFamily Family => PdfColorSpaceFamily.CalRgb; + + /// + public override int ComponentCount => 3; + + /// Gets the CalRGB dictionary; empty when the array has none. + public CosDictionary Dictionary => Element(1) as CosDictionary ?? []; + + /// Gets the diffuse white point, WhitePoint; D65 when missing or invalid. + /// ISO 32000-2 Table 63 (required). + public CieXyz WhitePoint => ColorEntries.WhitePoint(Cache!, Dictionary) ?? CieXyz.D65; + + /// Gets the diffuse black point, BlackPoint; [0 0 0] when missing or invalid. + /// ISO 32000-2 Table 63. + public CieXyz BlackPoint => ColorEntries.BlackPoint(Cache!, Dictionary, out _) ?? default; + + /// Gets the gammas [GR GG GB], Gamma; [1 1 1] when missing or invalid. + /// ISO 32000-2 Table 63. + public IReadOnlyList Gamma => + ColorEntries.Numbers(Cache!, Dictionary, ColorSpaceNames.Gamma) is [> 0, > 0, > 0] gamma ? gamma : [1.0, 1.0, 1.0]; + + /// Gets the linear interpretation of the decoded components, Matrix; the identity when missing or invalid. + /// ISO 32000-2 Table 63: [XA YA ZA XB YB ZB XC YC ZC]. + public IReadOnlyList Matrix => + ColorEntries.Numbers(Cache!, Dictionary, ColorSpaceNames.Matrix) is { Length: 9 } matrix ? matrix : IdentityMatrix; + + /// + internal override bool Validate() + { + if (CieChecks.Dictionary(this, Element(1), "CalRGB") is not { } dictionary) + { + return true; + } + + CieChecks.WhiteAndBlack(this, Cache!, dictionary, "CalRGB"); + if (dictionary.ContainsKey(ColorSpaceNames.Gamma) && ColorEntries.Numbers(Cache!, dictionary, ColorSpaceNames.Gamma) is not [> 0, > 0, > 0]) + { + Report(DiagnosticCodes.ColorSpaceEntryInvalid, "A CalRGB Gamma is not three positive numbers; [1 1 1] is used."); + } + + if (dictionary.ContainsKey(ColorSpaceNames.Matrix) && ColorEntries.Numbers(Cache!, dictionary, ColorSpaceNames.Matrix) is not { Length: 9 }) + { + Report(DiagnosticCodes.ColorSpaceEntryInvalid, "A CalRGB Matrix is not nine numbers; the identity is used."); + } + + return true; + } + + /// + internal override void AddDependencies(List dependencies) + { + base.AddDependencies(dependencies); + if (Element(1) is CosDictionary dictionary) + { + dependencies.Add(new FunctionDependency(dictionary, dictionary.Version)); + } + } +} diff --git a/src/Broadside/Graphics/PdfColor.cs b/src/Broadside/Graphics/PdfColor.cs new file mode 100644 index 00000000..91bc6677 --- /dev/null +++ b/src/Broadside/Graphics/PdfColor.cs @@ -0,0 +1,142 @@ +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; +using Broadside.Objects; + +namespace Broadside.Graphics; + +/// +/// A colour: a colour space and one number per component, as a colour operator sets it; for the Pattern colour space, also the +/// pattern. A value type with its components stored inline, so setting a colour allocates nothing. +/// +/// +/// +/// ISO 32000-2 §8.6.2 (colour values), §8.6.8 (colour operators, Table 73) and §8.7.3 (patterns). The components are kept as the +/// content stream gave them; conversion () clips each into its component's range. The colour space is +/// the one the operator selected: a DefaultRGB resource replaces DeviceRGB only when the colour is painted (§8.6.5.6), through +/// . +/// +/// +/// A colour in the Pattern colour space names its pattern (, ) and carries the matrix +/// of the content stream that named it (), the space the pattern matrix maps into (§8.7.2); for an +/// uncoloured tiling pattern the components are in the underlying colour space (§8.7.3.3). +/// +/// +public readonly struct PdfColor : IEquatable +{ + /// The most components a colour stores; a DeviceN colour space with more is painted through its alternate. + /// ISO 32000-2 Annex C, Table C.1: earlier PDF versions limited DeviceN to 32 colourants. + public const int MaxComponents = 32; + + private readonly PdfColorSpace? _colorSpace; + private readonly ComponentBuffer _components; + + /// Initializes a new instance of the struct. + /// The colour space. + /// The component values; values are not clipped. + /// There are more than components. + public PdfColor(PdfColorSpace colorSpace, ReadOnlySpan components) + { + ArgumentNullException.ThrowIfNull(colorSpace); + if (components.Length > MaxComponents) + { + throw new ArgumentException($"A colour has at most {MaxComponents} components.", nameof(components)); + } + + _colorSpace = colorSpace; + components.CopyTo(_components); + ComponentCount = components.Length; + PatternMatrix = Matrix.Identity; + } + + /// Initializes a new instance of the struct in the Pattern colour space. + internal PdfColor(PdfColorSpace colorSpace, ReadOnlySpan components, CosName? patternName, CosObject? pattern, Matrix patternMatrix) + : this(colorSpace, components) + { + PatternName = patternName; + Pattern = pattern; + PatternMatrix = patternMatrix; + } + + /// Gets the colour space; DeviceGray for a default instance. + public PdfColorSpace ColorSpace => _colorSpace ?? PdfDeviceGrayColorSpace.Instance; + + /// Gets the number of components. + public int ComponentCount { get; } + + /// Gets the component values. + [UnscopedRef] + public ReadOnlySpan Components => ((ReadOnlySpan)_components)[..ComponentCount]; + + /// Gets the name of the pattern in the Pattern subdictionary of the resources, for a Pattern colour. + /// ISO 32000-2 §8.6.8 (scn): for other colours and for the initial Pattern colour. + public CosName? PatternName { get; } + + /// Gets the pattern dictionary or stream the name resolved to, or when there is none. + /// ISO 32000-2 §8.7.3: a pattern colour with no pattern paints nothing (the initial colour of the Pattern space, Table 73). + public CosObject? Pattern { get; } + + /// + /// Gets the matrix of the content stream in which the pattern was selected (its CTM at the start of that stream), which the + /// pattern matrix maps pattern space into; the identity for colours that are not patterns. + /// + /// ISO 32000-2 §8.7.2. + public Matrix PatternMatrix { get; } + + /// Gets the value of component . + /// The component, from 0. + /// The value. + /// is not less than . + public float this[int index] + { + get + { + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, ComponentCount); + return _components[index]; + } + } + + /// Compares two colours by space, components and pattern. + /// The first colour. + /// The second colour. + /// when equal. + public static bool operator ==(PdfColor left, PdfColor right) => left.Equals(right); + + /// Compares two colours by space, components and pattern. + /// The first colour. + /// The second colour. + /// when different. + public static bool operator !=(PdfColor left, PdfColor right) => !left.Equals(right); + + /// + public bool Equals(PdfColor other) => + ReferenceEquals(ColorSpace, other.ColorSpace) + && Components.SequenceEqual(other.Components) + && Equals(PatternName, other.PatternName) + && ReferenceEquals(Pattern, other.Pattern) + && PatternMatrix == other.PatternMatrix; + + /// + public override bool Equals(object? obj) => obj is PdfColor other && Equals(other); + + /// + public override int GetHashCode() + { + var hash = default(HashCode); + hash.Add(ColorSpace); + foreach (float component in Components) + { + hash.Add(component); + } + + hash.Add(PatternName); + return hash.ToHashCode(); + } + + /// Storage for up to 32 components, so a colour is a value with no heap object behind it. + [InlineArray(MaxComponents)] + private struct ComponentBuffer + { + private float _element; + } +} diff --git a/src/Broadside/Graphics/PdfColorConverter.cs b/src/Broadside/Graphics/PdfColorConverter.cs new file mode 100644 index 00000000..9e1e285e --- /dev/null +++ b/src/Broadside/Graphics/PdfColorConverter.cs @@ -0,0 +1,183 @@ +using Broadside.Graphics.Colors; +using Broadside.Graphics.Functions; + +namespace Broadside.Graphics; + +/// +/// Converts colours of any colour space to a device colour model: the special spaces expanded, default colour spaces applied, and the +/// rest through the engine's colour management. Get one from . +/// +/// +/// +/// ISO 32000-2 §8.6 and §10.3 to §10.4. An Indexed colour is looked up in its table, converted once; a Separation or DeviceN tint +/// goes through its tint transform to the alternate space (a display always uses the alternate), except the colourant All +/// (1 − tint on every additive component) and None (); a Pattern colour converts through the +/// underlying space of an uncoloured pattern. Device spaces, including a nested Indexed base, Pattern underlying space and +/// Separation or DeviceN alternate, are replaced by the given defaults (§8.6.5.6). What remains, a device, CIE-based or ICCBased +/// space, goes to the the engine was configured with, every component clipped into its range first. +/// +/// +/// A converter is built once per document, source, conversion and defaults, and again when a COS object it was built from changes. +/// It is immutable, safe to use from several threads at once, and allocates nothing per call. +/// +/// +public sealed class PdfColorConverter +{ + private readonly ColorPipeline _pipeline; + private readonly FunctionDependency[] _dependencies; + + private PdfColorConverter(PdfColorSpace source, ColorConversion conversion, ColorPipeline pipeline, FunctionDependency[] dependencies) + { + Source = source; + Conversion = conversion; + _pipeline = pipeline; + _dependencies = dependencies; + } + + /// Gets the colour space converted from, as selected (before default colour spaces apply). + public PdfColorSpace Source { get; } + + /// Gets the conversion: target model, rendering intent and device controls. + public ColorConversion Conversion { get; } + + /// Gets the number of components of a source colour. + public int InputCount => _pipeline.InputCount; + + /// Gets the number of components of a device colour: 1, 3 or 4. + public int OutputCount => _pipeline.OutputCount; + + /// Gets a value indicating whether colours of the source space paint nothing (Separation None, an all-None DeviceN). + /// ISO 32000-2 §8.6.6.4 and §8.6.6.5. Converted colours are then no ink: white, or CMYK 0 0 0 0. + public bool PaintsNothing => _pipeline.PaintsNothing; + + /// Gets a value indicating whether nothing the converter was built from has changed since. + internal bool IsCurrent + { + get + { + foreach (FunctionDependency dependency in _dependencies) + { + if (!dependency.IsCurrent) + { + return false; + } + } + + return true; + } + } + + /// Converts one colour. + /// The colour; its components beyond are ignored and missing ones read as 0. + /// At least values; receives the device colour, each 0 to 1. + /// is too short. + public void Convert(in PdfColor color, Span destination) => Convert(color.Components, destination); + + /// Converts one colour given as its components. + /// The components; values beyond are ignored and missing ones read as 0. + /// At least values; receives the device colour, each 0 to 1. + /// is too short. + public void Convert(ReadOnlySpan components, Span destination) + { + if (destination.Length < OutputCount) + { + throw new ArgumentException("There is less room than the device colour needs.", nameof(destination)); + } + + int inputs = InputCount; + Span input = stackalloc float[Math.Max(inputs, 1)]; + input.Clear(); + components[..Math.Min(components.Length, inputs)].CopyTo(input); + _pipeline.Convert(input[..inputs], destination, 1); + } + + /// Converts colours stored one after the other. + /// At least × component values. + /// At least × values; receives the device colours. + /// The number of colours. + /// is negative. + /// A span is too short for colours. + public void Convert(ReadOnlySpan source, Span destination, int count) + { + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfLessThan(source.Length, (long)count * InputCount, nameof(source)); + ArgumentOutOfRangeException.ThrowIfLessThan(destination.Length, (long)count * OutputCount, nameof(destination)); + _pipeline.Convert(source, destination, count); + } + + /// Converts colours of 8-bit samples, as an image row holds them, to 8-bit device colours. + /// + /// At least × samples. Each maps linearly from 0..255 onto its component's + /// range (the default Decode of Table 88), except in an Indexed space, where a sample is the index. + /// + /// At least × bytes; receives the device colours, 0 to 255. + /// The number of colours. + /// is negative. + /// A span is too short for colours. + /// ISO 32000-2 §8.9.5.2. One-component spaces convert through a table of 256 colours built once. + public void Convert(ReadOnlySpan source, Span destination, int count) + { + ArgumentOutOfRangeException.ThrowIfNegative(count); + ArgumentOutOfRangeException.ThrowIfLessThan(source.Length, (long)count * InputCount, nameof(source)); + ArgumentOutOfRangeException.ThrowIfLessThan(destination.Length, (long)count * OutputCount, nameof(destination)); + _pipeline.Convert(source, destination, count); + } + + /// Builds the converter. + internal static PdfColorConverter Create(ColorSpaceCache cache, PdfColorSpace source, ColorConversion conversion, PdfDefaultColorSpaces defaults) + { + var dependencies = new List(); + ColorPipeline pipeline = Build(cache, source, conversion, defaults, dependencies, depth: 0); + return new PdfColorConverter(source, conversion, pipeline, [.. dependencies]); + } + + private static ColorPipeline Build(ColorSpaceCache cache, PdfColorSpace space, ColorConversion conversion, PdfDefaultColorSpaces defaults, List dependencies, int depth) + { + int outputs = DeviceConverter.Outputs(conversion.Target); + PdfColorSpace remapped = defaults.Remap(space); + if (!ReferenceEquals(remapped, space)) + { + // §8.6.5.6: a default is not itself remapped. + space = remapped; + defaults = PdfDefaultColorSpaces.None; + } + + space.AddDependencies(dependencies); + if (depth > 2 * ColorSpaceCache.MaxDepth) + { + return Build(cache, PdfDeviceGrayColorSpace.Instance, conversion, PdfDefaultColorSpaces.None, dependencies, 0); + } + + switch (space) + { + case PdfIndexedColorSpace indexed: + return new IndexedPipeline(indexed, Build(cache, indexed.Base, conversion, defaults, dependencies, depth + 1)); + case PdfSeparationColorSpace separation when separation.IsNone: + return new NoColorantPipeline(1, conversion.Target, outputs); + case PdfSeparationColorSpace separation when separation.IsAll: + return new AllColorantsPipeline(conversion.Target, outputs); + case PdfSeparationColorSpace separation: + return Tint(1, separation.TintTransform, separation.Alternate); + case PdfDeviceNColorSpace deviceN when deviceN.AreAllNone: + return new NoColorantPipeline(deviceN.ComponentCount, conversion.Target, outputs); + case PdfDeviceNColorSpace deviceN: + return Tint(deviceN.ComponentCount, deviceN.TintTransform, deviceN.Alternate); + case PdfPatternColorSpace { Underlying: { } underlying }: + return Build(cache, underlying, conversion, defaults, dependencies, depth + 1); + case PdfPatternColorSpace: + return new PatternPipeline(conversion.Target, outputs); + default: + return new ManagedPipeline(space, cache.Management.CreateConverter(space, conversion), outputs); + } + + ColorPipeline Tint(int inputs, PdfFunction? function, PdfColorSpace alternate) + { + if (function is not null) + { + dependencies.Add(new FunctionDependency(function.CosObject, FunctionDependency.VersionOf(function.CosObject))); + } + + return new TintPipeline(inputs, function, alternate, Build(cache, alternate, conversion, defaults, dependencies, depth + 1)); + } + } +} diff --git a/src/Broadside/Graphics/PdfColorSpace.cs b/src/Broadside/Graphics/PdfColorSpace.cs new file mode 100644 index 00000000..295b9865 --- /dev/null +++ b/src/Broadside/Graphics/PdfColorSpace.cs @@ -0,0 +1,180 @@ +using Broadside.Diagnostics; +using Broadside.Graphics.Colors; +using Broadside.Graphics.Functions; +using Broadside.Objects; + +namespace Broadside.Graphics; + +/// +/// A colour space: how colour values are to be interpreted. A live view over the colour space's name or array; the subclass says +/// which family it is. +/// +/// +/// +/// ISO 32000-2 §8.6.1 to §8.6.3, Table 61. Get one with , from a content stream with +/// , or from the colour in the graphics state (). +/// The device spaces are singletons ( and its siblings); every other space is one +/// instance per colour space object of a document, shared by every caller and thread. +/// +/// +/// Entries are read from the COS objects on every call (ADR 0004), with the repairs lenient reading applies (a missing white point +/// reads as D65, for instance); the deviations themselves are recorded once, when the document first reads the space. A space that +/// cannot be used at all (an unknown family, an Indexed space without a lookup table, a space that refers to itself) is read as +/// DeviceGray. Converting colours to a device is 's job. +/// +/// +public abstract class PdfColorSpace +{ + private protected PdfColorSpace(ColorSpaceCache? cache, CosObject cosObject, CosReference? reference) + { + Cache = cache; + CosObject = cosObject; + Reference = reference; + } + + /// Gets the colour space as stored: a for a family named alone, else a . + /// ISO 32000-2 §8.6.3: "either by name or by an array"; an array's first element names the family. + public CosObject CosObject { get; } + + /// Gets the indirect reference the colour space was reached through, or for a direct object. + public CosReference? Reference { get; } + + /// Gets the colour space family. + /// ISO 32000-2 §8.6.3, Table 61. + public abstract PdfColorSpaceFamily Family { get; } + + /// Gets the number of components of a colour value in this space; 0 for a Pattern space without an underlying space. + /// ISO 32000-2 §8.6.2, §8.6.8 (Table 73: the operand counts of sc and scn). + public abstract int ComponentCount { get; } + + /// Gets the earliest PDF version that has this colour space (Table 61), for a writer raising the file's version (ADR 0003). + /// + /// ISO 32000-2 §8.6.3: the device spaces, CalGray, CalRGB, Lab and Indexed 1.1 (an Indexed lookup string 1.2), Pattern and + /// Separation 1.2, ICCBased and DeviceN 1.3 (DeviceN attributes 1.6). + /// + public virtual PdfVersion MinimumVersion => Family switch + { + PdfColorSpaceFamily.Pattern or PdfColorSpaceFamily.Separation => new PdfVersion(1, 2), + PdfColorSpaceFamily.IccBased or PdfColorSpaceFamily.DeviceN => new PdfVersion(1, 3), + _ => new PdfVersion(1, 1), + }; + + /// Gets the document's colour spaces, for spaces that refer to others; for the device singletons. + internal ColorSpaceCache? Cache { get; } + + /// Gets the object diagnostics about this space are recorded against: its own reference, else its nearest indirect owner. + internal CosReference? DiagnosticReference => Reference ?? OwnerReference; + + /// Gets the nearest indirect object the space was found in, when the space itself is direct. + internal CosReference? OwnerReference { get; init; } + + /// Gets a value indicating whether the space was read from an inline image, where abbreviated names are allowed (§8.9.7). + internal bool IsInline { get; init; } + + /// Returns the range of values component takes. + /// The component, from 0. + /// The range: 0 to 1 unless the family defines another (Lab, ICCBased, Indexed). + /// is not less than . + /// ISO 32000-2 §8.6.2, §8.6.4 to §8.6.6. + public ComponentRange GetComponentRange(int index) + { + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, ComponentCount); + return GetRangeCore(index); + } + + /// Returns the colour CS and cs select along with this space. + /// The initial colour. + /// + /// ISO 32000-2 §8.6.8, Table 73 and §8.6.4 to §8.6.6: 0 for DeviceGray, CalGray and Indexed, 0 0 0 for DeviceRGB and CalRGB, + /// 0 0 0 1 for DeviceCMYK; for Lab and ICCBased each component 0 clipped into its range; 1.0 for every component of Separation + /// and DeviceN; for Pattern, a colour with no pattern, which paints nothing. + /// + public PdfColor GetInitialColor() + { + int count = Math.Min(ComponentCount, PdfColor.MaxComponents); + Span components = stackalloc float[count]; + for (int i = 0; i < count; i++) + { + components[i] = (float)GetInitialComponent(i); + } + + return new PdfColor(this, components); + } + + /// Returns the default Decode array of an image whose samples are in this space. + /// The image's bits per component (an Indexed space maps 0 to 2^bits − 1 onto the table). + /// 2 × numbers; empty for a Pattern space, which images cannot use. + /// ISO 32000-2 §8.9.5.2, Table 88. + public double[] GetDefaultDecode(int bitsPerComponent) + { + if (Family == PdfColorSpaceFamily.Pattern) + { + return []; + } + + if (Family == PdfColorSpaceFamily.Indexed) + { + return [0, Math.Pow(2, Math.Clamp(bitsPerComponent, 1, 16)) - 1]; + } + + double[] decode = new double[2 * ComponentCount]; + for (int i = 0; i < ComponentCount; i++) + { + ComponentRange range = GetRangeCore(i); + decode[2 * i] = range.Minimum; + decode[(2 * i) + 1] = range.Maximum; + } + + return decode; + } + + /// Returns the range of component , already checked. + /// The component. + /// The range. + private protected virtual ComponentRange GetRangeCore(int index) => new(0, 1); + + /// Returns the initial value of component . + /// The component. + /// 0 clipped into the component's range, unless the family says otherwise. + private protected virtual double GetInitialComponent(int index) => GetRangeCore(index).Clamp(0); + + /// Records the deviations of this space, once, when the document first reads it. + /// when the space cannot be used at all and is read as DeviceGray instead. + internal virtual bool Validate() => true; + + /// Adds the containers this space's conversion reads, so a converter built from it notices when they change. + /// The list to add to. + internal virtual void AddDependencies(List dependencies) + { + if (CosObject is CosArray array) + { + dependencies.Add(new FunctionDependency(array, array.Version)); + } + } + + /// Records a deviation found in this space. + /// The diagnostic code. + /// What was found and what is done about it. + /// The severity; Warning unless given. + internal void Report(string code, string message, DiagnosticSeverity severity = DiagnosticSeverity.Warning) => + Cache?.Diagnostics.Report(code, severity, message, offset: null, DiagnosticReference); + + /// Returns the nested colour space at array element , or when there is none. + /// The element. + /// The space as the document reads it; for a missing element, a cycle or nesting too deep. + private protected PdfColorSpace? NestedSpace(int index) => + CosObject is CosArray array && index < array.Count ? Cache!.Find(array[index], DiagnosticReference, IsInline, out _) : null; + + /// Returns the array element at , resolved; the null object when absent. + /// The element. + /// The element. + private protected CosObject Element(int index) => + CosObject is CosArray array && index < array.Count ? Cache!.Resolve(array[index]) : CosNull.Instance; + + /// Returns the unresolved array element at ; the null object when absent. + /// The element. + /// The element as stored. + private protected CosObject RawElement(int index) => + CosObject is CosArray array && index < array.Count ? array[index] : CosNull.Instance; +} diff --git a/src/Broadside/Graphics/PdfColorSpaceFamily.cs b/src/Broadside/Graphics/PdfColorSpaceFamily.cs new file mode 100644 index 00000000..91274a8a --- /dev/null +++ b/src/Broadside/Graphics/PdfColorSpaceFamily.cs @@ -0,0 +1,39 @@ +namespace Broadside.Graphics; + +/// The eleven colour space families of PDF. +/// ISO 32000-2 §8.6.3, Table 61. CalCMYK, removed from PDF, is read as (§8.6.5.1). +public enum PdfColorSpaceFamily +{ + /// DeviceGray (§8.6.4.2). + DeviceGray, + + /// DeviceRGB (§8.6.4.3). + DeviceRgb, + + /// DeviceCMYK (§8.6.4.4). + DeviceCmyk, + + /// CalGray (§8.6.5.2). + CalGray, + + /// CalRGB (§8.6.5.3). + CalRgb, + + /// Lab (§8.6.5.4). + Lab, + + /// ICCBased (§8.6.5.5). + IccBased, + + /// Indexed (§8.6.6.3). + Indexed, + + /// Pattern (§8.6.6.2). + Pattern, + + /// Separation (§8.6.6.4). + Separation, + + /// DeviceN (§8.6.6.5). + DeviceN, +} diff --git a/src/Broadside/Graphics/PdfDefaultColorSpaces.cs b/src/Broadside/Graphics/PdfDefaultColorSpaces.cs new file mode 100644 index 00000000..3140488c --- /dev/null +++ b/src/Broadside/Graphics/PdfDefaultColorSpaces.cs @@ -0,0 +1,60 @@ +namespace Broadside.Graphics; + +/// +/// The default colour spaces of a resource dictionary: the DefaultGray, DefaultRGB and DefaultCMYK entries of its +/// ColorSpace subdictionary, which replace the device spaces when colours are painted. +/// +/// +/// +/// ISO 32000-2 §8.6.5.6. When a device colour space is selected, the default of the current resource dictionary, if any, is used +/// in its place, with the colour values unchanged; this also applies to the base of an Indexed space, the underlying space of a +/// Pattern space and the alternate of a Separation or DeviceN space when the alternate is used. The look-up happens when an object +/// is painted, with the resources current then, so a form XObject's own defaults win inside it. Get the defaults current in a +/// content stream from , or for any resource dictionary from +/// ; applies them. +/// +/// +/// A default with the wrong number of components, or of the Lab, Indexed or Pattern family, is ignored with a diagnostic. A default +/// is not itself remapped (its own device base or alternate stays the device space). +/// +/// +public sealed class PdfDefaultColorSpaces +{ + internal PdfDefaultColorSpaces(PdfColorSpace? gray, PdfColorSpace? rgb, PdfColorSpace? cmyk) + { + Gray = gray; + Rgb = rgb; + Cmyk = cmyk; + } + + /// Gets the defaults of a resource dictionary that has none. + public static PdfDefaultColorSpaces None { get; } = new(null, null, null); + + /// Gets the space that replaces DeviceGray, or . + public PdfColorSpace? Gray { get; } + + /// Gets the space that replaces DeviceRGB, or . + public PdfColorSpace? Rgb { get; } + + /// Gets the space that replaces DeviceCMYK, or . + public PdfColorSpace? Cmyk { get; } + + /// Gets a value indicating whether no device space is replaced. + public bool IsEmpty => Gray is null && Rgb is null && Cmyk is null; + + /// Returns the space a colour selected in is painted in. + /// The selected space. + /// The default for a device space that has one; otherwise. + /// ISO 32000-2 §8.6.5.6. Only the space itself is replaced; nested spaces are replaced when converted. + public PdfColorSpace Remap(PdfColorSpace colorSpace) + { + ArgumentNullException.ThrowIfNull(colorSpace); + return colorSpace.Family switch + { + PdfColorSpaceFamily.DeviceGray => Gray ?? colorSpace, + PdfColorSpaceFamily.DeviceRgb => Rgb ?? colorSpace, + PdfColorSpaceFamily.DeviceCmyk => Cmyk ?? colorSpace, + _ => colorSpace, + }; + } +} diff --git a/src/Broadside/Graphics/PdfDeviceCmykColorSpace.cs b/src/Broadside/Graphics/PdfDeviceCmykColorSpace.cs new file mode 100644 index 00000000..1e469e9a --- /dev/null +++ b/src/Broadside/Graphics/PdfDeviceCmykColorSpace.cs @@ -0,0 +1,28 @@ +using Broadside.Graphics.Colors; + +namespace Broadside.Graphics; + +/// The DeviceCMYK colour space: cyan, magenta, yellow and black, each 0 to 1. +/// +/// ISO 32000-2 §8.6.4.4. Its initial colour is 0 0 0 1 (black). A CalCMYK space, removed from PDF, is read as this one +/// (§8.6.5.1). +/// +public sealed class PdfDeviceCmykColorSpace : PdfColorSpace +{ + private PdfDeviceCmykColorSpace() + : base(null, ColorSpaceNames.DeviceCmyk, null) + { + } + + /// Gets the one instance. + public static PdfDeviceCmykColorSpace Instance { get; } = new(); + + /// + public override PdfColorSpaceFamily Family => PdfColorSpaceFamily.DeviceCmyk; + + /// + public override int ComponentCount => 4; + + /// + private protected override double GetInitialComponent(int index) => index == 3 ? 1 : 0; +} diff --git a/src/Broadside/Graphics/PdfDeviceGrayColorSpace.cs b/src/Broadside/Graphics/PdfDeviceGrayColorSpace.cs new file mode 100644 index 00000000..7cbebc73 --- /dev/null +++ b/src/Broadside/Graphics/PdfDeviceGrayColorSpace.cs @@ -0,0 +1,22 @@ +using Broadside.Graphics.Colors; + +namespace Broadside.Graphics; + +/// The DeviceGray colour space: one component, 0 black to 1 white. +/// ISO 32000-2 §8.6.4.2. The initial colour space of the graphics state (Table 51); its initial colour is 0. +public sealed class PdfDeviceGrayColorSpace : PdfColorSpace +{ + private PdfDeviceGrayColorSpace() + : base(null, ColorSpaceNames.DeviceGray, null) + { + } + + /// Gets the one instance. + public static PdfDeviceGrayColorSpace Instance { get; } = new(); + + /// + public override PdfColorSpaceFamily Family => PdfColorSpaceFamily.DeviceGray; + + /// + public override int ComponentCount => 1; +} diff --git a/src/Broadside/Graphics/PdfDeviceNAttributes.cs b/src/Broadside/Graphics/PdfDeviceNAttributes.cs new file mode 100644 index 00000000..5f18b42c --- /dev/null +++ b/src/Broadside/Graphics/PdfDeviceNAttributes.cs @@ -0,0 +1,79 @@ +using Broadside.Graphics.Colors; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Graphics; + +/// The attributes dictionary of a DeviceN colour space: its subtype, spot colourants, process space and mixing hints. +/// +/// ISO 32000-2 §8.6.6.5, Table 70 (PDF 1.6). A live view; it is read and exposed, while blending by these attributes (NChannel +/// separations, mixing hints) is output-device work beyond a display's needs. +/// +public sealed class PdfDeviceNAttributes +{ + private readonly PdfColorSpace _owner; + + internal PdfDeviceNAttributes(PdfColorSpace owner, CosDictionary dictionary) + { + _owner = owner; + Dictionary = dictionary; + } + + /// Gets the attributes dictionary. + public CosDictionary Dictionary { get; } + + /// Gets the Subtype: DeviceN (the default) or NChannel. + /// ISO 32000-2 Table 70. + public CosName Subtype => Cache.Resolve(Dictionary.GetValueOrDefault(ColorSpaceNames.Subtype)) as CosName ?? ColorSpaceNames.DeviceN; + + /// Gets a value indicating whether is NChannel. + public bool IsNChannel => Subtype.Equals(ColorSpaceNames.NChannel); + + /// Gets the Colorants dictionary: for each spot colourant name, its Separation colour space. + /// ISO 32000-2 Table 70: required for an NChannel space with spot colourants. Entries that are not colour spaces are skipped. + public IReadOnlyDictionary Colorants + { + get + { + var colorants = new Dictionary(); + if (Cache.Resolve(Dictionary.GetValueOrDefault(ColorSpaceNames.Colorants)) is CosDictionary entries) + { + foreach ((CosName name, CosObject value) in entries) + { + if (Cache.Find(value, _owner.DiagnosticReference, inline: false, out _) is { } space) + { + colorants[name] = space; + } + } + } + + return colorants; + } + } + + /// Gets the Process dictionary: the process colour space and which components belong to it, or . + /// ISO 32000-2 Tables 70 and 71. + public PdfDeviceNProcess? Process => + Cache.Resolve(Dictionary.GetValueOrDefault(ColorSpaceNames.Process)) is CosDictionary process ? new PdfDeviceNProcess(_owner, process) : null; + + /// Gets the MixingHints dictionary, or . + /// ISO 32000-2 Tables 70 and 72. + public PdfDeviceNMixingHints? MixingHints => + Cache.Resolve(Dictionary.GetValueOrDefault(ColorSpaceNames.MixingHints)) is CosDictionary hints ? new PdfDeviceNMixingHints(_owner, hints) : null; + + private ColorSpaceCache Cache => _owner.Cache!; + + /// Records what is wrong with the attributes. + internal void Validate() + { + if (Dictionary.TryGetValue(ColorSpaceNames.Colorants, out CosObject? colorants) && Cache.Resolve(colorants) is not CosDictionary) + { + _owner.Report(DiagnosticCodes.ColorSpaceEntryInvalid, "A DeviceN attributes dictionary's Colorants is not a dictionary; it is ignored."); + } + + if (Process is { } process && (process.ColorSpace is null || process.Components.Count == 0)) + { + _owner.Report(DiagnosticCodes.ColorSpaceEntryInvalid, "A DeviceN Process dictionary lacks its ColorSpace or Components; it is ignored."); + } + } +} diff --git a/src/Broadside/Graphics/PdfDeviceNColorSpace.cs b/src/Broadside/Graphics/PdfDeviceNColorSpace.cs new file mode 100644 index 00000000..ee52d0f6 --- /dev/null +++ b/src/Broadside/Graphics/PdfDeviceNColorSpace.cs @@ -0,0 +1,149 @@ +using System.Globalization; +using Broadside.Graphics.Colors; +using Broadside.Graphics.Functions; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Graphics; + +/// A DeviceN colour space: several colourants, each a tint from 0 to 1, with an alternate space and a tint transform. +/// +/// +/// ISO 32000-2 §8.6.6.5, Tables 70 to 72: [/DeviceN names alternateSpace tintTransform attributes], the attributes +/// dictionary optional (PDF 1.6). Names shall be unique except None, and All shall not appear; components named +/// None are never painted directly but still reach the tint transform; a space whose names are all None never paints. +/// A display always paints through the alternate. The initial colour is 1.0 for every component. +/// +/// +/// Repairs: elements of the names array that are not names are skipped; an empty names array makes the space DeviceGray; the +/// alternate and tint transform are repaired as for . +/// +/// +public sealed class PdfDeviceNColorSpace : PdfColorSpace +{ + internal PdfDeviceNColorSpace(ColorSpaceCache cache, CosArray array, CosReference? reference) + : base(cache, array, reference) + { + } + + /// + public override PdfColorSpaceFamily Family => PdfColorSpaceFamily.DeviceN; + + /// + public override PdfVersion MinimumVersion => Element(4) is CosDictionary ? new PdfVersion(1, 6) : new PdfVersion(1, 3); + + /// Gets the names of the colourants, one per component. + /// ISO 32000-2 §8.6.6.5. + public IReadOnlyList ColorantNames + { + get + { + if (Element(1) is not CosArray array) + { + return []; + } + + var names = new List(array.Count); + foreach (CosObject item in array) + { + if (Cache!.Resolve(item) is CosName name) + { + names.Add(name); + } + } + + return names; + } + } + + /// + public override int ComponentCount + { + get + { + if (Element(1) is not CosArray array) + { + return 0; + } + + // Indexed, not foreach: the array's enumerator is boxed, and colour operators read this on every scn. + int count = 0; + for (int i = 0; i < array.Count; i++) + { + count += Cache!.Resolve(array[i]) is CosName ? 1 : 0; + } + + return count; + } + } + + /// Gets a value indicating whether every colourant is None: the space never paints. + public bool AreAllNone => ColorantNames is { Count: > 0 } names && names.All(static name => name.Equals(ColorSpaceNames.None)); + + /// Gets the alternate space, a device or CIE-based space; DeviceGray when the entry is unusable. + public PdfColorSpace Alternate => TintSpaces.Alternate(NestedSpace(2)); + + /// Gets the tint transform, or when the entry is not a function. + /// ISO 32000-2 §8.6.6.5: n inputs, as many outputs as the alternate has components. + public PdfFunction? TintTransform => TintSpaces.Function(Cache!, RawElement(3), ComponentCount, Alternate.ComponentCount); + + /// Gets the attributes dictionary, or when there is none. + /// ISO 32000-2 Table 70 (PDF 1.6). + public PdfDeviceNAttributes? Attributes => Element(4) is CosDictionary dictionary ? new PdfDeviceNAttributes(this, dictionary) : null; + + /// Gets a value indicating whether the attributes say NChannel, the subtype with Colorants, Process and MixingHints semantics. + /// ISO 32000-2 Table 70. + public bool IsNChannel => Attributes?.IsNChannel ?? false; + + /// + internal override bool Validate() + { + IReadOnlyList names = ColorantNames; + if (names.Count == 0) + { + Report(DiagnosticCodes.ColorSpaceInvalid, "A DeviceN colour space has no colourant names; DeviceGray is used."); + return false; + } + + if (Element(1) is CosArray array && array.Count != names.Count) + { + Report(DiagnosticCodes.DeviceNColorantsInvalid, "A DeviceN names array holds something that is not a name; it is skipped."); + } + + var seen = new HashSet(); + foreach (CosName name in names) + { + if (name.Equals(ColorSpaceNames.All) || (!name.Equals(ColorSpaceNames.None) && !seen.Add(name))) + { + Report(DiagnosticCodes.DeviceNColorantsInvalid, "A DeviceN names array repeats a colourant or names All, which it shall not."); + break; + } + } + + if (names.Count > PdfColor.MaxComponents) + { + Report( + DiagnosticCodes.ColorComponentLimitExceeded, + string.Create(CultureInfo.InvariantCulture, $"A DeviceN colour space has {names.Count} colourants; colours set in it are painted through its alternate."), + Diagnostics.DiagnosticSeverity.Information); + } + + Attributes?.Validate(); + return TintSpaces.Check(this, RawElement(2), RawElement(3), names.Count, special: AreAllNone); + } + + /// + internal override void AddDependencies(List dependencies) + { + base.AddDependencies(dependencies); + if (Element(1) is CosArray names) + { + dependencies.Add(new FunctionDependency(names, names.Version)); + } + + Alternate.AddDependencies(dependencies); + } + + /// + private protected override double GetInitialComponent(int index) => 1; +} diff --git a/src/Broadside/Graphics/PdfDeviceNMixingHints.cs b/src/Broadside/Graphics/PdfDeviceNMixingHints.cs new file mode 100644 index 00000000..981fa930 --- /dev/null +++ b/src/Broadside/Graphics/PdfDeviceNMixingHints.cs @@ -0,0 +1,73 @@ +using Broadside.Graphics.Colors; +using Broadside.Objects; + +namespace Broadside.Graphics; + +/// The MixingHints dictionary of a DeviceN attributes dictionary: how the colourants combine on a printing press. +/// ISO 32000-2 §8.6.6.5, Table 72 (PDF 1.6). A live view; exposed for output devices, not used to paint on a display. +public sealed class PdfDeviceNMixingHints +{ + private readonly PdfColorSpace _owner; + + internal PdfDeviceNMixingHints(PdfColorSpace owner, CosDictionary dictionary) + { + _owner = owner; + Dictionary = dictionary; + } + + /// Gets the mixing hints dictionary. + public CosDictionary Dictionary { get; } + + /// Gets Solidities: for each colourant (and the key Default), its solidity from 0 to 1. + /// ISO 32000-2 Table 72. Values that are not numbers are skipped; values are clipped to 0..1. + public IReadOnlyDictionary Solidities + { + get + { + var solidities = new Dictionary(); + if (Cache.Resolve(Dictionary.GetValueOrDefault(ColorSpaceNames.Solidities)) is CosDictionary entries) + { + foreach ((CosName name, CosObject value) in entries) + { + if (ColorEntries.Number(Cache, value) is double solidity) + { + solidities[name] = Math.Clamp(solidity, 0, 1); + } + } + } + + return solidities; + } + } + + /// Gets PrintingOrder: the colourant names in the order they are printed. + /// ISO 32000-2 Table 72 (required when Solidities is present). + public IReadOnlyList PrintingOrder => + Cache.Resolve(Dictionary.GetValueOrDefault(ColorSpaceNames.PrintingOrder)) is CosArray array + ? [.. array.Select(item => Cache.Resolve(item)).OfType()] + : []; + + /// Gets DotGain: for each colourant (and Default), the function mapping tint to dot gain. + /// ISO 32000-2 Table 72 and §7.10. Entries that are not functions are skipped. + public IReadOnlyDictionary DotGain + { + get + { + var gains = new Dictionary(); + if (Cache.Resolve(Dictionary.GetValueOrDefault(ColorSpaceNames.DotGain)) is CosDictionary entries) + { + foreach ((CosName name, CosObject value) in entries) + { + if (TintSpaces.Function(Cache, value, 1, 1) is { } function) + { + gains[name] = function; + } + } + } + + return gains; + } + } + + private ColorSpaceCache Cache => _owner.Cache!; +} diff --git a/src/Broadside/Graphics/PdfDeviceNProcess.cs b/src/Broadside/Graphics/PdfDeviceNProcess.cs new file mode 100644 index 00000000..795471e6 --- /dev/null +++ b/src/Broadside/Graphics/PdfDeviceNProcess.cs @@ -0,0 +1,32 @@ +using Broadside.Graphics.Colors; +using Broadside.Objects; + +namespace Broadside.Graphics; + +/// The Process dictionary of a DeviceN attributes dictionary: the process colour space and its component names. +/// ISO 32000-2 §8.6.6.5, Table 71 (PDF 1.6). A live view. +public sealed class PdfDeviceNProcess +{ + private readonly PdfColorSpace _owner; + + internal PdfDeviceNProcess(PdfColorSpace owner, CosDictionary dictionary) + { + _owner = owner; + Dictionary = dictionary; + } + + /// Gets the process dictionary. + public CosDictionary Dictionary { get; } + + /// Gets the process colour space (a device or CIE-based space other than Lab), or when missing. + /// ISO 32000-2 Table 71 (required). + public PdfColorSpace? ColorSpace => + Dictionary.TryGetValue(ColorSpaceNames.ColorSpace, out CosObject? value) ? _owner.Cache!.Find(value, _owner.DiagnosticReference, inline: false, out _) : null; + + /// Gets the names of the DeviceN components that correspond to the process space's components, in its order. + /// ISO 32000-2 Table 71 (required). + public IReadOnlyList Components => + _owner.Cache!.Resolve(Dictionary.GetValueOrDefault(ColorSpaceNames.Components)) is CosArray array + ? [.. array.Select(item => _owner.Cache.Resolve(item)).OfType()] + : []; +} diff --git a/src/Broadside/Graphics/PdfDeviceRgbColorSpace.cs b/src/Broadside/Graphics/PdfDeviceRgbColorSpace.cs new file mode 100644 index 00000000..89aa0482 --- /dev/null +++ b/src/Broadside/Graphics/PdfDeviceRgbColorSpace.cs @@ -0,0 +1,22 @@ +using Broadside.Graphics.Colors; + +namespace Broadside.Graphics; + +/// The DeviceRGB colour space: red, green and blue, each 0 to 1. +/// ISO 32000-2 §8.6.4.3. Its initial colour is 0 0 0 (black). +public sealed class PdfDeviceRgbColorSpace : PdfColorSpace +{ + private PdfDeviceRgbColorSpace() + : base(null, ColorSpaceNames.DeviceRgb, null) + { + } + + /// Gets the one instance. + public static PdfDeviceRgbColorSpace Instance { get; } = new(); + + /// + public override PdfColorSpaceFamily Family => PdfColorSpaceFamily.DeviceRgb; + + /// + public override int ComponentCount => 3; +} diff --git a/src/Broadside/Graphics/PdfIccBasedColorSpace.cs b/src/Broadside/Graphics/PdfIccBasedColorSpace.cs new file mode 100644 index 00000000..2c912efa --- /dev/null +++ b/src/Broadside/Graphics/PdfIccBasedColorSpace.cs @@ -0,0 +1,227 @@ +using Broadside.Graphics.Colors; +using Broadside.Graphics.Functions; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Graphics; + +/// An ICCBased colour space: colours described by an embedded ICC profile, with an alternate space for processors without one. +/// +/// +/// ISO 32000-2 §8.6.5.5, Tables 65 to 68: [/ICCBased stream], the stream holding the profile with N (1, 3 or 4), +/// Alternate, Range and Metadata. Only the profile header is read here (); converting +/// through the profile is the colour-management engine's job (Phase 3). Until then the managed default converts through +/// , or through the Lab equations when the profile's data colour space is Lab. +/// +/// +/// Repairs: when the header and N disagree, a valid header wins; a missing or unusable N is taken from the header, else +/// from the alternate, else 1. An alternate that is missing, of another component count, or not a device, CalGray, CalRGB or Lab +/// space gives way to DeviceGray, DeviceRGB or DeviceCMYK by component count. A Range that +/// is not 2 × N numbers reads as its default. +/// +/// +public sealed class PdfIccBasedColorSpace : PdfColorSpace +{ + private HeaderState? _header; + + internal PdfIccBasedColorSpace(ColorSpaceCache cache, CosArray array, CosReference? reference) + : base(cache, array, reference) + { + } + + /// + public override PdfColorSpaceFamily Family => PdfColorSpaceFamily.IccBased; + + /// Gets the profile stream. + public CosStream Stream => (CosStream)Element(1); + + /// Gets the stream's N entry, or when it is missing or not an integer. + /// ISO 32000-2 Table 65 (required): 1, 3 or 4. + public int? DeclaredComponentCount => + Cache!.Resolve(Stream.Dictionary.GetValueOrDefault(ColorSpaceNames.N)) is CosInteger n && n.Value is >= int.MinValue and <= int.MaxValue + ? (int)n.Value + : null; + + /// + /// ISO 32000-2 Table 65: N "shall match the number of components actually in the ICC profile". + public override int ComponentCount + { + get + { + if (ProfileHeader is { ComponentCount: 1 or 3 or 4 } header) + { + return header.ComponentCount; + } + + if (DeclaredComponentCount is int declared and (1 or 3 or 4)) + { + return declared; + } + + return DeclaredAlternate is { } alternate && IsAlternateFamily(alternate) ? alternate.ComponentCount : 1; + } + } + + /// Gets the space used in place of the profile: the Alternate entry when usable, else the device space with as many components. + /// ISO 32000-2 Table 65: absent, DeviceGray, DeviceRGB or DeviceCMYK depending on N. + public PdfColorSpace Alternate + { + get + { + int count = ComponentCount; + return DeclaredAlternate is { } alternate && IsAlternateFamily(alternate) && alternate.ComponentCount == count + ? alternate + : DeviceSpace(count); + } + } + + /// Gets the ranges of the components, 2 × N numbers; [0 1] each, or the Lab ranges of Table 68 for a Lab profile, when missing or invalid. + /// ISO 32000-2 Tables 65 and 68. + public IReadOnlyList Range => ReadRange(ComponentCount) ?? DefaultRange(ComponentCount); + + /// Gets the profile stream's Metadata stream, or . + /// ISO 32000-2 Table 65 (PDF 1.4). + public CosStream? Metadata => Cache!.Resolve(Stream.Dictionary.GetValueOrDefault(ColorSpaceNames.Metadata)) as CosStream; + + /// Gets the profile's header, or when the stream does not decode to an ICC profile. + /// ICC.1:2022 §7.2. Read once, and again when the stream changes. + public IccProfileHeader? ProfileHeader + { + get + { + CosStream stream = Stream; + HeaderState? state = Volatile.Read(ref _header); + if (state is null || !ReferenceEquals(state.Stream, stream) || state.Version != stream.Version) + { + ReadOnlyMemory data = Cache!.Document.DecodeStream(stream); + state = new HeaderState(stream, stream.Version, IccProfileHeader.Parse(data.Span), data.Length); + Volatile.Write(ref _header, state); + } + + return state.Header; + } + } + + /// Gets a value indicating whether the profile's data colour space is Lab, whose values the alternate cannot take. + internal bool IsLabProfile => ProfileHeader is { DataColorSpace: "Lab " } && ComponentCount == 3; + + private PdfColorSpace? DeclaredAlternate => + Stream.Dictionary.TryGetValue(ColorSpaceNames.Alternate, out CosObject? value) ? Cache!.Find(value, DiagnosticReference, IsInline, out _) : null; + + /// Returns the decoded profile. + /// The profile's bytes, decoded through the stream's filters. + /// ISO 32000-2 §8.6.5.5: the stream's data is the ICC profile. + public ReadOnlyMemory GetProfileData() => Cache!.Document.DecodeStream(Stream); + + /// + internal override bool Validate() + { + CosDictionary dictionary = Stream.Dictionary; + int? declared = DeclaredComponentCount; + IccProfileHeader? header = ProfileHeader; + if (declared is not (1 or 3 or 4)) + { + Report(DiagnosticCodes.ColorSpaceEntryInvalid, $"An ICCBased stream's N is missing or not 1, 3 or 4; {ComponentCount} is used."); + } + + if (header is null) + { + Report(DiagnosticCodes.IccProfileInvalid, "An ICCBased stream does not hold an ICC profile (fewer than 128 bytes or no 'acsp' signature); the alternate colour space is used."); + } + else + { + if (header.ProfileSize > _header!.Length) + { + Report(DiagnosticCodes.IccProfileInvalid, "An ICC profile's header states a size larger than the stream's data; the profile is truncated."); + } + + if (!header.IsSupportedForPdf && header.Version.Major < 5) + { + Report(DiagnosticCodes.IccProfileInvalid, $"An ICC profile of class '{header.DeviceClass}' and colour space '{header.DataColorSpace}' is not one Table 67 allows; the alternate colour space is used."); + } + + if (declared is 1 or 3 or 4 && header.ComponentCount is 1 or 3 or 4 && declared != header.ComponentCount) + { + Report(DiagnosticCodes.IccComponentCountMismatch, $"An ICCBased stream's N is {declared} but its profile has {header.ComponentCount} components; the profile's count is used."); + } + } + + if (dictionary.ContainsKey(ColorSpaceNames.Alternate) && !ReferenceEquals(Alternate, DeclaredAlternate)) + { + Report(DiagnosticCodes.ColorSpaceEntryInvalid, "An ICCBased Alternate has the wrong number of components or cannot be an alternate; the device colour space with as many components is used."); + } + + if (dictionary.ContainsKey(ColorSpaceNames.Range) && ReadRange(ComponentCount) is null) + { + Report(DiagnosticCodes.ColorSpaceEntryInvalid, "An ICCBased Range is not 2 x N numbers with each minimum below its maximum; the default is used."); + } + + return true; + } + + /// + internal override void AddDependencies(List dependencies) + { + base.AddDependencies(dependencies); + dependencies.Add(new FunctionDependency(Stream, Stream.Version)); + dependencies.Add(new FunctionDependency(Stream.Dictionary, Stream.Dictionary.Version)); + } + + /// + private protected override ComponentRange GetRangeCore(int index) + { + IReadOnlyList range = Range; + return new ComponentRange(range[2 * index], range[(2 * index) + 1]); + } + + /// Returns DeviceGray, DeviceRGB or DeviceCMYK for 1, 3 or 4 components. + internal static PdfColorSpace DeviceSpace(int count) => count switch + { + 3 => PdfDeviceRgbColorSpace.Instance, + 4 => PdfDeviceCmykColorSpace.Instance, + _ => PdfDeviceGrayColorSpace.Instance, + }; + + /// + /// A device space or CalGray, CalRGB or Lab. Another ICCBased space is not taken: an alternate exists for processors that cannot + /// use profiles, and refusing it rules out alternates that lead back to this space. + /// + private static bool IsAlternateFamily(PdfColorSpace space) => space.Family < PdfColorSpaceFamily.IccBased; + + private double[] DefaultRange(int count) + { + if (IsLabProfile) + { + return [0, 100, -128, 127, -128, 127]; + } + + double[] range = new double[2 * count]; + for (int i = 0; i < count; i++) + { + range[(2 * i) + 1] = 1; + } + + return range; + } + + private double[]? ReadRange(int count) + { + if (ColorEntries.Numbers(Cache!, Stream.Dictionary, ColorSpaceNames.Range) is not { } range || range.Length != 2 * count) + { + return null; + } + + for (int i = 0; i < count; i++) + { + if (range[2 * i] > range[(2 * i) + 1]) + { + return null; + } + } + + return range; + } + + /// The header read from one version of the stream. + private sealed record HeaderState(CosStream Stream, int Version, IccProfileHeader? Header, int Length); +} diff --git a/src/Broadside/Graphics/PdfIndexedColorSpace.cs b/src/Broadside/Graphics/PdfIndexedColorSpace.cs new file mode 100644 index 00000000..748ff021 --- /dev/null +++ b/src/Broadside/Graphics/PdfIndexedColorSpace.cs @@ -0,0 +1,116 @@ +using System.Globalization; +using Broadside.Graphics.Colors; +using Broadside.Graphics.Functions; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Graphics; + +/// An Indexed colour space: one component, an index from 0 to into a colour table in a base space. +/// +/// +/// ISO 32000-2 §8.6.6.3: [/Indexed base hival lookup] (/I in an inline image). The base is any device, CIE-based, +/// Separation or DeviceN space; the lookup table is a string or stream of m × (hival + 1) bytes, m being the base's component +/// count; byte values 0 to 255 map linearly onto each base component's range. An index is rounded to the nearest integer and clipped +/// to 0..hival. +/// +/// +/// Repairs: hival outside 0..255 is clipped; a short table reads as zeros past its end, a long one is cut. A space without a usable +/// base or lookup table is read as DeviceGray. +/// +/// +public sealed class PdfIndexedColorSpace : PdfColorSpace +{ + internal PdfIndexedColorSpace(ColorSpaceCache cache, CosArray array, CosReference? reference) + : base(cache, array, reference) + { + } + + /// + public override PdfColorSpaceFamily Family => PdfColorSpaceFamily.Indexed; + + /// + public override int ComponentCount => 1; + + /// + public override PdfVersion MinimumVersion => Element(3) is CosString ? new PdfVersion(1, 2) : new PdfVersion(1, 1); + + /// Gets the base colour space, the space of the table's colours. + /// ISO 32000-2 §8.6.6.3. + public PdfColorSpace Base => NestedSpace(1) ?? PdfDeviceGrayColorSpace.Instance; + + /// Gets hival, the largest index, 0 to 255. + /// ISO 32000-2 §8.6.6.3: an integer "whose value shall not be greater than 255". + public int HighValue => ColorEntries.Number(Cache!, Element(2)) is double value ? (int)Math.Clamp(Math.Round(value, MidpointRounding.AwayFromZero), 0, 255) : 0; + + /// Returns the lookup table as stored: a string's bytes, or a stream's decoded data. + /// The table; empty when there is none. + /// ISO 32000-2 §8.6.6.3: m × (hival + 1) bytes, component by component for each colour in turn. + public ReadOnlyMemory GetLookup() => Element(3) switch + { + CosString text => text.Bytes.ToArray(), + CosStream stream => Cache!.Document.DecodeStream(stream), + _ => ReadOnlyMemory.Empty, + }; + + /// + internal override bool Validate() + { + PdfColorSpace? baseSpace = Cache!.Find(RawElement(1), DiagnosticReference, IsInline, out ColorSpaceFailure failure); + if (baseSpace is null) + { + ColorSpaceCache.ReportFailure(this, failure, "an Indexed base"); + return false; + } + + if (baseSpace.Family is PdfColorSpaceFamily.Pattern or PdfColorSpaceFamily.Indexed) + { + Report(DiagnosticCodes.ColorSpaceInvalid, "An Indexed colour space's base is a Pattern or Indexed space, which it shall not be; DeviceGray is used."); + return false; + } + + if (ColorEntries.Number(Cache!, Element(2)) is not double hival) + { + Report(DiagnosticCodes.ColorSpaceInvalid, "An Indexed colour space's hival is not a number; DeviceGray is used."); + return false; + } + + if (hival is < 0 or > 255 || hival != Math.Floor(hival)) + { + Report(DiagnosticCodes.ColorSpaceEntryInvalid, string.Create(CultureInfo.InvariantCulture, $"An Indexed colour space's hival {hival} is not an integer from 0 to 255; {HighValue} is used.")); + } + + if (Element(3) is not (CosString or CosStream)) + { + Report(DiagnosticCodes.IndexedLookupInvalid, "An Indexed colour space has no lookup string or stream; DeviceGray is used."); + return false; + } + + int expected = baseSpace.ComponentCount * (HighValue + 1); + int length = GetLookup().Length; + if (length < expected) + { + Report(DiagnosticCodes.IndexedLookupInvalid, string.Create(CultureInfo.InvariantCulture, $"An Indexed lookup table has {length} bytes where {expected} are needed; the missing entries read as zeros.")); + } + else if (length > expected) + { + Report(DiagnosticCodes.IndexedLookupInvalid, string.Create(CultureInfo.InvariantCulture, $"An Indexed lookup table has {length} bytes where {expected} are needed; the rest are ignored.")); + } + + return true; + } + + /// + internal override void AddDependencies(List dependencies) + { + base.AddDependencies(dependencies); + Base.AddDependencies(dependencies); + if (Element(3) is CosStream stream) + { + dependencies.Add(new FunctionDependency(stream, stream.Version)); + } + } + + /// + private protected override ComponentRange GetRangeCore(int index) => new(0, HighValue); +} diff --git a/src/Broadside/Graphics/PdfLabColorSpace.cs b/src/Broadside/Graphics/PdfLabColorSpace.cs new file mode 100644 index 00000000..286536fa --- /dev/null +++ b/src/Broadside/Graphics/PdfLabColorSpace.cs @@ -0,0 +1,88 @@ +using Broadside.Graphics.Colors; +using Broadside.Graphics.Functions; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Graphics; + +/// A Lab colour space: components L* (0 to 100), a* and b* (within ), relative to a white point. +/// +/// ISO 32000-2 §8.6.5.4, Table 64: [/Lab dictionary]. M = (L* + 16) / 116, L = M + a* / 500, N = M − b* / 200; +/// X = XW·g(L), Y = YW·g(M), Z = ZW·g(N), with g(x) = x³ for x ≥ 6/29, else 108/841·(x − 4/29). A missing or invalid +/// Range reads as [−100 100 −100 100]; the initial colour is 0 0 0 clipped into the ranges. +/// +public sealed class PdfLabColorSpace : PdfColorSpace +{ + private static readonly double[] DefaultRange = [-100, 100, -100, 100]; + + internal PdfLabColorSpace(ColorSpaceCache cache, CosArray array, CosReference? reference) + : base(cache, array, reference) + { + } + + /// + public override PdfColorSpaceFamily Family => PdfColorSpaceFamily.Lab; + + /// + public override int ComponentCount => 3; + + /// Gets the Lab dictionary; empty when the array has none. + public CosDictionary Dictionary => Element(1) as CosDictionary ?? []; + + /// Gets the diffuse white point, WhitePoint; D65 when missing or invalid. + /// ISO 32000-2 Table 64 (required). + public CieXyz WhitePoint => ColorEntries.WhitePoint(Cache!, Dictionary) ?? CieXyz.D65; + + /// Gets the diffuse black point, BlackPoint; [0 0 0] when missing or invalid. + /// ISO 32000-2 Table 64. + public CieXyz BlackPoint => ColorEntries.BlackPoint(Cache!, Dictionary, out _) ?? default; + + /// Gets the ranges of a* and b*, [amin amax bmin bmax]; [−100 100 −100 100] when missing or invalid. + /// ISO 32000-2 Table 64. + public IReadOnlyList Range => ReadRange() ?? DefaultRange; + + /// + internal override bool Validate() + { + if (CieChecks.Dictionary(this, Element(1), "Lab") is not { } dictionary) + { + return true; + } + + CieChecks.WhiteAndBlack(this, Cache!, dictionary, "Lab"); + if (dictionary.ContainsKey(ColorSpaceNames.Range) && ReadRange() is null) + { + Report(DiagnosticCodes.ColorSpaceEntryInvalid, "A Lab Range is not four numbers [amin amax bmin bmax] with each minimum below its maximum; [-100 100 -100 100] is used."); + } + + return true; + } + + /// + internal override void AddDependencies(List dependencies) + { + base.AddDependencies(dependencies); + if (Element(1) is CosDictionary dictionary) + { + dependencies.Add(new FunctionDependency(dictionary, dictionary.Version)); + } + } + + /// + private protected override ComponentRange GetRangeCore(int index) + { + if (index == 0) + { + return new ComponentRange(0, 100); + } + + IReadOnlyList range = Range; + return new ComponentRange(range[2 * (index - 1)], range[(2 * (index - 1)) + 1]); + } + + private double[]? ReadRange() => + ColorEntries.Numbers(Cache!, Element(1) as CosDictionary, ColorSpaceNames.Range) is [double amin, double amax, double bmin, double bmax] range + && amin <= amax && bmin <= bmax + ? range + : null; +} diff --git a/src/Broadside/Graphics/PdfPatternColorSpace.cs b/src/Broadside/Graphics/PdfPatternColorSpace.cs new file mode 100644 index 00000000..674ea5d7 --- /dev/null +++ b/src/Broadside/Graphics/PdfPatternColorSpace.cs @@ -0,0 +1,68 @@ +using Broadside.Graphics.Colors; +using Broadside.Graphics.Functions; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Graphics; + +/// The Pattern colour space: colours are patterns, named by scn; for uncoloured patterns, with an underlying space. +/// +/// ISO 32000-2 §8.6.6.2 and §8.7.3.3: /Pattern alone for coloured tiling and shading patterns, [/Pattern base] for +/// uncoloured tiling patterns, whose colour is given in the underlying space base (which shall not be a Pattern space). The +/// initial colour is a pattern that paints nothing (Table 73). Images cannot use this space (Table 88). +/// +public sealed class PdfPatternColorSpace : PdfColorSpace +{ + private PdfPatternColorSpace() + : base(null, ColorSpaceNames.Pattern, null) + { + } + + internal PdfPatternColorSpace(ColorSpaceCache cache, CosArray array, CosReference? reference) + : base(cache, array, reference) + { + } + + /// + public override PdfColorSpaceFamily Family => PdfColorSpaceFamily.Pattern; + + /// Gets the underlying colour space of uncoloured patterns, or for /Pattern alone. + /// ISO 32000-2 §8.7.3.3. + public PdfColorSpace? Underlying => Cache is null ? null : NestedSpace(1) is { Family: not PdfColorSpaceFamily.Pattern } space ? space : null; + + /// + /// ISO 32000-2 §8.6.8: for an uncoloured pattern, scn takes the underlying space's components before the name. + public override int ComponentCount => Underlying?.ComponentCount ?? 0; + + /// Gets the space named /Pattern alone, for coloured patterns. + internal static PdfPatternColorSpace Colored { get; } = new(); + + /// + internal override bool Validate() + { + if (CosObject is CosArray { Count: > 1 } && Underlying is null) + { + PdfColorSpace? found = Cache!.Find(RawElement(1), DiagnosticReference, IsInline, out ColorSpaceFailure failure); + if (found is null) + { + ColorSpaceCache.ReportFailure(this, failure, "a Pattern underlying space"); + } + else + { + Report(DiagnosticCodes.ColorSpaceEntryInvalid, "A Pattern colour space's underlying space is itself a Pattern space; it is ignored."); + } + } + + return true; + } + + /// + internal override void AddDependencies(List dependencies) + { + base.AddDependencies(dependencies); + Underlying?.AddDependencies(dependencies); + } + + /// + private protected override ComponentRange GetRangeCore(int index) => Underlying!.GetComponentRange(index); +} diff --git a/src/Broadside/Graphics/PdfSeparationColorSpace.cs b/src/Broadside/Graphics/PdfSeparationColorSpace.cs new file mode 100644 index 00000000..1d5c6214 --- /dev/null +++ b/src/Broadside/Graphics/PdfSeparationColorSpace.cs @@ -0,0 +1,73 @@ +using Broadside.Graphics.Colors; +using Broadside.Graphics.Functions; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Graphics; + +/// A Separation colour space: one colourant, a tint from 0 (none) to 1 (full), with an alternate space for devices without it. +/// +/// +/// ISO 32000-2 §8.6.6.4: [/Separation name alternateSpace tintTransform]. The tint transform maps the tint to the alternate +/// space, a device or CIE-based space; a display, being additive, always paints through it. The colourant All marks every +/// colourant of the device (registration marks) and None paints nothing; for both the alternate and tint transform are +/// ignored. The initial colour is 1.0. +/// +/// +/// Repairs: an alternate that is not a device or CIE-based space reads as DeviceGray; a tint transform that is not a function is +/// replaced by the subtractive default (gray 1 − t, RGB (1 − t)×3, CMYK (0, 0, 0, t), else zeros). A colourant that is not a name +/// makes the space DeviceGray. +/// +/// +public sealed class PdfSeparationColorSpace : PdfColorSpace +{ + internal PdfSeparationColorSpace(ColorSpaceCache cache, CosArray array, CosReference? reference) + : base(cache, array, reference) + { + } + + /// + public override PdfColorSpaceFamily Family => PdfColorSpaceFamily.Separation; + + /// + public override int ComponentCount => 1; + + /// Gets the name of the colourant. + /// ISO 32000-2 §8.6.6.4: Cyan, Magenta, Yellow and Black are reserved for the process colourants. + public CosName ColorantName => Element(1) as CosName ?? ColorSpaceNames.None; + + /// Gets a value indicating whether the colourant is All, every colourant of the device. + public bool IsAll => ColorantName.Equals(ColorSpaceNames.All); + + /// Gets a value indicating whether the colourant is None, which paints nothing. + public bool IsNone => ColorantName.Equals(ColorSpaceNames.None); + + /// Gets the alternate space, a device or CIE-based space; DeviceGray when the entry is unusable. + public PdfColorSpace Alternate => TintSpaces.Alternate(NestedSpace(2)); + + /// Gets the tint transform, or when the entry is not a function. + /// ISO 32000-2 §8.6.6.4 and §7.10: one input, as many outputs as the alternate has components. + public PdfFunction? TintTransform => TintSpaces.Function(Cache!, RawElement(3), 1, Alternate.ComponentCount); + + /// + internal override bool Validate() + { + if (Element(1) is not CosName) + { + Report(DiagnosticCodes.ColorSpaceInvalid, "A Separation colour space's colourant is not a name; DeviceGray is used."); + return false; + } + + return TintSpaces.Check(this, RawElement(2), RawElement(3), 1, special: IsAll || IsNone); + } + + /// + internal override void AddDependencies(List dependencies) + { + base.AddDependencies(dependencies); + Alternate.AddDependencies(dependencies); + } + + /// + private protected override double GetInitialComponent(int index) => 1; +} diff --git a/src/Broadside/Parsing/DiagnosticCodes.Color.cs b/src/Broadside/Parsing/DiagnosticCodes.Color.cs new file mode 100644 index 00000000..a2af48d4 --- /dev/null +++ b/src/Broadside/Parsing/DiagnosticCodes.Color.cs @@ -0,0 +1,27 @@ +namespace Broadside.Parsing; + +/// Diagnostic codes for colour spaces, colour operators and colour conversion (issue #77). +internal static partial class DiagnosticCodes +{ + // Colour spaces (§8.6). + public const string ColorSpaceInvalid = nameof(ColorSpaceInvalid); + public const string ColorSpaceEntryInvalid = nameof(ColorSpaceEntryInvalid); + public const string ColorSpaceCycle = nameof(ColorSpaceCycle); + public const string ColorSpaceTooDeep = nameof(ColorSpaceTooDeep); + public const string IccProfileInvalid = nameof(IccProfileInvalid); + public const string IccComponentCountMismatch = nameof(IccComponentCountMismatch); + public const string IndexedLookupInvalid = nameof(IndexedLookupInvalid); + public const string TintTransformInvalid = nameof(TintTransformInvalid); + public const string DeviceNColorantsInvalid = nameof(DeviceNColorantsInvalid); + public const string DefaultColorSpaceInvalid = nameof(DefaultColorSpaceInvalid); + + // Colour operators in content streams (§8.6.8, Table 73). + public const string ContentColorSpaceMissing = nameof(ContentColorSpaceMissing); + public const string ContentColorSpaceAbbreviated = nameof(ContentColorSpaceAbbreviated); + public const string ContentColorOperandCount = nameof(ContentColorOperandCount); + public const string ContentColorOperatorMismatch = nameof(ContentColorOperatorMismatch); + public const string ContentColorOperatorInvalid = nameof(ContentColorOperatorInvalid); + public const string ContentColorOperatorIgnored = nameof(ContentColorOperatorIgnored); + public const string ContentPatternMissing = nameof(ContentPatternMissing); + public const string ColorComponentLimitExceeded = nameof(ColorComponentLimitExceeded); +} diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index ebfe5f58..9f80e1ca 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -4,6 +4,7 @@ using Broadside.Filters; using Broadside.Fonts; using Broadside.Graphics; +using Broadside.Graphics.Colors; using Broadside.Graphics.Functions; using Broadside.IO; using Broadside.Objects; @@ -72,7 +73,8 @@ private PdfDocument( CosDictionary catalog, IReadOnlyList revisions, PdfLinearization? linearization, - PdfSecurity? security) + PdfSecurity? security, + IColorManagement colorManagement) { Security = security; _source = source; @@ -84,6 +86,7 @@ private PdfDocument( Linearization = linearization; Pages = new PdfPageCollection(() => PageTreeReader.Read(this, diagnostics)); Functions = new FunctionCache(this, diagnostics); + ColorSpaces = new ColorSpaceCache(this, diagnostics, colorManagement); } /// @@ -689,6 +692,63 @@ public void DecodeStream(CosStream stream, IBufferWriter output) /// Gets the document's functions, compiled once each (issue #78): the seam colour spaces, graphics states and shadings use. internal FunctionCache Functions { get; } + /// Gets the document's colour spaces, default colour spaces and colour converters (issue #77). + internal ColorSpaceCache ColorSpaces { get; } + + /// Returns the colour space a colour space value describes. + /// + /// A family name (/DeviceRGB, /Pattern), a colour space array ([/ICCBased 5 0 R]), or a reference to one, such + /// as an image's ColorSpace entry or a value of a resource dictionary's ColorSpace subdictionary. + /// + /// + /// The space, shared by every caller asking for the same object. A value that is not a colour space, or one that cannot be used + /// (an unknown family, a space that refers to itself), reads as DeviceGray with a diagnostic. + /// + /// In strict mode, for the first deviation found in the space. + /// + /// ISO 32000-2 §8.6.3, Table 61. A name other than a family name (a resource name such as /CS0) is not looked up here; + /// content streams resolve those through . Deviations are recorded on + /// once, when the space is first read. + /// + public PdfColorSpace GetColorSpace(CosObject colorSpace) + { + ArgumentNullException.ThrowIfNull(colorSpace); + return ColorSpaces.Get(colorSpace); + } + + /// Returns the default colour spaces of a resource dictionary. + /// The resource dictionary, such as ; for none. + /// The defaults; when the dictionary has none. + /// ISO 32000-2 §8.6.5.6. Invalid defaults are ignored with a diagnostic. + public PdfDefaultColorSpaces GetDefaultColorSpaces(CosDictionary? resources) => ColorSpaces.GetDefaults(resources); + + /// Returns the converter from to RGB with the relative colorimetric intent. + /// The colour space. + /// The default colour spaces in effect where the colour is painted; for none. + /// The converter, shared by every caller asking for the same source and defaults. + /// ISO 32000-2 §8.6, §10.3 and §10.4; see . + public PdfColorConverter GetColorConverter(PdfColorSpace source, PdfDefaultColorSpaces? defaults) => + GetColorConverter(source, default, defaults); + + /// Returns the converter from to RGB with the relative colorimetric intent and no default spaces. + /// The colour space. + /// The converter, shared by every caller asking for the same source. + /// ISO 32000-2 §8.6, §10.3 and §10.4; see . + public PdfColorConverter GetColorConverter(PdfColorSpace source) => GetColorConverter(source, default, null); + + /// Returns the converter from under . + /// The colour space. + /// The target model, rendering intent and device controls. + /// The default colour spaces in effect where the colour is painted; for none. + /// The converter, shared by every caller asking for the same source, conversion and defaults. + /// In strict mode, for the first deviation found building it. + /// ISO 32000-2 §8.6, §10.3 and §10.4; see . + public PdfColorConverter GetColorConverter(PdfColorSpace source, ColorConversion conversion, PdfDefaultColorSpaces? defaults = null) + { + ArgumentNullException.ThrowIfNull(source); + return ColorSpaces.GetConverter(source, conversion, defaults ?? PdfDefaultColorSpaces.None); + } + private CosDictionary? ResolveTreeRoot(CosObject? root, string code, string kind) { switch (Resolve(root)) @@ -811,7 +871,7 @@ internal static PdfDocument Read(PdfSource source, EngineConfiguration configura } PdfLinearization? linearization = LinearizationReader.Read(source, loader, diagnostics); - var document = new PdfDocument(source, diagnostics, loader, streams, catalog, revisions, linearization, security); + var document = new PdfDocument(source, diagnostics, loader, streams, catalog, revisions, linearization, security, configuration.ColorManagement); // Table 15: ID is "required in PDF 2.0 or if an Encrypt entry is present" (the latter is the security handler's // EncryptionIdMissing). diff --git a/src/Broadside/PdfOptions.cs b/src/Broadside/PdfOptions.cs index 84fa3fef..88a02bc2 100644 --- a/src/Broadside/PdfOptions.cs +++ b/src/Broadside/PdfOptions.cs @@ -1,4 +1,5 @@ using Broadside.Filters; +using Broadside.Graphics; using Broadside.Objects; using Broadside.Security; using Microsoft.Extensions.Logging; @@ -153,6 +154,24 @@ public PdfOptions WithLoggerFactory(ILoggerFactory? loggerFactory) return this; } + /// Gets the colour management set with ; otherwise. + /// Not public, so configuration binding never sees it. + internal IColorManagement ColorManagement { get; private set; } = ManagedColorManagement.Default; + + /// + /// Uses to convert colours of device, CIE-based and ICCBased spaces to device colours, in place + /// of . + /// + /// The colour management. Shared by every document and thread of the engine. + /// These options. + /// ISO 32000-2 §8.6.5, §10.3 and §10.4. The colour-management extension point (ADR 0001). + public PdfOptions UseColorManagement(IColorManagement colorManagement) + { + ArgumentNullException.ThrowIfNull(colorManagement); + ColorManagement = colorManagement; + return this; + } + /// Gets the security handlers registered with , in order. /// Not public, so configuration binding never sees it. internal IReadOnlyList SecurityHandlers => _securityHandlers; diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index efdc0966..2cabb5de 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -1,4 +1,6 @@ #nullable enable +abstract Broadside.Graphics.PdfColorSpace.ComponentCount.get -> int +abstract Broadside.Graphics.PdfColorSpace.Family.get -> Broadside.Graphics.PdfColorSpaceFamily abstract Broadside.Objects.CosNumber.ToDouble() -> double Broadside.Content.ClipEvent Broadside.Content.ClipEvent.ClipEvent() -> void @@ -28,9 +30,12 @@ Broadside.Content.ContentContext Broadside.Content.ContentContext.CancellationToken.get -> System.Threading.CancellationToken Broadside.Content.ContentContext.CurrentPartIndex.get -> int Broadside.Content.ContentContext.CurrentStream.get -> Broadside.Objects.CosReference? +Broadside.Content.ContentContext.DefaultColorSpaces.get -> Broadside.Graphics.PdfDefaultColorSpaces! Broadside.Content.ContentContext.Depth.get -> int Broadside.Content.ContentContext.Document.get -> Broadside.PdfDocument! Broadside.Content.ContentContext.GetClip(int handle) -> Broadside.Content.ClipView +Broadside.Content.ContentContext.GetColorSpace(Broadside.Objects.CosObject! colorSpace) -> Broadside.Graphics.PdfColorSpace! +Broadside.Content.ContentContext.GetInlineImageColorSpace(Broadside.Objects.CosObject! colorSpace) -> Broadside.Graphics.PdfColorSpace! Broadside.Content.ContentContext.IsHidden.get -> bool Broadside.Content.ContentContext.Page.get -> Broadside.PdfPage? Broadside.Content.ContentContext.Resources.get -> Broadside.Objects.CosDictionary? @@ -265,6 +270,10 @@ Broadside.Content.ShadingEvent.IsHidden.get -> bool Broadside.Content.ShadingEvent.ResourceName.get -> System.ReadOnlySpan Broadside.Content.ShadingEvent.Shading.get -> Broadside.Objects.CosObject? Broadside.Content.ShadingEvent.ShadingEvent() -> void +Broadside.Graphics.BlackPointCompensation +Broadside.Graphics.BlackPointCompensation.Default = 0 -> Broadside.Graphics.BlackPointCompensation +Broadside.Graphics.BlackPointCompensation.Off = 2 -> Broadside.Graphics.BlackPointCompensation +Broadside.Graphics.BlackPointCompensation.On = 1 -> Broadside.Graphics.BlackPointCompensation Broadside.Graphics.BlendMode Broadside.Graphics.BlendMode.Color = 14 -> Broadside.Graphics.BlendMode Broadside.Graphics.BlendMode.ColorBurn = 7 -> Broadside.Graphics.BlendMode @@ -282,11 +291,49 @@ Broadside.Graphics.BlendMode.Overlay = 3 -> Broadside.Graphics.BlendMode Broadside.Graphics.BlendMode.Saturation = 13 -> Broadside.Graphics.BlendMode Broadside.Graphics.BlendMode.Screen = 2 -> Broadside.Graphics.BlendMode Broadside.Graphics.BlendMode.SoftLight = 9 -> Broadside.Graphics.BlendMode +Broadside.Graphics.CieXyz +Broadside.Graphics.CieXyz.CieXyz() -> void +Broadside.Graphics.CieXyz.CieXyz(double X, double Y, double Z) -> void +Broadside.Graphics.CieXyz.X.get -> double +Broadside.Graphics.CieXyz.X.init -> void +Broadside.Graphics.CieXyz.Y.get -> double +Broadside.Graphics.CieXyz.Y.init -> void +Broadside.Graphics.CieXyz.Z.get -> double +Broadside.Graphics.CieXyz.Z.init -> void +Broadside.Graphics.CmykConversion +Broadside.Graphics.CmykConversion.Characterized = 0 -> Broadside.Graphics.CmykConversion +Broadside.Graphics.CmykConversion.Classic = 1 -> Broadside.Graphics.CmykConversion +Broadside.Graphics.ColorConversion +Broadside.Graphics.ColorConversion.BlackGeneration.get -> Broadside.Graphics.PdfFunction? +Broadside.Graphics.ColorConversion.BlackGeneration.init -> void +Broadside.Graphics.ColorConversion.BlackPointCompensation.get -> Broadside.Graphics.BlackPointCompensation +Broadside.Graphics.ColorConversion.BlackPointCompensation.init -> void +Broadside.Graphics.ColorConversion.ColorConversion() -> void +Broadside.Graphics.ColorConversion.CompensatesBlackPoint.get -> bool +Broadside.Graphics.ColorConversion.Intent.get -> Broadside.Graphics.RenderingIntent +Broadside.Graphics.ColorConversion.Intent.init -> void +Broadside.Graphics.ColorConversion.Target.get -> Broadside.Graphics.DeviceColorModel +Broadside.Graphics.ColorConversion.Target.init -> void +Broadside.Graphics.ColorConversion.UndercolorRemoval.get -> Broadside.Graphics.PdfFunction? +Broadside.Graphics.ColorConversion.UndercolorRemoval.init -> void +Broadside.Graphics.ComponentRange +Broadside.Graphics.ComponentRange.Clamp(double value) -> double +Broadside.Graphics.ComponentRange.ComponentRange() -> void +Broadside.Graphics.ComponentRange.ComponentRange(double Minimum, double Maximum) -> void +Broadside.Graphics.ComponentRange.Maximum.get -> double +Broadside.Graphics.ComponentRange.Maximum.init -> void +Broadside.Graphics.ComponentRange.Minimum.get -> double +Broadside.Graphics.ComponentRange.Minimum.init -> void +Broadside.Graphics.DeviceColorModel +Broadside.Graphics.DeviceColorModel.Cmyk = 2 -> Broadside.Graphics.DeviceColorModel +Broadside.Graphics.DeviceColorModel.Gray = 1 -> Broadside.Graphics.DeviceColorModel +Broadside.Graphics.DeviceColorModel.Rgb = 0 -> Broadside.Graphics.DeviceColorModel Broadside.Graphics.FillRule Broadside.Graphics.FillRule.EvenOdd = 1 -> Broadside.Graphics.FillRule Broadside.Graphics.FillRule.NonZero = 0 -> Broadside.Graphics.FillRule Broadside.Graphics.GraphicsState Broadside.Graphics.GraphicsState.AlphaIsShape.get -> bool +Broadside.Graphics.GraphicsState.BlackPointCompensation.get -> Broadside.Graphics.BlackPointCompensation Broadside.Graphics.GraphicsState.BlendMode.get -> Broadside.Graphics.BlendMode Broadside.Graphics.GraphicsState.CharacterSpacing.get -> double Broadside.Graphics.GraphicsState.ClipHandle.get -> int @@ -294,6 +341,7 @@ Broadside.Graphics.GraphicsState.Ctm.get -> Broadside.Graphics.Matrix Broadside.Graphics.GraphicsState.DashArray.get -> System.ReadOnlySpan Broadside.Graphics.GraphicsState.DashPhase.get -> double Broadside.Graphics.GraphicsState.FillAlpha.get -> double +Broadside.Graphics.GraphicsState.FillColor.get -> Broadside.Graphics.PdfColor Broadside.Graphics.GraphicsState.FillOverprint.get -> bool Broadside.Graphics.GraphicsState.Flatness.get -> double Broadside.Graphics.GraphicsState.FontSize.get -> double @@ -308,11 +356,29 @@ Broadside.Graphics.GraphicsState.OverprintMode.get -> int Broadside.Graphics.GraphicsState.RenderingIntent.get -> Broadside.Graphics.RenderingIntent Broadside.Graphics.GraphicsState.StrokeAdjustment.get -> bool Broadside.Graphics.GraphicsState.StrokeAlpha.get -> double +Broadside.Graphics.GraphicsState.StrokeColor.get -> Broadside.Graphics.PdfColor Broadside.Graphics.GraphicsState.StrokeOverprint.get -> bool Broadside.Graphics.GraphicsState.TextKnockout.get -> bool Broadside.Graphics.GraphicsState.TextRenderingMode.get -> Broadside.Graphics.TextRenderingMode Broadside.Graphics.GraphicsState.TextRise.get -> double Broadside.Graphics.GraphicsState.WordSpacing.get -> double +Broadside.Graphics.IccProfileHeader +Broadside.Graphics.IccProfileHeader.ComponentCount.get -> int +Broadside.Graphics.IccProfileHeader.ConnectionSpace.get -> string! +Broadside.Graphics.IccProfileHeader.DataColorSpace.get -> string! +Broadside.Graphics.IccProfileHeader.DeviceClass.get -> string! +Broadside.Graphics.IccProfileHeader.Illuminant.get -> Broadside.Graphics.CieXyz +Broadside.Graphics.IccProfileHeader.IsSupportedForPdf.get -> bool +Broadside.Graphics.IccProfileHeader.PreferredCmm.get -> string! +Broadside.Graphics.IccProfileHeader.ProfileSize.get -> long +Broadside.Graphics.IccProfileHeader.RenderingIntent.get -> Broadside.Graphics.RenderingIntent +Broadside.Graphics.IccProfileHeader.Version.get -> System.Version! +Broadside.Graphics.IColorConverter +Broadside.Graphics.IColorConverter.Convert(System.ReadOnlySpan source, System.Span destination, int count) -> void +Broadside.Graphics.IColorConverter.InputCount.get -> int +Broadside.Graphics.IColorConverter.OutputCount.get -> int +Broadside.Graphics.IColorManagement +Broadside.Graphics.IColorManagement.CreateConverter(Broadside.Graphics.PdfColorSpace! source, Broadside.Graphics.ColorConversion conversion) -> Broadside.Graphics.IColorConverter! Broadside.Graphics.LineCap Broadside.Graphics.LineCap.Butt = 0 -> Broadside.Graphics.LineCap Broadside.Graphics.LineCap.ProjectingSquare = 2 -> Broadside.Graphics.LineCap @@ -321,6 +387,10 @@ Broadside.Graphics.LineJoin Broadside.Graphics.LineJoin.Bevel = 2 -> Broadside.Graphics.LineJoin Broadside.Graphics.LineJoin.Miter = 0 -> Broadside.Graphics.LineJoin Broadside.Graphics.LineJoin.Round = 1 -> Broadside.Graphics.LineJoin +Broadside.Graphics.ManagedColorManagement +Broadside.Graphics.ManagedColorManagement.CmykConversion.get -> Broadside.Graphics.CmykConversion +Broadside.Graphics.ManagedColorManagement.CreateConverter(Broadside.Graphics.PdfColorSpace! source, Broadside.Graphics.ColorConversion conversion) -> Broadside.Graphics.IColorConverter! +Broadside.Graphics.ManagedColorManagement.ManagedColorManagement(Broadside.Graphics.CmykConversion cmykConversion = Broadside.Graphics.CmykConversion.Characterized) -> void Broadside.Graphics.Matrix Broadside.Graphics.Matrix.A.get -> double Broadside.Graphics.Matrix.B.get -> double @@ -358,6 +428,113 @@ Broadside.Graphics.PathView.PathView() -> void Broadside.Graphics.PathView.PathView(System.ReadOnlySpan verbs, System.ReadOnlySpan points) -> void Broadside.Graphics.PathView.Points.get -> System.ReadOnlySpan Broadside.Graphics.PathView.Verbs.get -> System.ReadOnlySpan +Broadside.Graphics.PdfCalGrayColorSpace +Broadside.Graphics.PdfCalGrayColorSpace.BlackPoint.get -> Broadside.Graphics.CieXyz +Broadside.Graphics.PdfCalGrayColorSpace.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Graphics.PdfCalGrayColorSpace.Gamma.get -> double +Broadside.Graphics.PdfCalGrayColorSpace.WhitePoint.get -> Broadside.Graphics.CieXyz +Broadside.Graphics.PdfCalRgbColorSpace +Broadside.Graphics.PdfCalRgbColorSpace.BlackPoint.get -> Broadside.Graphics.CieXyz +Broadside.Graphics.PdfCalRgbColorSpace.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Graphics.PdfCalRgbColorSpace.Gamma.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Graphics.PdfCalRgbColorSpace.Matrix.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Graphics.PdfCalRgbColorSpace.WhitePoint.get -> Broadside.Graphics.CieXyz +Broadside.Graphics.PdfColor +Broadside.Graphics.PdfColor.ColorSpace.get -> Broadside.Graphics.PdfColorSpace! +Broadside.Graphics.PdfColor.ComponentCount.get -> int +Broadside.Graphics.PdfColor.Components.get -> System.ReadOnlySpan +Broadside.Graphics.PdfColor.Equals(Broadside.Graphics.PdfColor other) -> bool +Broadside.Graphics.PdfColor.Pattern.get -> Broadside.Objects.CosObject? +Broadside.Graphics.PdfColor.PatternMatrix.get -> Broadside.Graphics.Matrix +Broadside.Graphics.PdfColor.PatternName.get -> Broadside.Objects.CosName? +Broadside.Graphics.PdfColor.PdfColor() -> void +Broadside.Graphics.PdfColor.PdfColor(Broadside.Graphics.PdfColorSpace! colorSpace, System.ReadOnlySpan components) -> void +Broadside.Graphics.PdfColor.this[int index].get -> float +Broadside.Graphics.PdfColorConverter +Broadside.Graphics.PdfColorConverter.Conversion.get -> Broadside.Graphics.ColorConversion +Broadside.Graphics.PdfColorConverter.Convert(in Broadside.Graphics.PdfColor color, System.Span destination) -> void +Broadside.Graphics.PdfColorConverter.Convert(System.ReadOnlySpan source, System.Span destination, int count) -> void +Broadside.Graphics.PdfColorConverter.Convert(System.ReadOnlySpan components, System.Span destination) -> void +Broadside.Graphics.PdfColorConverter.Convert(System.ReadOnlySpan source, System.Span destination, int count) -> void +Broadside.Graphics.PdfColorConverter.InputCount.get -> int +Broadside.Graphics.PdfColorConverter.OutputCount.get -> int +Broadside.Graphics.PdfColorConverter.PaintsNothing.get -> bool +Broadside.Graphics.PdfColorConverter.Source.get -> Broadside.Graphics.PdfColorSpace! +Broadside.Graphics.PdfColorSpace +Broadside.Graphics.PdfColorSpace.CosObject.get -> Broadside.Objects.CosObject! +Broadside.Graphics.PdfColorSpace.GetComponentRange(int index) -> Broadside.Graphics.ComponentRange +Broadside.Graphics.PdfColorSpace.GetDefaultDecode(int bitsPerComponent) -> double[]! +Broadside.Graphics.PdfColorSpace.GetInitialColor() -> Broadside.Graphics.PdfColor +Broadside.Graphics.PdfColorSpace.Reference.get -> Broadside.Objects.CosReference? +Broadside.Graphics.PdfColorSpaceFamily +Broadside.Graphics.PdfColorSpaceFamily.CalGray = 3 -> Broadside.Graphics.PdfColorSpaceFamily +Broadside.Graphics.PdfColorSpaceFamily.CalRgb = 4 -> Broadside.Graphics.PdfColorSpaceFamily +Broadside.Graphics.PdfColorSpaceFamily.DeviceCmyk = 2 -> Broadside.Graphics.PdfColorSpaceFamily +Broadside.Graphics.PdfColorSpaceFamily.DeviceGray = 0 -> Broadside.Graphics.PdfColorSpaceFamily +Broadside.Graphics.PdfColorSpaceFamily.DeviceN = 10 -> Broadside.Graphics.PdfColorSpaceFamily +Broadside.Graphics.PdfColorSpaceFamily.DeviceRgb = 1 -> Broadside.Graphics.PdfColorSpaceFamily +Broadside.Graphics.PdfColorSpaceFamily.IccBased = 6 -> Broadside.Graphics.PdfColorSpaceFamily +Broadside.Graphics.PdfColorSpaceFamily.Indexed = 7 -> Broadside.Graphics.PdfColorSpaceFamily +Broadside.Graphics.PdfColorSpaceFamily.Lab = 5 -> Broadside.Graphics.PdfColorSpaceFamily +Broadside.Graphics.PdfColorSpaceFamily.Pattern = 8 -> Broadside.Graphics.PdfColorSpaceFamily +Broadside.Graphics.PdfColorSpaceFamily.Separation = 9 -> Broadside.Graphics.PdfColorSpaceFamily +Broadside.Graphics.PdfDefaultColorSpaces +Broadside.Graphics.PdfDefaultColorSpaces.Cmyk.get -> Broadside.Graphics.PdfColorSpace? +Broadside.Graphics.PdfDefaultColorSpaces.Gray.get -> Broadside.Graphics.PdfColorSpace? +Broadside.Graphics.PdfDefaultColorSpaces.IsEmpty.get -> bool +Broadside.Graphics.PdfDefaultColorSpaces.Remap(Broadside.Graphics.PdfColorSpace! colorSpace) -> Broadside.Graphics.PdfColorSpace! +Broadside.Graphics.PdfDefaultColorSpaces.Rgb.get -> Broadside.Graphics.PdfColorSpace? +Broadside.Graphics.PdfDeviceCmykColorSpace +Broadside.Graphics.PdfDeviceGrayColorSpace +Broadside.Graphics.PdfDeviceNAttributes +Broadside.Graphics.PdfDeviceNAttributes.Colorants.get -> System.Collections.Generic.IReadOnlyDictionary! +Broadside.Graphics.PdfDeviceNAttributes.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Graphics.PdfDeviceNAttributes.IsNChannel.get -> bool +Broadside.Graphics.PdfDeviceNAttributes.MixingHints.get -> Broadside.Graphics.PdfDeviceNMixingHints? +Broadside.Graphics.PdfDeviceNAttributes.Process.get -> Broadside.Graphics.PdfDeviceNProcess? +Broadside.Graphics.PdfDeviceNAttributes.Subtype.get -> Broadside.Objects.CosName! +Broadside.Graphics.PdfDeviceNColorSpace +Broadside.Graphics.PdfDeviceNColorSpace.Alternate.get -> Broadside.Graphics.PdfColorSpace! +Broadside.Graphics.PdfDeviceNColorSpace.AreAllNone.get -> bool +Broadside.Graphics.PdfDeviceNColorSpace.Attributes.get -> Broadside.Graphics.PdfDeviceNAttributes? +Broadside.Graphics.PdfDeviceNColorSpace.ColorantNames.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Graphics.PdfDeviceNColorSpace.IsNChannel.get -> bool +Broadside.Graphics.PdfDeviceNColorSpace.TintTransform.get -> Broadside.Graphics.PdfFunction? +Broadside.Graphics.PdfDeviceNMixingHints +Broadside.Graphics.PdfDeviceNMixingHints.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Graphics.PdfDeviceNMixingHints.DotGain.get -> System.Collections.Generic.IReadOnlyDictionary! +Broadside.Graphics.PdfDeviceNMixingHints.PrintingOrder.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Graphics.PdfDeviceNMixingHints.Solidities.get -> System.Collections.Generic.IReadOnlyDictionary! +Broadside.Graphics.PdfDeviceNProcess +Broadside.Graphics.PdfDeviceNProcess.ColorSpace.get -> Broadside.Graphics.PdfColorSpace? +Broadside.Graphics.PdfDeviceNProcess.Components.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Graphics.PdfDeviceNProcess.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Graphics.PdfDeviceRgbColorSpace +Broadside.Graphics.PdfIccBasedColorSpace +Broadside.Graphics.PdfIccBasedColorSpace.Alternate.get -> Broadside.Graphics.PdfColorSpace! +Broadside.Graphics.PdfIccBasedColorSpace.DeclaredComponentCount.get -> int? +Broadside.Graphics.PdfIccBasedColorSpace.GetProfileData() -> System.ReadOnlyMemory +Broadside.Graphics.PdfIccBasedColorSpace.Metadata.get -> Broadside.Objects.CosStream? +Broadside.Graphics.PdfIccBasedColorSpace.ProfileHeader.get -> Broadside.Graphics.IccProfileHeader? +Broadside.Graphics.PdfIccBasedColorSpace.Range.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Graphics.PdfIccBasedColorSpace.Stream.get -> Broadside.Objects.CosStream! +Broadside.Graphics.PdfIndexedColorSpace +Broadside.Graphics.PdfIndexedColorSpace.Base.get -> Broadside.Graphics.PdfColorSpace! +Broadside.Graphics.PdfIndexedColorSpace.GetLookup() -> System.ReadOnlyMemory +Broadside.Graphics.PdfIndexedColorSpace.HighValue.get -> int +Broadside.Graphics.PdfLabColorSpace +Broadside.Graphics.PdfLabColorSpace.BlackPoint.get -> Broadside.Graphics.CieXyz +Broadside.Graphics.PdfLabColorSpace.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Graphics.PdfLabColorSpace.Range.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Graphics.PdfLabColorSpace.WhitePoint.get -> Broadside.Graphics.CieXyz +Broadside.Graphics.PdfPatternColorSpace +Broadside.Graphics.PdfPatternColorSpace.Underlying.get -> Broadside.Graphics.PdfColorSpace? +Broadside.Graphics.PdfSeparationColorSpace +Broadside.Graphics.PdfSeparationColorSpace.Alternate.get -> Broadside.Graphics.PdfColorSpace! +Broadside.Graphics.PdfSeparationColorSpace.ColorantName.get -> Broadside.Objects.CosName! +Broadside.Graphics.PdfSeparationColorSpace.IsAll.get -> bool +Broadside.Graphics.PdfSeparationColorSpace.IsNone.get -> bool +Broadside.Graphics.PdfSeparationColorSpace.TintTransform.get -> Broadside.Graphics.PdfFunction? Broadside.Graphics.RenderingIntent Broadside.Graphics.RenderingIntent.AbsoluteColorimetric = 1 -> Broadside.Graphics.RenderingIntent Broadside.Graphics.RenderingIntent.Perceptual = 3 -> Broadside.Graphics.RenderingIntent @@ -437,11 +614,19 @@ Broadside.Objects.CosString.CosString(System.ReadOnlySpan bytes, bool hexa Broadside.Objects.CosString.DecodeText() -> string! Broadside.Objects.CosString.Equals(Broadside.Objects.CosString? other) -> bool Broadside.Objects.CosString.IsHexadecimal.get -> bool +Broadside.PdfDocument.GetColorConverter(Broadside.Graphics.PdfColorSpace! source) -> Broadside.Graphics.PdfColorConverter! +Broadside.PdfDocument.GetColorConverter(Broadside.Graphics.PdfColorSpace! source, Broadside.Graphics.ColorConversion conversion, Broadside.Graphics.PdfDefaultColorSpaces? defaults = null) -> Broadside.Graphics.PdfColorConverter! +Broadside.PdfDocument.GetColorConverter(Broadside.Graphics.PdfColorSpace! source, Broadside.Graphics.PdfDefaultColorSpaces? defaults) -> Broadside.Graphics.PdfColorConverter! +Broadside.PdfDocument.GetColorSpace(Broadside.Objects.CosObject! colorSpace) -> Broadside.Graphics.PdfColorSpace! +Broadside.PdfDocument.GetDefaultColorSpaces(Broadside.Objects.CosDictionary? resources) -> Broadside.Graphics.PdfDefaultColorSpaces! +Broadside.PdfOptions.UseColorManagement(Broadside.Graphics.IColorManagement! colorManagement) -> Broadside.PdfOptions! Broadside.PdfPage.ProcessContent(Broadside.Content.ContentProcessor! processor) -> void Broadside.PdfPage.ProcessContent(Broadside.Content.ContentProcessor! processor, Broadside.Content.ContentOptions! options) -> void const Broadside.Content.ContentOptions.DefaultMaxNestingDepth = 50 -> int const Broadside.Content.ContentOptions.DefaultMaxOperands = 65536 -> int const Broadside.Content.ContentOptions.DefaultMaxSaveDepth = 4096 -> int +const Broadside.Graphics.IccProfileHeader.Length = 128 -> int +const Broadside.Graphics.PdfColor.MaxComponents = 32 -> int const Broadside.Objects.CosReference.MaxGeneration = 65535 -> int override Broadside.Content.CompositeContentProcessor.BeginForm(in Broadside.Content.FormEvent form, Broadside.Content.ContentContext! context) -> Broadside.Content.ContentVisit override Broadside.Content.CompositeContentProcessor.BeginMarkedContent(in Broadside.Content.MarkedContentEvent mc, Broadside.Content.ContentContext! context) -> void @@ -467,6 +652,32 @@ override Broadside.Graphics.Matrix.Equals(object? obj) -> bool override Broadside.Graphics.Matrix.GetHashCode() -> int override Broadside.Graphics.Matrix.ToString() -> string! override Broadside.Graphics.PathPoint.ToString() -> string! +override Broadside.Graphics.PdfCalGrayColorSpace.ComponentCount.get -> int +override Broadside.Graphics.PdfCalGrayColorSpace.Family.get -> Broadside.Graphics.PdfColorSpaceFamily +override Broadside.Graphics.PdfCalRgbColorSpace.ComponentCount.get -> int +override Broadside.Graphics.PdfCalRgbColorSpace.Family.get -> Broadside.Graphics.PdfColorSpaceFamily +override Broadside.Graphics.PdfColor.Equals(object? obj) -> bool +override Broadside.Graphics.PdfColor.GetHashCode() -> int +override Broadside.Graphics.PdfDeviceCmykColorSpace.ComponentCount.get -> int +override Broadside.Graphics.PdfDeviceCmykColorSpace.Family.get -> Broadside.Graphics.PdfColorSpaceFamily +override Broadside.Graphics.PdfDeviceGrayColorSpace.ComponentCount.get -> int +override Broadside.Graphics.PdfDeviceGrayColorSpace.Family.get -> Broadside.Graphics.PdfColorSpaceFamily +override Broadside.Graphics.PdfDeviceNColorSpace.ComponentCount.get -> int +override Broadside.Graphics.PdfDeviceNColorSpace.Family.get -> Broadside.Graphics.PdfColorSpaceFamily +override Broadside.Graphics.PdfDeviceNColorSpace.MinimumVersion.get -> Broadside.PdfVersion +override Broadside.Graphics.PdfDeviceRgbColorSpace.ComponentCount.get -> int +override Broadside.Graphics.PdfDeviceRgbColorSpace.Family.get -> Broadside.Graphics.PdfColorSpaceFamily +override Broadside.Graphics.PdfIccBasedColorSpace.ComponentCount.get -> int +override Broadside.Graphics.PdfIccBasedColorSpace.Family.get -> Broadside.Graphics.PdfColorSpaceFamily +override Broadside.Graphics.PdfIndexedColorSpace.ComponentCount.get -> int +override Broadside.Graphics.PdfIndexedColorSpace.Family.get -> Broadside.Graphics.PdfColorSpaceFamily +override Broadside.Graphics.PdfIndexedColorSpace.MinimumVersion.get -> Broadside.PdfVersion +override Broadside.Graphics.PdfLabColorSpace.ComponentCount.get -> int +override Broadside.Graphics.PdfLabColorSpace.Family.get -> Broadside.Graphics.PdfColorSpaceFamily +override Broadside.Graphics.PdfPatternColorSpace.ComponentCount.get -> int +override Broadside.Graphics.PdfPatternColorSpace.Family.get -> Broadside.Graphics.PdfColorSpaceFamily +override Broadside.Graphics.PdfSeparationColorSpace.ComponentCount.get -> int +override Broadside.Graphics.PdfSeparationColorSpace.Family.get -> Broadside.Graphics.PdfColorSpaceFamily override Broadside.Objects.CosArray.IsDirty.get -> bool override Broadside.Objects.CosBoolean.Equals(object? obj) -> bool override Broadside.Objects.CosBoolean.GetHashCode() -> int @@ -485,6 +696,12 @@ override Broadside.Objects.CosReference.GetHashCode() -> int override Broadside.Objects.CosStream.IsDirty.get -> bool override Broadside.Objects.CosString.Equals(object? obj) -> bool override Broadside.Objects.CosString.GetHashCode() -> int +static Broadside.Graphics.CieXyz.D50.get -> Broadside.Graphics.CieXyz +static Broadside.Graphics.CieXyz.D65.get -> Broadside.Graphics.CieXyz +static Broadside.Graphics.ColorConversion.FromState(in Broadside.Graphics.GraphicsState state, Broadside.Graphics.DeviceColorModel target) -> Broadside.Graphics.ColorConversion +static Broadside.Graphics.IccProfileHeader.Parse(System.ReadOnlySpan profile) -> Broadside.Graphics.IccProfileHeader? +static Broadside.Graphics.ManagedColorManagement.Classic.get -> Broadside.Graphics.ManagedColorManagement! +static Broadside.Graphics.ManagedColorManagement.Default.get -> Broadside.Graphics.ManagedColorManagement! static Broadside.Graphics.Matrix.CreateScale(double sx, double sy) -> Broadside.Graphics.Matrix static Broadside.Graphics.Matrix.CreateTranslation(double tx, double ty) -> Broadside.Graphics.Matrix static Broadside.Graphics.Matrix.Identity.get -> Broadside.Graphics.Matrix @@ -492,6 +709,12 @@ static Broadside.Graphics.Matrix.Multiply(Broadside.Graphics.Matrix first, Broad static Broadside.Graphics.Matrix.operator !=(Broadside.Graphics.Matrix left, Broadside.Graphics.Matrix right) -> bool static Broadside.Graphics.Matrix.operator *(Broadside.Graphics.Matrix first, Broadside.Graphics.Matrix second) -> Broadside.Graphics.Matrix static Broadside.Graphics.Matrix.operator ==(Broadside.Graphics.Matrix left, Broadside.Graphics.Matrix right) -> bool +static Broadside.Graphics.PdfColor.operator !=(Broadside.Graphics.PdfColor left, Broadside.Graphics.PdfColor right) -> bool +static Broadside.Graphics.PdfColor.operator ==(Broadside.Graphics.PdfColor left, Broadside.Graphics.PdfColor right) -> bool +static Broadside.Graphics.PdfDefaultColorSpaces.None.get -> Broadside.Graphics.PdfDefaultColorSpaces! +static Broadside.Graphics.PdfDeviceCmykColorSpace.Instance.get -> Broadside.Graphics.PdfDeviceCmykColorSpace! +static Broadside.Graphics.PdfDeviceGrayColorSpace.Instance.get -> Broadside.Graphics.PdfDeviceGrayColorSpace! +static Broadside.Graphics.PdfDeviceRgbColorSpace.Instance.get -> Broadside.Graphics.PdfDeviceRgbColorSpace! static Broadside.Objects.CosBoolean.False.get -> Broadside.Objects.CosBoolean! static Broadside.Objects.CosBoolean.True.get -> Broadside.Objects.CosBoolean! static Broadside.Objects.CosNull.Instance.get -> Broadside.Objects.CosNull! @@ -518,6 +741,7 @@ virtual Broadside.Content.ContentProcessor.RestoreState(Broadside.Content.Conten virtual Broadside.Content.ContentProcessor.SaveState(Broadside.Content.ContentContext! context) -> void virtual Broadside.Content.ContentProcessor.ShowGlyph(in Broadside.Content.GlyphEvent glyph, Broadside.Content.ContentContext! context) -> void virtual Broadside.Content.ContentProcessor.VisitOperator(in Broadside.Content.ContentOperator op, Broadside.Content.ContentContext! context) -> void +virtual Broadside.Graphics.PdfColorSpace.MinimumVersion.get -> Broadside.PdfVersion virtual Broadside.Objects.CosObject.IsDirty.get -> bool Broadside.Diagnostics.Diagnostic Broadside.Diagnostics.Diagnostic.Code.get -> string! diff --git a/tests/Broadside.Fuzz/FuzzTargets.cs b/tests/Broadside.Fuzz/FuzzTargets.cs index 1e234565..1449e7b4 100644 --- a/tests/Broadside.Fuzz/FuzzTargets.cs +++ b/tests/Broadside.Fuzz/FuzzTargets.cs @@ -47,6 +47,7 @@ internal static class FuzzTargets ["structure-tree"] = StructureTree.Target, ["function-type4"] = FunctionType4, ["function-sampled"] = FunctionSampled, + ["colorspace"] = ColorSpaceTarget, }; private static readonly CosName ContentsKey = new("Contents"); @@ -652,6 +653,119 @@ private static void Decrypt(ReadOnlySpan data) /// must lie in the range, and once warm an evaluation must allocate nothing. /// /// ISO 32000-2 §7.10.5, Annex B. + /// + /// Colour spaces (ISO 32000-2 §8.6). The input's first 128 bytes are read as an ICC profile header. An input that starts with + /// %PDF- is opened as a file and every value of its first page's ColorSpace resources is read (the corpus seed + /// colorspace-families.pdf mutates into every family); any other input is parsed leniently as one COS object and read as + /// a colour space. Each space is read completely (every view property) and converted to RGB, gray and CMYK, from floats inside + /// and outside the component ranges and from bytes: every output must lie in 0..1 and lenient reading must never throw. + /// + private static void ColorSpaceTarget(ReadOnlySpan data) + { + _ = IccProfileHeader.Parse(data); + if (data.StartsWith("%PDF-"u8)) + { + using PdfDocument? file = OpenOrNull(data); + if (file is null || file.Pages.Count == 0 + || file.Pages[0].Resources is not { } resources + || file.Resolve(resources.GetValueOrDefault(new CosName("ColorSpace"))) is not CosDictionary spaces) + { + return; + } + + foreach (KeyValuePair entry in spaces) + { + ExerciseColorSpace(file, file.GetColorSpace(entry.Value), file.GetDefaultColorSpaces(resources)); + } + + return; + } + + using PdfDocument document = PdfDocument.Create(); + CosObject value = new CosParser(data, repairs: null).ParseObject(); + ExerciseColorSpace(document, document.GetColorSpace(value), PdfDefaultColorSpaces.None); + } + + private static void ExerciseColorSpace(PdfDocument document, PdfColorSpace space, PdfDefaultColorSpaces defaults) + { + int count = space.ComponentCount; + _ = (space.Family, space.MinimumVersion, space.GetDefaultDecode(8), space.GetInitialColor()); + for (int i = 0; i < count; i++) + { + _ = space.GetComponentRange(i); + } + + switch (space) + { + case PdfCalGrayColorSpace gray: + _ = (gray.WhitePoint, gray.BlackPoint, gray.Gamma); + break; + case PdfCalRgbColorSpace rgb: + _ = (rgb.WhitePoint, rgb.BlackPoint, rgb.Gamma.Count, rgb.Matrix.Count); + break; + case PdfLabColorSpace lab: + _ = (lab.WhitePoint, lab.Range.Count); + break; + case PdfIccBasedColorSpace icc: + _ = (icc.ProfileHeader?.IsSupportedForPdf, icc.Alternate, icc.Range.Count, icc.Metadata, icc.DeclaredComponentCount); + break; + case PdfIndexedColorSpace indexed: + _ = (indexed.Base, indexed.HighValue, indexed.GetLookup().Length); + break; + case PdfSeparationColorSpace separation: + _ = (separation.ColorantName, separation.IsAll, separation.IsNone, separation.Alternate, separation.TintTransform); + break; + case PdfDeviceNColorSpace deviceN: + _ = (deviceN.ColorantNames.Count, deviceN.AreAllNone, deviceN.Alternate, deviceN.TintTransform); + if (deviceN.Attributes is { } attributes) + { + _ = (attributes.Subtype, attributes.Colorants.Count, attributes.Process?.ColorSpace, attributes.Process?.Components.Count); + _ = (attributes.MixingHints?.Solidities.Count, attributes.MixingHints?.PrintingOrder.Count, attributes.MixingHints?.DotGain.Count); + } + + break; + case PdfPatternColorSpace pattern: + _ = pattern.Underlying; + break; + } + + int inputs = Math.Min(count, 64); + float[] components = new float[3 * Math.Max(inputs, 1)]; + float[] points = [-1e30f, 0.5f, 300f]; + for (int c = 0; c < 3; c++) + { + components.AsSpan(c * Math.Max(inputs, 1), Math.Max(inputs, 1)).Fill(points[c]); + } + + byte[] samples = new byte[3 * Math.Max(inputs, 1)]; + new Random(count).NextBytes(samples); + foreach (DeviceColorModel target in new[] { DeviceColorModel.Rgb, DeviceColorModel.Gray, DeviceColorModel.Cmyk }) + { + PdfColorConverter converter = document.GetColorConverter(space, new ColorConversion { Target = target }, defaults); + if (converter.InputCount != count) + { + throw new InvalidOperationException($"A converter takes {converter.InputCount} components for a space of {count}."); + } + + if (count > 64) + { + continue; + } + + float[] colors = new float[3 * converter.OutputCount]; + converter.Convert(components, colors, 3); + foreach (float value in colors) + { + if (!(value >= 0 && value <= 1)) + { + throw new InvalidOperationException($"A {space.Family} colour converted to {value}, outside 0..1."); + } + } + + converter.Convert(samples, new byte[3 * converter.OutputCount], 3); + } + } + private static void FunctionType4(ReadOnlySpan data) { if (data.IsEmpty) diff --git a/tests/Broadside.Fuzz/README.md b/tests/Broadside.Fuzz/README.md index db4781d3..bdd6d687 100644 --- a/tests/Broadside.Fuzz/README.md +++ b/tests/Broadside.Fuzz/README.md @@ -6,7 +6,7 @@ The fuzz harness: one console application, one target per parser or codec, selec dotnet run -c Release --project tests/Broadside.Fuzz -- --list ``` -Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters, and reads every font of each page's resources through the font model (each simple font's 256 glyph names and widths, which must be non-empty and finite, and its descriptor); a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. `xmp` reads the input as an XMP packet (ISO 16684-1) through the reader the document uses, and again from its first `> /RoleMap << /A /B /B /A >>` followed by `<< /S /A /P 4 0 R /Pg 3 0 R /K [0 5 0 R] /A [1 << /O /Layout >> 2] >>`. `content-lexer` reads the input as decoded content stream bytes with the content reader (ISO 32000-2 §7.8.2, #55): every operator must lie inside the input, after the previous one, with a keyword of at least one byte, and every operand, nested arrays and dictionaries included, must be readable; `content-interpreter` runs the input as a page's content through the interpreter with a processor that asks for every event and checks that path verbs and points agree, that clip handles chain back to the initial clip and that the state stack is balanced at the end; `document` now also interprets every page with that processor. Whole files are weak seeds for the two content targets; for libFuzzer and AFL seed them with decoded content streams (`qpdf --show-object=4 --filtered-stream-data tests/Corpus/filter-chain.pdf`) and with `ContentSamples.PathHeavy` output. `function-type4` compiles the input after its first byte as a Type 4 (PostScript calculator) program (byte 0 picks 1 to 4 inputs and 1 to 4 outputs) and `function-sampled` builds a Type 0 (sampled) function whose Size, BitsPerSample, Order and Encode come from bytes 0 to 4 and whose samples are the rest (ISO 32000-2 §7.10); both evaluate at fixed points inside and outside the domain, require every output inside the range, and require warm evaluations to allocate nothing. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). +Targets live in `FuzzTargets.cs` as a dictionary from name to `ReadOnlySpanAction`. A target takes one input, calls into `Broadside`, and either returns or throws; any exception that escapes is a finding. The targets today are `lexer` (the COS lexer over the whole input: every token inside the input, always making progress) and `object-parser` (the lenient COS object parser scanning the input as a file body, checking that every object it reads writes back to syntax that parses, without repair, to an equal object; it also runs the strict public `CosObject.TryParse`) and `document` (opens the input as a whole file in lenient mode and reads the version, trailer and every page's boxes, rotation, user unit and resources, and decodes each page's content stream through its filters, and reads every font of each page's resources through the font model (each simple font's 256 glyph names and widths, which must be non-empty and finite, and its descriptor); a `DiagnosticException` is the one allowed outcome, for a file in which even a scan finds no catalog (`CatalogNotFound`); it also reads the revisions and a linearized file's parameter dictionary and hint tables) and `windowed-document` (opens the input from memory and through a seekable stream read in place in windows, once with the default first window and once with windows that start at 16 bytes and double, and requires all three to give the same pages, objects and diagnostics, or fail the same way) and `hint-tables` (the linearization hint table decoder of Annex F over raw hint stream data: byte 0 selects the page count, bytes 1 and 2 the position of the shared object table, the rest is the data; it either fails with a reason or returns one entry per page). `xref-stream` reads the input as cross-reference stream data (bytes 0 to 2 are the W field widths, byte 3 picks the default Index or two subsections, the rest is the data) and checks the entries against the data; `repair` scans the input as a damaged whole file and rebuilds its cross-reference information from the scan, as a lenient open does when the file's own cannot be read (#41): every position the scan reports lies inside the input in file order, every rebuilt in-use entry is an object header the scan found, and the rebuilt trailer has Root (whole corpus files are the right seeds); `object-stream` reads the input as decoded object stream data (bytes 0 and 1 are N and First) and parses every member the header names, at its index and at a wrong one; whole files with cross-reference and object streams go through `document`. `save` opens the input as a whole file, saves it in the layout its length selects (length mod 3: table, cross-reference stream, cross-reference stream with object streams) and reopens the output, which must open with the same page count; `NotSupportedException` (encrypted input, object numbers above the save limit) is the one allowed outcome besides an unreadable input. The filter targets `filter-asciihex`, `filter-ascii85`, `filter-lzw` (first byte selects EarlyChange), `filter-flate` and `filter-runlength` decode the input as a raw stream body and check the output against the most the encoding can expand to; `filter-predictor` reads Predictor, Colors, BitsPerComponent and Columns from the first four bytes and checks that the output is whole rows. `encrypted-document` opens the input with the owner password `owner` (so mutations of the encrypted corpus files get past authentication), decodes every page's content streams and reads the Info strings; `PdfPasswordException`, `PdfCertificateException` and `PdfEncryptionNotSupportedException` are allowed outcomes, as they are now for `document`, `windowed-document` and `save`. `public-key` wraps the input in a document encrypted for certificate recipients (ISO 32000-2 §7.6.5): byte 0 selects where it goes (an extra recipient list before a valid one for a fixed certificate, in an `adbe.pkcs7.s4` or `adbe.pkcs7.s5` dictionary, or the `Recipients` string of a stream's own crypt filter), and the document is opened with that certificate; it must open, digest the input into the key, and decode its content streams (any input is a valid seed). `decrypt` decrypts the input after its first byte as a string with the crypt filter method that byte selects (RC4, AES-128 with Algorithm 1's object key, AES-256-CBC, AES-256-GCM) and checks the plaintext is no longer than the ciphertext; `mac-token` parses the input as a DER PDF MAC token (ISO/TS 32004 AuthenticatedData) and checks its structure. `xmp` reads the input as an XMP packet (ISO 16684-1) through the reader the document uses, and again from its first `> /RoleMap << /A /B /B /A >>` followed by `<< /S /A /P 4 0 R /Pg 3 0 R /K [0 5 0 R] /A [1 << /O /Layout >> 2] >>`. `content-lexer` reads the input as decoded content stream bytes with the content reader (ISO 32000-2 §7.8.2, #55): every operator must lie inside the input, after the previous one, with a keyword of at least one byte, and every operand, nested arrays and dictionaries included, must be readable; `content-interpreter` runs the input as a page's content through the interpreter with a processor that asks for every event and checks that path verbs and points agree, that clip handles chain back to the initial clip and that the state stack is balanced at the end; `document` now also interprets every page with that processor. Whole files are weak seeds for the two content targets; for libFuzzer and AFL seed them with decoded content streams (`qpdf --show-object=4 --filtered-stream-data tests/Corpus/filter-chain.pdf`) and with `ContentSamples.PathHeavy` output. `function-type4` compiles the input after its first byte as a Type 4 (PostScript calculator) program (byte 0 picks 1 to 4 inputs and 1 to 4 outputs) and `function-sampled` builds a Type 0 (sampled) function whose Size, BitsPerSample, Order and Encode come from bytes 0 to 4 and whose samples are the rest (ISO 32000-2 §7.10); both evaluate at fixed points inside and outside the domain, require every output inside the range, and require warm evaluations to allocate nothing. `colorspace` (ISO 32000-2 §8.6, #77) reads the input's first 128 bytes as an ICC profile header, then either opens an input starting with `%PDF-` and reads every value of its first page's `ColorSpace` resources (seed: `colorspace-families.pdf`), or parses any other input leniently as one COS object and reads it as a colour space; each space is read through every view property and converted to RGB, gray and CMYK from out-of-range floats and from bytes, every output in 0..1. For libFuzzer and AFL seed it with colour space arrays as text as well, for instance `[/Indexed [/ICCBased 5 0 R] 255 <...>]` or `[/DeviceN [/A /B] /DeviceCMYK << /FunctionType 4 ... >> << /Subtype /NChannel ... >>]`. Every parser and codec after them adds its own (CLAUDE.md, "Code conventions"). Exit codes: 0 no finding, 1 a finding, 2 usage error. diff --git a/tests/Broadside.TestSupport/Corpus.cs b/tests/Broadside.TestSupport/Corpus.cs index a4473ae7..2038d3fd 100644 --- a/tests/Broadside.TestSupport/Corpus.cs +++ b/tests/Broadside.TestSupport/Corpus.cs @@ -60,6 +60,10 @@ public static class Corpus "destinations-all.pdf", "outline-full.pdf", "functions.pdf", + "colorspace-families.pdf", + "color-operators.pdf", + "default-colorspaces.pdf", + "separation-special.pdf", ]; private static readonly string[] Malformed = diff --git a/tests/Broadside.Tests/Colors/ColorAllocationTests.cs b/tests/Broadside.Tests/Colors/ColorAllocationTests.cs new file mode 100644 index 00000000..e92e7102 --- /dev/null +++ b/tests/Broadside.Tests/Colors/ColorAllocationTests.cs @@ -0,0 +1,106 @@ +using System.Text; +using Broadside.Content; +using Broadside.Graphics; +using Broadside.Tests.Document; +using static Broadside.Tests.Colors.ColorTesting; + +namespace Broadside.Tests.Colors; + +/// +/// Setting colours and converting runs of colours are hot paths and allocate nothing once warm (CLAUDE.md "Code conventions"; +/// ISO 32000-2 §8.6.8). This is the build-breaking half; ColorConversionBenchmarks is the measuring half. In the heavy +/// collection, like the other allocation tests. +/// +[Collection(HeavyTestCollection.Name)] +public class ColorAllocationTests +{ + private const int WarmUp = 50; + + [Fact] + public void Setting_colours_in_every_kind_of_space_allocates_nothing_once_warm() + { + var content = new StringBuilder(); + for (int i = 0; i < 500; i++) + { + content.Append("/Sep cs 0.5 scn /Ref CS 0.25 SCN /Ix cs 1 sc /Lab cs 50 10 -10 sc /DN cs 0.1 0.2 scn ") + .Append("/P cs 1 0 0 /T scn 0.2 g 0.1 0.2 0.3 RG 0 0 0 1 k 0 0 1 1 re B\n"); + } + + using PdfDocument document = PdfDocument.Open(Page( + "<< /ColorSpace << /Sep [/Separation /Spot /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0.5 1 0] /N 1 >>] " + + "/Ref 5 0 R /Ix [/Indexed /DeviceRGB 1 ] /Lab [/Lab << /WhitePoint [0.9642 1 0.8249] >>] " + + "/DN [/DeviceN [/A /B] /DeviceRGB << /FunctionType 4 /Domain [0 1 0 1] /Range [0 1 0 1 0 1] /Length 9 >>] /P [/Pattern /DeviceRGB] >> " + + "/Pattern << /T 6 0 R >> >>", + content.ToString(), + "[/Separation /Other /DeviceGray << /FunctionType 2 /Domain [0 1] /C0 [1] /C1 [0] /N 1 >>]", + "<< /PatternType 1 /PaintType 2 /TilingType 1 /BBox [0 0 1 1] /XStep 1 /YStep 1 /Resources << >> /Length 0 >>\nstream\n\nendstream")); + PdfPage page = document.Pages[0]; + var processor = new ColorCounter(); + for (int pass = 0; pass < WarmUp; pass++) + { + page.ProcessContent(processor); + } + + processor.Paints = 0; + long before = GC.GetAllocatedBytesForCurrentThread(); + page.ProcessContent(processor); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.Equal(500, processor.Paints); + Assert.Equal(0, allocated); + } + + [Fact] + public void Converting_runs_of_colours_allocates_nothing_once_warm() + { + using PdfDocument document = PdfDocument.Create(); + PdfColorConverter[] converters = + [ + document.GetColorConverter(PdfDeviceCmykColorSpace.Instance), + document.GetColorConverter(document.GetColorSpace(Cos("[/Lab << /WhitePoint [0.9642 1 0.8249] >>]"))), + document.GetColorConverter(document.GetColorSpace(Cos("[/Separation /S /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0.5 1 0] /N 1 >>]"))), + document.GetColorConverter(document.GetColorSpace(Cos("[/Indexed /DeviceRGB 1 ]"))), + document.GetColorConverter(document.GetColorSpace(Cos("[/DeviceN [/A /B] /DeviceCMYK << /FunctionType 2 /Domain [0 1 0 1] /C0 [0 0 0 0] /C1 [1 1 0 0] /N 1 >>]"))), + ]; + byte[] samples = new byte[4096 * 4]; + byte[] output = new byte[4096 * 3]; + float[] components = new float[256 * 4]; + float[] colors = new float[256 * 3]; + for (int pass = 0; pass < WarmUp; pass++) + { + Run(); + } + + long before = GC.GetAllocatedBytesForCurrentThread(); + Run(); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.Equal(0, allocated); + + void Run() + { + foreach (PdfColorConverter converter in converters) + { + converter.Convert(samples, output, 4096); + converter.Convert(components, colors, 256); + } + } + } + + /// Counts paints and reads both colours, as a renderer would. + private sealed class ColorCounter : ContentProcessor + { + public int Paints { get; set; } + + public float Sum { get; private set; } + + public override ContentEvents Events => ContentEvents.Paths; + + public override void PaintPath(in PathEvent path, ContentContext context) + { + Paints++; + Sum += context.State.FillColor[0] + context.State.StrokeColor.ComponentCount; + _ = context.DefaultColorSpaces; + } + } +} diff --git a/tests/Broadside.Tests/Colors/ColorConversionTests.cs b/tests/Broadside.Tests/Colors/ColorConversionTests.cs new file mode 100644 index 00000000..c15596ff --- /dev/null +++ b/tests/Broadside.Tests/Colors/ColorConversionTests.cs @@ -0,0 +1,240 @@ +using Broadside.Graphics; +using Broadside.Objects; +using static Broadside.Tests.Colors.ColorTesting; + +namespace Broadside.Tests.Colors; + +/// +/// Conversion to device colours through and the managed colour management: the device formulas of +/// ISO 32000-2 §10.4.2 (with the clause's own example), the CIE-based spaces of §8.6.5 against sRGB reference values, and the +/// special spaces of §8.6.6. +/// +public class ColorConversionTests +{ + /// The sRGB (IEC 61966-2-1) primaries as a CalRGB Matrix with the D65 white: linear CalRGB values are linear sRGB. + private const string SrgbCalRgb = "[/CalRGB << /WhitePoint [0.95047 1 1.08883] /Matrix [0.4124564 0.2126729 0.0193339 0.3575761 0.7151522 0.1191920 0.1804375 0.0721750 0.9503041] >>]"; + + /// sRGB encoding of linear 0.5 (IEC 61966-2-1: 1.055 × 0.5^(1/2.4) − 0.055). + private const float HalfLinear = 0.7353570f; + + [Fact] + public void Gray_and_RGB_convert_by_the_formulas_of_10_4_2_2() + { + using PdfDocument document = PdfDocument.Create(); + float[] gray = new float[1]; + + Near([0.4f, 0.4f, 0.4f], document.Rgb(PdfDeviceGrayColorSpace.Instance, 0.4f)); + document.GetColorConverter(PdfDeviceRgbColorSpace.Instance, new ColorConversion { Target = DeviceColorModel.Gray }).Convert([0.2f, 0.7f, 0.4f], gray); + Near([0.517f], gray); + } + + [Fact] + public void RGB_to_CMYK_follows_the_example_of_10_4_2_3_before_black_generation_and_undercolour_removal() + { + using PdfDocument document = PdfDocument.Create(); + PdfFunction zero = document.GetFunction(Cos("<< /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [0] /N 1 >>"))!; + float[] cmyk = new float[4]; + + var none = new ColorConversion { Target = DeviceColorModel.Cmyk, BlackGeneration = zero, UndercolorRemoval = zero }; + document.GetColorConverter(PdfDeviceRgbColorSpace.Instance, none).Convert([0.2f, 0.7f, 0.4f], cmyk); + Near([0.8f, 0.3f, 0.6f, 0f], cmyk); + + // Without BG and UCR in the graphics state, Broadside removes all of the undercolour and replaces it by black. + document.GetColorConverter(PdfDeviceRgbColorSpace.Instance, new ColorConversion { Target = DeviceColorModel.Cmyk }).Convert([0.2f, 0.7f, 0.4f], cmyk); + Near([0.5f, 0f, 0.3f, 0.3f], cmyk); + } + + [Fact] + public void Gray_and_CMYK_convert_by_the_formulas_of_10_4_2_4() + { + using PdfDocument document = PdfDocument.Open(Page("<< >>", string.Empty), new PdfOptions().UseColorManagement(ManagedColorManagement.Classic)); + float[] cmyk = new float[4]; + float[] gray = new float[1]; + + document.GetColorConverter(PdfDeviceGrayColorSpace.Instance, new ColorConversion { Target = DeviceColorModel.Cmyk }).Convert([0.25f], cmyk); + Near([0f, 0f, 0f, 0.75f], cmyk); + document.GetColorConverter(PdfDeviceCmykColorSpace.Instance, new ColorConversion { Target = DeviceColorModel.Gray }).Convert([0.2f, 0.3f, 0.4f, 0.5f], gray); + Near([0.219f], gray); + } + + [Fact] + public void Classic_CMYK_to_RGB_is_the_formula_of_10_4_2_5() + { + using PdfDocument document = PdfDocument.Open(Page("<< >>", string.Empty), new PdfOptions().UseColorManagement(ManagedColorManagement.Classic)); + + Near([0f, 1f, 1f], document.Rgb(PdfDeviceCmykColorSpace.Instance, 1, 0, 0, 0)); + Near([0.3f, 0.2f, 0.1f], document.Rgb(PdfDeviceCmykColorSpace.Instance, 0.2f, 0.3f, 0.4f, 0.5f)); + Near([0f, 0f, 0f], document.Rgb(PdfDeviceCmykColorSpace.Instance, 0, 0, 0, 1)); + } + + [Fact] + public void The_default_CMYK_conversion_approximates_SWOP_printing() + { + using PdfDocument document = PdfDocument.Create(); + + // Paper stays exactly white; process cyan is the (0, 0.68, 0.94) viewers show, not the formula's (0, 1, 1); solid black is + // the SWOP black measured in CGATS TR 001 (L* 24, about 54/255), as no black point compensation is applied. + Near([1f, 1f, 1f], document.Rgb(PdfDeviceCmykColorSpace.Instance, 0, 0, 0, 0), 0); + Near([0f, 0.68f, 0.94f], document.Rgb(PdfDeviceCmykColorSpace.Instance, 1, 0, 0, 0), 0.03); + Near([0.21f, 0.21f, 0.21f], document.Rgb(PdfDeviceCmykColorSpace.Instance, 0, 0, 0, 1), 0.03); + } + + [Fact] + public void CalRGB_with_the_sRGB_primaries_and_gamma_1_reproduces_sRGB() + { + using PdfDocument document = PdfDocument.Create(); + PdfColorSpace space = document.GetColorSpace(Cos(SrgbCalRgb)); + + Near([1f, 1f, 1f], document.Rgb(space, 1, 1, 1), 2e-3); + Near([HalfLinear, 0f, 0f], document.Rgb(space, 0.5f, 0, 0), 2e-3); + Near([HalfLinear, HalfLinear, HalfLinear], document.Rgb(space, 0.5f, 0.5f, 0.5f), 2e-3); + } + + [Fact] + public void CalGray_maps_Y_to_sRGB_gray() + { + using PdfDocument document = PdfDocument.Create(); + PdfColorSpace space = document.GetColorSpace(Cos("[/CalGray << /WhitePoint [0.95047 1 1.08883] /Gamma 2 >>]")); + + Near([HalfLinear, HalfLinear, HalfLinear], document.Rgb(space, MathF.Sqrt(0.5f)), 2e-3); + Near([0f, 0f, 0f], document.Rgb(space, 0)); + } + + [Fact] + public void Lab_with_a_D50_white_is_adapted_to_the_sRGB_white() + { + using PdfDocument document = PdfDocument.Create(); + PdfColorSpace space = document.GetColorSpace(Cos("[/Lab << /WhitePoint [0.9642 1 0.8249] >>]")); + + // L* 50 is Y 0.1842, sRGB 119/255 (CIE 15 and IEC 61966-2-1). + Near([1f, 1f, 1f], document.Rgb(space, 100, 0, 0), 2e-3); + Near([0.4663f, 0.4663f, 0.4663f], document.Rgb(space, 50, 0, 0), 2e-3); + Near([0f, 0f, 0f], document.Rgb(space, 0, 0, 0), 2e-3); + + // Absolute colorimetric keeps the D50 white's colour: warmer than the sRGB white. + float[] absolute = new float[3]; + document.GetColorConverter(space, new ColorConversion { Intent = RenderingIntent.AbsoluteColorimetric }).Convert([100f, 0, 0], absolute); + Assert.True(absolute[2] < absolute[0] - 0.05, $"Expected a warm white, got [{string.Join(", ", absolute)}]."); + } + + [Fact] + public void Black_point_compensation_maps_the_source_black_point_to_black_unless_it_is_off() + { + using PdfDocument document = PdfDocument.Create(); + PdfColorSpace space = document.GetColorSpace(Cos("[/CalGray << /WhitePoint [0.95047 1 1.08883] /BlackPoint [0.047523 0.05 0.054441] >>]")); + float[] rgb = new float[3]; + + document.GetColorConverter(space, new ColorConversion { BlackPointCompensation = BlackPointCompensation.On }).Convert([0.05f], rgb); + Near([0f, 0f, 0f], rgb, 1e-3); + document.GetColorConverter(space, new ColorConversion { BlackPointCompensation = BlackPointCompensation.Off }).Convert([0.05f], rgb); + Near([0.2474f, 0.2474f, 0.2474f], rgb, 2e-3); + document.GetColorConverter(space, new ColorConversion { Intent = RenderingIntent.AbsoluteColorimetric }).Convert([0.05f], rgb); + Assert.True(rgb[1] > 0.2f); + } + + [Fact] + public void An_ICC_Lab_profile_converts_as_Lab_and_another_profile_through_its_alternate() + { + using PdfDocument document = PdfDocument.Open(Page( + "<< >>", + string.Empty, + IccProfiles.Stream(IccProfiles.Header("spac", "Lab "), "/N 3 /Alternate /DeviceRGB"), + IccProfiles.Stream(IccProfiles.Header("mntr", "RGB "), "/N 3 /Alternate " + SrgbCalRgb + " /Range [0 1 0 1 0 0.5]"))); + PdfColorSpace lab = document.GetColorSpace(Cos("[/ICCBased 5 0 R]")); + PdfColorSpace rgb = document.GetColorSpace(Cos("[/ICCBased 6 0 R]")); + + Near([0.4663f, 0.4663f, 0.4663f], document.Rgb(lab, 50, 0, 0), 2e-3); + Near([HalfLinear, 0f, HalfLinear], document.Rgb(rgb, 0.5f, 0f, 1f), 2e-3); + } + + [Fact] + public void Indexed_colours_come_from_the_table_scaled_to_the_base_ranges() + { + using PdfDocument document = PdfDocument.Create(); + PdfColorSpace rgb = document.GetColorSpace(Cos("[/Indexed /DeviceRGB 1 ]")); + PdfColorSpace lab = document.GetColorSpace(Cos("[/Indexed [/Lab << /WhitePoint [0.9642 1 0.8249] >>] 0 ]")); + byte[] bytes = new byte[6]; + + Near([0f, 0f, 1f], document.Rgb(rgb, 1)); + Near([0f, 0f, 1f], document.Rgb(rgb, 7.6f)); + Near([1f, 0f, 0f], document.Rgb(rgb, 0.4f)); + document.GetColorConverter(rgb).Convert(new byte[] { 1, 0 }, bytes, 2); + Assert.Equal(new byte[] { 0, 0, 255, 255, 0, 0 }, bytes); + Near([1f, 1f, 1f], document.Rgb(lab, 0), 5e-3); + } + + [Fact] + public void Separation_tints_go_through_the_tint_transform_to_the_alternate() + { + using PdfDocument document = PdfDocument.Open(Page("<< >>", string.Empty), new PdfOptions().UseColorManagement(ManagedColorManagement.Classic)); + PdfColorSpace gold = document.GetColorSpace(Cos("[/Separation /Gold /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0.2 1 0] /N 1 >>]")); + byte[] bytes = new byte[6]; + + Near([1f, 0.8f, 0f], document.Rgb(gold, 1)); + Near([1f, 0.9f, 0.5f], document.Rgb(gold, 0.5f)); + document.GetColorConverter(gold).Convert(new byte[] { 255, 0 }, bytes, 2); + Assert.Equal(new byte[] { 255, 204, 0, 255, 255, 255 }, bytes); + } + + [Fact] + public void A_missing_tint_transform_is_replaced_by_subtractive_ink_on_the_alternate() + { + using PdfDocument document = PdfDocument.Open(Page("<< >>", string.Empty), new PdfOptions().UseColorManagement(ManagedColorManagement.Classic)); + + Near([0.75f, 0.75f, 0.75f], document.Rgb(document.GetColorSpace(Cos("[/Separation /S /DeviceRGB 0]")), 0.25f)); + Near([0.75f, 0.75f, 0.75f], document.Rgb(document.GetColorSpace(Cos("[/Separation /S /DeviceCMYK /Identity]")), 0.25f)); + Near([0.4f, 0.4f, 0.4f], document.Rgb(document.GetColorSpace(Cos("[/DeviceN [/A /B] /DeviceGray 0]")), 0.6f, 0.1f)); + } + + [Fact] + public void All_marks_every_colourant_and_None_paints_nothing() + { + using PdfDocument document = PdfDocument.Create(); + const string tint = "<< /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [0] /N 1 >>"; + PdfColorSpace all = document.GetColorSpace(Cos($"[/Separation /All /DeviceGray {tint}]")); + PdfColorSpace none = document.GetColorSpace(Cos($"[/Separation /None /DeviceGray {tint}]")); + PdfColorSpace allNone = document.GetColorSpace(Cos("[/DeviceN [/None /None] /DeviceGray << /FunctionType 4 /Domain [0 1 0 1] /Range [0 1] /Length 5 >>]")); + float[] cmyk = new float[4]; + + Near([0.7f, 0.7f, 0.7f], document.Rgb(all, 0.3f)); + document.GetColorConverter(all, new ColorConversion { Target = DeviceColorModel.Cmyk }).Convert([0.3f], cmyk); + Near([0.3f, 0.3f, 0.3f, 0.3f], cmyk); + Assert.False(document.GetColorConverter(all).PaintsNothing); + Assert.True(document.GetColorConverter(none).PaintsNothing); + Assert.True(document.GetColorConverter(allNone).PaintsNothing); + Near([1f, 1f, 1f], document.Rgb(none, 1)); + } + + [Fact] + public void An_uncoloured_pattern_converts_through_its_underlying_space() + { + using PdfDocument document = PdfDocument.Create(); + PdfColorSpace space = document.GetColorSpace(Cos("[/Pattern /DeviceRGB]")); + + Near([0f, 1f, 0f], document.Rgb(space, 0, 1, 0)); + Assert.Equal(3, document.GetColorConverter(space).InputCount); + } + + [Fact] + public void A_converter_is_shared_and_rebuilt_when_its_space_changes() + { + using PdfDocument document = PdfDocument.Create(); + var array = (CosArray)Cos("[/CalGray << /WhitePoint [0.95047 1 1.08883] /Gamma 1 >>]"); + PdfColorSpace space = document.GetColorSpace(array); + PdfColorConverter converter = document.GetColorConverter(space); + + Assert.Same(converter, document.GetColorConverter(space)); + Near([HalfLinear, HalfLinear, HalfLinear], document.Rgb(space, 0.5f), 2e-3); + ((CosDictionary)array[1])[new CosName("Gamma")] = new CosReal(2); + Assert.NotSame(converter, document.GetColorConverter(space)); + Near([0.5371f, 0.5371f, 0.5371f], document.Rgb(space, 0.5f), 2e-3); + } + + [Fact] + public void Components_are_clipped_into_their_ranges_before_conversion() + { + using PdfDocument document = PdfDocument.Create(); + + Near([1f, 0f, 1f], document.Rgb(PdfDeviceRgbColorSpace.Instance, 7, -3, float.MaxValue)); + } +} diff --git a/tests/Broadside.Tests/Colors/ColorManagementTests.cs b/tests/Broadside.Tests/Colors/ColorManagementTests.cs new file mode 100644 index 00000000..39fe1d94 --- /dev/null +++ b/tests/Broadside.Tests/Colors/ColorManagementTests.cs @@ -0,0 +1,112 @@ +using System.Collections.Concurrent; +using Broadside.Graphics; +using Broadside.TestSupport; +using static Broadside.Tests.Colors.ColorTesting; + +namespace Broadside.Tests.Colors; + +/// +/// The colour-management extension point (ADR 0001; ISO 32000-2 §10.3, §10.4): replaced through the options, used for every +/// conversion of a base space, never handed an Indexed, Separation, DeviceN or Pattern space. +/// +public class ColorManagementTests +{ + [Fact] + public void A_decorator_sees_only_device_CIE_based_and_ICCBased_spaces_while_a_page_of_every_family_is_painted() + { + var counting = new CountingColorManagement(ManagedColorManagement.Default); + using PdfDocument document = PdfDocument.Open(Corpus.Path("colorspace-families.pdf"), new PdfOptions().UseColorManagement(counting)); + var recorder = new ColorRecorder(); + document.Pages[0].ProcessContent(recorder); + + Assert.Equal(12, recorder.Paints.Count); + Assert.Equal( + [PdfColorSpaceFamily.DeviceGray, PdfColorSpaceFamily.DeviceRgb, PdfColorSpaceFamily.DeviceCmyk, PdfColorSpaceFamily.CalGray, + PdfColorSpaceFamily.CalRgb, PdfColorSpaceFamily.Lab, PdfColorSpaceFamily.IccBased], + counting.Requested.Keys.Order()); + Assert.True(counting.Conversions > 0); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_replacement_decides_the_device_colour() + { + var magenta = new ConstantColorManagement(); + using PdfDocument document = PdfDocument.Open(Page("<< >>", "0.2 0.4 0.6 rg 0 0 1 1 re f"), new PdfOptions().UseColorManagement(magenta)); + var recorder = new ColorRecorder(); + document.Pages[0].ProcessContent(recorder); + + Assert.Equal([1f, 0f, 1f], Assert.Single(recorder.Paints).FillRgb); + } + + [Fact] + public void Two_engines_with_different_colour_management_do_not_interfere() + { + byte[] file = Page("<< >>", string.Empty); + using PdfDocument classic = new PdfEngine(new PdfOptions().UseColorManagement(ManagedColorManagement.Classic)).Open(file); + using PdfDocument managed = PdfDocument.Open(file); + + Near([0f, 1f, 1f], classic.Rgb(PdfDeviceCmykColorSpace.Instance, 1, 0, 0, 0)); + Assert.True(managed.Rgb(PdfDeviceCmykColorSpace.Instance, 1, 0, 0, 0)[1] < 0.8f); + } + + [Fact] + public void The_managed_default_refuses_special_spaces() + { + using PdfDocument document = PdfDocument.Create(); + + Assert.Throws(() => ManagedColorManagement.Default.CreateConverter(document.GetColorSpace(Cos("[/Indexed /DeviceRGB 0 <000000>]")), default)); + } + + /// Counts the converters requested per source family and the colours converted, then defers to the inner management. + private sealed class CountingColorManagement(IColorManagement inner) : IColorManagement + { + private int _conversions; + + public ConcurrentDictionary Requested { get; } = new(); + + public int Conversions => _conversions; + + public IColorConverter CreateConverter(PdfColorSpace source, ColorConversion conversion) + { + Requested.AddOrUpdate(source.Family, 1, static (_, count) => count + 1); + return new Counting(inner.CreateConverter(source, conversion), this); + } + + private sealed class Counting(IColorConverter inner, CountingColorManagement owner) : IColorConverter + { + public int InputCount => inner.InputCount; + + public int OutputCount => inner.OutputCount; + + public void Convert(ReadOnlySpan source, Span destination, int count) + { + Interlocked.Add(ref owner._conversions, count); + inner.Convert(source, destination, count); + } + } + } + + /// Paints everything magenta. + private sealed class ConstantColorManagement : IColorManagement + { + public IColorConverter CreateConverter(PdfColorSpace source, ColorConversion conversion) => new Magenta(source.ComponentCount); + + private sealed class Magenta(int inputs) : IColorConverter + { + public int InputCount => inputs; + + public int OutputCount => 3; + + public void Convert(ReadOnlySpan source, Span destination, int count) + { + for (int i = 0; i < count; i++) + { + destination[3 * i] = 1; + destination[(3 * i) + 1] = 0; + destination[(3 * i) + 2] = 1; + } + } + } + } +} diff --git a/tests/Broadside.Tests/Colors/ColorOperatorTests.cs b/tests/Broadside.Tests/Colors/ColorOperatorTests.cs new file mode 100644 index 00000000..fecc1145 --- /dev/null +++ b/tests/Broadside.Tests/Colors/ColorOperatorTests.cs @@ -0,0 +1,146 @@ +using Broadside.Graphics; +using Broadside.Objects; +using static Broadside.Tests.Colors.ColorTesting; + +namespace Broadside.Tests.Colors; + +/// +/// The colour operators of ISO 32000-2 §8.6.8, Table 73, observed through the public processor seam: the fill and stroke colours of +/// the graphics state at each paint. +/// +public class ColorOperatorTests +{ + private const string Rect = " 0 0 10 10 re f\n"; + + [Fact] + public void The_initial_colours_are_device_gray_black() + { + (List paints, string[] codes) = Run(Page("<< >>", "0 0 10 10 re B")); + + Assert.Equal("DeviceGray 0", Assert.Single(paints).FillText); + Assert.Equal("DeviceGray 0", paints[0].StrokeText); + Assert.Empty(codes); + } + + [Fact] + public void G_g_RG_rg_K_k_select_the_device_space_and_set_the_colour() + { + (List paints, string[] codes) = Run(Page( + "<< >>", + "0.25 g 0.75 G" + Rect + "0.1 0.2 0.3 rg 0.4 0.5 0.6 RG" + Rect + "0.1 0.2 0.3 0.4 k 0.5 0.6 0.7 0.8 K" + Rect)); + + Assert.Equal(["DeviceGray 0.25", "DeviceRgb 0.1 0.2 0.3", "DeviceCmyk 0.1 0.2 0.3 0.4"], paints.Select(p => p.FillText)); + Assert.Equal(["DeviceGray 0.75", "DeviceRgb 0.4 0.5 0.6", "DeviceCmyk 0.5 0.6 0.7 0.8"], paints.Select(p => p.StrokeText)); + Assert.Empty(codes); + } + + [Fact] + public void Cs_selects_a_named_resource_and_its_initial_colour_and_sc_sets_the_components() + { + (List paints, string[] codes) = Run(Page( + "<< /ColorSpace << /CS0 [/CalRGB << /WhitePoint [0.9505 1 1.089] >>] /Sep 5 0 R >> >>", + "/CS0 cs" + Rect + "0.5 0.25 1 sc" + Rect + "/Sep cs" + Rect + "0.3 scn" + Rect + "/DeviceCMYK CS 0 0 10 10 re S", + "[/Separation /Spot /DeviceGray << /FunctionType 2 /Domain [0 1] /C0 [1] /C1 [0] /N 1 >>]")); + + Assert.Equal(["CalRgb 0 0 0", "CalRgb 0.5 0.25 1", "Separation 1", "Separation 0.3", "Separation 0.3"], paints.Select(p => p.FillText)); + Assert.Equal("DeviceCmyk 0 0 0 1", paints[^1].StrokeText); + Assert.Empty(codes); + } + + [Fact] + public void CS_and_cs_reset_the_colour_to_the_initial_colour_of_each_family() + { + (List paints, string[] codes) = Run(Page( + "<< /ColorSpace << /Lab [/Lab << /WhitePoint [0.9642 1 0.8249] /Range [10 50 -20 -5] >>] /Icc [/ICCBased 5 0 R] " + + "/DN [/DeviceN [/A /B] /DeviceGray << /FunctionType 2 /Domain [0 1 0 1] /C0 [1] /C1 [0] /N 1 >>] " + + "/Ix [/Indexed /DeviceRGB 1 ] >> >>", + "0.5 0.5 0.5 rg /Lab cs" + Rect + "/Icc cs" + Rect + "/DN cs" + Rect + "/Ix cs" + Rect + "/DeviceRGB cs" + Rect, + "<< /N 3 /Range [0.2 1 -1 -0.5 0 1] /Length 0 >>\nstream\n\nendstream")); + + Assert.Equal(["Lab 0 10 -5", "IccBased 0.2 -0.5 0", "DeviceN 1 1", "Indexed 0", "DeviceRgb 0 0 0"], paints.Select(p => p.FillText)); + Assert.Contains("IccProfileInvalid", codes); + } + + [Fact] + public void Scn_in_a_pattern_space_names_the_pattern_and_captures_the_components_of_an_uncoloured_pattern() + { + (List paints, string[] codes) = Run(Page( + "<< /ColorSpace << /P [/Pattern /DeviceRGB] >> /Pattern << /Tile 5 0 R /Shade 6 0 R >> >>", + "/P cs" + Rect + "1 0 0 /Tile scn" + Rect + "/Pattern cs /Shade scn" + Rect, + "<< /PatternType 1 /PaintType 2 /TilingType 1 /BBox [0 0 1 1] /XStep 1 /YStep 1 /Resources << >> /Length 0 >>\nstream\n\nendstream", + "<< /PatternType 2 /Shading << /ShadingType 2 /ColorSpace /DeviceRGB /Coords [0 0 1 0] /Function << /FunctionType 2 /Domain [0 1] /C0 [0 0 0] /C1 [1 1 1] /N 1 >> >> >>")); + + Assert.Equal(["Pattern 0 0 0", "Pattern 1 0 0 /Tile", "Pattern /Shade"], paints.Select(p => p.FillText)); + Assert.Null(paints[0].Fill.Pattern); + Assert.IsType(paints[1].Fill.Pattern); + Assert.IsType(paints[2].Fill.Pattern); + Assert.True(paints[2].Fill.PatternMatrix.IsIdentity); + Assert.Equal([1f, 0f, 0f], paints[1].FillRgb); + Assert.Empty(codes); + } + + [Fact] + public void A_name_missing_from_the_resources_reads_as_device_gray_with_a_diagnostic() + { + (List paints, string[] codes) = Run(Page("<< >>", "1 0 0 rg /Nowhere cs 0.5 sc" + Rect)); + + Assert.Equal("DeviceGray 0.5", Assert.Single(paints).FillText); + Assert.Equal(["ContentColorSpaceMissing"], codes); + } + + [Fact] + public void An_inline_image_abbreviation_outside_an_inline_image_is_read_after_the_resources() + { + (List paints, string[] codes) = Run(Page("<< /ColorSpace << /G [/CalGray << /WhitePoint [0.9505 1 1.089] >>] >> >>", "/RGB cs 1 0 0 sc" + Rect + "/G cs" + Rect)); + + Assert.Equal(["DeviceRgb 1 0 0", "CalGray 0"], paints.Select(p => p.FillText)); + Assert.Equal(["ContentColorSpaceAbbreviated"], codes); + } + + [Fact] + public void Too_few_components_skip_the_operator_and_too_many_use_the_last_ones() + { + (List paints, string[] codes) = Run(Page("<< >>", "/DeviceRGB cs 0.5 0.5 sc" + Rect + "0.9 0.1 0.2 0.3 sc" + Rect)); + + Assert.Equal(["DeviceRgb 0 0 0", "DeviceRgb 0.1 0.2 0.3"], paints.Select(p => p.FillText)); + Assert.Equal(["ContentColorOperandCount"], codes); + } + + [Fact] + public void Sc_in_a_pattern_space_and_scn_with_a_name_elsewhere_are_skipped() + { + (List paints, string[] codes) = Run(Page("<< /Pattern << /P0 5 0 R >> >>", "0.5 g /P0 scn" + Rect + "/Pattern cs 0.5 sc" + Rect + "0.2 scn" + Rect, "<< /PatternType 2 /Shading << >> >>")); + + Assert.Equal(["DeviceGray 0.5", "Pattern", "Pattern"], paints.Select(p => p.FillText)); + Assert.Equal(["ContentColorOperatorInvalid"], codes); + } + + [Fact] + public void Sc_in_a_separation_space_is_accepted_with_a_diagnostic() + { + (List paints, string[] codes) = Run(Page( + "<< /ColorSpace << /S [/Separation /Spot /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0 0 1] /N 1 >>] >> >>", + "/S cs 0.4 sc" + Rect)); + + Assert.Equal("Separation 0.4", Assert.Single(paints).FillText); + Assert.Equal(["ContentColorOperatorMismatch"], codes); + } + + [Fact] + public void A_pattern_missing_from_the_resources_gives_a_colour_without_a_pattern() + { + (List paints, string[] codes) = Run(Page("<< >>", "/Pattern cs /Nowhere scn" + Rect)); + + Assert.Null(Assert.Single(paints).Fill.Pattern); + Assert.Equal(["ContentPatternMissing"], codes); + } + + [Fact] + public void Strict_mode_throws_for_a_missing_colour_space() + { + using PdfDocument document = PdfDocument.Open(Page("<< >>", "/Nowhere cs" + Rect), new PdfOptions().UseStrict()); + + var exception = Assert.Throws(() => document.Pages[0].ProcessContent(new ColorRecorder())); + Assert.Equal("ContentColorSpaceMissing", exception.Diagnostic.Code); + } +} diff --git a/tests/Broadside.Tests/Colors/ColorRepairTests.cs b/tests/Broadside.Tests/Colors/ColorRepairTests.cs new file mode 100644 index 00000000..14f4d442 --- /dev/null +++ b/tests/Broadside.Tests/Colors/ColorRepairTests.cs @@ -0,0 +1,60 @@ +using Broadside.Diagnostics; +using static Broadside.Tests.Colors.ColorTesting; + +namespace Broadside.Tests.Colors; + +/// +/// Every real-world deviation of colour spaces and colour operators (ISO 32000-2 §8.6) as a lenient/strict pair: lenient reading +/// repairs it, paints the page and records exactly one kind of diagnostic; strict reading throws that diagnostic (ADR 0005). +/// +public class ColorRepairTests +{ + private const string Paint = " 0 0 10 10 re f"; + + private const string Gray = "<< /FunctionType 2 /Domain [0 1] /C0 [1] /C1 [0] /N 1 >>"; + + public static TheoryData Deviations => new() + { + { "missing named space", "<< >>", "/Nowhere cs" + Paint, "ContentColorSpaceMissing" }, + { "abbreviation outside an inline image", "<< >>", "/CMYK cs 0 0 0 1 sc" + Paint, "ContentColorSpaceAbbreviated" }, + { "unknown family", "<< /ColorSpace << /X [/Hexachrome 1] >> >>", "/X cs" + Paint, "ColorSpaceInvalid" }, + { "device space as an array", "<< /ColorSpace << /X [/DeviceRGB] >> >>", "/X cs" + Paint, "ColorSpaceEntryInvalid" }, + { "CalRGB without a white point", "<< /ColorSpace << /X [/CalRGB << >>] >> >>", "/X cs" + Paint, "ColorSpaceEntryInvalid" }, + { "negative CalGray gamma", "<< /ColorSpace << /X [/CalGray << /WhitePoint [0.95 1 1.09] /Gamma -2 >>] >> >>", "/X cs" + Paint, "ColorSpaceEntryInvalid" }, + { "negative black point", "<< /ColorSpace << /X [/CalGray << /WhitePoint [0.95 1 1.09] /BlackPoint [-1 0 0] >>] >> >>", "/X cs" + Paint, "ColorSpaceEntryInvalid" }, + { "Lab range minimum above maximum", "<< /ColorSpace << /X [/Lab << /WhitePoint [0.96 1 0.82] /Range [10 -10 0 1] >>] >> >>", "/X cs" + Paint, "ColorSpaceEntryInvalid" }, + { "ICCBased stream that is not a profile", "<< /ColorSpace << /X [/ICCBased << /N 3 /Length 1 >>] >> >>", "/X cs" + Paint, "ColorSpaceInvalid" }, + { "Indexed hival above 255", "<< /ColorSpace << /X [/Indexed /DeviceGray 256 <" + new string('0', 512) + ">] >> >>", "/X cs" + Paint, "ColorSpaceEntryInvalid" }, + { "Indexed lookup short", "<< /ColorSpace << /X [/Indexed /DeviceRGB 1 ] >> >>", "/X cs 1 sc" + Paint, "IndexedLookupInvalid" }, + { "Indexed lookup long", "<< /ColorSpace << /X [/Indexed /DeviceGray 0 <0000>] >> >>", "/X cs" + Paint, "IndexedLookupInvalid" }, + { "Indexed lookup missing", "<< /ColorSpace << /X [/Indexed /DeviceGray 1 7] >> >>", "/X cs" + Paint, "IndexedLookupInvalid" }, + { "Indexed base Indexed", "<< /ColorSpace << /X [/Indexed [/Indexed /DeviceGray 0 <00>] 0 <00>] >> >>", "/X cs" + Paint, "ColorSpaceInvalid" }, + { "tint transform not a function", "<< /ColorSpace << /X [/Separation /S /DeviceGray 3] >> >>", "/X cs" + Paint, "TintTransformInvalid" }, + { "tint transform with too few outputs", "<< /ColorSpace << /X [/Separation /S /DeviceCMYK " + Gray + "] >> >>", "/X cs" + Paint, "TintTransformInvalid" }, + { "alternate that cannot be an alternate", "<< /ColorSpace << /X [/Separation /S /Pattern " + Gray + "] >> >>", "/X cs" + Paint, "ColorSpaceEntryInvalid" }, + { "DeviceN repeated names", "<< /ColorSpace << /X [/DeviceN [/A /A] /DeviceGray 6 0 R] >> >>", "/X cs" + Paint, "DeviceNColorantsInvalid" }, + { "default of the wrong size", "<< /ColorSpace << /DefaultRGB /DeviceCMYK >> >>", "1 0 0 rg" + Paint, "DefaultColorSpaceInvalid" }, + { "SC in a Separation space", "<< /ColorSpace << /X [/Separation /S /DeviceGray " + Gray + "] >> >>", "/X cs 0.5 sc" + Paint, "ContentColorOperatorMismatch" }, + { "sc in a Pattern space", "<< >>", "/Pattern cs 0.5 sc" + Paint, "ContentColorOperatorInvalid" }, + { "scn with a name in DeviceRGB", "<< >>", "/DeviceRGB cs 1 0 0 /P scn" + Paint, "ContentColorOperatorInvalid" }, + { "too few components", "<< >>", "/DeviceCMYK cs 1 sc" + Paint, "ContentColorOperandCount" }, + { "too many components", "<< >>", "/DeviceGray cs 1 0.5 sc" + Paint, "ContentColorOperandCount" }, + { "pattern not in the resources", "<< >>", "/Pattern cs /P scn" + Paint, "ContentPatternMissing" }, + { "space that contains itself", "<< /ColorSpace << /X 5 0 R >> >>", "/X cs" + Paint, "ColorSpaceCycle" }, + }; + + [Theory] + [MemberData(nameof(Deviations))] + public void A_deviation_is_repaired_with_one_kind_of_diagnostic_and_strict_mode_throws_it(string deviation, string resources, string content, string code) + { + byte[] file = Page(resources, content, "[/Indexed 5 0 R 0 <00>]", "<< /FunctionType 4 /Domain [0 1 0 1] /Range [0 1] /Length 5 >>\nstream\n{pop}\nendstream"); + + (List paints, string[] codes) = Run(file); + Assert.Single(paints); + Assert.True(codes.Distinct().SequenceEqual([code]), $"{deviation}: {string.Join(", ", codes)}"); + + using PdfDocument strict = PdfDocument.Open(file, new PdfOptions().UseStrict()); + var exception = Assert.Throws(() => strict.Pages[0].ProcessContent(new ColorRecorder())); + Assert.Equal(code, exception.Diagnostic.Code); + } +} diff --git a/tests/Broadside.Tests/Colors/ColorSpaceFamilyTests.cs b/tests/Broadside.Tests/Colors/ColorSpaceFamilyTests.cs new file mode 100644 index 00000000..35b95197 --- /dev/null +++ b/tests/Broadside.Tests/Colors/ColorSpaceFamilyTests.cs @@ -0,0 +1,311 @@ +using Broadside.Diagnostics; +using Broadside.Graphics; +using Broadside.Objects; +using static Broadside.Tests.Colors.ColorTesting; + +namespace Broadside.Tests.Colors; + +/// +/// Every colour space family of ISO 32000-2 §8.6.3 (Table 61) read through : the typed +/// views, their initial colours (Table 73), default decode arrays (Table 88) and the repairs lenient reading applies. +/// +public class ColorSpaceFamilyTests +{ + private static readonly CosReference Five = new(5, 0); + + [Fact] + public void Device_family_names_are_the_device_singletons() + { + using PdfDocument document = PdfDocument.Create(); + + Assert.Same(PdfDeviceGrayColorSpace.Instance, document.GetColorSpace(new CosName("DeviceGray"))); + Assert.Same(PdfDeviceRgbColorSpace.Instance, document.GetColorSpace(new CosName("DeviceRGB"))); + Assert.Same(PdfDeviceCmykColorSpace.Instance, document.GetColorSpace(new CosName("DeviceCMYK"))); + Assert.Equal([0f, 0f, 0f, 1f], PdfDeviceCmykColorSpace.Instance.GetInitialColor().Components.ToArray()); + Assert.Equal([0.0, 1, 0, 1, 0, 1], PdfDeviceRgbColorSpace.Instance.GetDefaultDecode(8)); + Assert.Equal(new PdfVersion(1, 1), PdfDeviceGrayColorSpace.Instance.MinimumVersion); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void CalGray_and_CalRGB_expose_their_dictionaries_with_defaults() + { + using PdfDocument document = PdfDocument.Create(); + var gray = (PdfCalGrayColorSpace)document.GetColorSpace(Cos("[/CalGray << /WhitePoint [0.9505 1 1.089] /Gamma 2.2 >>]")); + var rgb = (PdfCalRgbColorSpace)document.GetColorSpace(Cos("[/CalRGB << /WhitePoint [0.9505 1 1.089] /BlackPoint [0.01 0.01 0.01] /Gamma [1.8 1.8 1.8] >>]")); + + Assert.Equal(new CieXyz(0.9505, 1, 1.089), gray.WhitePoint); + Assert.Equal(default, gray.BlackPoint); + Assert.Equal(2.2, gray.Gamma); + Assert.Equal(1, gray.ComponentCount); + Assert.Equal(new CieXyz(0.01, 0.01, 0.01), rgb.BlackPoint); + Assert.Equal([1.8, 1.8, 1.8], rgb.Gamma); + Assert.Equal([1.0, 0, 0, 0, 1, 0, 0, 0, 1], rgb.Matrix); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_missing_white_point_reads_as_D65_with_a_diagnostic_and_strict_mode_throws() + { + using PdfDocument document = PdfDocument.Create(); + var space = (PdfCalRgbColorSpace)document.GetColorSpace(Cos("[/CalRGB << /Gamma [0 1 1] >>]")); + + Assert.Equal(CieXyz.D65, space.WhitePoint); + Assert.Equal([1.0, 1, 1], space.Gamma); + Assert.Equal(["ColorSpaceEntryInvalid"], document.Diagnostics.Select(d => d.Code).Distinct()); + + using PdfDocument strict = PdfDocument.Open(Page("<< >>", string.Empty), new PdfOptions().UseStrict()); + Assert.Throws(() => strict.GetColorSpace(Cos("[/CalRGB << /Gamma [0 1 1] >>]"))); + } + + [Fact] + public void Lab_ranges_bound_its_components_and_its_initial_colour() + { + using PdfDocument document = PdfDocument.Create(); + var lab = (PdfLabColorSpace)document.GetColorSpace(Cos("[/Lab << /WhitePoint [0.9642 1 0.8249] /Range [-50 50 10 60] >>]")); + var bad = (PdfLabColorSpace)document.GetColorSpace(Cos("[/Lab << /WhitePoint [0.9642 1 0.8249] /Range [50 -50 0 1] >>]")); + + Assert.Equal(new ComponentRange(0, 100), lab.GetComponentRange(0)); + Assert.Equal(new ComponentRange(10, 60), lab.GetComponentRange(2)); + Assert.Equal([0f, 0f, 10f], lab.GetInitialColor().Components.ToArray()); + Assert.Equal([0.0, 100, -50, 50, 10, 60], lab.GetDefaultDecode(8)); + Assert.Equal([-100.0, 100, -100, 100], bad.Range); + Assert.Equal(["ColorSpaceEntryInvalid"], document.Diagnostics.Select(d => d.Code)); + } + + [Fact] + public void ICCBased_reads_the_profile_header_and_falls_back_to_the_device_space_by_N() + { + using PdfDocument document = PdfDocument.Open(Page("<< >>", string.Empty, IccProfiles.Stream(IccProfiles.Header("mntr", "RGB "), "/N 3 /Range [0 1 0 1 0 0.5]"))); + var space = (PdfIccBasedColorSpace)document.GetColorSpace(Cos("[/ICCBased 5 0 R]")); + + IccProfileHeader header = Assert.IsType(space.ProfileHeader); + Assert.Equal(new Version(2, 1, 0), header.Version); + Assert.Equal("mntr", header.DeviceClass); + Assert.Equal("RGB ", header.DataColorSpace); + Assert.Equal(3, header.ComponentCount); + Assert.True(header.IsSupportedForPdf); + Assert.Equal(0.9642, header.Illuminant.X, 4); + Assert.Equal(3, space.ComponentCount); + Assert.Equal(3, space.DeclaredComponentCount); + Assert.Same(PdfDeviceRgbColorSpace.Instance, space.Alternate); + Assert.Equal(new ComponentRange(0, 0.5), space.GetComponentRange(2)); + Assert.Equal(128, space.GetProfileData().Length); + Assert.Equal(new PdfVersion(1, 3), space.MinimumVersion); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_valid_profile_header_wins_over_a_wrong_N_and_an_unusable_alternate_gives_way() + { + using PdfDocument document = PdfDocument.Open(Page("<< >>", string.Empty, IccProfiles.Stream(IccProfiles.Header("scnr", "GRAY"), "/N 3 /Alternate /DeviceRGB"))); + var space = (PdfIccBasedColorSpace)document.GetColorSpace(Cos("[/ICCBased 5 0 R]")); + + Assert.Equal(1, space.ComponentCount); + Assert.Same(PdfDeviceGrayColorSpace.Instance, space.Alternate); + Assert.Equal(["IccComponentCountMismatch", "ColorSpaceEntryInvalid"], document.Diagnostics.Select(d => d.Code)); + } + + [Fact] + public void A_stream_that_is_not_a_profile_uses_the_alternate_with_a_diagnostic() + { + using PdfDocument document = PdfDocument.Open(Page("<< >>", string.Empty, "<< /N 4 /Alternate /DeviceCMYK /Length 3 >>\nstream\nabc\nendstream")); + var space = (PdfIccBasedColorSpace)document.GetColorSpace(Cos("[/ICCBased 5 0 R]")); + + Assert.Null(space.ProfileHeader); + Assert.Equal(4, space.ComponentCount); + Assert.Same(PdfDeviceCmykColorSpace.Instance, space.Alternate); + Assert.Equal(["IccProfileInvalid"], document.Diagnostics.Select(d => d.Code)); + } + + [Fact] + public void A_Lab_profile_takes_the_Lab_ranges_of_Table_68() + { + using PdfDocument document = PdfDocument.Open(Page("<< >>", string.Empty, IccProfiles.Stream(IccProfiles.Header("spac", "Lab ", major: 4, minorAndFix: 0x30), "/N 3"))); + var space = (PdfIccBasedColorSpace)document.GetColorSpace(Cos("[/ICCBased 5 0 R]")); + + Assert.Equal([0.0, 100, -128, 127, -128, 127], space.Range); + Assert.Equal(new Version(4, 3, 0), space.ProfileHeader!.Version); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_version_5_profile_is_not_supported_and_needs_no_diagnostic() + { + using PdfDocument document = PdfDocument.Open(Page("<< >>", string.Empty, IccProfiles.Stream(IccProfiles.Header("mntr", "RGB ", major: 5, minorAndFix: 0), "/N 3"))); + var space = (PdfIccBasedColorSpace)document.GetColorSpace(Cos("[/ICCBased 5 0 R]")); + + Assert.False(space.ProfileHeader!.IsSupportedForPdf); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Indexed_exposes_its_base_high_value_and_lookup_table() + { + using PdfDocument document = PdfDocument.Open(Page("<< >>", string.Empty, "<< /Length 6 >>\nstream\n\xFF\x00\x00\x00\x00\xFF\nendstream")); + var space = (PdfIndexedColorSpace)document.GetColorSpace(Cos("[/Indexed /DeviceRGB 1 5 0 R]")); + var text = (PdfIndexedColorSpace)document.GetColorSpace(Cos("[/Indexed /DeviceGray 2 (\x00\x80\xFF)]")); + + Assert.Same(PdfDeviceRgbColorSpace.Instance, space.Base); + Assert.Equal(1, space.HighValue); + Assert.Equal(new byte[] { 255, 0, 0, 0, 0, 255 }, space.GetLookup().ToArray()); + Assert.Equal(new ComponentRange(0, 1), space.GetComponentRange(0)); + Assert.Equal([0.0, 15], space.GetDefaultDecode(4)); + Assert.Equal(new PdfVersion(1, 1), space.MinimumVersion); + Assert.Equal(new PdfVersion(1, 2), text.MinimumVersion); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Indexed_repairs_its_high_value_and_lookup_length() + { + using PdfDocument document = PdfDocument.Create(); + var high = (PdfIndexedColorSpace)document.GetColorSpace(Cos("[/Indexed /DeviceGray 300 <00>]")); + + Assert.Equal(255, high.HighValue); + Assert.Equal(["ColorSpaceEntryInvalid", "IndexedLookupInvalid"], document.Diagnostics.Select(d => d.Code)); + } + + [Theory] + [InlineData("[/Indexed /DeviceRGB 1 3]", "IndexedLookupInvalid")] + [InlineData("[/Indexed /Pattern 0 <00>]", "ColorSpaceInvalid")] + [InlineData("[/Indexed /DeviceRGB /x <00>]", "ColorSpaceInvalid")] + [InlineData("[/Unknown 1 2]", "ColorSpaceInvalid")] + [InlineData("[]", "ColorSpaceInvalid")] + [InlineData("<< /N 3 >>", "ColorSpaceInvalid")] + [InlineData("[/DeviceN [] /DeviceGray 0]", "ColorSpaceInvalid")] + [InlineData("[/Separation (x) /DeviceGray 0]", "ColorSpaceInvalid")] + public void A_space_that_cannot_be_used_reads_as_device_gray(string syntax, string code) + { + using PdfDocument document = PdfDocument.Create(); + + Assert.Same(PdfDeviceGrayColorSpace.Instance, document.GetColorSpace(Cos(syntax))); + Assert.Equal(code, document.Diagnostics[0].Code); + } + + [Fact] + public void A_space_that_contains_itself_is_a_cycle_and_reads_as_device_gray() + { + using PdfDocument document = PdfDocument.Open(Page("<< >>", string.Empty, "[/Indexed 5 0 R 1 <0000>]")); + + Assert.Same(PdfDeviceGrayColorSpace.Instance, document.GetColorSpace(Five)); + Assert.Equal(["ColorSpaceCycle"], document.Diagnostics.Select(d => d.Code)); + Assert.All(document.Diagnostics, d => Assert.Equal(Five, d.ObjectReference)); + } + + [Fact] + public void A_device_space_written_as_an_array_is_read_with_a_diagnostic_and_CalCMYK_silently_as_DeviceCMYK() + { + using PdfDocument document = PdfDocument.Create(); + + Assert.Same(PdfDeviceRgbColorSpace.Instance, document.GetColorSpace(Cos("[/DeviceRGB]"))); + Assert.Same(PdfDeviceCmykColorSpace.Instance, document.GetColorSpace(Cos("[/CalCMYK << /WhitePoint [0.9505 1 1.089] >>]"))); + Assert.Equal(["ColorSpaceEntryInvalid"], document.Diagnostics.Select(d => d.Code)); + } + + [Fact] + public void Separation_exposes_its_colourant_alternate_and_tint_transform() + { + using PdfDocument document = PdfDocument.Create(); + var spot = (PdfSeparationColorSpace)document.GetColorSpace(Cos("[/Separation /Gold /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0.2 1 0] /N 1 >>]")); + var all = (PdfSeparationColorSpace)document.GetColorSpace(Cos("[/Separation /All /DeviceGray << /FunctionType 2 /Domain [0 1] /C0 [1] /C1 [0] /N 1 >>]")); + var none = (PdfSeparationColorSpace)document.GetColorSpace(Cos("[/Separation /None /DeviceGray << /FunctionType 2 /Domain [0 1] /C0 [1] /C1 [0] /N 1 >>]")); + + Assert.Equal("Gold", spot.ColorantName.Value); + Assert.Same(PdfDeviceCmykColorSpace.Instance, spot.Alternate); + Assert.Equal(4, spot.TintTransform!.OutputCount); + Assert.Equal([1f], spot.GetInitialColor().Components.ToArray()); + Assert.False(spot.IsAll || spot.IsNone); + Assert.True(all.IsAll); + Assert.True(none.IsNone); + Assert.Equal(new PdfVersion(1, 2), spot.MinimumVersion); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_separation_whose_tint_transform_is_not_a_function_is_recorded() + { + using PdfDocument document = PdfDocument.Create(); + var space = (PdfSeparationColorSpace)document.GetColorSpace(Cos("[/Separation /Spot /DeviceRGB 0]")); + + Assert.Null(space.TintTransform); + Assert.Equal(["TintTransformInvalid"], document.Diagnostics.Select(d => d.Code)); + } + + [Fact] + public void DeviceN_exposes_its_colourants_and_NChannel_attributes() + { + using PdfDocument document = PdfDocument.Create(); + var space = (PdfDeviceNColorSpace)document.GetColorSpace(Cos( + "[/DeviceN [/Cyan /Orange /None] /DeviceCMYK << /FunctionType 4 /Domain [0 1 0 1 0 1] /Range [0 1 0 1 0 1 0 1] >> " + + "<< /Subtype /NChannel /Colorants << /Orange [/Separation /Orange /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0.6 1 0] /N 1 >>] >> " + + "/Process << /ColorSpace /DeviceCMYK /Components [/Cyan /Magenta /Yellow /Black] >> " + + "/MixingHints << /Solidities << /Orange 0.8 /Default 2 >> /PrintingOrder [/Cyan /Orange] /DotGain << /Orange << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 1 >> >> >> >>]")); + + Assert.Equal(["Cyan", "Orange", "None"], space.ColorantNames.Select(n => n.Value)); + Assert.Equal(3, space.ComponentCount); + Assert.False(space.AreAllNone); + Assert.True(space.IsNChannel); + PdfDeviceNAttributes attributes = space.Attributes!; + Assert.IsType(Assert.Single(attributes.Colorants).Value); + Assert.Same(PdfDeviceCmykColorSpace.Instance, attributes.Process!.ColorSpace); + Assert.Equal(4, attributes.Process.Components.Count); + Assert.Equal(1.0, attributes.MixingHints!.Solidities[new CosName("Default")]); + Assert.Equal(["Cyan", "Orange"], attributes.MixingHints.PrintingOrder.Select(n => n.Value)); + Assert.Single(attributes.MixingHints.DotGain); + Assert.Equal([1f, 1f, 1f], space.GetInitialColor().Components.ToArray()); + Assert.Equal(new PdfVersion(1, 6), space.MinimumVersion); + Assert.DoesNotContain(document.Diagnostics, d => d.Code.StartsWith("Color", StringComparison.Ordinal) || d.Code.StartsWith("DeviceN", StringComparison.Ordinal)); + } + + [Fact] + public void DeviceN_names_that_repeat_or_name_All_are_recorded() + { + using PdfDocument document = PdfDocument.Create(); + var space = (PdfDeviceNColorSpace)document.GetColorSpace(Cos("[/DeviceN [/A /A /None /None] /DeviceGray << /FunctionType 4 /Domain [0 1 0 1 0 1 0 1] /Range [0 1] >>]")); + + Assert.Equal(4, space.ComponentCount); + Assert.Contains("DeviceNColorantsInvalid", document.Diagnostics.Select(d => d.Code)); + } + + [Fact] + public void Pattern_spaces_with_and_without_an_underlying_space() + { + using PdfDocument document = PdfDocument.Create(); + var colored = (PdfPatternColorSpace)document.GetColorSpace(new CosName("Pattern")); + var uncolored = (PdfPatternColorSpace)document.GetColorSpace(Cos("[/Pattern /DeviceCMYK]")); + var nested = (PdfPatternColorSpace)document.GetColorSpace(Cos("[/Pattern [/Pattern /DeviceRGB]]")); + + Assert.Null(colored.Underlying); + Assert.Equal(0, colored.ComponentCount); + Assert.Empty(colored.GetDefaultDecode(8)); + Assert.Same(PdfDeviceCmykColorSpace.Instance, uncolored.Underlying); + Assert.Equal(4, uncolored.ComponentCount); + Assert.Null(nested.Underlying); + Assert.Equal(["ColorSpaceEntryInvalid"], document.Diagnostics.Select(d => d.Code)); + } + + [Fact] + public void One_object_reads_as_one_shared_view_until_it_changes() + { + using PdfDocument document = PdfDocument.Open(Page("<< >>", string.Empty, "[/CalGray << /WhitePoint [0.9505 1 1.089] /Gamma 1.5 >>]")); + PdfColorSpace first = document.GetColorSpace(Five); + + Assert.Same(first, document.GetColorSpace(Five)); + var array = (CosArray)document.Resolve(Five); + array[0] = new CosName("DeviceRGB"); + array.RemoveAt(1); + Assert.Same(PdfDeviceRgbColorSpace.Instance, document.GetColorSpace(Five)); + } + + [Fact] + public void Views_read_their_entries_live() + { + using PdfDocument document = PdfDocument.Create(); + var array = (CosArray)Cos("[/CalGray << /WhitePoint [0.9505 1 1.089] /Gamma 1.5 >>]"); + var space = (PdfCalGrayColorSpace)document.GetColorSpace(array); + + ((CosDictionary)array[1])[new CosName("Gamma")] = new CosReal(2.5); + Assert.Equal(2.5, space.Gamma); + } +} diff --git a/tests/Broadside.Tests/Colors/ColorTesting.cs b/tests/Broadside.Tests/Colors/ColorTesting.cs new file mode 100644 index 00000000..b5b178ea --- /dev/null +++ b/tests/Broadside.Tests/Colors/ColorTesting.cs @@ -0,0 +1,108 @@ +using System.Globalization; +using System.Text; +using Broadside.Content; +using Broadside.Graphics; +using Broadside.Objects; +using Broadside.Tests.Document; + +namespace Broadside.Tests.Colors; + +/// Builds documents for colour tests and reads colours back through the public processor seam. +internal static class ColorTesting +{ + /// + /// A one-page document whose page has and the content ; further objects + /// are numbered from 5. + /// + public static byte[] Page(string resources, string content, params string[] objects) => new TestPdf().Build( + [ + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + $"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources {resources} /Contents 4 0 R >>", + $"<< /Length {Encoding.Latin1.GetByteCount(content)} >>\nstream\n{content}\nendstream", + .. objects, + ]); + + /// Opens and records the colours of every paint of its first page. + public static (List Paints, string[] Codes) Run(byte[] file, PdfOptions? options = null) + { + using PdfDocument document = PdfDocument.Open(file, options ?? new PdfOptions()); + var recorder = new ColorRecorder(); + document.Pages[0].ProcessContent(recorder); + return (recorder.Paints, [.. document.Diagnostics.Select(static d => d.Code)]); + } + + /// Parses one COS object written in PDF syntax. + public static CosObject Cos(string syntax) => CosObject.Parse(Encoding.Latin1.GetBytes(syntax)); + + /// Converts one colour to RGB through 's colour management. + public static float[] Rgb(this PdfDocument document, PdfColorSpace space, params float[] components) + { + float[] rgb = new float[3]; + document.GetColorConverter(space).Convert(components, rgb); + return rgb; + } + + /// Converts one colour with . + public static float[] ConvertOne(this PdfColorConverter converter, params float[] components) + { + float[] output = new float[converter.OutputCount]; + converter.Convert(components, output); + return output; + } + + /// Asserts that two colours agree to within . + public static void Near(float[] expected, ReadOnlySpan actual, double tolerance = 1e-4) + { + Assert.Equal(expected.Length, actual.Length); + for (int i = 0; i < expected.Length; i++) + { + Assert.True( + Math.Abs(expected[i] - actual[i]) <= tolerance, + $"Component {i}: expected {expected[i]}, got {actual[i]} (all: [{string.Join(", ", actual.ToArray())}])."); + } + } + + /// Writes a colour as "Family c0 c1 ...". + public static string Describe(in PdfColor color) + { + var text = new StringBuilder(color.ColorSpace.Family.ToString()); + foreach (float component in color.Components) + { + text.Append(' ').Append(component.ToString("R", CultureInfo.InvariantCulture)); + } + + if (color.PatternName is { } name) + { + text.Append(" /").Append(name.Value); + } + + return text.ToString(); + } +} + +/// What a paint saw: the fill and stroke colours as set, the RGB they convert to with the defaults in effect. +internal sealed record Paint(PdfColor Fill, PdfColor Stroke, PdfDefaultColorSpaces Defaults, float[] FillRgb, bool PaintsNothing) +{ + public string FillText => ColorTesting.Describe(Fill); + + public string StrokeText => ColorTesting.Describe(Stroke); +} + +/// Records the graphics state's colours on every path paint, converted to RGB with the current default colour spaces. +internal sealed class ColorRecorder : ContentProcessor +{ + public List Paints { get; } = []; + + public override ContentEvents Events => ContentEvents.Paths; + + public override void PaintPath(in PathEvent path, ContentContext context) + { + PdfColor fill = context.State.FillColor; + PdfDefaultColorSpaces defaults = context.DefaultColorSpaces; + PdfColorConverter converter = context.Document.GetColorConverter(fill.ColorSpace, ColorConversion.FromState(context.State, DeviceColorModel.Rgb), defaults); + float[] rgb = new float[3]; + converter.Convert(fill, rgb); + Paints.Add(new Paint(fill, context.State.StrokeColor, defaults, rgb, converter.PaintsNothing)); + } +} diff --git a/tests/Broadside.Tests/Colors/CorpusColorTests.cs b/tests/Broadside.Tests/Colors/CorpusColorTests.cs new file mode 100644 index 00000000..7778b2d2 --- /dev/null +++ b/tests/Broadside.Tests/Colors/CorpusColorTests.cs @@ -0,0 +1,138 @@ +using Broadside.Content; +using Broadside.Graphics; +using Broadside.Objects; +using Broadside.TestSupport; +using static Broadside.Tests.Colors.ColorTesting; + +namespace Broadside.Tests.Colors; + +/// +/// The colour corpus files (tests/Corpus/README.md) read through the public seams. Expected device colours are poppler's +/// (pdftoppm -r 72, rectangle centres) where both apply the same model, and otherwise the managed default's documented +/// values: poppler converts CMYK with its own formula and uses the ICC profiles, which Phase 3 brings. +/// +public class CorpusColorTests +{ + [Fact] + public void Every_family_of_colorspace_families_pdf_is_typed_and_painted() + { + (List paints, string[] codes) = Run(File.ReadAllBytes(Corpus.Path("colorspace-families.pdf"))); + + Assert.Equal( + ["DeviceGray 0.5", "DeviceRgb 1 0 0", "DeviceCmyk 0 1 0 0", "CalGray 0.5", "CalRgb 0 0 1", "Lab 50 60 40", "IccBased 0 1 0", + "IccBased 0.25", "Indexed 2", "Separation 1", "DeviceN 1 0.4", "Pattern 0 0.5 0 /P0"], + paints.Select(p => p.FillText)); + // CMYK colours (rectangles 3, 10, 11) are the CGATS TR 001 measurements of those patches in sRGB (tools/CmykFit/fit.py's + // pipeline), which the default characterisation approximates; poppler shows (236, 0, 140), (248, 156, 14) and + // (18, 123, 202) with its own formula. ICCBased gray converts through DeviceGray until the ICC engine (poppler: 62). + int[][] expected = + [ + [128, 128, 128], [255, 0, 0], [236, 41, 144], [128, 128, 128], [0, 0, 255], [214, 60, 55], [0, 255, 0], [64, 64, 64], + [0, 0, 255], [250, 168, 54], [0, 131, 200], [0, 128, 0], + ]; + for (int i = 0; i < expected.Length; i++) + { + Near([.. expected[i].Select(v => v / 255f)], paints[i].FillRgb, 12 / 255.0); + } + + Assert.Empty(codes); + } + + [Fact] + public void The_twelve_operators_of_color_operators_pdf_set_fill_and_stroke_colours() + { + (List paints, string[] codes) = Run(File.ReadAllBytes(Corpus.Path("color-operators.pdf"))); + + Assert.Equal( + ["DeviceGray 0.75", "DeviceRgb 0 0 1", "DeviceCmyk 0 1 0 0", "CalGray 0.8", "Separation 1", "Separation 0.25", "Pattern 1 0 0 /P0", "DeviceRgb 0 0 0"], + paints.Select(p => p.FillText)); + Assert.Equal( + ["DeviceGray 0.25", "DeviceRgb 1 0 0", "DeviceCmyk 0 0 0 1", "CalGray 0.2", "Separation 1", "Separation 0.5", "Pattern 0 0 1 /P0", "DeviceCmyk 0 0 0 1"], + paints.Select(p => p.StrokeText)); + Assert.Empty(codes); + } + + [Fact] + public void Inline_image_colour_spaces_resolve_abbreviations_and_the_abbreviated_Indexed_space() + { + using PdfDocument operators = PdfDocument.Open(Corpus.Path("color-operators.pdf")); + using PdfDocument gray = PdfDocument.Open(Corpus.Path("inline-image.pdf")); + var indexed = new InlineImageSpaces(); + var device = new InlineImageSpaces(); + + operators.Pages[0].ProcessContent(indexed); + gray.Pages[0].ProcessContent(device); + + PdfIndexedColorSpace space = Assert.IsType(Assert.Single(indexed.Spaces)); + Assert.Same(PdfDeviceRgbColorSpace.Instance, space.Base); + byte[] rgb = new byte[6]; + operators.GetColorConverter(space).Convert(new byte[] { 0, 1 }, rgb, 2); + Assert.Equal(new byte[] { 255, 0, 0, 0, 0, 255 }, rgb); + Assert.Same(PdfDeviceGrayColorSpace.Instance, Assert.Single(device.Spaces)); + Assert.Empty(operators.Diagnostics); + } + + [Fact] + public void Default_colour_spaces_of_default_colorspaces_pdf_apply_at_paint_time() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("default-colorspaces.pdf")); + var recorder = new ColorRecorder(); + document.Pages[0].ProcessContent(recorder); + + Assert.Equal(["DeviceRgb 0.5 0.5 0.5", "DeviceGray 0.5"], recorder.Paints.Select(p => p.FillText)); + Assert.IsType(recorder.Paints[0].Defaults.Rgb); + + // The page's CalRGB and CalGray defaults (gamma 1, D50) take 0.5 to linear 0.5, sRGB 188/255; poppler shows (188, 188, 188) + // where the device colour would be 128. + Near([0.7354f, 0.7354f, 0.7354f], recorder.Paints[0].FillRgb, 2e-3); + Near([0.7354f, 0.7354f, 0.7354f], recorder.Paints[1].FillRgb, 2e-3); + + // The form has its own DefaultRGB (gamma 2.2, D65: 0.5 is sRGB 0.504; poppler 128), the image's Indexed base remaps to the + // page's (poppler 188). + var form = (CosStream)document.Resolve(new CosReference(5, 0)); + PdfDefaultColorSpaces formDefaults = document.GetDefaultColorSpaces((CosDictionary)document.Resolve(form.Dictionary[new CosName("Resources")])); + Near([0.504f, 0.504f, 0.504f], document.GetColorConverter(PdfDeviceRgbColorSpace.Instance, formDefaults).ConvertOne(0.5f, 0.5f, 0.5f), 3e-3); + var image = (CosStream)document.Resolve(new CosReference(6, 0)); + PdfColorSpace indexed = document.GetColorSpace(image.Dictionary[new CosName("ColorSpace")]); + byte[] pixels = new byte[6]; + document.GetColorConverter(indexed, recorder.Paints[0].Defaults).Convert(new byte[] { 0, 1 }, pixels, 2); + Assert.Equal(255, pixels[0]); + Assert.InRange(pixels[3], 187, 189); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void All_paints_every_colourant_and_None_paints_nothing_in_separation_special_pdf() + { + (List paints, string[] codes) = Run(File.ReadAllBytes(Corpus.Path("separation-special.pdf"))); + + Assert.Equal(4, paints.Count); + Near([0.5f, 0.5f, 0.5f], paints[1].FillRgb); + Assert.False(paints[1].PaintsNothing); + Assert.True(paints[2].PaintsNothing); + Assert.True(paints[3].PaintsNothing); + Assert.Empty(codes); + } + + /// Resolves the colour space of every inline image through . + private sealed class InlineImageSpaces : ContentProcessor + { + public List Spaces { get; } = []; + + public override ContentEvents Events => ContentEvents.Operators; + + public override void VisitOperator(in ContentOperator op, ContentContext context) + { + if (op.Code != ContentOperatorCode.BeginInlineImage) + { + return; + } + + var dictionary = (CosDictionary)op.Operands[0].ToCosObject(); + if (dictionary.TryGetValue(new CosName("CS"), out CosObject? value) || dictionary.TryGetValue(new CosName("ColorSpace"), out value)) + { + Spaces.Add(context.GetInlineImageColorSpace(value)); + } + } + } +} diff --git a/tests/Broadside.Tests/Colors/DefaultColorSpaceTests.cs b/tests/Broadside.Tests/Colors/DefaultColorSpaceTests.cs new file mode 100644 index 00000000..9f1d6a01 --- /dev/null +++ b/tests/Broadside.Tests/Colors/DefaultColorSpaceTests.cs @@ -0,0 +1,94 @@ +using Broadside.Graphics; +using static Broadside.Tests.Colors.ColorTesting; + +namespace Broadside.Tests.Colors; + +/// +/// DefaultGray, DefaultRGB and DefaultCMYK (ISO 32000-2 §8.6.5.6) as a processor sees them at paint time: the colour keeps the space +/// the operator selected, the converter with the current defaults paints it in the default space, including nested device spaces. +/// +public class DefaultColorSpaceTests +{ + /// CalGray and CalRGB whose gamma-1 values are linear sRGB, so a remapped 0.5 paints as 0.7354, not 0.5. + private const string Defaults = + "/DefaultGray [/CalGray << /WhitePoint [0.95047 1 1.08883] >>] " + + "/DefaultRGB [/CalRGB << /WhitePoint [0.95047 1 1.08883] /Matrix [0.4124564 0.2126729 0.0193339 0.3575761 0.7151522 0.1191920 0.1804375 0.0721750 0.9503041] >>]"; + + private const float Remapped = 0.7353570f; + + private const string Rect = " 0 0 10 10 re f\n"; + + [Fact] + public void Device_colours_paint_in_the_default_spaces_of_the_current_resources() + { + (List paints, string[] codes) = Run(Page($"<< /ColorSpace << {Defaults} >> >>", "0.5 g" + Rect + "0.5 0.5 0.5 rg" + Rect + "0 0 0 0.5 k" + Rect)); + + Assert.Equal(["DeviceGray 0.5", "DeviceRgb 0.5 0.5 0.5", "DeviceCmyk 0 0 0 0.5"], paints.Select(p => p.FillText)); + Near([Remapped, Remapped, Remapped], paints[0].FillRgb, 2e-3); + Near([Remapped, Remapped, Remapped], paints[1].FillRgb, 2e-3); + Assert.IsType(paints[1].Defaults.Rgb); + Assert.Null(paints[2].Defaults.Cmyk); + Assert.Empty(codes); + } + + [Fact] + public void The_initial_device_gray_is_remapped_too() + { + (List paints, _) = Run(Page("<< /ColorSpace << /DefaultGray [/CalGray << /WhitePoint [0.95047 1 1.08883] >>] >> >>", "0 0 10 10 re f")); + + Assert.IsType(Assert.Single(paints).Defaults.Remap(paints[0].Fill.ColorSpace)); + Near([0f, 0f, 0f], paints[0].FillRgb); + } + + [Fact] + public void Nested_device_spaces_of_Indexed_Separation_and_Pattern_are_remapped() + { + (List paints, string[] codes) = Run(Page( + $"<< /ColorSpace << {Defaults} /Ix [/Indexed /DeviceGray 1 <0080>] " + + "/Sep [/Separation /Spot /DeviceGray << /FunctionType 2 /Domain [0 1] /C0 [1] /C1 [0] /N 1 >>] /Pat [/Pattern /DeviceRGB] >> " + + "/Pattern << /T 5 0 R >> >>", + "/Ix cs 1 sc" + Rect + "/Sep cs 0.5 scn" + Rect + "/Pat cs 0.5 0.5 0.5 /T scn" + Rect, + "<< /PatternType 1 /PaintType 2 /TilingType 1 /BBox [0 0 1 1] /XStep 1 /YStep 1 /Resources << >> /Length 0 >>\nstream\n\nendstream")); + + Near([0.7366f, 0.7366f, 0.7366f], paints[0].FillRgb, 2e-3); + Near([Remapped, Remapped, Remapped], paints[1].FillRgb, 2e-3); + Near([Remapped, Remapped, Remapped], paints[2].FillRgb, 2e-3); + Assert.Empty(codes); + } + + [Fact] + public void A_default_is_not_remapped_again() + { + // A Separation may be DefaultGray; its own DeviceGray alternate stays DeviceGray. + (List paints, string[] codes) = Run(Page( + "<< /ColorSpace << /DefaultGray [/Separation /S /DeviceGray << /FunctionType 2 /Domain [0 1] /C0 [0.2] /C1 [0.2] /N 1 >>] >> >>", + "0.9 g" + Rect)); + + Near([0.2f, 0.2f, 0.2f], Assert.Single(paints).FillRgb); + Assert.Empty(codes); + } + + [Fact] + public void A_default_of_the_wrong_size_or_family_is_ignored_with_a_diagnostic() + { + (List paints, string[] codes) = Run(Page( + "<< /ColorSpace << /DefaultRGB /DeviceGray /DefaultCMYK [/Lab << /WhitePoint [0.9642 1 0.8249] >>] >> >>", + "0.5 0.5 0.5 rg" + Rect)); + + Assert.True(Assert.Single(paints).Defaults.IsEmpty); + Near([0.5f, 0.5f, 0.5f], paints[0].FillRgb); + Assert.Equal(["DefaultColorSpaceInvalid"], codes); + } + + [Fact] + public void The_defaults_of_any_resource_dictionary_are_available_from_the_document() + { + using PdfDocument document = PdfDocument.Open(Page($"<< /ColorSpace << {Defaults} >> >>", string.Empty)); + PdfDefaultColorSpaces defaults = document.GetDefaultColorSpaces(document.Pages[0].Resources); + + Assert.IsType(defaults.Gray); + Assert.Same(defaults, document.GetDefaultColorSpaces(document.Pages[0].Resources)); + Assert.Same(PdfDefaultColorSpaces.None, document.GetDefaultColorSpaces(null)); + Assert.Same(PdfDeviceCmykColorSpace.Instance, defaults.Remap(PdfDeviceCmykColorSpace.Instance)); + } +} diff --git a/tests/Broadside.Tests/Colors/IccProfiles.cs b/tests/Broadside.Tests/Colors/IccProfiles.cs new file mode 100644 index 00000000..bc0e164f --- /dev/null +++ b/tests/Broadside.Tests/Colors/IccProfiles.cs @@ -0,0 +1,34 @@ +using System.Buffers.Binary; +using System.Text; + +namespace Broadside.Tests.Colors; + +/// Synthesizes ICC profile headers (ICC.1:2022 §7.2, Table 17) for ICCBased colour space tests. +internal static class IccProfiles +{ + /// A 128-byte header (and nothing else) with the given class, data colour space and version. + public static byte[] Header(string deviceClass, string colorSpace, byte major = 2, byte minorAndFix = 0x10, int? size = null) + { + byte[] header = new byte[128]; + BinaryPrimitives.WriteUInt32BigEndian(header, (uint)(size ?? header.Length)); + Encoding.ASCII.GetBytes("bsde").CopyTo(header, 4); + header[8] = major; + header[9] = minorAndFix; + Encoding.ASCII.GetBytes(deviceClass).CopyTo(header, 12); + Encoding.ASCII.GetBytes(colorSpace).CopyTo(header, 16); + Encoding.ASCII.GetBytes("XYZ ").CopyTo(header, 20); + Encoding.ASCII.GetBytes("acsp").CopyTo(header, 36); + BinaryPrimitives.WriteUInt32BigEndian(header.AsSpan(64), 1); + BinaryPrimitives.WriteInt32BigEndian(header.AsSpan(68), 0x0000F6D6); + BinaryPrimitives.WriteInt32BigEndian(header.AsSpan(72), 0x00010000); + BinaryPrimitives.WriteInt32BigEndian(header.AsSpan(76), 0x0000D32D); + return header; + } + + /// An ICCBased stream object holding in ASCIIHex, with extra dictionary entries. + public static string Stream(byte[] profile, string entries) + { + string hex = Convert.ToHexString(profile) + ">"; + return $"<< {entries} /Filter /ASCIIHexDecode /Length {hex.Length} >>\nstream\n{hex}\nendstream"; + } +} diff --git a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt index 5c8d21a5..998bcd97 100644 --- a/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt +++ b/tests/Broadside.Tests/Snapshots/CorpusSmokeTests.Corpus_file_names_match_snapshot.verified.txt @@ -4,6 +4,9 @@ asciihex-stream.pdf, broken-xref-offsets.pdf, catalog-version-extensions.pdf, + color-operators.pdf, + colorspace-families.pdf, + default-colorspaces.pdf, destinations-all.pdf, empty-page.pdf, encrypted-aes-128.pdf, @@ -47,6 +50,7 @@ pdf20-header.pdf, png-predictor.pdf, runlength-stream.pdf, + separation-special.pdf, startxref-wrong.pdf, tagged-structure.pdf, text-standard14-alias.pdf, diff --git a/tests/Corpus/README.md b/tests/Corpus/README.md index b6daf94e..df7a89d2 100644 --- a/tests/Corpus/README.md +++ b/tests/Corpus/README.md @@ -84,6 +84,10 @@ Verification was run with qpdf 12.4.2 (`qpdf --check`), poppler (`pdfinfo`, `pdf | `destinations-all.pdf` | A `/Names << /Dests >>` tree with one entry per Table 149 form: `XYZ` with numbers, with three nulls and with zoom 0; `Fit`; `FitH` with a number and with null; `FitV`; `FitR`; `FitB`; `FitBH`; `FitBV`; a value in the dictionary form `<< /D [3 0 R /Fit] /Note ... >>`; a value that is an indirect array. The PDF 1.1 catalog `/Dests` dictionary keyed by name (`/Chap6 [3 0 R /FitV 72]`), and an outline whose items refer to `/Dest /Chap6` (name) and `/Dest (alpha)` (string). | 12.3.2.2, 12.3.2.4, 7.7.2, 12.3.3 | `qpdf --check`; `qpdf --json --json-key=outlines` lists both items | clean | | `outline-full.pdf` | An outline three levels deep: Part I (open, `/Count 2`) holding Chapter 1 (closed, `/Count -1`, holding Section 1.1) and Chapter 2 (a URI action); Part II (closed, `/Count -2`) holding Chapter 3 (UTF-16BE title `Chapter 3 – Übersicht`, `/C [1 0 0]`, `/F 3` bold italic, `/A << /S /GoTo /D (alpha) >>`) and Chapter 4 (`/SE` to a structure element, `/Dest [3 0 R /FitB]`). Outline `/Count 4`. | 12.3.3 Tables 150-152, 12.6.4.2, 12.6.4.8 | `qpdf --check`; `qpdf --json --json-key=outlines` shows the tree with Part I and Chapter 1 open/closed as stated | clean | | `functions.pdf` | One page, six rectangles filled in six `/Separation` spaces whose tint transforms are functions: CS0 Type 0 (8-bit, 1 in, 4 out to DeviceCMYK, `/Size [3]`) at tint 0.5; CS1 Type 2 `/N 1` to DeviceRGB at 0.5; CS2 Type 2 `/N 2` to DeviceGray at 0.5; CS3 Type 3 stitching two Type 2 halves with `/Bounds [0.5] /Encode [0 1 1 0]` at 0.75; CS4 Type 4, the LogoGreen program of 8.6.6.4, at 0.5; CS5 shares CS1's indirect function (object 12) at 0.25. | 7.10.2-7.10.5, 8.6.6.4 | `qpdf --check`; `pdftoppm -r 72` rectangle centres (RGB): CS0 (202, 147, 208) = CMYK (0.2 0.4 0 0); CS1 (128, 128, 255); CS2 (191, 191, 191); CS3 (64, 64, 64); CS4 (134, 198, 183) = CMYK (0.42 0 0.22 0.105); CS5 (191, 191, 255) | clean | +| `colorspace-families.pdf` | One page, twelve 100x100 rectangles, one per `/ColorSpace` resource, in reading order: CS0 DeviceGray 0.5; CS1 DeviceRGB 1 0 0; CS2 DeviceCMYK 0 1 0 0; CS3 CalGray (D65, gamma 2.2) 0.5; CS4 CalRGB (D65, sRGB primaries, gamma 2.2) 0 0 1; CS5 Lab (D50) 50 60 40; CS6 ICCBased with a generated ICC v2 `mntr` RGB matrix/TRC profile (D50 sRGB primaries, gamma 2.2) and `/Alternate /DeviceRGB`, 0 1 0; CS7 ICCBased with a generated `mntr` GRAY profile (gamma 2.2) and no Alternate, 0.25; CS8 Indexed DeviceRGB (red, green, blue) index 2; CS9 Separation to DeviceCMYK (Type 2, C1 [0 0.4 1 0]) at 1; CS10 DeviceN [/Cyan /Magenta] to DeviceCMYK (Type 4 `{0 0}`) at 1 0.4; CS11 `[/Pattern /DeviceRGB]` with an uncoloured tiling pattern (cell half filled) in 0 0.5 0. | 8.6.3-8.6.6, 8.7.3.3 | `qpdf --check`; `pdftoppm -r 72` rectangle centres (RGB): (128,128,128), (255,0,0), (236,0,140), (128,128,128), (0,0,255), (214,60,55), (0,255,0), (62,62,62), (0,0,255), (248,156,14), (18,123,202), (0,128,0) | clean | +| `color-operators.pdf` | The twelve colour operators of Table 73, each pair followed by a filled and stroked rectangle (`8 w`, `B`): `0.25 G 0.75 g`; `1 0 0 RG 0 0 1 rg`; `0 0 0 1 K 0 1 0 0 k`; `/CS0 CS 0.2 SC /CS0 cs 0.8 sc` (CalGray D65); `/CS1 CS /CS1 cs` (Separation to DeviceGray: CS resets to the initial tint 1.0); `/CS1 CS 0.5 SCN /CS1 cs 0.25 scn`; `/CS2 CS 0 0 1 /P0 SCN /CS2 cs 1 0 0 /P0 scn` (`[/Pattern /DeviceRGB]`, uncoloured tiling pattern P0); `/DeviceCMYK CS /DeviceRGB cs` (initial 0 0 0 1 and 0 0 0). Then a 2x1 inline image `/CS [/I /RGB 1 ]` (red, blue). | 8.6.8, 8.9.7 | `qpdf --check`; `pdftoppm -r 72` fills (191,191,191), (0,0,255), (236,0,140), (231,231,231), (0,0,0), (191,191,191), red pattern, (0,0,0); strokes (64,64,64), (255,0,0), (35,31,32), (124,124,124), (0,0,0), (128,128,128), blue pattern, (35,31,32); image red then blue | clean | +| `default-colorspaces.pdf` | Page `/ColorSpace` with `DefaultRGB` = CalRGB (D50, gamma 1, D50-adapted sRGB primaries) and `DefaultGray` = CalGray (D50, gamma 1), so a remapped 0.5 shows as 188 and a device 0.5 as 128: a `0.5 0.5 0.5 rg` rectangle, a `0.5 g` rectangle, Form XObject Fm0 whose own Resources have `DefaultRGB` = CalRGB (D65, gamma 2.2) painting `0.5 0.5 0.5 rg`, and a 2x1 image in `[/Indexed /DeviceRGB 1 ]`. Gamma 1 deviates from the ticket's gamma 2.2 so the remap is visible (gamma 2.2 at 0.5 is 128 either way). | 8.6.5.6 | `qpdf --check`; `pdftoppm -r 72` (poppler honours default spaces): (188,188,188), (188,188,188), form (128,128,128), image (255,0,0) and (188,188,188) | clean | +| `separation-special.pdf` | Over a 0.8 gray band, three rectangles at tint 0.5: CS0 `[/Separation /All /DeviceGray f]` (every colourant: 1 - tint on RGB, 50% gray), CS1 `[/Separation /None /DeviceGray f]` (paints nothing) and CS2 `[/DeviceN [/None /None] /DeviceGray g]` (never paints); the tint transforms, which would paint white, are ignored. | 8.6.6.4, 8.6.6.5 | `qpdf --check`; `pdftoppm -r 72`: band (204,204,204), CS0 (255,255,255) (poppler goes through the tint transform for All; the spec says 50% gray), CS1 and CS2 (204,204,204) | clean | The crypt filter `/Length` entries in the R4 and R6 files are `16` and `32` (bytes), the form Acrobat and qpdf write and that Table 25 describes for the standard security handler; the same table also says the key "shall have the value of 128/256". Readers should accept both forms. diff --git a/tests/Corpus/color-operators.pdf b/tests/Corpus/color-operators.pdf new file mode 100644 index 0000000000000000000000000000000000000000..8388e9e3b3c6e3cfa9ecb23621353af472cadae6 GIT binary patch literal 1297 zcmZuxOLEgd5QVKy(Hk$ZW@O8;t6W*wi9#wQh$vMd<;r4^Cyv08%xDY=mt?^W;3B+k z$%e$1tKP?(y9tto=R zB^@3Hww$veub(?KcHvnuuW8m}^IJrz)}<%?pCfB_9XXA&Fm3XL=XPG0N%crG1^a=H z=wK8{ywbz0ramX2@Y2@R+T{Sq$fwn^a@oq{wpnJ1W+-HN;>?psuI~$P)2cwCnd**W z6$6{@s^RDs5IKIP;gZ>vamE)_Nny6CJcUR0TanvsoMc_*tQM*wsH+E4lnhpL5Tuni zVkxXIgaC;iA$n@Ow+^A3pqD2TPRZR?Y1!O{C#q5H|Q}atqSKJ!Y(B{h2)Z`wR7=J%(UT z(KJKKh_WdYsVJ|p98#SF;eHp*EG4ZS`p_l`3HM;?t)=bZD&IIAMQ|!;h?09^o2$+Q|yirOIul#`~rxades>8R) zi)zq+NYHaE$4R1a5kHcI$8VBOX-KC>^y)PopVEhb+uruI-FQ3}oBh*Hj7%Y-ru+nuh?XK4#vo@JZp#_UqYh;*o3zO!s&Lw>X*_F`j79-7daIXYT@Z zJK(CCiw1Gri|LNGGL0(uqVk_?fYE*-(-C_0Le>YjFJ+?`r^?38J5wyJlcOvvepniS a?+Tlk`z}XV?Tzz-Q)}G|I-TS9N$?k+U`65p literal 0 HcmV?d00001 diff --git a/tests/Corpus/colorspace-families.pdf b/tests/Corpus/colorspace-families.pdf new file mode 100644 index 0000000000000000000000000000000000000000..9ec429a61f4749bc29aeddeb6746148957826a7e GIT binary patch literal 2934 zcmcguF>fP96rKbmzy(lT0o_9)5(Tk$X1(@WicY%tNQ5p4ksXN()=5m(6KBEMwRR^* z45Ffdj*f~7@dGFj`~mtaPC^t^&>$+R6D8l<*|nY62M7ThZT#lVH*dc8-nX;6ad>-Y zQ`XzHjh}vg@USMyqx9sR+SV2|j;0esjjpzOoQ|k*s7EFz1wfB(-mIBq$Uq)nUEpwy zJMl25fzR-Jh>~6;mgK@ho>^YV+hhh%w@+i=3}d~WUedq=z9kj4JF1A6Sio{>@&?rC znLNG7A`oQe-E^F0{fUl@8}>bF+&1^)$n0i%iut~*9KGFb9;<5H-9Ns=4xa`{eO%x< zoY6Gv{3A_N=$hsGHz-CvUpKDTeh5VRYzv)(U@V~iuz^ls}A@;S+V$QnW zlnOc4l~gVKc(Q}S)%~E&qqYoCr@EA#;wJWOp(&mjIV7;G!tn+S&1N zk>|02A2wX^I#|;;6P;-rrwKLslhjs=i}r9ycP^5MrwfsC_tJA6CoB`m9q^oB5ST}@ z7}cAcD8>hc5P7060W5hP!0JvlHr$8O6RQDmqA4~FXE{lPgG{Y88Nd#Lq_{#XU*~6z zhaRCJ#pA+r^M{5-TWX&gdnOs#GinAQBXXM=eO?1KkD?rX2`G=K3GL&Ss1)Csp;LxP zhVUcnF-V51QK|?u$N6eC&R^WHwHniOu|T7w6_k_~X$1@l5Wr*NC9_q))|^=$CB(#5 z!P<_P;!-5kMA%iRkWs3n|M@z4-wJ*wUb zJom3&)?6YFAr4ZC(#bT7M`!j`y2x=TWX6oAJjXTXUm@nTocq!*g$N%B@x-Td-^ph} zeETud_;K!g`3oVQ`$&jy9z++}eHTxxt@}d!)p%L;{7#sw3R*9f>9-coJ=D9eTofz+Kb|0zaTr zn)xISO};3Z`&xL7Uh_!>4%d8PxU^RKon>DTEcuiS@U?X{o(kHKa^je|zL)#) h`-VEGNs8|ku0`>koLimQB1hHgc(sj<*WTEv{Q+mNf_wk~ literal 0 HcmV?d00001 diff --git a/tests/Corpus/default-colorspaces.pdf b/tests/Corpus/default-colorspaces.pdf new file mode 100644 index 0000000000000000000000000000000000000000..eafdf8ac4fb12ee77784ed86f37d31175c111452 GIT binary patch literal 1345 zcmb_c&2Abo5N@yg6m#L&_0RrGhy$ch)JCC6rB*^Y7;s=Cc1?|`lD=dQeS`KzI^*3y zfL6J5SC-e~&z^5)zS+*?V)#acS54v4opB^_F*g!e8HcMa=wbWaX z2)Kq`FVOXZfV4h7(BRnnaO%2r+zOM zw-_>B)>0T*_1JLmUoVoNv%Ma$FITgBJ$Ihy!<~mLLF9kg`bwF?S3o42?Rf=^s9hNN7~nQu zbBNJ%j|*QfZ|`K^-gNDQtGLn>nw>p|R+vzgI-d7c=}n6p-))BN8FcNdO~N zRSKpul+cc2RS1b$4yBM(Yc2{@bQmRBQ~3l1912nRDaU&el1W+>=%rDGuh_mksGNUR z=P8pEt}o45@<;|RC2w3|3#07I1*$;;d#B6gin@~ZOShe9J22J8)YN|YQ4>wsxL)W7 zy&xffE9aUzNI-Wu&@Rv#MNc>wkSW<#!Dkipm(uPt#%8Im$ZEU5Ho& KozB~ bytes: ] return simple_file(objects) +# --------------------------------------------------------------------------- +# Colour spaces (clause 8.6) +# --------------------------------------------------------------------------- + +def s15f16(value: float) -> bytes: + """ICC.1:2022 4.6 s15Fixed16Number.""" + return struct.pack(">i", round(value * 65536)) + + +def icc_profile(device_class: bytes, space: bytes, tags: list[tuple[bytes, bytes]]) -> bytes: + """A version 2.1 ICC profile (ICC.1:2022 7.2 header, 7.3 tag table): XYZ PCS, D50 illuminant, the tags 4-byte aligned.""" + count = len(tags) + offset = 128 + 4 + 12 * count + table = struct.pack(">I", count) + data = b"" + for sig, body in tags: + table += sig + struct.pack(">II", offset + len(data), len(body)) + data += body + b"\x00" * (-len(body) % 4) + size = 128 + len(table) + len(data) + header = (struct.pack(">I", size) + b"\x00" * 4 + bytes([2, 0x10, 0, 0]) + device_class + space + b"XYZ " + + struct.pack(">6H", 2026, 1, 1, 0, 0, 0) + b"acsp" + b"\x00" * 24 + struct.pack(">I", 0) + + s15f16(0.9642) + s15f16(1.0) + s15f16(0.8249) + b"\x00" * 48) + assert len(header) == 128 + return header + table + data + + +def icc_desc(text: bytes) -> bytes: + """ICC.1:2001 textDescriptionType (version 2 profiles): ASCII, empty Unicode and ScriptCode parts.""" + return b"desc" + b"\x00" * 4 + struct.pack(">I", len(text) + 1) + text + b"\x00" + b"\x00" * 8 + b"\x00" * 3 + b"\x00" * 67 + + +def icc_xyz(x: float, y: float, z: float) -> bytes: + return b"XYZ " + b"\x00" * 4 + s15f16(x) + s15f16(y) + s15f16(z) + + +def icc_gamma(gamma: float) -> bytes: + """curveType with one entry, a u8Fixed8Number gamma.""" + return b"curv" + b"\x00" * 4 + struct.pack(">IH", 1, round(gamma * 256)) + + +ICC_COPYRIGHT = b"text" + b"\x00" * 4 + b"No copyright, use freely\x00" + + +def icc_rgb_profile() -> bytes: + """Display (mntr) RGB matrix/TRC profile: the sRGB primaries adapted to D50 (IEC 61966-2-1 Annex), gamma 2.2.""" + return icc_profile(b"mntr", b"RGB ", [ + (b"desc", icc_desc(b"Broadside RGB gamma 2.2")), + (b"cprt", ICC_COPYRIGHT), + (b"wtpt", icc_xyz(0.9642, 1.0, 0.8249)), + (b"rXYZ", icc_xyz(0.4361, 0.2225, 0.0139)), + (b"gXYZ", icc_xyz(0.3851, 0.7169, 0.0971)), + (b"bXYZ", icc_xyz(0.1431, 0.0606, 0.7141)), + (b"rTRC", icc_gamma(2.2)), + (b"gTRC", icc_gamma(2.2)), + (b"bTRC", icc_gamma(2.2)), + ]) + + +def icc_gray_profile() -> bytes: + """Display (mntr) GRAY profile: a gamma 2.2 tone curve.""" + return icc_profile(b"mntr", b"GRAY", [ + (b"desc", icc_desc(b"Broadside gray gamma 2.2")), + (b"cprt", ICC_COPYRIGHT), + (b"wtpt", icc_xyz(0.9642, 1.0, 0.8249)), + (b"kTRC", icc_gamma(2.2)), + ]) + + +D65 = b"/WhitePoint [0.9505 1 1.089]" +SRGB_MATRIX = b"/Matrix [0.4124 0.2126 0.0193 0.3576 0.7152 0.1192 0.1805 0.0722 0.9505]" + + +def colour_rects(entries: list[tuple[bytes, bytes]], columns: int = 4) -> bytes: + """One 100 x 100 rectangle per (colour space resource, colour operator text), left to right, top to bottom.""" + content = b"" + for i, (name, colour) in enumerate(entries): + x = 40 + (i % columns) * 140 + y = 640 - (i // columns) * 140 + content += b"/%s cs %s %d %d 100 100 re f\n" % (name, colour, x, y) + return content + + +def gen_colorspace_families() -> bytes: + """8.6.3 Table 61: one ColorSpace resource per family and one filled rectangle each (8.6.4 to 8.6.6), in reading order: + CS0 DeviceGray 0.5; CS1 DeviceRGB 1 0 0; CS2 DeviceCMYK 0 1 0 0; CS3 CalGray (D65, gamma 2.2) 0.5; CS4 CalRGB (D65, sRGB + primaries, gamma 2.2) 0 0 1; CS5 Lab (D50) 50 60 40; CS6 ICCBased RGB (an ICC v2 mntr matrix/TRC profile, /Alternate + /DeviceRGB) 0 1 0; CS7 ICCBased GRAY (gamma 2.2, no Alternate) 0.25; CS8 Indexed DeviceRGB, index 2 of red, green, blue; + CS9 Separation /Spot to DeviceCMYK (Type 2, C1 [0 0.4 1 0]) at 1; CS10 DeviceN [/Cyan /Magenta] to DeviceCMYK (Type 4 + {0 0}) at 1 0.4 (both CMYK values are IT8.7/3 patches measured in CGATS TR 001); CS11 [/Pattern /DeviceRGB] with the uncoloured tiling pattern P0 (a 10 x 10 cell, half filled) in 0 0.5 0.""" + entries = [(b"CS%d" % i, colour) for i, colour in enumerate([ + b"0.5 sc", b"1 0 0 sc", b"0 1 0 0 sc", b"0.5 sc", b"0 0 1 sc", b"50 60 40 sc", b"0 1 0 scn", b"0.25 scn", + b"2 sc", b"1 scn", b"1 0.4 scn", b"0 0.5 0 /P0 scn"])] + spaces = [ + b"/DeviceGray", b"/DeviceRGB", b"/DeviceCMYK", + b"[/CalGray << " + D65 + b" /Gamma 2.2 >>]", + b"[/CalRGB << " + D65 + b" /Gamma [2.2 2.2 2.2] " + SRGB_MATRIX + b" >>]", + b"[/Lab << /WhitePoint [0.9642 1 0.8249] /Range [-128 127 -128 127] >>]", + b"[/ICCBased 6 0 R]", b"[/ICCBased 7 0 R]", + b"[/Indexed /DeviceRGB 2 ]", + b"[/Separation /Spot /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0.4 1 0] /N 1 >>]", + b"[/DeviceN [/Cyan /Magenta] /DeviceCMYK 8 0 R]", + b"[/Pattern /DeviceRGB]", + ] + resources = (b"<< /ColorSpace << " + b" ".join(b"/CS%d %s" % (i, s) for i, s in enumerate(spaces)) + + b" >> /Pattern << /P0 5 0 R >> >>") + rgb = icc_rgb_profile() + gray = icc_gray_profile() + return simple_file([ + (1, catalog()), + (2, pages()), + (3, page(contents=4, resources=False, extra=b" /Resources " + resources)), + (4, stream(b"", colour_rects(entries))), + (5, stream(b"/PatternType 1 /PaintType 2 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 /Resources << >>", + b"0 0 10 5 re f")), + (6, stream(b"/N 3 /Alternate /DeviceRGB", rgb)), + (7, stream(b"/N 1", gray)), + (8, stream(b"/FunctionType 4 /Domain [0 1 0 1] /Range [0 1 0 1 0 1 0 1]", b"{0 0}")), + ], binary=True) + + +def gen_color_operators() -> bytes: + """8.6.8 Table 73: all twelve colour operators, each followed by a filled and stroked rectangle (B), in reading order: + (1) 0.25 G 0.75 g; (2) 1 0 0 RG 0 0 1 rg; (3) 0 0 0 1 K 0 1 0 0 k; (4) /CS0 CS 0.2 SC /CS0 cs 0.8 sc with CS0 CalGray; + (5) /CS1 CS /CS1 cs with CS1 Separation (CS resets both colours to the initial tint 1.0); (6) /CS1 CS 0.5 SCN /CS1 cs + 0.25 scn; (7) /CS2 CS 0 0 1 /P0 SCN /CS2 cs 1 0 0 /P0 scn with CS2 [/Pattern /DeviceRGB] and the uncoloured tiling pattern + P0; (8) /DeviceCMYK CS /DeviceRGB cs (initial colours 0 0 0 1 and 0 0 0). Then an inline image (8.9.7 Tables 91-92) in + the abbreviated Indexed space /CS [/I /RGB 1 ], two pixels: red, blue.""" + ops = [b"0.25 G 0.75 g", b"1 0 0 RG 0 0 1 rg", b"0 0 0 1 K 0 1 0 0 k", b"/CS0 CS 0.2 SC /CS0 cs 0.8 sc", + b"/CS1 CS /CS1 cs", b"/CS1 CS 0.5 SCN /CS1 cs 0.25 scn", b"/CS2 CS 0 0 1 /P0 SCN /CS2 cs 1 0 0 /P0 scn", + b"/DeviceCMYK CS /DeviceRGB cs"] + content = b"8 w\n" + for i, op in enumerate(ops): + x = 40 + (i % 4) * 140 + y = 640 - (i // 4) * 140 + content += b"%s %d %d 100 100 re B\n" % (op, x, y) + content += b"q 200 0 0 100 40 300 cm BI /W 2 /H 1 /CS [/I /RGB 1 ] /BPC 8 ID \x00\x01 EI Q\n" + resources = (b"<< /ColorSpace << /CS0 [/CalGray << " + D65 + b" >>] " + b"/CS1 [/Separation /Spot /DeviceGray << /FunctionType 2 /Domain [0 1] /C0 [1] /C1 [0] /N 1 >>] " + b"/CS2 [/Pattern /DeviceRGB] >> /Pattern << /P0 5 0 R >> >>") + return simple_file([ + (1, catalog()), + (2, pages()), + (3, page(contents=4, resources=False, extra=b" /Resources " + resources)), + (4, stream(b"", content)), + (5, stream(b"/PatternType 1 /PaintType 2 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 /Resources << >>", + b"0 0 10 5 re f")), + ], binary=True) + + +def gen_default_colorspaces() -> bytes: + """8.6.5.6 default colour spaces. The page's ColorSpace resources have DefaultRGB = CalRGB (D50 white, gamma 1, the sRGB + primaries adapted to D50) and DefaultGray = CalGray (D50, gamma 1), so a remapped 0.5 is linear and shows as sRGB 188, a + device 0.5 as 128. Reading order: (1) 0.5 0.5 0.5 rg rectangle; (2) 0.5 g rectangle; (3) the Form XObject Fm0, whose own + Resources have DefaultRGB = CalRGB (D65, gamma 2.2, sRGB primaries), painting 0.5 0.5 0.5 rg (inside it its DefaultRGB + applies, found at paint time: 128); (4) Im0, a 2 x 1 image in [/Indexed /DeviceRGB 1 ] (the base DeviceRGB + remapped to the page's DefaultRGB), pixels 0 and 1.""" + d50 = b"/WhitePoint [0.9642 1 0.8249]" + d50_matrix = b"/Matrix [0.4361 0.2225 0.0139 0.3851 0.7169 0.0971 0.1431 0.0606 0.7141]" + content = (b"0.5 0.5 0.5 rg 40 640 100 100 re f\n" + b"0.5 g 180 640 100 100 re f\n" + b"q 1 0 0 1 320 640 cm /Fm0 Do Q\n" + b"q 100 0 0 100 460 640 cm /Im0 Do Q\n") + resources = (b"<< /ColorSpace << /DefaultRGB [/CalRGB << " + d50 + b" " + d50_matrix + b" >>] " + b"/DefaultGray [/CalGray << " + d50 + b" >>] >> /XObject << /Fm0 5 0 R /Im0 6 0 R >> >>") + form_resources = b"<< /ColorSpace << /DefaultRGB [/CalRGB << " + D65 + b" /Gamma [2.2 2.2 2.2] " + SRGB_MATRIX + b" >>] >> >>" + return simple_file([ + (1, catalog()), + (2, pages()), + (3, page(contents=4, resources=False, extra=b" /Resources " + resources)), + (4, stream(b"", content)), + (5, stream(b"/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Resources " + form_resources, + b"0.5 0.5 0.5 rg 0 0 100 100 re f")), + (6, stream(b"/Type /XObject /Subtype /Image /Width 2 /Height 1 /BitsPerComponent 8 " + b"/ColorSpace [/Indexed /DeviceRGB 1 ]", b"\x00\x01")), + ], binary=True) + + +def gen_separation_special() -> bytes: + """8.6.6.4 and 8.6.6.5 special colourant names, one rectangle each at tint 0.5 over a light gray (0.8) band: CS0 Separation + /All (every colourant; on an RGB device 1 - tint on every component, a 50% gray); CS1 Separation /None (paints nothing, the + band shows through); CS2 DeviceN [/None /None] (never paints). The tint transforms, which would paint white, are ignored.""" + tint = b"<< /FunctionType 2 /Domain [0 1] /C0 [1] /C1 [1] /N 1 >>" + content = (b"0.8 g 0 600 612 160 re f\n" + + colour_rects([(b"CS0", b"0.5 scn"), (b"CS1", b"0.5 scn"), (b"CS2", b"0.5 0.5 scn")])) + resources = (b"<< /ColorSpace << /CS0 [/Separation /All /DeviceGray " + tint + b"] /CS1 [/Separation /None /DeviceGray " + + tint + b"] /CS2 [/DeviceN [/None /None] /DeviceGray 5 0 R] >> >>") + return simple_file([ + (1, catalog()), + (2, pages()), + (3, page(contents=4, resources=False, extra=b" /Resources " + resources)), + (4, stream(b"", content)), + (5, stream(b"/FunctionType 4 /Domain [0 1 0 1] /Range [0 1]", b"{pop pop 1}")), + ]) + + FILES = { "empty-page.pdf": gen_empty_page, "pdf20-header.pdf": gen_pdf20_header, @@ -1729,6 +1924,10 @@ def gen_functions() -> bytes: "outline-full.pdf": gen_outline_full, "outline-broken.pdf": gen_outline_broken, "functions.pdf": gen_functions, + "colorspace-families.pdf": gen_colorspace_families, + "color-operators.pdf": gen_color_operators, + "default-colorspaces.pdf": gen_default_colorspaces, + "separation-special.pdf": gen_separation_special, } diff --git a/tests/Corpus/separation-special.pdf b/tests/Corpus/separation-special.pdf new file mode 100644 index 0000000000000000000000000000000000000000..84724344c7c9a59c5e47c7eeafa13f19929fdf0b GIT binary patch literal 954 zcmb`GO^?$s5Qgvm6?5s4+D@CKl~$EtmvR8gs^L~~FzGY|W$nmu(JqMp&Ww|=DcvKH z+%z+f-}&%(c7L~hrRTZOpum0oE^cl>etv2ZBZu)wXdg#@#A9vVxJNiB;xnBDD}o2chOGsJOMNZ?Dc2c!ZOn!W5JpsCf!qX<+bD!zx{UoNblCWU+=yD znHfnVjMMbnJy=Ia=lP%i{O@zTNtd9;Ah{eL9xO=5u-~E|;S?_v@CU;Bl@F~qYUz|D7r!pt`;?2oEwV6oAd>XSHa;;eb zd4gF9xy~F1dE$Yj9IPMjmsiMy6_c=TtQ+?eM$9j3slYHVc7W)}3xgH?=Eun^06LWV zFf1P1fVEW#-+sc2doiEh z91oDCn$?h}nKh8FIgoDFqVe{PX#4?1N2#!`G|#~ftbvcBqfA;Wl*3Sjzq0{Y!7`mobRH}2_eBYhr{HScU7y&l)N+cV;%T%>1+Y+yW; zopsvj0+t-1+?0d1lQxgb<7dR5BedIRRI6Jpd&%;$($do6GV=X5Or^#OW0|p%bT|*w zEJ=~MHpXwKb62bA@z`jV^)M`X#OWLM_h;fJZC& zVE2s2?-&NyEIoTW(3C??7hOcM9;jlRwqepXPPs{T*mDFn0RIMI8M3gnh%7Z$Rik`M z1;FI?_|&Kpz%&_*G3c_>LzLg;BPlOTKIR;ue1HnyFy$jxLdov}mbLi@oi^zKcxgsB z6d2)l(=PJJu!p5#5A@KG)8+)!vufY4lOwe2DRkkY4|w3#J>PDb~-> z=$uG9<)ip5x;^0?lYmc{g0UBSDaJQ0otyMggD#qc>1`gb6HdkH1|mUZWAiXH9C{N> zS3}mfTUyD+o%LN7vdc`CmYRx9Teeh^xs5<3jAXA9{E6@|@Tb@{?xo?Fy$nq2bUSj% zLUa;(Ze`OSRduKQ;eN0i5`;xdND#@ zF-rr|3%8V2ldWCV#?2+=q?hv9hH17&AVIswM;@kJezca`PBykS@2+nsBAY6KO3L7b z91Km9o<-g3L>y z@r9)%|7SouL)9v44`SMs@#e|LS+OwCGt#RYjY!6W!h3zRa{nVGHew%iFVsOb^vrMX>(B{ zUNq<_#J>lO>aJnh4P58~hVd1%qkf7(tmO0+@wgCKum}+&P_4@^z+YZLj(7xl34GG; zBuDxWlH>g@@=(89;A<1PZ9C}%8FmmpF8H`nMLAjMbbI|EhXD~o=oCR*vFcKz(X^FE z3D z$N-QW2oMMDrWp`az)`fzbHu=tFj@-G02+X17~m?Wo2)J#boxlY8}x{gwD{~U=OF2E zyT*%vz|o9OHxRJXW>gz+P6MLLBODpqZWC1~ue3lDVFZTZ555Hj3Zw7<)+cB)$hYF1 zvM*rv9Hb7jF(YOLg<38%W9gVn)d!=5)K7#JUJ?enoKG##+AeET2r9QynTLUz{@kO( z^W|X%+$Ji2e%d(5%Mr9gP}nA;@LYf^fOTOlpt3!9U!<>9X2q>UIq`X54X-wa1r*s> zTY&(x8PCHi2`6rl#XukrL+~_$fQYQ0hl~-6%t92cg9b5Kap^CMJoa}HU?-f!wP6>? zR54@1+UM~0bC^NF$&95OZsYI~4re(0FpCD}lYu~h8!YJtDaMwJus#o*cL}I-AR6HN zlD%Hq-C-YUr+pi7wghYlx38EQ+)`a;Dz};F&1E*zV0i_IqDO@k z7rzaWO#VT{yAORxcq1zcc%yaVSFOszV%Zx)~GoEkmVHJx*+ zXL@ud`Hb(C{%`fax$hy1aQT%@M!el1;|SJ2!YLTa?Vt^EMg=X524%>2Wwem-z4Pk= z0VV-e=^*3QtPV~Dh=)87Nv&5^^QM#fo2gajyXQ>j_k~icZY5U*ldC>Z2|#?c*aYXy zDSUpfi)NBxYJ*I&GUAt^A%0zsfF&8QJh3O>!xlsKFo69^lXSFlDXI0E;tF+56-sJ7 zUKy0PPR3M)G_6qg00v;IGvHll2>_EE0oGyiymG6oKdA_H7gN8l2w_A_UPX_^j7w{z zeZ9(_uKw#Wt-Kc?4EDyEW$Bn#WySk3DS=v5z@*ABJ4neBdd844-&66Jp0Y>gj9aZ| zIRWfV+(`nMoSy>Y#;_US0MjEzZ-4^AiW#rI1eQ7MA`^b~6Gezb#Dr{Y=s^@o_9%rO z){);qg3du*cq94cFaEsNksE*GALZUFwT_p+xDG0>)-p)6fTYBIED|F5!fE3UF3m*^ z4){C+W8)K1%6Ax{4@*K8z;3TyH$8NE{p9FW{jtMARl}@dZgjrt-HD|q8{ij{2Azb- z<2eH6;uO5{ocD!aP@0jCQW=!$E99J~rca>N|%2dv=T_;ATQ(p2f zX)~wknff!s=aOg3-b`ECV4PFTQSYiQnC8tFE0;>^f|~lEyq@2P4V_CkAvobT{vZ=D zMiG>pQh@S6*yB@QM9o;Su;1q)R&B>4?ebOIWs!D;q+K3a37svUM1_?fQCNgkZdF9o zfavdnC;2&4R(MTbb^QhNglRoGeuWZ4aPvyc4F!n`c~Vdzu}b2zl!k?f?JMPXQK5iP zkSY`gVM?Gz1utYd+zC`U!g8`B=;Mp37M}0~F`K~~d{OF;$o*=VjWs|fNc-H~SF7i# znev&@vsJSVv!j30e0IlN!`$e*&A0Nl+{oMVLA5CJ%PMh$f|sJ4s=-{})Uwyy#A(B& zf!1~_1I&*Jl32+Rz@pI=v3Cvc2{hnYcM zIGQ41LGn|3l&V+TRJ&-3=E&(7yQtl(+HkUeQZa?U z7(bi#PU?GEKgznqUNK!fe7#_))*S5W4w zMbWz+^+vveS(T1i73O%UG4Oc*U{7k!pBWJ*`Epsf1h)E5u*X358E`?s58%@L1#o@l zh%hvtv7(k=G2t&*@iRw+SCnF+8EAH1BL}A3%YhE>6|l-ozII!u!ZGQA}#(c&vsvbT-fIgS84zIa`aK)^JtbO&JAo&y7 z3B=G>-$}oH75xjd^7}VaP2`!1{WmoQp*$K74tr&|ONgnpxh6`15)a#YA z$=|P@wY{<9dpj;x37Yh|>>Pj}P4QXq|CdkVF9WyLw$L{i?AiCx#$ZS1FAJ|1hWZ8{ zGP?lC8Xn3!NRqU-gPT{00FTWKN=^>`tD94x=$n^QLjZ>Hu_(q2RbH3V$0;G2OS|p7 ziGaGJAQ~rUAV|z9A;b)Ua`Yw2LMo&~!T? zCD5`QpD<~k?zt7eaVdV|Y|3)#n#rcy`t(<7PSm`#4T_2Ssb>}w^KP%rno@q8l!1Ov zEGFh~Nol{*uYDtRHubISbJ_FyTZZj74BJtMq|{f`C)6)#C+lw~CQT(D^GzK&`d7b( zTFnVfFw68_z4mf6{SJu8NX5d`5!E@v;MlgxkzzU7l-mSYfxU?AcLB0|RwtcE{$5eh3qO>iTGQ=nS;8zFG3A((^6nok{wRac}H;iQOS zgF7a1&8V^o*FZq3MBqoi%nKaJ-^xGj|qT8$by3vDK({$I+4+Rux*4V3^)?wfqARr8;UnM|)Y+)`){@ zRa-R>A;nRIG-@?^6&8(EA%(%Bv8biL{W4UO4>(0V(RXxym_0($Enf!`R9cl5b@h?R zMJMP*7^RfX7dv}DCh48`=X$S%Ep{%clJmwz9f(IDSh2&fQvoNY>W&vr3<7EVi9O%* z4QssAX_1C<;Dp30TsWb4uL`Y%Fw{0FuvObHh40ld)=h{)1$fL$z}VObZH&eHNNY@A z>COQrkcmjOgD8POmUzJn^y3Vd0aCFHJwU_|HSO(>8W?<#3$fugnUwA=5YUP_&zSIA zm>%*l-k}E{3aNMl!G}ya0-9b7u=aUG^5l0|r#mP0lby%bOqotqOywWXp3HvjnH#DK z=$4o|)%oJsB(a>NKiNE;H$D2&o~44?#iY7P#qIT()7@vPXF6xtv(}(0V-latdtNz( zPi;J*T25XwHTrUfpuQVl9GkA6rp`3Y=+CsyCV#j6c52!bb*gDvf2wr`pUFF`gc&qT zshg(oWus{>XRiL;C+6|_yq_o+jkSyEbqmJY*X%RYG(Ll$X?`_+Ivy%+q}RbpIWNf{ z#9=Ax?!{qA8K3H~!s6M^*T+Jd($~gjawh91sbfuGJnWo;v8Q<9eoLDb)MmXlwxB5u z%1a+UNXFtTA3o4w8TI%>PE*RCzZ@b*ESiO3*|8y8Cl0bBlv@5(4SNs zrJ|Cl6iQE}N=Xr-t*a8B7q{ZT%ramw;T;Fq_&hV`S!L!7b?)tBRfFpUb{&l9`bvli@w&p9^COnoZA2A{&B%98@&0JyXP z;s4L!y+xt6603|zePl1d1>)sdiZvBf14Q28@+@kve2z%uo^`OB&pkT4AJ3z(fT=Ay z=kQvmFLImEhuDr!eTm_cB{jOcJ~&w+h26?9hN3ps$_u|eMsVo=+gAzi&8vW51_}|b zNPQ^U&Znr-g!penfkMdOccQWYKTb$}8R1f7c4hQ@qW2*{>v2?Ew~A7U^bQuHC+;yl zQ7^%k1rN}p>VvR|kgRc56;J`ZlX9u7@+khoYXhG^Us18B;1`@3`UQ$F&Z`1?l$an= zPH5Q;>m)x08h~2@O`HUpWNREi1Mju|95h~yH_obF73W#uz4d%2Oc&wZ0KOr7gy2Ve z?bdcDh`4(el(9AnZOl$w(3a4L3|c<*Aw9w;v$7A27qJ}Ik4N``f=zuJ!)-l(BUPPN zZR{;q7{*6&Ulg7IzQeu3-!Myz6tu>KbEM`J2ba|iMD`vqB^e@_E`{K z)EwUzp-F4Ri_v0cb+q2156=$unm(ji`P6|Nv=s>=#u2JBqkxj`(H%!;w(7z&OU;~c zojD-^GwY(*kM>3_WvXz$Y)rDBL~~LHx*%PV%*k+85uSS#rkGOzO^*`H8#!I`TB|yI zDj=Ch1dS(Ap1=0z@+t^k>Ah3>%q*SLKb1)P_rhH^Hj~ z<8$2|gvl7?kD|vQ!te)PC~O1gJL2X7F~z*4z(EP~Z$2!tN4FGJh?a<$m6Fhki>OE- zECv>2sPeF&X!N!yBncQcnrw-&(Z%^dQ6aGsekmcj*doM>EiZ3)3N|n)^`&!0D5qOu z{f1vRL|-ugr(!HpCBnTHS#|F4Y|f17jnwa@zIj;mqti0by9EZRM&=-7V0|M4La=s~ z{M##5SiDZUc=}@&=a)qMEWBCB?D=r`dh%(@B3e5{R)w;vF6rm37uVm)YPylt^owBu zim#ScJtlH-7^ad$E{q^k@s;<5(Ho}~_lSrz!~~8=jNDu0XiHZ)3gj!Gr)tvphJr^5 zQvx%u65?PcpdOj{k_$zB{RP#WX{r${-j>rAcsgP|wReV|tv@?_E7f=-)p${Szwwo- zEssG1@{1yL4QI7_=vJgD(Ljx%De$efBEVV@WGEyejXm=)1AAgDl4pFZR^Pr*uxBRc zWXrVamDZ`&P{AG{^ch3$k@ym*I_W7H5V^-{t61V+`C=pXxsg=gh+BfYQJzgiwmT=g z11m!O8A(0ya5$V5h!#KixMP7(1I8jjDDXpK`MJ$A)KtzX`Bdkrxapkf`ZG^VkDe*G zm6UTMDd)}2B8QkN9&;$@q$RWo^z+EBV;t|5uTNre0(u$wj$&E`2W7E1U;@xpiU8(0 zsNmwn$AyB_KqrJ=SVco{{8=N&StR5IM5HuaD46R6Bvb%}Zl0#Vr?by&J~J{)Eo~^d zr7yjqFTGeGVxxL1&LHW=$Gc;wAtL-x7$8EdAmDg!Dy1i7l|6x%{+Z&Bzf@(Ak1Yy7 za>Y)*gqk8$yJ`Qzj^4NJbJT48Tg^Xc4(;d_pnfiWEj~e%l#ml@cuvYcu`MDeo`f=b zTFS!XO&59@y4st>8j=}-*O;OLht+sjQ;_m-BGHZVG9HACMCklE86Un7io_`&Vafok zz(RCMV9Ir-bNMr!)1$9e{&nS>`Qp~n(qU`HvY`oO5xk=xBPX(9pIz{95}tz&!2`J|bbBL8B2pa2j}~JkYgwzykm0fqxzX zimIxTv7in%lp$r#P$+}r!uY5YA6{d&pr17;Lt-0(S?FD_7(!=986PJ<=yAFYX`CEh zs2paxQBOXcjvOQ|PUIGjU>t+Y2x>&?p7{!DB;fHmrwM%ExHIC*ziP zcLvRtk9IBUx zGR-|Pw`PtB>S`8MTcKvsc2v!WU%|-ee0jrU{jxTBDu25C)#`6oFXXk%>*qV?N3WQE z;=hm?%4-R&Z&^xdxvAX=`%EGK35MHW)ZEixYwGcPT1=bp@WEzG2f@+%shD;r{xGEO zeRyAqC0g-^50rok7O~KGHG5N(KU6~Y(>40NS<0UpviD|af2N9q^3O`M_vR_DS2W1? z7Ak+4p@1q*H86mfYGA-XID$X!{lf+BUu$_i@AzuM-nUNDzpsUcg2}&4tUDNP827)3 ze|+d3G(gkWKkT|X`})7sI^O=xol`&3F4Q{iehpP!y9|xj-Zr|wkN@w>j)mM$9zJ{U zKWiNY?|=P`o}YgYO&b4j#_{9de;)?C@zb`=&%b@y@!sHHeY}1At}yZbw!U2E)W6j_ z?$mtu*XM7%f7!8E{msGI@oQ-87e3ne@o#_dNv-3Q8}Au@`Pa3Mmy-U^<{xc4hZ>*$ z@^>#id*sWP9lt;Lo8d17Uaxf!$9}tT>rekGO#Gc^oOSHK#Me1qc;EQV4by+T?09SW z>W;g=`_*L_d-G4WoErJRU3UB^?fC!7lmFjZhi3kF4?`_y(Zrtr9RJ}LzI49U(Roq6 z`)gT0hZQns|7ia`K)jBN8yK*AYy$(FdSGD4kM24L1{h>;bMf$hRT%zdx*%)`cAOOi z`nRB&K_LbP{2PopfifiI1?i8h48eHck4orbgNs9Voqn57knOyb=Y>9ldLY4w4iw2) z07OoYIepB_Pzi6taeMSuw6s*b72P%hley>}%sJ?U!-u^A8888k-;?Wc`5&Id@Vwt* zNuOYvPcZebmFokQk)ED9C>?WP8!^6Han$p1gw%mga{ literal 0 HcmV?d00001 diff --git a/tools/CmykFit/fit.py b/tools/CmykFit/fit.py new file mode 100644 index 00000000..cb6916cb --- /dev/null +++ b/tools/CmykFit/fit.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Fits the DeviceCMYK to sRGB polynomial of Broadside's managed colour management. + +ISO 32000-2 §10.4.2.5 gives a "crude" DeviceCMYK to DeviceRGB conversion (red = 1 - min(1, c + k), ...) for processors without +a CMYK characterisation. Viewers instead convert through a SWOP profile, so a rich cyan shows as about (0, 0.68, 0.94), not +(0, 1, 1). Broadside's default approximates that characterisation with a cubic polynomial per sRGB channel whose coefficients +this script derives from public measurement data, so no profile or third-party coefficient table is copied into the core. + +Data: ANSI CGATS TR 001-1995 "Color characterization data for Type 1 printing" (SWOP), file TR001CLR.AVG of TR001-DATADISK.zip, +published by the Association for PRINT Technologies at https://printtechnologies.org/standards/characterization-data-sets +(928 IT8.7/3 patches: CMYK dot values and CIELAB, D50, 2 degree observer). The dataset is not redistributed here; pass the path of +the extracted TR001CLR.AVG: + + python3 -I tools/CmykFit/fit.py path/to/TR001CLR.AVG + +Pipeline per patch: L*a*b* (D50) to XYZ; media-relative scaling so the paper (0 0 0 0) is the D50 white, as the ICC relative +colorimetric intent does; Bradford adaptation D50 to D65; XYZ to linear sRGB (IEC 61966-2-1); sRGB encoding; clamp to [0, 1]. +Then a least-squares fit, per channel, of 1 plus the 34 monomials c^i m^j y^l k^n with 1 <= i + j + l + n <= 3 (inputs as fractions +0..1; the constant is fixed at 1 so that the paper, 0 0 0 0, is exactly white). +Prints the C# coefficient table (term order as generated below) and the fit's error in 8-bit units. Stdlib only, deterministic. +""" + +from __future__ import annotations + +import itertools +import math +import sys + +D50 = (0.9642, 1.0, 0.8249) +D65 = (0.95047, 1.0, 1.08883) +BRADFORD = ((0.8951, 0.2664, -0.1614), (-0.7502, 1.7135, 0.0367), (0.0389, -0.0685, 1.0296)) +BRADFORD_INV = ((0.9869929, -0.1470543, 0.1599627), (0.4323053, 0.5183603, 0.0492912), (-0.0085287, 0.0400428, 0.9684867)) +XYZ_TO_SRGB = ((3.2404542, -1.5371385, -0.4985314), (-0.9692660, 1.8760108, 0.0415560), (0.0556434, -0.2040259, 1.0572252)) + + +def mul(m, v): + return tuple(sum(m[r][c] * v[c] for c in range(3)) for r in range(3)) + + +def lab_to_xyz(lab, white): + l, a, b = lab + fy = (l + 16) / 116 + fx = fy + a / 500 + fz = fy - b / 200 + + def g(t): + return t ** 3 if t >= 6 / 29 else 108 / 841 * (t - 4 / 29) + + return (white[0] * g(fx), white[1] * g(fy), white[2] * g(fz)) + + +def adapt(xyz, source, target): + lms = mul(BRADFORD, xyz) + ws = mul(BRADFORD, source) + wt = mul(BRADFORD, target) + return mul(BRADFORD_INV, tuple(lms[i] * wt[i] / ws[i] for i in range(3))) + + +def encode(c): + c = 12.92 * c if c <= 0.0031308 else 1.055 * math.copysign(abs(c) ** (1 / 2.4), c) - 0.055 + return min(1.0, max(0.0, c)) + + +def read(path): + rows = [] + inside = False + with open(path, encoding="ascii") as fh: + for line in fh: + line = line.strip() + if line == "BEGIN_DATA": + inside = True + continue + if line == "END_DATA": + break + if not inside or not line or line.startswith("#"): + continue + f = line.split() + if f[2] == "Paper": + # The unprinted-paper patch is written as "Paper" instead of four zero dot values. + rows.append(((0.0, 0.0, 0.0, 0.0), tuple(float(v) for v in f[3:6]))) + else: + rows.append((tuple(float(v) / 100 for v in f[2:6]), tuple(float(v) for v in f[6:9]))) + return rows + + +# Every monomial of degree 1 to 3; the constant term is fixed at 1 so that 0 0 0 0 (the paper) is exactly white. +TERMS = [e for d in range(1, 4) for e in itertools.product(range(4), repeat=4) if sum(e) == d] + + +def features(cmyk): + return [math.prod(cmyk[i] ** e[i] for i in range(4)) for e in TERMS] + + +def solve(a, b): + n = len(b) + m = [row[:] + [b[i]] for i, row in enumerate(a)] + for col in range(n): + pivot = max(range(col, n), key=lambda r: abs(m[r][col])) + m[col], m[pivot] = m[pivot], m[col] + for r in range(n): + if r != col and m[r][col] != 0: + f = m[r][col] / m[col][col] + m[r] = [x - f * y for x, y in zip(m[r], m[col])] + return [m[i][n] / m[i][i] for i in range(n)] + + +def main(argv): + rows = read(argv[1]) + papers = [lab for cmyk, lab in rows if cmyk == (0, 0, 0, 0)] + paper = lab_to_xyz(tuple(sum(p[i] for p in papers) / len(papers) for i in range(3)), D50) + samples = [] + for cmyk, lab in rows: + xyz = lab_to_xyz(lab, D50) + xyz = tuple(xyz[i] * D50[i] / paper[i] for i in range(3)) + rgb = tuple(encode(v) for v in mul(XYZ_TO_SRGB, adapt(xyz, D50, D65))) + samples.append((features(cmyk), rgb)) + + n = len(TERMS) + ata = [[sum(s[0][i] * s[0][j] for s in samples) for j in range(n)] for i in range(n)] + coefficients = [] + for channel in range(3): + atb = [sum(s[0][i] * (s[1][channel] - 1) for s in samples) for i in range(n)] + coefficients.append(solve(ata, atb)) + + errors = [abs(min(1.0, max(0.0, 1 + sum(c * f for c, f in zip(coefficients[ch], s[0])))) - s[1][ch]) * 255 + for s in samples for ch in range(3)] + print(f"// {len(samples)} patches, {len(papers)} paper samples; error in 8-bit units: rms " + f"{math.sqrt(sum(e * e for e in errors) / len(errors)):.2f}, max {max(errors):.2f}") + print("// Terms after the constant 1: " + " ".join("c%dm%dy%dk%d" % e for e in TERMS)) + for name, row in zip(("Red", "Green", "Blue"), coefficients): + print(f"private static readonly double[] {name} =") + print("[") + for i in range(0, n, 5): + print(" " + " ".join(f"{v:.6f}," for v in row[i:i + 5])) + print("];") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) From de0055644f6399f9aa191a101e80d196f5b87959 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:55:24 -0500 Subject: [PATCH 049/152] fix(bench): link the action and annotation walkers DocumentWalker now uses (#48) Co-Authored-By: Claude Opus 5.5 --- bench/Broadside.Benchmarks/Broadside.Benchmarks.csproj | 2 ++ 1 file changed, 2 insertions(+) diff --git a/bench/Broadside.Benchmarks/Broadside.Benchmarks.csproj b/bench/Broadside.Benchmarks/Broadside.Benchmarks.csproj index 826937b4..c857a346 100644 --- a/bench/Broadside.Benchmarks/Broadside.Benchmarks.csproj +++ b/bench/Broadside.Benchmarks/Broadside.Benchmarks.csproj @@ -14,6 +14,8 @@ + + From 3fff03e7a8d6ad4c14a834efc6ccce0c190e8871 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 18:00:09 -0500 Subject: [PATCH 050/152] build: stop tracking Python bytecode Remove tools/CmykFit/__pycache__ committed with #77 and ignore __pycache__/ and *.pyc repo-wide. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 4 ++++ tools/CmykFit/__pycache__/fit.cpython-314.pyc | Bin 14933 -> 0 bytes 2 files changed, 4 insertions(+) delete mode 100644 tools/CmykFit/__pycache__/fit.cpython-314.pyc diff --git a/.gitignore b/.gitignore index cf2eb6e1..dca2f11d 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,7 @@ BenchmarkDotNet.Artifacts/ # OS .DS_Store + +# Python +__pycache__/ +*.pyc diff --git a/tools/CmykFit/__pycache__/fit.cpython-314.pyc b/tools/CmykFit/__pycache__/fit.cpython-314.pyc deleted file mode 100644 index c903300cffbe069d06393ef173bcfb894b04dfb4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 14933 zcmb_@3s@W1ndpp05<(K+bD!zx{UoNblCWU+=yD znHfnVjMMbnJy=Ia=lP%i{O@zTNtd9;Ah{eL9xO=5u-~E|;S?_v@CU;Bl@F~qYUz|D7r!pt`;?2oEwV6oAd>XSHa;;eb zd4gF9xy~F1dE$Yj9IPMjmsiMy6_c=TtQ+?eM$9j3slYHVc7W)}3xgH?=Eun^06LWV zFf1P1fVEW#-+sc2doiEh z91oDCn$?h}nKh8FIgoDFqVe{PX#4?1N2#!`G|#~ftbvcBqfA;Wl*3Sjzq0{Y!7`mobRH}2_eBYhr{HScU7y&l)N+cV;%T%>1+Y+yW; zopsvj0+t-1+?0d1lQxgb<7dR5BedIRRI6Jpd&%;$($do6GV=X5Or^#OW0|p%bT|*w zEJ=~MHpXwKb62bA@z`jV^)M`X#OWLM_h;fJZC& zVE2s2?-&NyEIoTW(3C??7hOcM9;jlRwqepXPPs{T*mDFn0RIMI8M3gnh%7Z$Rik`M z1;FI?_|&Kpz%&_*G3c_>LzLg;BPlOTKIR;ue1HnyFy$jxLdov}mbLi@oi^zKcxgsB z6d2)l(=PJJu!p5#5A@KG)8+)!vufY4lOwe2DRkkY4|w3#J>PDb~-> z=$uG9<)ip5x;^0?lYmc{g0UBSDaJQ0otyMggD#qc>1`gb6HdkH1|mUZWAiXH9C{N> zS3}mfTUyD+o%LN7vdc`CmYRx9Teeh^xs5<3jAXA9{E6@|@Tb@{?xo?Fy$nq2bUSj% zLUa;(Ze`OSRduKQ;eN0i5`;xdND#@ zF-rr|3%8V2ldWCV#?2+=q?hv9hH17&AVIswM;@kJezca`PBykS@2+nsBAY6KO3L7b z91Km9o<-g3L>y z@r9)%|7SouL)9v44`SMs@#e|LS+OwCGt#RYjY!6W!h3zRa{nVGHew%iFVsOb^vrMX>(B{ zUNq<_#J>lO>aJnh4P58~hVd1%qkf7(tmO0+@wgCKum}+&P_4@^z+YZLj(7xl34GG; zBuDxWlH>g@@=(89;A<1PZ9C}%8FmmpF8H`nMLAjMbbI|EhXD~o=oCR*vFcKz(X^FE z3D z$N-QW2oMMDrWp`az)`fzbHu=tFj@-G02+X17~m?Wo2)J#boxlY8}x{gwD{~U=OF2E zyT*%vz|o9OHxRJXW>gz+P6MLLBODpqZWC1~ue3lDVFZTZ555Hj3Zw7<)+cB)$hYF1 zvM*rv9Hb7jF(YOLg<38%W9gVn)d!=5)K7#JUJ?enoKG##+AeET2r9QynTLUz{@kO( z^W|X%+$Ji2e%d(5%Mr9gP}nA;@LYf^fOTOlpt3!9U!<>9X2q>UIq`X54X-wa1r*s> zTY&(x8PCHi2`6rl#XukrL+~_$fQYQ0hl~-6%t92cg9b5Kap^CMJoa}HU?-f!wP6>? zR54@1+UM~0bC^NF$&95OZsYI~4re(0FpCD}lYu~h8!YJtDaMwJus#o*cL}I-AR6HN zlD%Hq-C-YUr+pi7wghYlx38EQ+)`a;Dz};F&1E*zV0i_IqDO@k z7rzaWO#VT{yAORxcq1zcc%yaVSFOszV%Zx)~GoEkmVHJx*+ zXL@ud`Hb(C{%`fax$hy1aQT%@M!el1;|SJ2!YLTa?Vt^EMg=X524%>2Wwem-z4Pk= z0VV-e=^*3QtPV~Dh=)87Nv&5^^QM#fo2gajyXQ>j_k~icZY5U*ldC>Z2|#?c*aYXy zDSUpfi)NBxYJ*I&GUAt^A%0zsfF&8QJh3O>!xlsKFo69^lXSFlDXI0E;tF+56-sJ7 zUKy0PPR3M)G_6qg00v;IGvHll2>_EE0oGyiymG6oKdA_H7gN8l2w_A_UPX_^j7w{z zeZ9(_uKw#Wt-Kc?4EDyEW$Bn#WySk3DS=v5z@*ABJ4neBdd844-&66Jp0Y>gj9aZ| zIRWfV+(`nMoSy>Y#;_US0MjEzZ-4^AiW#rI1eQ7MA`^b~6Gezb#Dr{Y=s^@o_9%rO z){);qg3du*cq94cFaEsNksE*GALZUFwT_p+xDG0>)-p)6fTYBIED|F5!fE3UF3m*^ z4){C+W8)K1%6Ax{4@*K8z;3TyH$8NE{p9FW{jtMARl}@dZgjrt-HD|q8{ij{2Azb- z<2eH6;uO5{ocD!aP@0jCQW=!$E99J~rca>N|%2dv=T_;ATQ(p2f zX)~wknff!s=aOg3-b`ECV4PFTQSYiQnC8tFE0;>^f|~lEyq@2P4V_CkAvobT{vZ=D zMiG>pQh@S6*yB@QM9o;Su;1q)R&B>4?ebOIWs!D;q+K3a37svUM1_?fQCNgkZdF9o zfavdnC;2&4R(MTbb^QhNglRoGeuWZ4aPvyc4F!n`c~Vdzu}b2zl!k?f?JMPXQK5iP zkSY`gVM?Gz1utYd+zC`U!g8`B=;Mp37M}0~F`K~~d{OF;$o*=VjWs|fNc-H~SF7i# znev&@vsJSVv!j30e0IlN!`$e*&A0Nl+{oMVLA5CJ%PMh$f|sJ4s=-{})Uwyy#A(B& zf!1~_1I&*Jl32+Rz@pI=v3Cvc2{hnYcM zIGQ41LGn|3l&V+TRJ&-3=E&(7yQtl(+HkUeQZa?U z7(bi#PU?GEKgznqUNK!fe7#_))*S5W4w zMbWz+^+vveS(T1i73O%UG4Oc*U{7k!pBWJ*`Epsf1h)E5u*X358E`?s58%@L1#o@l zh%hvtv7(k=G2t&*@iRw+SCnF+8EAH1BL}A3%YhE>6|l-ozII!u!ZGQA}#(c&vsvbT-fIgS84zIa`aK)^JtbO&JAo&y7 z3B=G>-$}oH75xjd^7}VaP2`!1{WmoQp*$K74tr&|ONgnpxh6`15)a#YA z$=|P@wY{<9dpj;x37Yh|>>Pj}P4QXq|CdkVF9WyLw$L{i?AiCx#$ZS1FAJ|1hWZ8{ zGP?lC8Xn3!NRqU-gPT{00FTWKN=^>`tD94x=$n^QLjZ>Hu_(q2RbH3V$0;G2OS|p7 ziGaGJAQ~rUAV|z9A;b)Ua`Yw2LMo&~!T? zCD5`QpD<~k?zt7eaVdV|Y|3)#n#rcy`t(<7PSm`#4T_2Ssb>}w^KP%rno@q8l!1Ov zEGFh~Nol{*uYDtRHubISbJ_FyTZZj74BJtMq|{f`C)6)#C+lw~CQT(D^GzK&`d7b( zTFnVfFw68_z4mf6{SJu8NX5d`5!E@v;MlgxkzzU7l-mSYfxU?AcLB0|RwtcE{$5eh3qO>iTGQ=nS;8zFG3A((^6nok{wRac}H;iQOS zgF7a1&8V^o*FZq3MBqoi%nKaJ-^xGj|qT8$by3vDK({$I+4+Rux*4V3^)?wfqARr8;UnM|)Y+)`){@ zRa-R>A;nRIG-@?^6&8(EA%(%Bv8biL{W4UO4>(0V(RXxym_0($Enf!`R9cl5b@h?R zMJMP*7^RfX7dv}DCh48`=X$S%Ep{%clJmwz9f(IDSh2&fQvoNY>W&vr3<7EVi9O%* z4QssAX_1C<;Dp30TsWb4uL`Y%Fw{0FuvObHh40ld)=h{)1$fL$z}VObZH&eHNNY@A z>COQrkcmjOgD8POmUzJn^y3Vd0aCFHJwU_|HSO(>8W?<#3$fugnUwA=5YUP_&zSIA zm>%*l-k}E{3aNMl!G}ya0-9b7u=aUG^5l0|r#mP0lby%bOqotqOywWXp3HvjnH#DK z=$4o|)%oJsB(a>NKiNE;H$D2&o~44?#iY7P#qIT()7@vPXF6xtv(}(0V-latdtNz( zPi;J*T25XwHTrUfpuQVl9GkA6rp`3Y=+CsyCV#j6c52!bb*gDvf2wr`pUFF`gc&qT zshg(oWus{>XRiL;C+6|_yq_o+jkSyEbqmJY*X%RYG(Ll$X?`_+Ivy%+q}RbpIWNf{ z#9=Ax?!{qA8K3H~!s6M^*T+Jd($~gjawh91sbfuGJnWo;v8Q<9eoLDb)MmXlwxB5u z%1a+UNXFtTA3o4w8TI%>PE*RCzZ@b*ESiO3*|8y8Cl0bBlv@5(4SNs zrJ|Cl6iQE}N=Xr-t*a8B7q{ZT%ramw;T;Fq_&hV`S!L!7b?)tBRfFpUb{&l9`bvli@w&p9^COnoZA2A{&B%98@&0JyXP z;s4L!y+xt6603|zePl1d1>)sdiZvBf14Q28@+@kve2z%uo^`OB&pkT4AJ3z(fT=Ay z=kQvmFLImEhuDr!eTm_cB{jOcJ~&w+h26?9hN3ps$_u|eMsVo=+gAzi&8vW51_}|b zNPQ^U&Znr-g!penfkMdOccQWYKTb$}8R1f7c4hQ@qW2*{>v2?Ew~A7U^bQuHC+;yl zQ7^%k1rN}p>VvR|kgRc56;J`ZlX9u7@+khoYXhG^Us18B;1`@3`UQ$F&Z`1?l$an= zPH5Q;>m)x08h~2@O`HUpWNREi1Mju|95h~yH_obF73W#uz4d%2Oc&wZ0KOr7gy2Ve z?bdcDh`4(el(9AnZOl$w(3a4L3|c<*Aw9w;v$7A27qJ}Ik4N``f=zuJ!)-l(BUPPN zZR{;q7{*6&Ulg7IzQeu3-!Myz6tu>KbEM`J2ba|iMD`vqB^e@_E`{K z)EwUzp-F4Ri_v0cb+q2156=$unm(ji`P6|Nv=s>=#u2JBqkxj`(H%!;w(7z&OU;~c zojD-^GwY(*kM>3_WvXz$Y)rDBL~~LHx*%PV%*k+85uSS#rkGOzO^*`H8#!I`TB|yI zDj=Ch1dS(Ap1=0z@+t^k>Ah3>%q*SLKb1)P_rhH^Hj~ z<8$2|gvl7?kD|vQ!te)PC~O1gJL2X7F~z*4z(EP~Z$2!tN4FGJh?a<$m6Fhki>OE- zECv>2sPeF&X!N!yBncQcnrw-&(Z%^dQ6aGsekmcj*doM>EiZ3)3N|n)^`&!0D5qOu z{f1vRL|-ugr(!HpCBnTHS#|F4Y|f17jnwa@zIj;mqti0by9EZRM&=-7V0|M4La=s~ z{M##5SiDZUc=}@&=a)qMEWBCB?D=r`dh%(@B3e5{R)w;vF6rm37uVm)YPylt^owBu zim#ScJtlH-7^ad$E{q^k@s;<5(Ho}~_lSrz!~~8=jNDu0XiHZ)3gj!Gr)tvphJr^5 zQvx%u65?PcpdOj{k_$zB{RP#WX{r${-j>rAcsgP|wReV|tv@?_E7f=-)p${Szwwo- zEssG1@{1yL4QI7_=vJgD(Ljx%De$efBEVV@WGEyejXm=)1AAgDl4pFZR^Pr*uxBRc zWXrVamDZ`&P{AG{^ch3$k@ym*I_W7H5V^-{t61V+`C=pXxsg=gh+BfYQJzgiwmT=g z11m!O8A(0ya5$V5h!#KixMP7(1I8jjDDXpK`MJ$A)KtzX`Bdkrxapkf`ZG^VkDe*G zm6UTMDd)}2B8QkN9&;$@q$RWo^z+EBV;t|5uTNre0(u$wj$&E`2W7E1U;@xpiU8(0 zsNmwn$AyB_KqrJ=SVco{{8=N&StR5IM5HuaD46R6Bvb%}Zl0#Vr?by&J~J{)Eo~^d zr7yjqFTGeGVxxL1&LHW=$Gc;wAtL-x7$8EdAmDg!Dy1i7l|6x%{+Z&Bzf@(Ak1Yy7 za>Y)*gqk8$yJ`Qzj^4NJbJT48Tg^Xc4(;d_pnfiWEj~e%l#ml@cuvYcu`MDeo`f=b zTFS!XO&59@y4st>8j=}-*O;OLht+sjQ;_m-BGHZVG9HACMCklE86Un7io_`&Vafok zz(RCMV9Ir-bNMr!)1$9e{&nS>`Qp~n(qU`HvY`oO5xk=xBPX(9pIz{95}tz&!2`J|bbBL8B2pa2j}~JkYgwzykm0fqxzX zimIxTv7in%lp$r#P$+}r!uY5YA6{d&pr17;Lt-0(S?FD_7(!=986PJ<=yAFYX`CEh zs2paxQBOXcjvOQ|PUIGjU>t+Y2x>&?p7{!DB;fHmrwM%ExHIC*ziP zcLvRtk9IBUx zGR-|Pw`PtB>S`8MTcKvsc2v!WU%|-ee0jrU{jxTBDu25C)#`6oFXXk%>*qV?N3WQE z;=hm?%4-R&Z&^xdxvAX=`%EGK35MHW)ZEixYwGcPT1=bp@WEzG2f@+%shD;r{xGEO zeRyAqC0g-^50rok7O~KGHG5N(KU6~Y(>40NS<0UpviD|af2N9q^3O`M_vR_DS2W1? z7Ak+4p@1q*H86mfYGA-XID$X!{lf+BUu$_i@AzuM-nUNDzpsUcg2}&4tUDNP827)3 ze|+d3G(gkWKkT|X`})7sI^O=xol`&3F4Q{iehpP!y9|xj-Zr|wkN@w>j)mM$9zJ{U zKWiNY?|=P`o}YgYO&b4j#_{9de;)?C@zb`=&%b@y@!sHHeY}1At}yZbw!U2E)W6j_ z?$mtu*XM7%f7!8E{msGI@oQ-87e3ne@o#_dNv-3Q8}Au@`Pa3Mmy-U^<{xc4hZ>*$ z@^>#id*sWP9lt;Lo8d17Uaxf!$9}tT>rekGO#Gc^oOSHK#Me1qc;EQV4by+T?09SW z>W;g=`_*L_d-G4WoErJRU3UB^?fC!7lmFjZhi3kF4?`_y(Zrtr9RJ}LzI49U(Roq6 z`)gT0hZQns|7ia`K)jBN8yK*AYy$(FdSGD4kM24L1{h>;bMf$hRT%zdx*%)`cAOOi z`nRB&K_LbP{2PopfifiI1?i8h48eHck4orbgNs9Voqn57knOyb=Y>9ldLY4w4iw2) z07OoYIepB_Pzi6taeMSuw6s*b72P%hley>}%sJ?U!-u^A8888k-;?Wc`5&Id@Vwt* zNuOYvPcZebmFokQk)ED9C>?WP8!^6Han$p1gw%mga{ From 282aa58e46e32a0f84c6f6caf30b0dd73d173056 Mon Sep 17 00:00:00 2001 From: Michael Stonis <120685+michaelstonis@users.noreply.github.com> Date: Fri, 9 Oct 2026 18:09:57 -0500 Subject: [PATCH 051/152] feat(forms): read the interactive form field tree, typed fields and XFA detection (#74) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - PdfDocument.AcroForm -> PdfAcroForm: Fields, AllFields, TerminalFields, FindField(s) by name, dictionary or action target, NeedAppearances, SignatureFlags, CalculationOrder, DefaultResources, DefaultAppearance, Quadding, Xfa (ISO 32000-2 §12.7.1-12.7.3). - Field tree read once (iterative, cycle-safe, depth cap 256) and rebuilt when a field dictionary or Kids/Fields array it read changes; FT, Ff, V, DV inherited whole through the field chain (unnamed levels included), DA and Q then from the form (§12.7.4). - Typed fields: text, push button, check box, radio group, combo box, list box, signature, unknown; flags as typed bools plus raw Ff; values decoded; export values through Opt (§12.7.5). Signature Lock typed, V and SV raw (Phase 5). - PdfWidgetAnnotation.Field and PdfTerminalField.Widgets link both ways with the instances PdfPage.Annotations lists (AnnotationIndex); widgets outside the tree resolve through Parent. - XFA: XfaFormPresent / XfaFormDynamic Information diagnostics at open; packets kept raw. - Lenient repairs with diagnostics, strict throws (no Information); corpus files acroform-fields.pdf and acroform-xfa.pdf; FormWalker in the document walker and fuzz target; real-world snapshot updated; conformance 12.7.1-12.7.5 split and filled, Annex K partial. Co-Authored-By: Claude Opus 5.5 --- docs/conformance/iso-32000-2.md | 27 +- src/Broadside/Annotations/AnnotationIndex.cs | 7 +- .../Annotations/PdfWidgetAnnotation.cs | 16 + src/Broadside/Forms/FieldTree.cs | 521 ++++++++++++++++++ src/Broadside/Forms/FormNames.cs | 50 ++ src/Broadside/Forms/PdfAcroForm.cs | 301 ++++++++++ src/Broadside/Forms/PdfButtonField.cs | 314 +++++++++++ src/Broadside/Forms/PdfChoiceField.cs | 289 ++++++++++ src/Broadside/Forms/PdfField.cs | 373 +++++++++++++ src/Broadside/Forms/PdfFieldEnums.cs | 88 +++ src/Broadside/Forms/PdfNonTerminalField.cs | 23 + src/Broadside/Forms/PdfSignatureField.cs | 164 ++++++ src/Broadside/Forms/PdfTerminalField.cs | 62 +++ src/Broadside/Forms/PdfTextField.cs | 76 +++ src/Broadside/Forms/PdfXfaForm.cs | 97 ++++ .../Parsing/DiagnosticCodes.Forms.cs | 47 ++ src/Broadside/PdfActionTarget.cs | 4 +- src/Broadside/PdfDocument.Forms.cs | 83 +++ src/Broadside/PdfDocument.cs | 1 + src/Broadside/PublicAPI.Unshipped.txt | 137 +++++ tests/Broadside.Fuzz/Broadside.Fuzz.csproj | 1 + tests/Broadside.TestSupport/Corpus.cs | 2 + tests/Broadside.TestSupport/DocumentWalker.cs | 3 +- tests/Broadside.TestSupport/FormWalker.cs | 94 ++++ tests/Broadside.Tests/Document/EngineTests.cs | 2 +- ...histograms_match_the_snapshot.verified.txt | 40 +- .../Document/WellFormedCorpusTests.cs | 5 +- .../Files/FilesAndLayersCorpusTests.cs | 2 +- .../Filters/CorpusFilterTests.cs | 2 +- tests/Broadside.Tests/Forms/FieldTreeTests.cs | 121 ++++ .../Broadside.Tests/Forms/FieldValueTests.cs | 169 ++++++ .../Forms/MalformedFormTests.cs | 277 ++++++++++ tests/Broadside.Tests/Forms/XfaFormTests.cs | 70 +++ .../Hosting/DependencyInjectionTests.cs | 2 +- .../LogicalStructure/StructureCorpusTests.cs | 2 +- ...pus_file_names_match_snapshot.verified.txt | 2 + tests/Broadside.Tests/Writing/SaveTests.cs | 2 +- tests/Corpus/README.md | 2 + tests/Corpus/acroform-fields.pdf | Bin 0 -> 4758 bytes tests/Corpus/acroform-xfa.pdf | Bin 0 -> 1716 bytes tests/Corpus/generate.py | 87 +++ 41 files changed, 3537 insertions(+), 28 deletions(-) create mode 100644 src/Broadside/Forms/FieldTree.cs create mode 100644 src/Broadside/Forms/FormNames.cs create mode 100644 src/Broadside/Forms/PdfAcroForm.cs create mode 100644 src/Broadside/Forms/PdfButtonField.cs create mode 100644 src/Broadside/Forms/PdfChoiceField.cs create mode 100644 src/Broadside/Forms/PdfField.cs create mode 100644 src/Broadside/Forms/PdfFieldEnums.cs create mode 100644 src/Broadside/Forms/PdfNonTerminalField.cs create mode 100644 src/Broadside/Forms/PdfSignatureField.cs create mode 100644 src/Broadside/Forms/PdfTerminalField.cs create mode 100644 src/Broadside/Forms/PdfTextField.cs create mode 100644 src/Broadside/Forms/PdfXfaForm.cs create mode 100644 src/Broadside/Parsing/DiagnosticCodes.Forms.cs create mode 100644 src/Broadside/PdfDocument.Forms.cs create mode 100644 tests/Broadside.TestSupport/FormWalker.cs create mode 100644 tests/Broadside.Tests/Forms/FieldTreeTests.cs create mode 100644 tests/Broadside.Tests/Forms/FieldValueTests.cs create mode 100644 tests/Broadside.Tests/Forms/MalformedFormTests.cs create mode 100644 tests/Broadside.Tests/Forms/XfaFormTests.cs create mode 100644 tests/Corpus/acroform-fields.pdf create mode 100644 tests/Corpus/acroform-xfa.pdf diff --git a/docs/conformance/iso-32000-2.md b/docs/conformance/iso-32000-2.md index cac731e6..47e021bb 100644 --- a/docs/conformance/iso-32000-2.md +++ b/docs/conformance/iso-32000-2.md @@ -175,24 +175,31 @@ Clause numbers at the second level; split rows to the third level as clauses are | 12.5.6.16 | Sound annotations | done | `PdfSoundAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Deprecated in PDF 2.0: Table 188 exposed as data, never played | | 12.5.6.17 | Movie annotations | done | `PdfMovieAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Deprecated in PDF 2.0: Table 189 exposed as data; A is the activation (bool or dict), not an action | | 12.5.6.18 | Screen annotations | done | `PdfScreenAnnotation`, `PdfAppearanceCharacteristics`, `PdfAnnotationAdditionalActions` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed`, `Broadside.Tests.Annotations.AnnotationSubtypeTests.Screen_and_widget_annotations_expose_their_trigger_event_actions` | Table 190 T, MK, A, AA (Table 197 through #73's `GetAnnotationAdditionalActions`) | -| 12.5.6.19 | Widget annotations | partial | `PdfWidgetAnnotation`, `PdfAppearanceCharacteristics`, `PdfHighlightMode`, `PdfAnnotationAdditionalActions` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed`, `Broadside.Tests.Annotations.AnnotationSubtypeTests.Screen_and_widget_annotations_expose_their_trigger_event_actions` | Tables 191 and 192 (H with T read as P, MK, A, AA through #73's `GetAnnotationAdditionalActions`, Parent raw); field entries and widget/field linking are #74's | +| 12.5.6.19 | Widget annotations | partial | `PdfWidgetAnnotation`, `PdfAppearanceCharacteristics`, `PdfHighlightMode`, `PdfAnnotationAdditionalActions` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed`, `Broadside.Tests.Annotations.AnnotationSubtypeTests.Screen_and_widget_annotations_expose_their_trigger_event_actions`, `Broadside.Tests.Forms.FieldTreeTests.Terminal_fields_and_the_widgets_on_the_pages_link_both_ways_to_the_same_instances` | Tables 191 and 192 (H with T read as P, MK, A, AA through #73's `GetAnnotationAdditionalActions`, Parent raw); the widget's field is `PdfWidgetAnnotation.Field` (#74, 12.7.2) | | 12.5.6.20 | Printer's mark annotations | done | `PdfPrinterMarkAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | MN (§14.11.3, Table 398) | | 12.5.6.21 | Trap network annotations | done | `PdfTrapNetAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed`, `Broadside.Tests.Annotations.MalformedAnnotationTests.A_trap_network_that_is_not_the_last_annotation_is_recorded` | Deprecated in PDF 2.0: Table 403 exposed as data; `TrapNetPlacementInvalid` | | 12.5.6.22 | Watermark annotations | done | `PdfWatermarkAnnotation`, `PdfFixedPrint` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Tables 193 and 194; applying FixedPrint is the renderer's | | 12.5.6.23 | Redaction annotations | done | `PdfRedactAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Table 195; reading never applies the redaction | | 12.5.6.24 | Projection annotations | done | `PdfProjectionAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Annotations_subtypes_pdf_maps_each_standard_subtype_to_its_class_and_an_unknown_one_to_the_generic_class`, `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | Tables 166 and 172 only | | 12.5.6.25 | 3D and RichMedia annotations | partial | `Pdf3DAnnotation`, `PdfRichMediaAnnotation` | `Broadside.Tests.Annotations.AnnotationSubtypeTests.Subtype_specific_entries_are_typed` | parse-and-preserve, CLAUDE.md out of scope: Table 309 and Table 333 entries exposed as stored, never rendered or played | -| 12.6.1 | General | n/a | | | Introductory text; the A entries it lists are read by `PdfOutlineItem.Action` and `PdfDocument.GetAction` (link, screen and widget annotations until #71/#74 type them) | +| 12.6.1 | General | n/a | | | Introductory text; the A entries it lists are read by `PdfOutlineItem.Action` and `PdfDocument.GetAction` (link, screen and widget annotations, typed by #71; field triggers by #74) | | 12.6.2 | Action dictionaries | done | `PdfAction`, `PdfActionKind`, `PdfUnknownAction` | `Broadside.Tests.Actions.ActionTypeTests.Actions_all_pdf_types_each_table_201_action_in_table_order`, `Broadside.Tests.Actions.ActionTypeTests.An_action_type_the_table_does_not_list_is_kept_as_an_unknown_action`, `Broadside.Tests.Actions.TriggerEventTests.The_action_tree_is_walked_depth_first_in_execution_order`, `Broadside.Tests.Actions.TriggerEventTests.A_cycle_of_next_actions_is_cut_with_information_and_a_shared_action_is_yielded_once`, `Broadside.Tests.Actions.TriggerEventTests.A_next_entry_with_elements_that_are_not_actions_skips_them_with_a_warning`, `Broadside.Tests.Actions.PreservedActionTests.Reading_every_action_changes_no_object` | Table 196: S (missing -> `ActionInvalid`, unknown -> `PdfUnknownAction`), Next as one dictionary or an array (`PdfAction.Next`, one level, live; bad elements `ActionNextInvalid`); `EnumerateActionTree` walks the tree depth first in execution order, iteratively, each dictionary once, cycles cut with `ActionCycle` (Information: Note 1 calls them anomalous, not invalid), depth cap 64 (`ActionTreeTooDeep`). Type Action is optional and never added | -| 12.6.3 | Trigger events | done | `PdfAdditionalActions`, `PdfAnnotationAdditionalActions`, `PdfPageAdditionalActions`, `PdfFieldAdditionalActions`, `PdfDocumentAdditionalActions` | `Broadside.Tests.Actions.TriggerEventTests.The_catalog_page_annotation_and_field_triggers_are_typed_by_their_owner`, `Broadside.Tests.Actions.TriggerEventTests.An_additional_actions_entry_that_is_not_a_dictionary_reads_as_none_with_a_warning`, `Broadside.Tests.Actions.TriggerEventTests.Documents_without_actions_have_no_open_action_and_no_additional_actions` | Tables 197-200 typed by owner (C is close for a page, calculate for a field); catalog `PdfDocument.AdditionalActions` and `PdfPage.AdditionalActions`; annotation and field AA through `PdfDocument.GetAnnotationAdditionalActions` / `GetFieldAdditionalActions` until #71/#74 wire their views; `Actions` lists unknown triggers too. Never created on read. Event ordering is viewer behaviour, documented only | +| 12.6.3 | Trigger events | done | `PdfAdditionalActions`, `PdfAnnotationAdditionalActions`, `PdfPageAdditionalActions`, `PdfFieldAdditionalActions`, `PdfDocumentAdditionalActions` | `Broadside.Tests.Actions.TriggerEventTests.The_catalog_page_annotation_and_field_triggers_are_typed_by_their_owner`, `Broadside.Tests.Actions.TriggerEventTests.An_additional_actions_entry_that_is_not_a_dictionary_reads_as_none_with_a_warning`, `Broadside.Tests.Actions.TriggerEventTests.Documents_without_actions_have_no_open_action_and_no_additional_actions` | Tables 197-200 typed by owner (C is close for a page, calculate for a field); catalog `PdfDocument.AdditionalActions` and `PdfPage.AdditionalActions`; annotation and field AA through `PdfDocument.GetAnnotationAdditionalActions` / `GetFieldAdditionalActions` and wired to `PdfWidgetAnnotation.AdditionalActions` (#71) and `PdfField.AdditionalActions` (#74); + `Actions` lists unknown triggers too. Never created on read. Event ordering is viewer behaviour, documented only | | 12.6.4 | Action types | done | `PdfActionKind`, `PdfGoToAction`, `PdfRemoteGoToAction`, `PdfEmbeddedGoToAction`, `PdfEmbeddedTarget`, `PdfGoToDocumentPartAction`, `PdfLaunchAction`, `PdfWindowsLaunchParameters`, `PdfThreadAction`, `PdfUriAction`, `PdfSoundAction`, `PdfMovieAction`, `PdfHideAction`, `PdfActionTarget`, `PdfNamedAction`, `PdfSetOcgStateAction`, `PdfOcgStateChange`, `PdfRenditionAction`, `PdfTransitionAction`, `PdfGoTo3DViewAction`, `PdfJavaScriptAction`, `PdfRichMediaExecuteAction`, `PdfRichMediaCommand` | `Broadside.Tests.Actions.ActionEntryTests.Go_to_actions_read_their_local_remote_and_embedded_destinations`, `Broadside.Tests.Actions.ActionEntryTests.Launch_and_thread_actions_read_their_files_platform_parameters_and_article_indexes`, `Broadside.Tests.Actions.ActionEntryTests.A_relative_uri_is_resolved_against_the_catalog_base_without_being_fetched`, `Broadside.Tests.Actions.ActionEntryTests.Multimedia_actions_are_exposed_as_data_with_their_defaults`, `Broadside.Tests.Actions.ActionEntryTests.Scripts_and_multimedia_are_recorded_as_out_of_scope_information_and_never_as_warnings`, `Broadside.Tests.Actions.ActionEntryTests.Hide_named_and_transition_actions_read_their_targets_names_and_transitions`, `Broadside.Tests.Actions.ActionEntryTests.A_set_ocg_state_action_lists_its_changes_and_applies_them_to_a_state_snapshot`, `Broadside.Tests.Actions.ActionEntryTests.A_javascript_action_reads_its_script_from_a_stream_and_is_never_run`, `Broadside.Tests.Actions.PreservedActionTests.Scripts_sounds_movies_renditions_and_rich_media_read_as_data_in_their_stored_forms`, `Broadside.Tests.Actions.PreservedActionTests.Saving_after_reading_every_action_keeps_their_bytes_and_their_values`, `Broadside.Tests.Actions.MalformedActionTests.An_action_missing_a_required_entry_is_read_with_a_warning`, `Broadside.Tests.Actions.MalformedActionTests.Entries_of_the_wrong_type_read_as_absent_or_default_with_a_warning`, `Broadside.Tests.Actions.MalformedActionTests.A_uri_that_is_not_utf8_or_not_a_string_is_read_with_a_warning`, `Broadside.Tests.Actions.MalformedActionTests.A_cycle_of_embedded_target_dictionaries_is_refused_with_a_warning`, `Broadside.Tests.Actions.MalformedActionTests.Strict_mode_throws_when_an_invalid_action_is_read_not_when_the_document_opens`, `Broadside.Tests.Actions.MalformedActionTests.Strict_mode_records_out_of_scope_scripts_without_throwing` | 12.6.4.1-12.6.4.18, every Table 201 type typed (corpus `actions-all.pdf`). Remote/embedded destinations are remote (page numbers of the other file, never resolved here); GoToE target dictionaries (Table 205) with cycle refusal (`ActionTargetCycle`); file entries are `PdfFileSpecification` (#76); SetOCGState applies to a `PdfOptionalContentState` snapshot without changing the document; URI decoded as UTF-8 with UTF-16/PDFDocEncoding/name repairs (`UriInvalid`) and `ResolveUri` against the catalog Base. Sound, Movie, Rendition, GoTo3DView, JavaScript and RichMediaExecute are typed and preserved (byte-identical save of `actions-preserved.pdf`), not executed (out of scope): `ActionOutOfScope` Information. Nothing is ever performed. Missing required entries `ActionInvalid`, wrong types `ActionEntryInvalid`, lazily at read | -| 12.7.1 | General | not started | | | | -| 12.7.2 | Interactive Forms | not started | | | | -| 12.7.3 | Interactive form dictionary | not started | | | | -| 12.7.4 | Field dictionaries | not started | | | Field AA (Table 199) is typed by `PdfDocument.GetFieldAdditionalActions` (#73, 12.6.3); #74 wires it to fields | -| 12.7.5 | Field types | not started | | | | +| 12.7.1 | General | done | `PdfAcroForm`, `PdfDocument` | `Broadside.Tests.Forms.FieldTreeTests.Acroform_fields_pdf_reads_the_field_hierarchy_with_fully_qualified_names_and_typed_fields`, `Broadside.Tests.Forms.FieldTreeTests.A_document_without_an_acroform_has_no_form_and_its_widgets_no_field` | One global form per document: `PdfDocument.AcroForm` (null without a catalog AcroForm dictionary; a non-dictionary records `AcroFormInvalid`). Non-interactive forms are 12.7.9 | +| 12.7.2 | Interactive Forms | done | `PdfField`, `PdfNonTerminalField`, `PdfTerminalField`, `PdfWidgetAnnotation`, `PdfAcroForm` | `Broadside.Tests.Forms.FieldTreeTests.Acroform_fields_pdf_reads_the_field_hierarchy_with_fully_qualified_names_and_typed_fields`, `Broadside.Tests.Forms.FieldTreeTests.Terminal_fields_and_the_widgets_on_the_pages_link_both_ways_to_the_same_instances`, `Broadside.Tests.Forms.FieldTreeTests.Concurrent_readers_get_the_same_field_and_widget_instances`, `Broadside.Tests.Forms.FieldTreeTests.A_mutation_of_the_field_tree_is_seen_on_the_next_read`, `Broadside.Tests.Forms.MalformedFormTests.A_malformed_field_tree_reads_what_it_can_with_exactly_the_documented_diagnostics`, `Broadside.Tests.Forms.MalformedFormTests.Strict_mode_throws_from_the_field_tree_not_from_open`, `Broadside.Tests.Forms.MalformedFormTests.A_deviation_in_the_field_tree_is_recorded_once_when_the_tree_is_read` | Terminal vs non-terminal by the kids that have T; a field merged with its single widget; `PdfTerminalField.Widgets` and `PdfWidgetAnnotation.Field` give the same instances as `PdfPage.Annotations` (#71 `AnnotationIndex`). The tree is a snapshot rebuilt when a field dictionary or Kids/Fields array it read changes (container `Version`). Iterative walk, each dictionary once (`FieldTreeCycle`), depth cap 256 (`FieldTreeTooDeep`); mixed Kids (`FieldKidsMixed`), missing/mismatched Parent (structure wins), widgets outside the tree resolved through Parent (`WidgetNotInFieldTree`). Corpus `acroform-fields.pdf` | +| 12.7.3 | Interactive form dictionary | done | `PdfAcroForm`, `PdfSignatureFlags`, `PdfXfaForm` | `Broadside.Tests.Forms.FieldValueTests.The_interactive_form_dictionary_exposes_its_defaults_resources_flags_and_calculation_order`, `Broadside.Tests.Forms.MalformedFormTests.A_deviation_in_the_field_tree_is_recorded_once_when_the_tree_is_read`, `Broadside.Tests.Forms.XfaFormTests.Opening_a_form_with_an_xfa_resource_records_an_information_diagnostic_and_exposes_the_packets` | Table 224: Fields (missing/not an array `AcroFormFieldsMissing`, except an empty dictionary), NeedAppearances (reported only, never acted on), SigFlags (Table 225), CO as fields, DR raw, DA as bytes (not parsed: Phase 4), Q, XFA (Annex K row). Wrong types `AcroFormEntryInvalid` | +| 12.7.4.1 | General | done | `PdfField`, `PdfFieldType`, `PdfFieldKind`, `PdfFieldAdditionalActions` | `Broadside.Tests.Forms.FieldValueTests.Ft_ff_v_da_and_q_are_inherited_from_the_nearest_ancestor_and_da_and_q_then_from_the_form`, `Broadside.Tests.Forms.FieldValueTests.A_text_field_reads_its_names_value_default_length_and_trigger_actions`, `Broadside.Tests.Forms.MalformedFormTests.A_malformed_field_entry_reads_as_its_default_with_one_diagnostic_when_read`, `Broadside.Tests.Forms.MalformedFormTests.A_deviation_in_the_field_tree_is_recorded_once_when_the_tree_is_read`, `Broadside.Tests.Forms.MalformedFormTests.An_unnamed_level_is_transparent_for_names_but_its_entries_are_inherited`, `Broadside.Tests.Forms.FieldValueTests.Reading_every_form_entry_records_nothing_and_writes_nothing` | Table 226 and 227: FT, Ff, V, DV inherited whole from the nearest dictionary (unnamed levels included), never bit-merged; Ff as raw `Flags` plus typed bools (negative/real/reserved bits `FieldFlagsInvalid`); V/DV raw as `ValueObject`/`DefaultValueObject`, decoded by each field class; TU, TM own; AA own through #73 `GetFieldAdditionalActions`. Indirect-object rule `FieldNotIndirect`; missing FT `FieldTypeMissing` (`PdfUnknownField`). Inheritance is unlimited in range except the 256 depth cap | +| 12.7.4.2 | Field names | done | `PdfField`, `PdfAcroForm`, `PdfActionTarget` | `Broadside.Tests.Forms.FieldTreeTests.Acroform_fields_pdf_reads_the_field_hierarchy_with_fully_qualified_names_and_typed_fields`, `Broadside.Tests.Forms.MalformedFormTests.A_malformed_field_tree_reads_what_it_can_with_exactly_the_documented_diagnostics`, `Broadside.Tests.Forms.MalformedFormTests.An_unnamed_level_is_transparent_for_names_but_its_entries_are_inherited`, `Broadside.Tests.Forms.FieldValueTests.A_push_button_has_no_value_and_its_widget_action_names_fields_that_resolve_through_the_form` | Partial and fully qualified names (text strings); T-less dictionaries are widgets, or with Kids transparent levels (`FieldNameMissing`); a period in T `FieldNameHasPeriod`; repeated names kept and all returned by `FindFields`, `FieldNameDuplicateInconsistent` only when FT, V or DV differ. Action targets (hide, submit-form, reset-form Fields) resolve through `PdfAcroForm.FindFields(PdfActionTarget)` | +| 12.7.4.3 | Variable text | done | `PdfField`, `PdfAcroForm` | `Broadside.Tests.Forms.FieldValueTests.Ft_ff_v_da_and_q_are_inherited_from_the_nearest_ancestor_and_da_and_q_then_from_the_form`, `Broadside.Tests.Forms.FieldValueTests.Choice_fields_read_options_values_and_selected_indices`, `Broadside.Tests.Forms.MalformedFormTests.A_malformed_field_entry_reads_as_its_default_with_one_diagnostic_when_read` | Table 228: DA (field chain, then AcroForm; missing on a text/choice field `DefaultAppearanceMissing`), Q (field chain, then AcroForm, then 0), DS and RV own. DA is not parsed and no appearance is generated (Phase 4) | +| 12.7.5.1 | General | n/a | | | Introductory text | +| 12.7.5.2 | Button fields | done | `PdfButtonField`, `PdfPushButtonField`, `PdfToggleButtonField`, `PdfCheckBoxField`, `PdfRadioButtonField` | `Broadside.Tests.Forms.FieldValueTests.A_check_box_reads_its_state_on_state_and_widget_states_across_pages`, `Broadside.Tests.Forms.FieldValueTests.A_radio_group_with_index_named_states_maps_its_value_to_the_export_value_of_the_selected_widget`, `Broadside.Tests.Forms.FieldValueTests.A_push_button_has_no_value_and_its_widget_action_names_fields_that_resolve_through_the_form`, `Broadside.Tests.Forms.MalformedFormTests.A_malformed_field_entry_reads_as_its_default_with_one_diagnostic_when_read`, `Broadside.Tests.Forms.MalformedFormTests.A_deviation_in_the_field_tree_is_recorded_once_when_the_tree_is_read` | 12.7.5.2.1-12.7.5.2.4, Tables 229-230: kind from inherited Ff (both Pushbutton and Radio: push button, `ButtonFlagsConflict`); value as a name (default Off), on states from each widget's N subdictionary, export values through Opt (inheritable; index-named states, duplicates), `GetAppearanceState` (AS wins over V); `ButtonValueStateMismatch`, `ButtonValueUnknownState`, `ButtonStatesAmbiguous`, `ButtonOnStateMissing`, `ButtonOptLengthMismatch` | +| 12.7.5.3 | Text fields | done | `PdfTextField` | `Broadside.Tests.Forms.FieldValueTests.A_text_field_reads_its_names_value_default_length_and_trigger_actions`, `Broadside.Tests.Forms.FieldValueTests.Ft_ff_v_da_and_q_are_inherited_from_the_nearest_ancestor_and_da_and_q_then_from_the_form`, `Broadside.Tests.Forms.MalformedFormTests.A_malformed_field_entry_reads_as_its_default_with_one_diagnostic_when_read` | Tables 231-232: V as text string or text stream, MaxLen inheritable, every flag typed (RichText bit 26 vs RadiosInUnison); Comb without MaxLen or with Multiline/Password/FileSelect `TextCombInvalid`. A password value is returned as stored | +| 12.7.5.4 | Choice fields | done | `PdfChoiceField`, `PdfComboBoxField`, `PdfListBoxField`, `PdfChoiceOption` | `Broadside.Tests.Forms.FieldValueTests.Choice_fields_read_options_values_and_selected_indices`, `Broadside.Tests.Forms.MalformedFormTests.A_choice_option_list_on_an_ancestor_is_used_with_a_diagnostic`, `Broadside.Tests.Forms.MalformedFormTests.A_choice_value_given_as_the_display_text_matches_and_i_tells_duplicates_apart`, `Broadside.Tests.Forms.MalformedFormTests.A_malformed_field_entry_reads_as_its_default_with_one_diagnostic_when_read` | Tables 233-234: Opt (own; an ancestor's with `ChoiceOptionsInherited`; bad elements kept as empty options, `ChoiceOptionInvalid`), V as one string or an array (an empty string is no selection), selected indices matched on export then display text, I used only when it agrees with V (V wins, p.558), TI, flags. A value no option has `ChoiceValueNotInOptions` unless an editable combo box | +| 12.7.5.5 | Signature fields | partial | `PdfSignatureField`, `PdfSignatureFieldLock`, `PdfSignatureFieldLockAction` | `Broadside.Tests.Forms.FieldValueTests.A_signature_field_exposes_its_lock_and_seed_value_and_is_invisible_and_unsigned`, `Broadside.Tests.Forms.MalformedFormTests.A_malformed_field_tree_reads_what_it_can_with_exactly_the_documented_diagnostics`, `Broadside.Tests.Forms.MalformedFormTests.A_malformed_field_entry_reads_as_its_default_with_one_diagnostic_when_read` | Tables 235-236: V raw as `SignatureDictionary` (Table 255 is Phase 5), visibility rule (zero Rect, Hidden/NoView), Lock typed (Action, Fields, P), SV raw (Table 237-238 typed in Phase 5); several widgets `SignatureFieldMultipleWidgets`, direct Lock/SV `SignatureFieldDictNotIndirect`. Missing: seed value and certificate seed value views, signature validation (Phase 5) | | 12.7.6.1 | General | n/a | | | Introductory text | -| 12.7.6.2 | Submit-form action | done | `PdfSubmitFormAction`, `PdfSubmitFormFlags`, `PdfActionTarget` | `Broadside.Tests.Actions.ActionEntryTests.Form_actions_read_their_url_fields_flags_and_character_set`, `Broadside.Tests.Actions.MalformedActionTests.An_action_missing_a_required_entry_is_read_with_a_warning` | Tables 239-240: F (URL file specification, `PdfFileSpecification.IsUrl`), Fields (field dictionaries and names; names unresolved until #74), Flags (bits 1-12 and 14), CharSet (2.0). Flags and CharSet read from the action only ("inheritable" names no parent). Never submitted | +| 12.7.6.2 | Submit-form action | done | `PdfSubmitFormAction`, `PdfSubmitFormFlags`, `PdfActionTarget` | `Broadside.Tests.Actions.ActionEntryTests.Form_actions_read_their_url_fields_flags_and_character_set`, `Broadside.Tests.Actions.MalformedActionTests.An_action_missing_a_required_entry_is_read_with_a_warning` | Tables 239-240: F (URL file specification, `PdfFileSpecification.IsUrl`), Fields (field dictionaries and names; names resolved by `PdfAcroForm.FindFields(PdfActionTarget)`, #74), Flags (bits 1-12 and 14), CharSet (2.0). Flags and CharSet read from the action only ("inheritable" names no parent). Never submitted | | 12.7.6.3 | Reset-form action | done | `PdfResetFormAction`, `PdfResetFormFlags`, `PdfActionTarget` | `Broadside.Tests.Actions.ActionEntryTests.Form_actions_read_their_url_fields_flags_and_character_set`, `Broadside.Tests.Actions.MalformedActionTests.An_action_missing_a_required_entry_is_read_with_a_warning` | Tables 241-242. Never performed | | 12.7.6.4 | Import-data action | done | `PdfImportDataAction` | `Broadside.Tests.Actions.ActionEntryTests.Form_actions_read_their_url_fields_flags_and_character_set`, `Broadside.Tests.Actions.MalformedActionTests.An_action_missing_a_required_entry_is_read_with_a_warning` | Table 243: F as `PdfFileSpecification`. Never imported | | 12.7.7 | Named pages | not started | | | | @@ -281,7 +288,7 @@ Clause numbers at the second level; split rows to the third level as clauses are | Annex H | Example PDF files | not started | | | | | Annex I | PDF versions and compatibility | not started | | | | | Annex J | XObject comparison | not started | | | | -| Annex K | XFA forms | n/a | | | XFA is parse-and-preserve (CLAUDE.md out of scope) | +| Annex K | XFA forms | partial | `PdfXfaForm`, `PdfXfaPacket` | `Broadside.Tests.Forms.XfaFormTests.Opening_a_form_with_an_xfa_resource_records_an_information_diagnostic_and_exposes_the_packets`, `Broadside.Tests.Forms.XfaFormTests.Strict_mode_opens_an_xfa_form_because_information_is_never_thrown`, `Broadside.Tests.Forms.XfaFormTests.A_dynamic_xfa_form_is_distinguished_by_the_catalogs_needs_rendering`, `Broadside.Tests.Forms.XfaFormTests.A_malformed_packet_array_skips_the_bad_pairs_with_a_warning` | Parse-and-preserve, detection only (CLAUDE.md out of scope): an XFA stream or packet array is exposed as raw packets and recorded at open as `XfaFormPresent` (Information, never thrown in strict mode), a dynamic form (catalog NeedsRendering) as `XfaFormDynamic`; malformed packet arrays `XfaPacketsInvalid`. The XDP is never parsed or rendered. Corpus `acroform-xfa.pdf` | | Annex L | Parent-child relationships between the standard structure elements | not started | | | | | Annex M | Differences between the standard structure namespaces | not started | | | | | Annex N | Best practice for halftones | not started | | | | diff --git a/src/Broadside/Annotations/AnnotationIndex.cs b/src/Broadside/Annotations/AnnotationIndex.cs index 87feba0a..e047cdf6 100644 --- a/src/Broadside/Annotations/AnnotationIndex.cs +++ b/src/Broadside/Annotations/AnnotationIndex.cs @@ -67,9 +67,10 @@ public PdfAnnotation GetOrCreate(CosDictionary dictionary, CosReference? referen /// /// Returns the annotation names, as the page that holds it lists it: the page of - /// first, then any page; an annotation no page holds gets a view without a page. when the value is not a dictionary. + /// first (when given), then any page; an annotation no page holds gets a view without a page. when the value + /// is not a dictionary. /// - public PdfAnnotation? Find(CosObject? value, PdfAnnotation from) + public PdfAnnotation? Find(CosObject? value, PdfAnnotation? from) { if (_document.Resolve(value) is not CosDictionary dictionary) { @@ -81,7 +82,7 @@ public PdfAnnotation GetOrCreate(CosDictionary dictionary, CosReference? referen return known; } - if (from.Page is { } page) + if (from?.Page is { } page) { _ = page.Annotations; if (TryGetCurrent(dictionary) is { } onPage) diff --git a/src/Broadside/Annotations/PdfWidgetAnnotation.cs b/src/Broadside/Annotations/PdfWidgetAnnotation.cs index 9cd6d940..840c4df8 100644 --- a/src/Broadside/Annotations/PdfWidgetAnnotation.cs +++ b/src/Broadside/Annotations/PdfWidgetAnnotation.cs @@ -1,3 +1,4 @@ +using Broadside.Forms; using Broadside.Objects; namespace Broadside.Annotations; @@ -31,4 +32,19 @@ internal PdfWidgetAnnotation(PdfDocument document, CosDictionary dictionary, Cos /// Gets the field dictionary this widget is a kid of (Parent), as stored, or ; required when the field has several widgets. /// ISO 32000-2 §12.5.6.19, Table 191, and §12.7.4. public CosDictionary? Parent => ReadDictionary(AnnotationNames.Parent); + + /// + /// Gets the terminal field the widget belongs to: the field whose Kids lists it, or the field merged with it; + /// when the document has no interactive form or the widget belongs to no field. The same instance the form's field tree holds, whose + /// lists this widget. + /// + /// + /// ISO 32000-2 §12.7.2 and §12.5.6.19. A widget the tree from Fields does not reach is resolved through its Parent + /// chain with a WidgetNotInFieldTree diagnostic. + /// + public PdfTerminalField? Field => Document.AcroForm?.FieldOf(this); + + /// Whether 's subtype (a name, or a string read as one) is Widget. + internal static bool IsWidget(PdfDocument document, CosDictionary dictionary) => + ReadSubtype(document, dictionary, out _) is { } subtype && string.Equals(subtype.Value, "Widget", StringComparison.Ordinal); } diff --git a/src/Broadside/Forms/FieldTree.cs b/src/Broadside/Forms/FieldTree.cs new file mode 100644 index 00000000..75e52444 --- /dev/null +++ b/src/Broadside/Forms/FieldTree.cs @@ -0,0 +1,521 @@ +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Forms; + +/// +/// A snapshot of an interactive form's field hierarchy: the field views, their names, and which field each widget dictionary belongs +/// to. Built once from the Fields array (or, for a widget no field lists, from the top of its Parent chain) and rebuilt +/// when a dictionary or array it read has changed. +/// +/// +/// ISO 32000-2 §12.7.2 and §12.7.4. The walk is iterative and visits each dictionary once: a dictionary met again (a Kids cycle +/// or a field under two parents) is skipped with FieldTreeCycle, and nesting beyond is cut with +/// FieldTreeTooDeep. A dictionary with T is a field; one without is a widget, or, when it has Kids, an unnamed +/// level whose kids belong to the field above it (§12.7.4.2). Nothing is written to the COS objects. +/// +internal sealed class FieldTree +{ + /// The deepest nesting of field dictionaries read; deeper ones are cut with a diagnostic. + public const int MaxDepth = 256; + + private readonly List<(CosObject Container, int Version)> _tracked = []; + private readonly CosObject? _fieldsEntry; + private readonly Dictionary _orphans = new(ReferenceEqualityComparer.Instance); + + private FieldTree(CosObject? fieldsEntry) => _fieldsEntry = fieldsEntry; + + /// Gets the root fields, in order. + public List Roots { get; } = []; + + /// Gets every field, depth first in Kids order. + public List All { get; } = []; + + /// Gets the fields by fully qualified name (several when names repeat). + public Dictionary> ByName { get; } = new(StringComparer.Ordinal); + + /// Gets the field each field dictionary is. + public Dictionary ByDictionary { get; } = new(ReferenceEqualityComparer.Instance); + + /// Gets the terminal field each widget dictionary belongs to (a merged dictionary maps to itself). + public Dictionary ByWidget { get; } = new(ReferenceEqualityComparer.Instance); + + /// The entry, resolved; when absent or a reference to nothing. + public static CosObject? Get(PdfDocument document, CosDictionary dictionary, CosName key) => + dictionary.TryGetValue(key, out CosObject? value) && document.Resolve(value) is not CosNull and var resolved ? resolved : null; + + /// Builds the tree of from its Fields array. + public static FieldTree Build(PdfAcroForm form) + { + PdfDocument document = form.Document; + form.Dictionary.TryGetValue(FormNames.Fields, out CosObject? entry); + var tree = new FieldTree(entry); + var builder = new Builder(form, tree); + switch (document.Resolve(entry)) + { + case CosArray fields: + tree.Track(fields); + builder.AddRoots(fields); + break; + case CosNull when form.Dictionary.Count == 0: + // An empty interactive form dictionary is how many writers say "no form"; it is read as a form without fields. + break; + case CosNull: + form.Report(DiagnosticCodes.AcroFormFieldsMissing, "The interactive form dictionary has no Fields array, which Table 224 requires; the form has no fields."); + break; + default: + form.Report(DiagnosticCodes.AcroFormFieldsMissing, "The interactive form dictionary's Fields entry shall be an array; the form has no fields."); + break; + } + + builder.Run(); + builder.CheckDuplicates(); + return tree; + } + + /// Whether nothing the tree read has changed since it was built. + public bool IsCurrent(CosDictionary acroForm) + { + acroForm.TryGetValue(FormNames.Fields, out CosObject? entry); + if (!ReferenceEquals(entry, _fieldsEntry)) + { + return false; + } + + foreach ((CosObject container, int version) in _tracked) + { + int now = container switch + { + CosDictionary dictionary => dictionary.Version, + CosArray array => array.Version, + _ => version, + }; + if (now != version) + { + return false; + } + } + + return true; + } + + /// + /// Finds the field a widget belongs to when the tree does not list it: its own dictionary when it has T, else the first + /// dictionary with T up its Parent chain; a field outside the tree is read from the top of that chain. + /// + public PdfTerminalField? FindOutside(PdfAcroForm form, CosDictionary widget, CosReference? widgetReference) + { + PdfDocument document = form.Document; + CosDictionary? candidate = widget; + CosReference? reference = widgetReference; + var seen = new HashSet(ReferenceEqualityComparer.Instance); + while (candidate is not null && !candidate.ContainsKey(FormNames.T)) + { + if (!seen.Add(candidate) || seen.Count > MaxDepth) + { + return null; + } + + reference = candidate.TryGetValue(FormNames.Parent, out CosObject? up) ? up as CosReference : null; + candidate = Get(document, candidate, FormNames.Parent) as CosDictionary; + } + + if (candidate is null) + { + return null; + } + + if (ByDictionary.TryGetValue(candidate, out PdfField? listed)) + { + return listed as PdfTerminalField; + } + + CosDictionary top = candidate; + CosReference? candidateReference = reference; + seen.Clear(); + while (Get(document, top, FormNames.Parent) is CosDictionary parent && seen.Add(top) && seen.Count <= MaxDepth) + { + reference = top[FormNames.Parent] as CosReference; + top = parent; + } + + if (!top.ContainsKey(FormNames.T)) + { + // An unnamed dictionary at the top: read from the named field below it. + (top, reference) = (candidate, candidateReference); + } + + + lock (_orphans) + { + if (!_orphans.TryGetValue(top, out FieldTree? orphan)) + { + orphan = new FieldTree(fieldsEntry: null); + var builder = new Builder(form, orphan); + builder.AddOrphanRoot(top, reference); + builder.Run(); + _orphans[top] = orphan; + } + + return orphan.ByWidget.GetValueOrDefault(widget) ?? orphan.ByDictionary.GetValueOrDefault(candidate) as PdfTerminalField; + } + } + + private void Track(CosObject container) => _tracked.Add((container, container switch + { + CosDictionary dictionary => dictionary.Version, + CosArray array => array.Version, + _ => 0, + })); + + /// A dictionary waiting to be read as a field: how it was reached, under which field, through which unnamed levels. + private readonly record struct Pending(CosObject Element, CosDictionary Dictionary, PdfNonTerminalField? Parent, CosDictionary[] Intermediates, int Depth); + + /// A kid of a field after unnamed levels are expanded. + private readonly record struct Kid(CosObject Element, CosDictionary Dictionary, CosDictionary[] Intermediates); + + private sealed class Builder(PdfAcroForm form, FieldTree tree) + { + private readonly PdfDocument _document = form.Document; + private readonly HashSet _visited = new(ReferenceEqualityComparer.Instance); + private readonly Stack _pending = new(); + private readonly List _roots = []; + + public void AddRoots(CosArray fields) + { + for (int index = 0; index < fields.Count; index++) + { + CosObject element = fields[index]; + if (_document.Resolve(element) is not CosDictionary dictionary) + { + form.Report(DiagnosticCodes.FieldReferenceInvalid, $"Element {index} of the interactive form's Fields array is not a field dictionary; it is skipped."); + continue; + } + + if (element is not CosReference) + { + form.Report(DiagnosticCodes.FieldNotIndirect, $"Element {index} of the interactive form's Fields array is a direct dictionary; field dictionaries shall be indirect objects (§12.7.4.1). It is read anyway."); + } + + if (!_visited.Add(dictionary)) + { + Report(DiagnosticCodes.FieldTreeCycle, "The field dictionary appears more than once in the field tree; only its first occurrence is read.", element, null); + continue; + } + + if (Get(_document, dictionary, FormNames.Parent) is not null) + { + Report(DiagnosticCodes.FieldNotRoot, "A field in the interactive form's Fields array has a Parent entry, but Fields shall hold only root fields (Table 224); it is read as a root.", element, null); + } + + if (dictionary.ContainsKey(FormNames.T)) + { + _roots.Add(new Pending(element, dictionary, null, [], 1)); + } + else if (Get(_document, dictionary, FormNames.Kids) is not null) + { + Report(DiagnosticCodes.FieldNameMissing, "A dictionary in the field tree has kids but no partial name (T); its kids are read as kids of the field above it.", element, null); + tree.Track(dictionary); + var fieldKids = new List(); + var widgetKids = new List(); + Expand(dictionary, element as CosReference ?? form.Reference, [dictionary], 1, fieldKids, widgetKids); + foreach (Kid kid in fieldKids) + { + _roots.Add(new Pending(kid.Element, kid.Dictionary, null, kid.Intermediates, 2)); + } + + if (widgetKids.Count > 0) + { + Report(DiagnosticCodes.FieldNameMissing, "Widget annotations under an unnamed root dictionary belong to no field; they are ignored.", element, null); + } + } + else + { + Report(DiagnosticCodes.FieldNameMissing, "A dictionary in the interactive form's Fields array has no partial name (T), so it is a widget annotation, not a field (§12.7.4.2); it is skipped.", element, null); + } + } + } + + public void AddOrphanRoot(CosDictionary top, CosReference? reference) + { + _visited.Add(top); + if (top.ContainsKey(FormNames.T)) + { + _roots.Add(new Pending((CosObject?)reference ?? top, top, null, [], 1)); + } + } + + public void Run() + { + for (int index = _roots.Count - 1; index >= 0; index--) + { + _pending.Push(_roots[index]); + } + + while (_pending.TryPop(out Pending item)) + { + Read(item); + } + } + + public void CheckDuplicates() + { + foreach ((string name, List fields) in tree.ByName) + { + PdfField first = fields[0]; + foreach (PdfField other in fields.Skip(1)) + { + if (!Same(first.FieldTypeName, other.FieldTypeName) || !Same(first.ValueObject, other.ValueObject) || !Same(first.DefaultValueObject, other.DefaultValueObject)) + { + other.Report(DiagnosticCodes.FieldNameDuplicateInconsistent, $"Fields named {name} shall have the same FT, V and DV (§12.7.4.2); they differ."); + break; + } + } + } + } + + private static bool Same(CosObject? left, CosObject? right) => (left, right) switch + { + (null, null) => true, + (CosArray a, CosArray b) => ReferenceEquals(a, b) || (a.Count == b.Count && a.Zip(b).All(pair => Equals(pair.First, pair.Second))), + (CosNumber a, CosNumber b) => a.ToDouble() == b.ToDouble(), + _ => Equals(left, right), + }; + + private void Read(Pending item) + { + CosDictionary dictionary = item.Dictionary; + tree.Track(dictionary); + if (item.Depth > MaxDepth) + { + Report(DiagnosticCodes.FieldTreeTooDeep, $"The field tree is nested more than {MaxDepth} levels deep; deeper fields are not read.", item.Element, item.Parent); + return; + } + + string partialName = ReadPartialName(item); + string fullName = item.Parent is null ? partialName : item.Parent.FullyQualifiedName + "." + partialName; + var info = new FieldInfo(form, dictionary, item.Element as CosReference, item.Parent, partialName, fullName, item.Intermediates); + + var fieldKids = new List(); + var widgetKids = new List(); + bool hasKids = Expand(dictionary, item.Element as CosReference ?? item.Parent?.DiagnosticReference ?? form.Reference, [], item.Depth, fieldKids, widgetKids); + PdfField field; + if (fieldKids.Count > 0) + { + var container = new PdfNonTerminalField(info); + if (widgetKids.Count > 0) + { + container.Report(DiagnosticCodes.FieldKidsMixed, "The field's Kids array holds both fields and widget annotations (§12.7.2); the widgets are ignored."); + } + + for (int index = fieldKids.Count - 1; index >= 0; index--) + { + Kid kid = fieldKids[index]; + _pending.Push(new Pending(kid.Element, kid.Dictionary, container, kid.Intermediates, item.Depth + 1 + kid.Intermediates.Length)); + } + + field = container; + } + else + { + CosObject[] widgets = hasKids + ? [.. widgetKids.Select(kid => kid.Element)] + : Annotations.PdfWidgetAnnotation.IsWidget(_document, dictionary) ? [item.Element] : []; + PdfTerminalField terminal = Create(info, widgets); + if (hasKids) + { + foreach (Kid kid in widgetKids) + { + tree.ByWidget.TryAdd(kid.Dictionary, terminal); + } + } + else if (widgets.Length > 0) + { + tree.ByWidget.TryAdd(dictionary, terminal); + } + + if (terminal is PdfSignatureField && widgets.Length > 1) + { + terminal.Report(DiagnosticCodes.SignatureFieldMultipleWidgets, "A signature field shall never refer to more than one annotation (§12.7.5.5); all its widgets are kept."); + } + + field = terminal; + } + + if (item.Parent is { } parent) + { + parent.AddChild(field); + } + else + { + tree.Roots.Add(field); + } + + tree.All.Add(field); + tree.ByDictionary.TryAdd(dictionary, field); + if (!tree.ByName.TryGetValue(fullName, out List? named)) + { + tree.ByName[fullName] = named = []; + } + + named.Add(field); + } + + /// Reads the kids of , expanding unnamed levels; returns whether it has a Kids entry. + private bool Expand(CosDictionary container, CosReference? containerReference, CosDictionary[] intermediates, int depth, List fieldKids, List widgetKids) + { + CosObject? value = Get(_document, container, FormNames.Kids); + if (value is null) + { + return false; + } + + if (value is not CosArray kids) + { + ReportOn(containerReference, DiagnosticCodes.FieldEntryInvalid, "The field's Kids entry shall be an array; it is ignored."); + return false; + } + + tree.Track(kids); + for (int index = 0; index < kids.Count; index++) + { + CosObject element = kids[index]; + if (_document.Resolve(element) is not CosDictionary kid) + { + ReportOn(containerReference, DiagnosticCodes.FieldReferenceInvalid, $"Element {index} of the field's Kids array is not a dictionary; it is skipped."); + continue; + } + + if (element is not CosReference) + { + ReportOn(containerReference, DiagnosticCodes.FieldNotIndirect, $"Element {index} of the field's Kids array is a direct dictionary; Table 226 requires indirect references. It is read anyway."); + } + + if (!_visited.Add(kid)) + { + ReportOn(containerReference, DiagnosticCodes.FieldTreeCycle, $"Element {index} of the field's Kids array appears elsewhere in the field tree too (a cycle, or a kid of two parents); only its first occurrence is read."); + continue; + } + + switch (Get(_document, kid, FormNames.Parent)) + { + case null: + ReportAt(element, containerReference, DiagnosticCodes.FieldParentMissing, "A kid in the field tree has no Parent entry, which Table 226 requires; the dictionary whose Kids holds it is used."); + break; + case var parent when !ReferenceEquals(parent, container): + ReportAt(element, containerReference, DiagnosticCodes.FieldParentMismatch, "A kid's Parent entry does not name the dictionary whose Kids array holds it; the tree is followed."); + break; + } + + if (kid.ContainsKey(FormNames.T)) + { + fieldKids.Add(new Kid(element, kid, intermediates)); + } + else if (Get(_document, kid, FormNames.Kids) is not null) + { + ReportAt(element, containerReference, DiagnosticCodes.FieldNameMissing, "A dictionary in the field tree has kids but no partial name (T); its kids are read as kids of the field above it."); + tree.Track(kid); + if (depth + intermediates.Length + 1 > MaxDepth) + { + ReportAt(element, containerReference, DiagnosticCodes.FieldTreeTooDeep, $"The field tree is nested more than {MaxDepth} levels deep; deeper fields are not read."); + continue; + } + + Expand(kid, element as CosReference ?? containerReference, [.. intermediates, kid], depth, fieldKids, widgetKids); + } + else + { + widgetKids.Add(new Kid(element, kid, intermediates)); + } + } + + return true; + } + + private string ReadPartialName(Pending item) + { + switch (Get(_document, item.Dictionary, FormNames.T)) + { + case CosString text: + string name = text.DecodeText(); + if (name.Contains('.', StringComparison.Ordinal)) + { + Report(DiagnosticCodes.FieldNameHasPeriod, "A partial field name shall not contain a period (§12.7.4.2); it is kept, so looking the field up by name may be ambiguous.", item.Element, item.Parent); + } + + return name; + case CosName nameObject: + Report(DiagnosticCodes.FieldEntryInvalid, "The field's T entry shall be a text string; it is a name, read as its text.", item.Element, item.Parent); + return nameObject.Value; + + default: + Report(DiagnosticCodes.FieldEntryInvalid, "The field's T entry shall be a text string; the field's partial name reads as empty.", item.Element, item.Parent); + return string.Empty; + } + } + + private PdfTerminalField Create(FieldInfo info, CosObject[] widgets) + { + CosName? type = Inherited(info, FormNames.FT) as CosName; + CosObject? flagsValue = Inherited(info, FormNames.Ff); + uint flags = flagsValue is CosNumber number && double.IsFinite(number.ToDouble()) ? (uint)(long)number.ToDouble() : 0; + switch (type?.Value) + { + case "Btn": + bool push = (flags & (1u << 16)) != 0; + bool radio = (flags & (1u << 15)) != 0; + PdfTerminalField button = push + ? new PdfPushButtonField(info, widgets) + : radio ? new PdfRadioButtonField(info, widgets) : new PdfCheckBoxField(info, widgets); + if (push && radio) + { + button.Report(DiagnosticCodes.ButtonFlagsConflict, "The button field sets both Pushbutton and Radio; Radio may be set only if Pushbutton is clear (Table 229). It is read as a push button."); + } + + return button; + case "Tx": + return new PdfTextField(info, widgets); + case "Ch": + return (flags & (1u << 17)) != 0 ? new PdfComboBoxField(info, widgets) : new PdfListBoxField(info, widgets); + case "Sig": + return new PdfSignatureField(info, widgets); + default: + var unknown = new PdfUnknownField(info, widgets); + unknown.Report( + DiagnosticCodes.FieldTypeMissing, + type is null + ? "The terminal field has no FT entry, of its own or inherited, which Table 226 requires; its type is unknown." + : $"The terminal field's type {type.Value} is not one Table 226 defines; its type is unknown."); + return unknown; + } + } + + private CosObject? Inherited(FieldInfo info, CosName key) + { + if (Get(_document, info.Dictionary, key) is { } own) + { + return own; + } + + foreach (CosDictionary intermediate in info.Intermediates) + { + if (Get(_document, intermediate, key) is { } carried) + { + return carried; + } + } + + return info.Parent?.Inherited(key); + } + + private void Report(string code, string message, CosObject element, PdfField? parent) => + _document.DiagnosticSink.Report(code, DiagnosticSeverity.Warning, message, objectReference: element as CosReference ?? parent?.DiagnosticReference ?? form.Reference); + + private void ReportAt(CosObject element, CosReference? containerReference, string code, string message) => + _document.DiagnosticSink.Report(code, DiagnosticSeverity.Warning, message, objectReference: element as CosReference ?? containerReference); + + private void ReportOn(CosReference? containerReference, string code, string message) => + _document.DiagnosticSink.Report(code, DiagnosticSeverity.Warning, message, objectReference: containerReference); + } +} diff --git a/src/Broadside/Forms/FormNames.cs b/src/Broadside/Forms/FormNames.cs new file mode 100644 index 00000000..c159e18d --- /dev/null +++ b/src/Broadside/Forms/FormNames.cs @@ -0,0 +1,50 @@ +using Broadside.Objects; + +namespace Broadside.Forms; + +/// Names looked up by the interactive form views (issue #74); kept apart from so parallel tickets do not collide. +internal static class FormNames +{ + // Catalog (§7.7.2, Table 29) and interactive form dictionary (§12.7.3, Table 224). + public static readonly CosName AcroForm = new("AcroForm"); + public static readonly CosName NeedsRendering = new("NeedsRendering"); + public static readonly CosName Fields = new("Fields"); + public static readonly CosName NeedAppearances = new("NeedAppearances"); + public static readonly CosName SigFlags = new("SigFlags"); + public static readonly CosName CO = new("CO"); + public static readonly CosName DR = new("DR"); + public static readonly CosName DA = new("DA"); + public static readonly CosName Q = new("Q"); + public static readonly CosName XFA = new("XFA"); + + // Field dictionaries (§12.7.4, Tables 226 and 228). + public static readonly CosName FT = new("FT"); + public static readonly CosName Parent = new("Parent"); + public static readonly CosName Kids = new("Kids"); + public static readonly CosName T = new("T"); + public static readonly CosName TU = new("TU"); + public static readonly CosName TM = new("TM"); + public static readonly CosName Ff = new("Ff"); + public static readonly CosName V = new("V"); + public static readonly CosName DV = new("DV"); + public static readonly CosName AA = new("AA"); + public static readonly CosName DS = new("DS"); + public static readonly CosName RV = new("RV"); + + // Field types (Table 226). + public static readonly CosName Btn = new("Btn"); + public static readonly CosName Tx = new("Tx"); + public static readonly CosName Ch = new("Ch"); + public static readonly CosName Sig = new("Sig"); + + // Field-type entries (Tables 230, 232, 234, 235, 236). + public static readonly CosName Opt = new("Opt"); + public static readonly CosName MaxLen = new("MaxLen"); + public static readonly CosName TI = new("TI"); + public static readonly CosName I = new("I"); + public static readonly CosName Lock = new("Lock"); + public static readonly CosName SV = new("SV"); + public static readonly CosName Action = new("Action"); + public static readonly CosName P = new("P"); + public static readonly CosName Off = new("Off"); +} diff --git a/src/Broadside/Forms/PdfAcroForm.cs b/src/Broadside/Forms/PdfAcroForm.cs new file mode 100644 index 00000000..8ae7dfd1 --- /dev/null +++ b/src/Broadside/Forms/PdfAcroForm.cs @@ -0,0 +1,301 @@ +using Broadside.Annotations; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Forms; + +/// A document's interactive form (AcroForm): its fields, their widgets, and the form-wide defaults. A live view over the interactive form dictionary. +/// +/// +/// ISO 32000-2 §12.7.1 to §12.7.3, Table 224. All fields of a document make up one global form. The field hierarchy is read from +/// Fields through the fields' Kids once, when first needed, and read again when a dictionary or array it read has +/// changed; the field views are the same instances until then, also when read from several threads. The other entries are read +/// on every call. +/// +/// +/// Malformed trees (cycles, kids under two parents, missing or mismatched Parent entries, missing names or types) are read as +/// far as they can be, each deviation recorded as a diagnostic when the tree is read (lenient mode); in strict mode reading the +/// tree throws. Nothing is written to the file: no appearance is generated and no missing entry is filled in. +/// +/// +public sealed class PdfAcroForm +{ + private readonly object _gate = new(); + private volatile FieldTree? _tree; + + internal PdfAcroForm(PdfDocument document, CosDictionary dictionary, CosReference? reference) + { + Document = document; + Dictionary = dictionary; + Reference = reference; + } + + /// Gets the interactive form dictionary. + /// ISO 32000-2 §12.7.3, Table 224. + public CosDictionary Dictionary { get; } + + /// Gets the indirect reference to the interactive form dictionary, or when the catalog holds it directly. + public CosReference? Reference { get; } + + /// Gets the root fields (Fields), in order. + /// ISO 32000-2 §12.7.3, Table 224 (required): "the document's root fields (those with no ancestors in the field hierarchy)". + public IReadOnlyList Fields => Tree.Roots; + + /// Gets every field of the form, depth first in Kids order: each non-terminal field before its children. + /// ISO 32000-2 §12.7.2. + public IReadOnlyList AllFields => Tree.All; + + /// Gets the terminal fields of the form, depth first in Kids order. + /// ISO 32000-2 §12.7.2. + public IReadOnlyList TerminalFields => [.. Tree.All.OfType()]; + + /// Gets a value indicating whether a processor shall construct appearances for all widgets (NeedAppearances, deprecated in PDF 2.0); default false. + /// ISO 32000-2 §12.7.3, Table 224. Reported only: reading never generates appearances. + public bool NeedAppearances + { + get + { + switch (Get(FormNames.NeedAppearances)) + { + case null: + return false; + case CosBoolean value: + return value.Value; + default: + Report(DiagnosticCodes.AcroFormEntryInvalid, "The interactive form's NeedAppearances entry shall be a boolean; it reads as false."); + return false; + } + } + } + + /// Gets the document-level signature flags (SigFlags, PDF 1.3); none when absent. + /// ISO 32000-2 §12.7.3, Tables 224 and 225. Bits the table does not define are kept, with a diagnostic. + public PdfSignatureFlags SignatureFlags + { + get + { + switch (Get(FormNames.SigFlags)) + { + case null: + return PdfSignatureFlags.None; + case CosInteger { Value: >= 0 and <= uint.MaxValue } integer: + if ((integer.Value & ~3L) != 0) + { + Report(DiagnosticCodes.AcroFormEntryInvalid, "The interactive form's SigFlags sets bits Table 225 does not define, which shall be 0; they are kept."); + } + + return (PdfSignatureFlags)(int)(uint)integer.Value; + default: + Report(DiagnosticCodes.AcroFormEntryInvalid, "The interactive form's SigFlags entry shall be an unsigned integer; it reads as 0."); + return PdfSignatureFlags.None; + } + } + } + + /// Gets the fields with calculation actions in the order their values are recalculated (CO, PDF 1.3); empty when absent. + /// + /// ISO 32000-2 §12.7.3, Table 224, and §12.6.3. An element that is not one of the form's fields is skipped with an + /// AcroFormEntryInvalid diagnostic. Calculations are not run. + /// + public IReadOnlyList CalculationOrder + { + get + { + if (Get(FormNames.CO) is not { } value) + { + return []; + } + + if (value is not CosArray array) + { + Report(DiagnosticCodes.AcroFormEntryInvalid, "The interactive form's CO entry shall be an array of field references; it is ignored."); + return []; + } + + var fields = new List(array.Count); + foreach (CosObject element in array) + { + if (Document.Resolve(element) is CosDictionary dictionary && FindField(dictionary) is { } listed) + { + fields.Add(listed); + } + else + { + Report(DiagnosticCodes.AcroFormEntryInvalid, "An element of the interactive form's CO array is not a field of the form; it is skipped."); + } + } + + return fields; + } + } + + /// Gets the default resources used by the form's appearance streams (DR), or . + /// ISO 32000-2 §12.7.3, Table 224, and §7.8.3. Only the form's: fields have no resources of their own. + public CosDictionary? DefaultResources + { + get + { + switch (Get(FormNames.DR)) + { + case null: + return null; + case CosDictionary resources: + return resources; + default: + Report(DiagnosticCodes.AcroFormEntryInvalid, "The interactive form's DR entry shall be a resource dictionary; it is ignored."); + return null; + } + } + } + + /// Gets the document-wide default appearance string (DA), or ; read as bytes, one character per byte, not parsed. + /// ISO 32000-2 §12.7.3, Table 224, and §12.7.4.3. Fields without a DA of their own or inherited use it (). + public string? DefaultAppearance + { + get + { + switch (Get(FormNames.DA)) + { + case null: + return null; + case CosString value: + return System.Text.Encoding.Latin1.GetString(value.Bytes); + default: + Report(DiagnosticCodes.AcroFormEntryInvalid, "The interactive form's DA entry shall be a string; it is ignored."); + return null; + } + } + } + + /// Gets the document-wide justification of variable text (Q); default left. + /// ISO 32000-2 §12.7.3, Table 224, and §12.7.4.3, Table 228. A value other than 0, 1 or 2 reads as left with a diagnostic. + public PdfTextJustification Quadding + { + get + { + switch (Get(FormNames.Q)) + { + case null: + return PdfTextJustification.Left; + case CosInteger { Value: >= 0 and <= 2 } value: + return (PdfTextJustification)(int)value.Value; + default: + Report(DiagnosticCodes.AcroFormEntryInvalid, "The interactive form's Q entry shall be 0, 1 or 2; it reads as 0 (left)."); + return PdfTextJustification.Left; + } + } + } + + /// Gets the form's XFA resource (XFA, deprecated in PDF 2.0), or when it has none. + /// ISO 32000-2 §12.7.3, Table 224, and Annex K. Kept as data; never rendered. + public PdfXfaForm? Xfa => Get(FormNames.XFA) is (CosStream or CosArray) and var value ? new PdfXfaForm(this, value) : null; + + /// Gets the document the form belongs to. + internal PdfDocument Document { get; } + + private FieldTree Tree + { + get + { + FieldTree? tree = _tree; + if (tree is not null && tree.IsCurrent(Dictionary)) + { + return tree; + } + + lock (_gate) + { + tree = _tree; + if (tree is null || !tree.IsCurrent(Dictionary)) + { + tree = FieldTree.Build(this); + _tree = tree; + } + + return tree; + } + } + } + + /// Returns the fields whose fully qualified name is : usually one, several when the file repeats a name. + /// The name, partial names joined by periods. + /// The fields in tree order; empty when there is none. + /// ISO 32000-2 §12.7.4.2: fields with the same name are the same field and shall have the same type and values. + public IReadOnlyList FindFields(string fullyQualifiedName) + { + ArgumentNullException.ThrowIfNull(fullyQualifiedName); + return Tree.ByName.TryGetValue(fullyQualifiedName, out List? fields) ? fields : []; + } + + /// Returns the first field whose fully qualified name is , or . + /// The name, partial names joined by periods. + /// The field, or . + /// ISO 32000-2 §12.7.4.2. + public PdfField? FindField(string fullyQualifiedName) => FindFields(fullyQualifiedName) is [var first, ..] ? first : null; + + /// Returns the field whose field dictionary is , or when the form's tree has none. + /// A field dictionary. + /// The field, or . + /// ISO 32000-2 §12.7.4.1. + public PdfField? FindField(CosDictionary dictionary) + { + ArgumentNullException.ThrowIfNull(dictionary); + return Tree.ByDictionary.GetValueOrDefault(dictionary); + } + + /// + /// Returns the fields an action target names: a hide action's T or a submit-form or reset-form action's Fields + /// element. A name gives every field with that fully qualified name; a dictionary gives the field it is, or the field of a widget. + /// + /// The target. + /// The fields; empty when the target names nothing in the form (a hide target may be an annotation that is no widget). + /// ISO 32000-2 §12.6.4.11, Table 214, and §12.7.6.2-12.7.6.3, Tables 239 and 241; names per §12.7.4.2. Descendants are not added. + public IReadOnlyList FindFields(PdfActionTarget target) + { + ArgumentNullException.ThrowIfNull(target); + if (target.FieldName is { } name) + { + return FindFields(name); + } + + if (target.Dictionary is not { } dictionary) + { + return []; + } + + FieldTree tree = Tree; + if (tree.ByDictionary.TryGetValue(dictionary, out PdfField? field)) + { + return [field]; + } + + return tree.ByWidget.TryGetValue(dictionary, out PdfTerminalField? owner) ? [owner] : []; + } + + /// Returns the field belongs to, recording a widget that the tree from Fields does not reach. + internal PdfTerminalField? FieldOf(PdfWidgetAnnotation widget) + { + FieldTree tree = Tree; + if (tree.ByWidget.TryGetValue(widget.Dictionary, out PdfTerminalField? field)) + { + return field; + } + + PdfTerminalField? outside = tree.FindOutside(this, widget.Dictionary, widget.Reference); + + widget.Report( + DiagnosticCodes.WidgetNotInFieldTree, + outside is null + ? "The widget annotation belongs to no terminal field: neither it nor a dictionary up its Parent chain is a terminal field with a partial name (T)." + + : "The widget annotation is not reached from the interactive form's Fields array through Kids (§12.7.2); its field is found through its Parent chain."); + return outside; + } + + /// Reports a deviation in the interactive form dictionary. + internal void Report(string code, string message, DiagnosticSeverity severity = DiagnosticSeverity.Warning) => + Document.DiagnosticSink.Report(code, severity, message, objectReference: Reference ?? Document.CatalogReference); + + private CosObject? Get(CosName key) => FieldTree.Get(Document, Dictionary, key); +} diff --git a/src/Broadside/Forms/PdfButtonField.cs b/src/Broadside/Forms/PdfButtonField.cs new file mode 100644 index 00000000..395e7496 --- /dev/null +++ b/src/Broadside/Forms/PdfButtonField.cs @@ -0,0 +1,314 @@ +using System.Globalization; +using Broadside.Annotations; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Forms; + +/// A button field: a push button, a check box or a set of radio buttons. +/// +/// ISO 32000-2 §12.7.5.2, Table 229; field type Btn. The kind comes from the inheritable flags: Pushbutton (bit 17) selects a +/// push button, else Radio (bit 16) a set of radio buttons, else a check box. When both are set the field is a push button (Radio +/// "may be set only if the Pushbutton flag is clear") and a ButtonFlagsConflict diagnostic is recorded. +/// +public abstract class PdfButtonField : PdfTerminalField +{ + private protected PdfButtonField(FieldInfo info, PdfFieldKind kind, CosObject[] widgets) + : base(info, kind, widgets) + { + } +} + +/// A push button: a control that responds to the user at once and keeps no value. +/// +/// ISO 32000-2 §12.7.5.2.2: it "shall not use the V and DV entries". What it does is its widget's action +/// () and its caption the widget's appearance characteristics. +/// +public sealed class PdfPushButtonField : PdfButtonField +{ + internal PdfPushButtonField(FieldInfo info, CosObject[] widgets) + : base(info, PdfFieldKind.PushButton, widgets) + { + } +} + +/// A check box or a set of radio buttons: buttons with an on and an off state, whose value names the appearance state that is on. +/// +/// +/// ISO 32000-2 §12.7.5.2.3, §12.7.5.2.4 and Table 230. Each widget's normal appearance has its on state, under any name, and +/// optionally Off. The field's value V names the on state that is selected, Off when none is. Widgets select +/// their appearance with AS, which "shall also be" that value; when they disagree, AS decides the appearance and +/// V remains the value, and a ButtonValueStateMismatch diagnostic is recorded. +/// +/// +/// With Opt (PDF 1.4), entry i is the export value of the i-th widget in Kids, and on states may +/// be named by that position (/0, /1), so widgets can share an export value and still be told apart. +/// +/// +public abstract class PdfToggleButtonField : PdfButtonField +{ + private protected PdfToggleButtonField(FieldInfo info, PdfFieldKind kind, CosObject[] widgets) + : base(info, kind, widgets) + { + } + + /// Gets the selected on state (V, inheritable); Off when the value is absent or nothing is selected. + /// + /// ISO 32000-2 §12.7.5.2.3 and §12.7.5.2.4 (default Off). A string reads as the name it spells with a + /// FieldValueTypeInvalid diagnostic; a name no widget has as its on state records ButtonValueUnknownState and is + /// returned as stored. + /// + public CosName Value + { + get + { + CosName value = ReadState(ValueObject, FormNames.V) ?? FormNames.Off; + Check(value); + return value; + } + } + + /// Gets the state the field reverts to on a reset-form action (DV, inheritable), or . + /// ISO 32000-2 §12.7.4.1, Table 226. + public CosName? DefaultValue => ReadState(DefaultValueObject, FormNames.DV); + + /// Gets the export value of each widget in Kids order (Opt, inheritable, PDF 1.4); empty when absent. + /// + /// ISO 32000-2 §12.7.5.2.3, Table 230. An element that is not a text string reads as an empty string, and an array whose length + /// differs from the number of widgets records ButtonOptLengthMismatch; both keep positions aligned with Kids. + /// + public IReadOnlyList Options + { + get + { + switch (Inherited(FormNames.Opt)) + { + case null: + return []; + case CosArray array: + var options = new string[array.Count]; + for (int index = 0; index < array.Count; index++) + { + if (Document.Resolve(array[index]) is CosString text) + { + options[index] = text.DecodeText(); + } + else + { + options[index] = string.Empty; + Report(DiagnosticCodes.FieldEntryInvalid, $"Element {index} of the button field's Opt array is not a text string; it reads as empty."); + } + } + + if (options.Length != WidgetElements.Count) + { + Report(DiagnosticCodes.ButtonOptLengthMismatch, "The button field's Opt array shall have one entry per widget in Kids (Table 230); its length differs."); + } + + return options; + default: + return InvalidEntry(FormNames.Opt, "an array of text strings") ?? []; + } + } + } + + /// Gets the names of the widgets' on states, each once, in Kids order. + /// ISO 32000-2 §12.7.5.2.3: every state of a widget's normal appearance other than Off. + public IReadOnlyList OnStateNames + { + get + { + var names = new List(); + foreach (PdfWidgetAnnotation widget in Widgets) + { + if (GetOnState(widget) is { } state && !names.Contains(state)) + { + names.Add(state); + } + } + + return names; + } + } + + /// Gets the widgets whose on state is the field's value: none when it is Off; several for duplicated check boxes or radio buttons in unison. + /// ISO 32000-2 §12.7.5.2.3 (example 2) and §12.7.5.2.4, Table 229 (RadiosInUnison). + public IReadOnlyList SelectedWidgets + { + get + { + CosName value = Value; + return FormNames.Off.Equals(value) ? [] : [.. Widgets.Where(widget => value.Equals(GetOnState(widget)))]; + } + } + + /// + /// Gets the export value of the selected state: the Opt entry of the first selected widget when there is an Opt, else + /// the state's name; when the value is Off. + /// + /// ISO 32000-2 §12.7.5.2.3, Table 230. + public string? ExportValue + { + get + { + CosName value = Value; + if (FormNames.Off.Equals(value)) + { + return null; + } + + IReadOnlyList options = Options; + if (options.Count > 0) + { + foreach (PdfWidgetAnnotation widget in Widgets) + { + if (value.Equals(GetOnState(widget)) && IndexOfWidget(widget.Dictionary) is var index && index >= 0 && index < options.Count) + { + return options[index]; + } + } + + if (int.TryParse(value.Value, NumberStyles.None, CultureInfo.InvariantCulture, out int position) && position < options.Count) + { + return options[position]; + } + } + + return value.Value; + } + } + + /// Returns the on state of : the state of its normal appearance other than Off. + /// One of the field's widgets. + /// + /// The state name; when the widget has no appearance states. A normal appearance with states but none other + /// than Off records ButtonOnStateMissing; with several, the one equal to the value is used, else the first, with + /// ButtonStatesAmbiguous. + /// + /// ISO 32000-2 §12.7.5.2.3 and §12.5.5. + public CosName? GetOnState(PdfWidgetAnnotation widget) + { + ArgumentNullException.ThrowIfNull(widget); + if (widget.AppearanceDictionary?.Normal is not { HasStates: true } normal) + { + return null; + } + + CosName[] on = [.. normal.StateNames.Where(state => !FormNames.Off.Equals(state))]; + switch (on.Length) + { + case 0: + Report(DiagnosticCodes.ButtonOnStateMissing, "A widget of the button field has appearance states but none other than Off, so it has no on state."); + return null; + case 1: + return on[0]; + default: + Report(DiagnosticCodes.ButtonStatesAmbiguous, "A widget of the button field has more than one on state in its normal appearance; the one equal to the value, else the first, is used."); + CosName? value = ReadState(ValueObject, FormNames.V); + return on.FirstOrDefault(state => state.Equals(value)) ?? on[0]; + } + } + + /// Returns the export value of : its Opt entry when there is an Opt, else its on state's name. + /// One of the field's widgets. + /// The export value, or when the widget has no on state and no Opt entry. + /// ISO 32000-2 §12.7.5.2.3, Table 230. + public string? GetWidgetExportValue(PdfWidgetAnnotation widget) + { + ArgumentNullException.ThrowIfNull(widget); + IReadOnlyList options = Options; + int index = IndexOfWidget(widget.Dictionary); + return index >= 0 && index < options.Count ? options[index] : GetOnState(widget)?.Value; + } + + /// + /// Returns the appearance state shows: its AS; without one, the field's value when the widget + /// has it as its on state, else Off. + /// + /// One of the field's widgets. + /// The state name. + /// ISO 32000-2 §12.7.5.2.3: "the value of the AS key shall be used instead of the V key to determine which appearance to use". + public CosName GetAppearanceState(PdfWidgetAnnotation widget) + { + ArgumentNullException.ThrowIfNull(widget); + if (widget.AppearanceState is { } state) + { + return state; + } + + CosName value = ReadState(ValueObject, FormNames.V) ?? FormNames.Off; + return value.Equals(GetOnState(widget)) ? value : FormNames.Off; + } + + /// Reads a state value: a name, or a string read as the name it spells with a diagnostic. + private CosName? ReadState(CosObject? value, CosName key) + { + switch (value) + { + case null: + return null; + case CosName name: + return name; + case CosString text: + ReportValueType(key, "a name; it is a string, read as the name it spells"); + return new CosName(text.Bytes); + default: + ReportValueType(key, "a name; it reads as Off"); + return null; + } + } + + /// Checks the value against the widgets' states: a value no widget has, and widgets whose AS disagrees with it. + private void Check(CosName value) + { + bool known = FormNames.Off.Equals(value); + bool anyStates = false; + foreach (PdfWidgetAnnotation widget in Widgets) + { + CosName? on = GetOnState(widget); + anyStates |= on is not null; + known |= value.Equals(on); + if (on is not null && widget.AppearanceState is { } state && !state.Equals(value.Equals(on) ? value : FormNames.Off)) + { + Report(DiagnosticCodes.ButtonValueStateMismatch, "A widget's AS entry differs from the button field's value, which it shall equal (§12.7.5.2.3); AS decides the appearance."); + } + } + + if (!known && anyStates) + { + Report(DiagnosticCodes.ButtonValueUnknownState, $"The button field's value {value.Value} is not the on state of any of its widgets; nothing is shown selected."); + } + } +} + +/// A check box: one or more widgets that toggle together between an on and an off state. +/// ISO 32000-2 §12.7.5.2.3; Pushbutton and Radio flags clear. +public sealed class PdfCheckBoxField : PdfToggleButtonField +{ + internal PdfCheckBoxField(FieldInfo info, CosObject[] widgets) + : base(info, PdfFieldKind.CheckBox, widgets) + { + } + + /// Gets a value indicating whether the box is checked: its value is a state other than Off. + /// ISO 32000-2 §12.7.5.2.3. + public bool IsChecked => !FormNames.Off.Equals(Value); +} + +/// A set of radio buttons: widgets of which at most one is on, unless several share an on state and turn on in unison. +/// ISO 32000-2 §12.7.5.2.4; Radio flag set, Pushbutton clear. +public sealed class PdfRadioButtonField : PdfToggleButtonField +{ + internal PdfRadioButtonField(FieldInfo info, CosObject[] widgets) + : base(info, PdfFieldKind.RadioButton, widgets) + { + } + + /// Gets a value indicating whether exactly one button shall be on at all times (Ff bit 15, NoToggleToOff). + /// ISO 32000-2 §12.7.5.2.4, Table 229. + public bool IsNoToggleToOff => HasFlag(15); + + /// Gets a value indicating whether buttons with the same on state turn on and off together (Ff bit 26, RadiosInUnison, PDF 1.5). + /// ISO 32000-2 §12.7.5.2.4, Table 229. + public bool IsRadiosInUnison => HasFlag(26); +} diff --git a/src/Broadside/Forms/PdfChoiceField.cs b/src/Broadside/Forms/PdfChoiceField.cs new file mode 100644 index 00000000..4d48c96a --- /dev/null +++ b/src/Broadside/Forms/PdfChoiceField.cs @@ -0,0 +1,289 @@ +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Forms; + +/// One option of a choice field: the value exported for it and the text displayed for it. +/// ISO 32000-2 §12.7.5.4, Table 234 (Opt): a text string is both; a two-element array is [export display]. +public sealed class PdfChoiceOption +{ + internal PdfChoiceOption(string exportValue, string displayText) + { + ExportValue = exportValue; + DisplayText = displayText; + } + + /// Gets the value exported when the option is selected. + public string ExportValue { get; } + + /// Gets the text shown for the option. + public string DisplayText { get; } + + /// + public override string ToString() => ExportValue == DisplayText ? ExportValue : $"{ExportValue} ({DisplayText})"; +} + +/// A choice field: a list of text options, of which one or (for a multi-select list box) several are selected. +/// +/// ISO 32000-2 §12.7.5.4, Tables 233 and 234; field type Ch. The Combo flag (bit 18) selects a , +/// else a . Its text is variable text (§12.7.4.3). +/// +public abstract class PdfChoiceField : PdfTerminalField +{ + private protected PdfChoiceField(FieldInfo info, PdfFieldKind kind, CosObject[] widgets) + : base(info, kind, widgets) + { + } + + /// Gets the options presented to the user, in Opt order (never sorted); empty when there is no Opt. + /// + /// ISO 32000-2 §12.7.5.4, Table 234: Opt is not inheritable, but an ancestor's is used when the field has none, as viewers + /// do, with a ChoiceOptionsInherited diagnostic. An element that is neither a text string nor a pair of them reads as an + /// empty option, so indices stay aligned, with a ChoiceOptionInvalid diagnostic. + /// + public IReadOnlyList Options + { + get + { + CosObject? value = Own(FormNames.Opt); + if (value is null && Inherited(FormNames.Opt) is { } inherited) + { + Report(DiagnosticCodes.ChoiceOptionsInherited, "The choice field has no Opt entry, which is not inheritable (Table 234); its ancestor's is used."); + value = inherited; + } + + switch (value) + { + case null: + return []; + case CosArray array: + var options = new PdfChoiceOption[array.Count]; + for (int index = 0; index < array.Count; index++) + { + options[index] = ReadOption(Document.Resolve(array[index]), index); + } + + return options; + default: + return InvalidEntry(FormNames.Opt, "an array") ?? []; + } + } + } + + /// Gets the selected items as stored (V, inheritable): one text string, or an array of them; empty when nothing is selected. + /// + /// ISO 32000-2 §12.7.5.4. Writers store the export value, though the clause names the displayed text for an + /// [export display] option; matches either. An empty string, which some writers store for + /// "nothing selected", is not an item. + /// + + public IReadOnlyList Values => ReadValues(ValueObject, FormNames.V); + + /// Gets the items selected after a reset-form action (DV, inheritable); empty when there are none. + /// ISO 32000-2 §12.7.4.1, Table 226, and §12.7.5.4. + public IReadOnlyList DefaultValues => ReadValues(DefaultValueObject, FormNames.DV); + + /// + /// Gets the indices in of the selected items, ascending: each value matched against the options' export + /// values, then their displayed text. I decides between options with the same text when it agrees with the value. + /// + /// + /// ISO 32000-2 §12.7.5.4, Table 234: when I differs from V, "the V entry shall be used". A value no option has records + /// ChoiceValueNotInOptions, except in an editable combo box, where any text is legal. + /// + public IReadOnlyList SelectedIndices + { + get + { + IReadOnlyList options = Options; + IReadOnlyList values = Values; + IReadOnlyList stored = StoredIndices; + if (stored.Count == values.Count && stored.Count > 0 && Matches(stored, options, values)) + { + return stored; + } + + var selected = new SortedSet(); + foreach (string value in values) + { + int index = Find(options, value, selected, export: true); + index = index >= 0 ? index : Find(options, value, selected, export: false); + if (index >= 0) + { + selected.Add(index); + } + else if (!AllowsFreeText) + { + Report(DiagnosticCodes.ChoiceValueNotInOptions, "A value of the choice field is none of its options."); + } + } + + return [.. selected]; + } + } + + /// Gets the indices of the selected options as stored in I (PDF 1.4); empty when absent. Entries that are not ascending in-range integers are left out. + /// ISO 32000-2 §12.7.5.4, Table 234; not inheritable. A left-out entry records ChoiceIndicesInvalid. + public IReadOnlyList StoredIndices + { + get + { + switch (Own(FormNames.I)) + { + case null: + return []; + case CosArray array: + int count = Options.Count; + var indices = new List(array.Count); + bool invalid = false; + foreach (CosObject element in array) + { + if (Document.Resolve(element) is CosInteger { Value: >= 0 } integer && integer.Value < count && (indices.Count == 0 || integer.Value > indices[^1])) + { + indices.Add((int)integer.Value); + } + else + { + invalid = true; + } + } + + if (invalid) + { + Report(DiagnosticCodes.ChoiceIndicesInvalid, "The choice field's I array shall hold ascending indices into Opt; the entries that do not are ignored."); + } + + return indices; + default: + Report(DiagnosticCodes.ChoiceIndicesInvalid, "The choice field's I entry shall be an array of integers; it is ignored."); + return []; + } + } + } + + /// Gets the index in of the first option visible in a scrolling list (TI); default 0. + /// ISO 32000-2 §12.7.5.4, Table 234; not inheritable. + public int TopIndex => ReadInteger(FormNames.TI, inheritable: false) ?? 0; + + /// Gets a value indicating whether the writer is asked to sort the options (Ff bit 20, Sort); readers keep Opt order. + /// ISO 32000-2 §12.7.5.4, Table 233. + public bool IsSort => HasFlag(20); + + /// Gets a value indicating whether several options may be selected at once (Ff bit 22, MultiSelect, PDF 1.4). + /// ISO 32000-2 §12.7.5.4, Table 233. + public bool IsMultiSelect => HasFlag(22); + + /// Gets a value indicating whether a new selection is committed as soon as it is made (Ff bit 27, CommitOnSelChange, PDF 1.5). + /// ISO 32000-2 §12.7.5.4, Table 233. + public bool IsCommitOnSelectionChange => HasFlag(27); + + /// Gets a value indicating whether a value need not be one of the options. + private protected virtual bool AllowsFreeText => false; + + private static bool Matches(IReadOnlyList indices, IReadOnlyList options, IReadOnlyList values) + { + var remaining = values.ToList(); + foreach (int index in indices) + { + PdfChoiceOption option = options[index]; + int at = remaining.IndexOf(option.ExportValue); + at = at >= 0 ? at : remaining.IndexOf(option.DisplayText); + if (at < 0) + { + return false; + } + + remaining.RemoveAt(at); + } + + return true; + } + + private static int Find(IReadOnlyList options, string value, SortedSet taken, bool export) + { + for (int index = 0; index < options.Count; index++) + { + if (!taken.Contains(index) && string.Equals(export ? options[index].ExportValue : options[index].DisplayText, value, StringComparison.Ordinal)) + { + return index; + } + } + + return -1; + } + + private PdfChoiceOption ReadOption(CosObject element, int index) + { + switch (element) + { + case CosString text: + string both = text.DecodeText(); + return new PdfChoiceOption(both, both); + case CosArray { Count: 2 } pair when Document.Resolve(pair[0]) is CosString export && Document.Resolve(pair[1]) is CosString display: + return new PdfChoiceOption(export.DecodeText(), display.DecodeText()); + default: + Report(DiagnosticCodes.ChoiceOptionInvalid, $"Element {index} of the choice field's Opt array is neither a text string nor a pair of them; it reads as an empty option."); + return new PdfChoiceOption(string.Empty, string.Empty); + } + } + + private string[] ReadValues(CosObject? value, CosName key) + { + switch (value) + { + case null: + return []; + case CosArray array: + var values = new List(array.Count); + foreach (CosObject element in array) + { + if (Document.Resolve(element) is CosString text) + { + if (text.DecodeText() is { Length: > 0 } item) + { + values.Add(item); + } + } + else + { + ReportValueType(key, "a text string or an array of them; an element that is not a string is ignored"); + } + } + + return [.. values]; + default: + return ReadTextValue(value, key) is { Length: > 0 } single ? [single] : []; + } + } +} + +/// A combo box: a drop-down list, optionally with a text box for a value that is not one of the options. +/// ISO 32000-2 §12.7.5.4, Table 233; Combo flag set. +public sealed class PdfComboBoxField : PdfChoiceField +{ + internal PdfComboBoxField(FieldInfo info, CosObject[] widgets) + : base(info, PdfFieldKind.ComboBox, widgets) + { + } + + /// Gets a value indicating whether the combo box includes an editable text box (Ff bit 19, Edit). + /// ISO 32000-2 §12.7.5.4, Table 233. + public bool IsEditable => HasFlag(19); + + /// Gets a value indicating whether text typed into the editable box shall not be spell-checked (Ff bit 23, DoNotSpellCheck, PDF 1.4). + /// ISO 32000-2 §12.7.5.4, Table 233: meaningful only with Combo and Edit set. + public bool IsDoNotSpellCheck => HasFlag(23); + + /// + private protected override bool AllowsFreeText => IsEditable; +} + +/// A scrollable list box. +/// ISO 32000-2 §12.7.5.4, Table 233; Combo flag clear. +public sealed class PdfListBoxField : PdfChoiceField +{ + internal PdfListBoxField(FieldInfo info, CosObject[] widgets) + : base(info, PdfFieldKind.ListBox, widgets) + { + } +} diff --git a/src/Broadside/Forms/PdfField.cs b/src/Broadside/Forms/PdfField.cs new file mode 100644 index 00000000..54e2681a --- /dev/null +++ b/src/Broadside/Forms/PdfField.cs @@ -0,0 +1,373 @@ +using Broadside.Annotations; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Forms; + +/// A field of an interactive form: a live view over its field dictionary and the ancestors it inherits from. +/// +/// +/// ISO 32000-2 §12.7.2 and §12.7.4.1, Table 226. A field whose children are fields is a ; every +/// other field is a of the class its type (FT) and flags (Ff) select. +/// +/// +/// Inheritable entries (FT, Ff, V, DV, DA, Q and the type-specific ones the tables mark +/// inheritable) come from the field when it has them and otherwise from the nearest ancestor that does, the whole value and never +/// merged; DA and Q then fall back to the interactive form dictionary. Ancestors are the fields on the path from the +/// form's Fields array that the field was found through (§12.7.4.1: inheritance is not limited in range), including any +/// unnamed dictionaries between them. Every property reads the dictionaries when called and writes nothing; a malformed entry +/// reads as its default and records a diagnostic the first time it is read (lenient mode), or throws (strict mode). +/// +/// +public abstract class PdfField +{ + private readonly CosDictionary[] _intermediates; + + private protected PdfField(FieldInfo info, PdfFieldKind kind) + { + Form = info.Form; + Dictionary = info.Dictionary; + Reference = info.Reference; + Parent = info.Parent; + PartialName = info.PartialName; + FullyQualifiedName = info.FullyQualifiedName; + _intermediates = info.Intermediates; + Kind = kind; + } + + /// Gets the interactive form the field belongs to. + /// ISO 32000-2 §12.7.1: all fields make up a single, global interactive form. + public PdfAcroForm Form { get; } + + /// Gets the field dictionary. + /// ISO 32000-2 §12.7.4.1, Table 226. + public CosDictionary Dictionary { get; } + + /// Gets the indirect reference to the field dictionary, or when it is held directly (§12.7.4.1 requires an indirect object). + /// ISO 32000-2 §12.7.4.1. + public CosReference? Reference { get; } + + /// Gets the field's parent in the field hierarchy, or for a root field. + /// + /// ISO 32000-2 §12.7.4.1, Table 226 (Parent). The field whose Kids the field was found in, which is what its + /// Parent entry shall name; when the two disagree the tree wins and a FieldParentMismatch diagnostic is recorded. + /// + public PdfNonTerminalField? Parent { get; } + + /// Gets what the field is: non-terminal, or the kind of terminal field its type and flags select. + /// ISO 32000-2 §12.7.2, §12.7.5. + public PdfFieldKind Kind { get; } + + /// Gets the partial field name (T). + /// ISO 32000-2 §12.7.4.2, Table 226 (required); a text string, which shall not contain a period. + public string PartialName { get; } + + /// Gets the fully qualified field name: the partial names of the field's ancestors and its own, joined by periods. + /// ISO 32000-2 §12.7.4.2. + public string FullyQualifiedName { get; } + + /// Gets the alternative field name shown in the user interface and used for accessibility (TU, PDF 1.3), or . + /// ISO 32000-2 §12.7.4.1, Table 226; not inheritable. + public string? AlternateName => ReadOwnText(FormNames.TU); + + /// Gets the name used when exporting the field's data (TM, PDF 1.3), or . + /// ISO 32000-2 §12.7.4.1, Table 226; not inheritable. + public string? MappingName => ReadOwnText(FormNames.TM); + + /// Gets the field type (FT, inheritable) as stored, or when neither the field nor an ancestor has one. + /// ISO 32000-2 §12.7.4.1, Table 226 (required for terminal fields). + public CosName? FieldTypeName => Inherited(FormNames.FT) as CosName; + + /// Gets the field type (FT, inheritable). + /// ISO 32000-2 §12.7.4.1, Table 226. A non-terminal field may carry one for its descendants; it has no type of its own. + public PdfFieldType FieldType => ToFieldType(FieldTypeName); + + /// Gets the field flags (Ff, inheritable), every bit as stored; 0 when absent. + /// + /// ISO 32000-2 §12.7.4.1, Tables 226 and 227: an unsigned 32-bit integer. The value of the nearest dictionary that has the entry + /// is used whole, never combined with an ancestor's. A real number is truncated and a negative integer read as its 32-bit pattern, + /// with a FieldFlagsInvalid diagnostic; so is a bit no field type defines, which is kept. The type-specific bits are the + /// properties of each field class. + /// + public uint Flags => ReadFlags(Inherited(FormNames.Ff), report: true); + + /// Gets a value indicating whether the user may not change the field's value (Ff bit 1, ReadOnly). + /// ISO 32000-2 §12.7.4.1, Table 227. + public bool IsReadOnly => HasFlag(1); + + /// Gets a value indicating whether the field shall have a value when it is exported by a submit-form action (Ff bit 2, Required). + /// ISO 32000-2 §12.7.4.1, Table 227. + public bool IsRequired => HasFlag(2); + + /// Gets a value indicating whether a submit-form action shall not export the field (Ff bit 3, NoExport). + /// ISO 32000-2 §12.7.4.1, Table 227. + public bool IsNoExport => HasFlag(3); + + /// Gets the field's value (V, inheritable) as stored and resolved, or ; the field classes decode it. + /// ISO 32000-2 §12.7.4.1, Table 226. Never falls back to . + public CosObject? ValueObject => Inherited(FormNames.V); + + /// Gets the value the field reverts to on a reset-form action (DV, inheritable) as stored and resolved, or . + /// ISO 32000-2 §12.7.4.1, Table 226. + public CosObject? DefaultValueObject => Inherited(FormNames.DV); + + /// + /// Gets the default appearance string (DA): the field's or its nearest ancestor's, else the interactive form's; + /// when none has one. Read as bytes, one character per byte; not parsed. + /// + /// + /// ISO 32000-2 §12.7.4.3, Table 228 (required and inheritable for fields containing variable text) and §12.7.3, Table 224. A + /// text or choice field without one records DefaultAppearanceMissing. + /// + public string? DefaultAppearance + { + get + { + CosObject? value = Inherited(FormNames.DA); + string? text = value switch + { + null => Form.DefaultAppearance, + CosString bytes => System.Text.Encoding.Latin1.GetString(bytes.Bytes), + _ => InvalidEntry(FormNames.DA, "a string"), + }; + + if (text is null && value is null && Kind != PdfFieldKind.NonTerminal && FieldType is PdfFieldType.Text or PdfFieldType.Choice) + { + Report(DiagnosticCodes.DefaultAppearanceMissing, "The field contains variable text but neither it, its ancestors nor the interactive form has a DA entry, which Table 228 requires."); + } + + return text; + } + } + + /// Gets the justification of the field's variable text (Q): the field's or its nearest ancestor's, else the interactive form's; default left. + /// ISO 32000-2 §12.7.4.3, Table 228 (inheritable) and §12.7.3, Table 224. A value other than 0, 1 or 2 reads as left with a diagnostic. + public PdfTextJustification Quadding + { + get + { + CosObject? value = Inherited(FormNames.Q); + if (value is null) + { + return Form.Quadding; + } + + if (value is CosInteger { Value: >= 0 and <= 2 } integer) + { + return (PdfTextJustification)(int)integer.Value; + } + + Report(DiagnosticCodes.FieldEntryInvalid, "The field's Q entry shall be 0, 1 or 2; it reads as 0 (left)."); + return PdfTextJustification.Left; + } + } + + /// Gets the default style string (DS, PDF 1.5), or . + /// ISO 32000-2 §12.7.4.3, Table 228; not inheritable. Kept as text: its syntax is the XFA specification's. + public string? DefaultStyle => ReadOwnText(FormNames.DS); + + /// Gets the rich text value (RV, PDF 1.5) from a text string or text stream, or . + /// ISO 32000-2 §12.7.4.3, Table 228; not inheritable. Kept as text: its syntax is the XFA specification's. + public string? RichValue + { + get + { + switch (Own(FormNames.RV)) + { + case null: + return null; + case CosString text: + return text.DecodeText(); + case CosStream stream: + return new CosString(Document.DecodeStream(stream).Span).DecodeText(); + default: + return InvalidEntry(FormNames.RV, "a text string or text stream"); + } + } + } + + /// Gets the actions performed on the field's trigger events (AA: keystroke, format, validate, calculate), or . + /// + /// ISO 32000-2 §12.7.4.1, Table 226, and §12.6.3, Table 199; the field's own entry (not inheritable), read through + /// . A field merged with its widget shares the dictionary with the widget's + /// annotation triggers (). + /// + public PdfFieldAdditionalActions? AdditionalActions => + Dictionary.TryGetValue(FormNames.AA, out CosObject? value) ? Document.GetFieldAdditionalActions(value, DiagnosticReference) : null; + + /// Gets the document the field belongs to. + internal PdfDocument Document => Form.Document; + + /// Gets the object diagnostics about the field are reported against: the field, else its nearest indirect ancestor, else the form. + internal CosReference? DiagnosticReference + { + get + { + for (PdfField? current = this; current is not null; current = current.Parent) + { + if (current.Reference is { } reference) + { + return reference; + } + } + + return Form.Reference; + } + } + + /// Maps an FT name to its type. + internal static PdfFieldType ToFieldType(CosName? name) => name?.Value switch + { + "Btn" => PdfFieldType.Button, + "Tx" => PdfFieldType.Text, + "Ch" => PdfFieldType.Choice, + "Sig" => PdfFieldType.Signature, + _ => PdfFieldType.Unknown, + }; + + /// Returns the inheritable entry : the field's, an unnamed dictionary's above it, or the nearest ancestor's; resolved. + internal CosObject? Inherited(CosName key) + { + for (PdfField? current = this; current is not null; current = current.Parent) + { + if (FieldTree.Get(Document, current.Dictionary, key) is { } value) + { + return value; + } + + foreach (CosDictionary intermediate in current._intermediates) + { + if (FieldTree.Get(Document, intermediate, key) is { } carried) + { + return carried; + } + } + } + + return null; + } + + /// Returns the field's own entry , resolved; when absent or null. + internal CosObject? Own(CosName key) => FieldTree.Get(Document, Dictionary, key); + + /// Reports a deviation in this field. + internal void Report(string code, string message, DiagnosticSeverity severity = DiagnosticSeverity.Warning) => + Document.DiagnosticSink.Report(code, severity, message, objectReference: DiagnosticReference); + + /// Reads an Ff value: an unsigned 32-bit integer; reports what it repairs when is set. + internal uint ReadFlags(CosObject? value, bool report) + { + long bits; + switch (value) + { + case null: + return 0; + case CosInteger integer when integer.Value is >= 0 and <= uint.MaxValue: + bits = integer.Value; + break; + case CosInteger integer when integer.Value is < 0 and >= int.MinValue: + bits = (uint)(int)integer.Value; + if (report) + { + Report(DiagnosticCodes.FieldFlagsInvalid, "The field's Ff entry is negative; it reads as its 32-bit pattern."); + } + + break; + case CosReal real when double.IsFinite(real.Value) && real.Value is >= 0 and <= uint.MaxValue: + bits = (long)real.Value; + if (report) + { + Report(DiagnosticCodes.FieldFlagsInvalid, "The field's Ff entry shall be an integer; it is a real number, truncated."); + } + + break; + default: + if (report) + { + Report(DiagnosticCodes.FieldFlagsInvalid, "The field's Ff entry shall be an integer; it reads as 0."); + } + + return 0; + } + + // Bits 1-3 (Table 227) and 13-27 (Tables 229, 231, 233) are defined; every other bit shall be 0. + if (report && (bits & ~0x7FFF007L) != 0) + { + Report(DiagnosticCodes.FieldFlagsInvalid, "The field's Ff entry sets bits no field type defines, which shall be 0; they are kept."); + } + + return (uint)bits; + } + + /// Whether flag bit (1-based, as the tables number them) is set. + private protected bool HasFlag(int position) => (Flags & (1u << (position - 1))) != 0; + + /// Reads the field's own text string entry (§7.9.2.2); another type reads as absent with a diagnostic. + private protected string? ReadOwnText(CosName key) => Own(key) switch + { + null => null, + CosString text => text.DecodeText(), + _ => InvalidEntry(key, "a text string"), + }; + + /// Reads an integer entry, own or inherited; another type reads as absent with a diagnostic. + private protected int? ReadInteger(CosName key, bool inheritable) + { + switch (inheritable ? Inherited(key) : Own(key)) + { + case null: + return null; + case CosInteger integer when integer.Value is >= int.MinValue and <= int.MaxValue: + return (int)integer.Value; + default: + return InvalidEntry(key, "an integer"); + } + } + + /// Decodes a text value (a text string, or a text stream from PDF 1.5); a name or number reads as its text with a diagnostic. + private protected string? ReadTextValue(CosObject? value, CosName key) + { + switch (value) + { + case null: + return null; + case CosString text: + return text.DecodeText(); + case CosStream stream: + return new CosString(Document.DecodeStream(stream).Span).DecodeText(); + case CosName name: + ReportValueType(key, "a text string; it is a name, read as its text"); + return name.Value; + case CosNumber number: + ReportValueType(key, "a text string; it is a number, read as its text"); + return number is CosInteger integer + ? integer.Value.ToString(System.Globalization.CultureInfo.InvariantCulture) + : number.ToDouble().ToString(System.Globalization.CultureInfo.InvariantCulture); + default: + ReportValueType(key, "a text string; it reads as absent"); + return null; + } + } + + /// Reports a value (V or DV) of the wrong type. + private protected void ReportValueType(CosName key, string what) => + Report(DiagnosticCodes.FieldValueTypeInvalid, $"The field's {key.Value} entry shall be {what}."); + + /// Reports an entry of the wrong type and returns the default. + private protected T? InvalidEntry(CosName key, string expected) + { + Report(DiagnosticCodes.FieldEntryInvalid, $"The field's {key.Value} entry shall be {expected}; it is ignored."); + return default; + } +} + +/// What the field tree knows about a field when it creates the view. +internal sealed record FieldInfo( + PdfAcroForm Form, + CosDictionary Dictionary, + CosReference? Reference, + PdfNonTerminalField? Parent, + string PartialName, + string FullyQualifiedName, + CosDictionary[] Intermediates); diff --git a/src/Broadside/Forms/PdfFieldEnums.cs b/src/Broadside/Forms/PdfFieldEnums.cs new file mode 100644 index 00000000..0ca72918 --- /dev/null +++ b/src/Broadside/Forms/PdfFieldEnums.cs @@ -0,0 +1,88 @@ +namespace Broadside.Forms; + +/// The type of a form field, its inheritable FT entry. +/// ISO 32000-2 §12.7.4.1, Table 226. +public enum PdfFieldType +{ + /// No FT in the field or its ancestors, or a name Table 226 does not define. + Unknown = 0, + + /// Btn: a push button, check box or radio button field (§12.7.5.2). + Button = 1, + + /// Tx: a text field (§12.7.5.3). + Text = 2, + + /// Ch: a combo box or list box (§12.7.5.4). + Choice = 3, + + /// Sig (PDF 1.3): a signature field (§12.7.5.5). + Signature = 4, +} + +/// What a field is: a non-terminal field or one of the terminal field kinds, from its type and flags. +/// +/// ISO 32000-2 §12.7.2 (terminal and non-terminal fields), §12.7.5.2 Table 229 (Pushbutton and Radio decide the button kind) and +/// §12.7.5.4 Table 233 (Combo decides the choice kind). +/// +public enum PdfFieldKind +{ + /// A terminal field whose type is missing or unknown (). + Unknown = 0, + + /// A field whose children are fields (). + NonTerminal = 1, + + /// A text field (). + Text = 2, + + /// A push button (). + PushButton = 3, + + /// A check box (). + CheckBox = 4, + + /// A set of radio buttons (). + RadioButton = 5, + + /// A combo box (). + ComboBox = 6, + + /// A scrollable list box (). + ListBox = 7, + + /// A signature field (). + Signature = 8, +} + +/// The document-level signature flags of an interactive form, its SigFlags entry. +/// ISO 32000-2 §12.7.3, Table 225 (PDF 1.3). Bits the table does not define are kept as read. +[Flags] +public enum PdfSignatureFlags +{ + /// No flag set (the default). + None = 0, + + /// Bit 1: the document contains at least one signature field. + SignaturesExist = 1 << 0, + + /// Bit 2: the document contains signatures that a save other than an incremental update may invalidate. + AppendOnly = 1 << 1, +} + +/// Which fields a signature field lock dictionary locks, its Action entry. +/// ISO 32000-2 §12.7.5.5, Table 236. +public enum PdfSignatureFieldLockAction +{ + /// The entry is missing or is a name the table does not define. + Unknown = 0, + + /// All: all fields in the document. + All = 1, + + /// Include: the fields named in Fields. + Include = 2, + + /// Exclude: all fields except those named in Fields. + Exclude = 3, +} diff --git a/src/Broadside/Forms/PdfNonTerminalField.cs b/src/Broadside/Forms/PdfNonTerminalField.cs new file mode 100644 index 00000000..bdaeb1bb --- /dev/null +++ b/src/Broadside/Forms/PdfNonTerminalField.cs @@ -0,0 +1,23 @@ +namespace Broadside.Forms; + +/// A field whose children are fields: a container for entries its descendants inherit. +/// +/// ISO 32000-2 §12.7.2 and §12.7.4.1, Table 226: "a non-terminal field does not logically have a type of its own"; an FT it +/// carries is for its descendants. +/// +public sealed class PdfNonTerminalField : PdfField +{ + private readonly List _children = []; + + internal PdfNonTerminalField(FieldInfo info) + : base(info, PdfFieldKind.NonTerminal) + { + } + + /// Gets the field's children, in Kids order. + /// ISO 32000-2 §12.7.4.1, Table 226 (Kids). A snapshot of the field tree, taken when the tree was read. + public IReadOnlyList Children => _children; + + /// Adds a child while the field tree is built. + internal void AddChild(PdfField child) => _children.Add(child); +} diff --git a/src/Broadside/Forms/PdfSignatureField.cs b/src/Broadside/Forms/PdfSignatureField.cs new file mode 100644 index 00000000..a7cff27a --- /dev/null +++ b/src/Broadside/Forms/PdfSignatureField.cs @@ -0,0 +1,164 @@ +using Broadside.Annotations; +using Broadside.Diagnostics; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Forms; + +/// A signature field: the place of a digital signature, signed when its value is a signature dictionary. +/// +/// ISO 32000-2 §12.7.5.5, Tables 235 to 237; field type Sig (PDF 1.3). A signature field "shall never refer to more than one +/// annotation"; one with several widgets keeps them all and records SignatureFieldMultipleWidgets. Signature dictionaries, +/// seed values and validation are read raw here. +/// +public sealed class PdfSignatureField : PdfTerminalField +{ + internal PdfSignatureField(FieldInfo info, CosObject[] widgets) + : base(info, PdfFieldKind.Signature, widgets) + { + } + + /// Gets the signature dictionary the field holds when it is signed (V, inheritable), or . + /// ISO 32000-2 §12.7.5.5 and §12.8.1, Table 255. A value that is not a dictionary reads as absent with a FieldValueTypeInvalid diagnostic. + public CosDictionary? SignatureDictionary + { + get + { + switch (ValueObject) + { + case null: + return null; + case CosDictionary signature: + return signature; + default: + ReportValueType(FormNames.V, "a signature dictionary; it reads as absent"); + return null; + } + } + } + + /// Gets a value indicating whether the field has a signature value. + /// ISO 32000-2 §12.7.5.5. + public bool IsSigned => SignatureDictionary is not null; + + /// + /// Gets a value indicating whether the signature is visible: it has a widget whose rectangle has a width or height and whose + /// Hidden and NoView flags are clear. + /// + /// ISO 32000-2 §12.7.5.5: processors "shall treat such signatures as not visible". + public bool IsVisible => Widgets.Any(widget => + (widget.Rect.Width != 0 || widget.Rect.Height != 0) && (widget.Flags & (PdfAnnotationFlags.Hidden | PdfAnnotationFlags.NoView)) == 0); + + /// Gets the fields locked when the field is signed (Lock, PDF 1.5), or . + /// ISO 32000-2 §12.7.5.5, Tables 235 and 236; shall be an indirect reference, else read with SignatureFieldDictNotIndirect. + public PdfSignatureFieldLock? Lock => ReadIndirectDictionary(FormNames.Lock) is { } dictionary ? new PdfSignatureFieldLock(this, dictionary) : null; + + /// Gets the seed value dictionary that constrains the signature applied to the field (SV, PDF 1.5), as stored, or . + /// ISO 32000-2 §12.7.5.5, Tables 235 and 237; shall be an indirect reference, else read with SignatureFieldDictNotIndirect. + public CosDictionary? SeedValue => ReadIndirectDictionary(FormNames.SV); + + private CosDictionary? ReadIndirectDictionary(CosName key) + { + switch (Own(key)) + { + case null: + return null; + case CosDictionary dictionary: + if (Dictionary[key] is not CosReference) + { + Report(DiagnosticCodes.SignatureFieldDictNotIndirect, $"The signature field's {key.Value} entry shall be an indirect reference; it is a direct dictionary, read anyway."); + } + + return dictionary; + default: + return InvalidEntry(key, "a dictionary"); + } + } +} + +/// A signature field lock dictionary: the fields whose values may no longer change once the signature field is signed. +/// ISO 32000-2 §12.7.5.5, Table 236 (PDF 1.5). A live view over the dictionary. +public sealed class PdfSignatureFieldLock +{ + private readonly PdfSignatureField _field; + + internal PdfSignatureFieldLock(PdfSignatureField field, CosDictionary dictionary) + { + _field = field; + Dictionary = dictionary; + } + + /// Gets the lock dictionary. + public CosDictionary Dictionary { get; } + + /// Gets which fields are locked (Action, required). + /// ISO 32000-2 §12.7.5.5, Table 236. A missing or unknown name reads as with a diagnostic. + public PdfSignatureFieldLockAction Action + { + get + { + PdfSignatureFieldLockAction action = (FieldTree.Get(_field.Document, Dictionary, FormNames.Action) as CosName)?.Value switch + { + "All" => PdfSignatureFieldLockAction.All, + "Include" => PdfSignatureFieldLockAction.Include, + "Exclude" => PdfSignatureFieldLockAction.Exclude, + _ => PdfSignatureFieldLockAction.Unknown, + }; + if (action == PdfSignatureFieldLockAction.Unknown) + { + _field.Report(DiagnosticCodes.FieldEntryInvalid, "The signature field lock dictionary's Action shall be All, Include or Exclude (Table 236)."); + } + + return action; + } + } + + /// Gets the fully qualified names of the fields included or excluded (Fields); empty when absent. + /// ISO 32000-2 §12.7.5.5, Table 236: required for Include and Exclude. Resolve them with . + public IReadOnlyList FieldNames + { + get + { + if (FieldTree.Get(_field.Document, Dictionary, FormNames.Fields) is not CosArray array) + { + if (Action is PdfSignatureFieldLockAction.Include or PdfSignatureFieldLockAction.Exclude) + { + _field.Report(DiagnosticCodes.FieldEntryInvalid, "The signature field lock dictionary has no Fields array, which Table 236 requires for Include and Exclude."); + } + + return []; + } + + return [.. array.Select(element => _field.Document.Resolve(element)).OfType().Select(name => name.DecodeText())]; + } + } + + /// Gets the access permissions granted once signed (P, PDF 2.0): 1, 2 or 3; when absent (no effect). + /// ISO 32000-2 §12.7.5.5, Table 236. Another value reads as absent with a diagnostic. + public int? Permissions + { + get + { + switch (FieldTree.Get(_field.Document, Dictionary, FormNames.P)) + { + case null: + return null; + case CosInteger { Value: >= 1 and <= 3 } integer: + return (int)integer.Value; + default: + _field.Report(DiagnosticCodes.FieldEntryInvalid, "The signature field lock dictionary's P shall be 1, 2 or 3 (Table 236); it is ignored.", DiagnosticSeverity.Warning); + return null; + } + } + } +} + +/// A terminal field whose type (FT) is missing or is not one Table 226 defines. +/// ISO 32000-2 §12.7.4.1, Table 226: FT is required for terminal fields. Read with a FieldTypeMissing diagnostic, its widgets kept. +public sealed class PdfUnknownField : PdfTerminalField +{ + internal PdfUnknownField(FieldInfo info, CosObject[] widgets) + : base(info, PdfFieldKind.Unknown, widgets) + { + } +} diff --git a/src/Broadside/Forms/PdfTerminalField.cs b/src/Broadside/Forms/PdfTerminalField.cs new file mode 100644 index 00000000..5ebe8977 --- /dev/null +++ b/src/Broadside/Forms/PdfTerminalField.cs @@ -0,0 +1,62 @@ +using Broadside.Annotations; +using Broadside.Objects; + +namespace Broadside.Forms; + +/// A field without child fields: it holds a value and is shown on pages by its widget annotations. +/// +/// ISO 32000-2 §12.7.2: a terminal field's children are widget annotations, or, when it has a single widget, field and widget may be +/// one merged dictionary. and link the two both ways with the same +/// instances lists. +/// +public abstract class PdfTerminalField : PdfField +{ + private readonly CosObject[] _widgets; + + private protected PdfTerminalField(FieldInfo info, PdfFieldKind kind, CosObject[] widgets) + : base(info, kind) => _widgets = widgets; + + /// + /// Gets the field's widget annotations, in Kids order: the field dictionary itself when it is merged with its only widget. + /// Each is the instance the page holding it lists; a widget no page lists has no . + /// + /// + /// ISO 32000-2 §12.7.2, §12.7.4.1 (Table 226, Kids) and §12.5.6.19. A kid whose subtype is not Widget is not listed. + /// + public IReadOnlyList Widgets + { + get + { + var widgets = new List(_widgets.Length); + foreach (CosObject element in _widgets) + { + // A kid that is not a widget annotation (a Kids-only stub without Subtype, as in the radio example of §12.7.5.2.4) + // gets no annotation view here, so reading the field records nothing about it. + if (Document.Resolve(element) is CosDictionary dictionary && PdfWidgetAnnotation.IsWidget(Document, dictionary) && + Document.AnnotationIndex.Find(element, from: null) is PdfWidgetAnnotation widget) + { + widgets.Add(widget); + } + } + + return widgets; + } + } + + /// Gets the widget dictionaries (or references to them) in Kids order, as the tree read them. + internal IReadOnlyList WidgetElements => _widgets; + + /// Returns the position of among the field's widgets (its index in Kids), or -1. + internal int IndexOfWidget(CosDictionary widget) + { + for (int index = 0; index < _widgets.Length; index++) + { + if (ReferenceEquals(Document.Resolve(_widgets[index]), widget)) + { + return index; + } + } + + return -1; + } +} diff --git a/src/Broadside/Forms/PdfTextField.cs b/src/Broadside/Forms/PdfTextField.cs new file mode 100644 index 00000000..ff99e432 --- /dev/null +++ b/src/Broadside/Forms/PdfTextField.cs @@ -0,0 +1,76 @@ +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Forms; + +/// A text field: a box the user types text into. +/// ISO 32000-2 §12.7.5.3, Tables 231 and 232; field type Tx. Its text is variable text (§12.7.4.3). +public sealed class PdfTextField : PdfTerminalField +{ + internal PdfTextField(FieldInfo info, CosObject[] widgets) + : base(info, PdfFieldKind.Text, widgets) + { + } + + /// Gets the field's text (V, inheritable): a text string, or a text stream (PDF 1.5); when there is none. + /// + /// ISO 32000-2 §12.7.5.3. A name or number reads as its text with a FieldValueTypeInvalid diagnostic. A password field + /// may hold a value although writers should never store one; it is returned as stored. + /// + public string? Value => ReadTextValue(ValueObject, FormNames.V); + + /// Gets the text the field reverts to on a reset-form action (DV, inheritable), or . + /// ISO 32000-2 §12.7.4.1, Table 226, and §12.7.5.3. + public string? DefaultValue => ReadTextValue(DefaultValueObject, FormNames.DV); + + /// Gets the maximum length of the field's text in characters (MaxLen, inheritable), or when unlimited. + /// ISO 32000-2 §12.7.5.3, Table 232. + public int? MaxLength => ReadInteger(FormNames.MaxLen, inheritable: true); + + /// Gets a value indicating whether the text may span several lines (Ff bit 13, Multiline). + /// ISO 32000-2 §12.7.5.3, Table 231. + public bool IsMultiline => HasFlag(13); + + /// Gets a value indicating whether the field is for a password, not echoed (Ff bit 14, Password). + /// ISO 32000-2 §12.7.5.3, Table 231. + public bool IsPassword => HasFlag(14); + + /// Gets a value indicating whether the text is the path of a file submitted as the value (Ff bit 21, FileSelect, PDF 1.4). + /// ISO 32000-2 §12.7.5.3, Table 231. + public bool IsFileSelect => HasFlag(21); + + /// Gets a value indicating whether the text shall not be spell-checked (Ff bit 23, DoNotSpellCheck, PDF 1.4). + /// ISO 32000-2 §12.7.5.3, Table 231. + public bool IsDoNotSpellCheck => HasFlag(23); + + /// Gets a value indicating whether the field shall not scroll to fit more text (Ff bit 24, DoNotScroll, PDF 1.4). + /// ISO 32000-2 §12.7.5.3, Table 231. + public bool IsDoNotScroll => HasFlag(24); + + /// Gets a value indicating whether the field is divided into equally spaced combs (Ff bit 25, Comb, PDF 1.5). + /// + /// ISO 32000-2 §12.7.5.3, Table 231: may be set only with MaxLen and with Multiline, Password and FileSelect clear. The flag + /// is returned as stored; when those conditions fail a TextCombInvalid diagnostic is recorded. + /// + public bool IsComb + { + get + { + if (!HasFlag(25)) + { + return false; + } + + if (MaxLength is null || IsMultiline || IsPassword || IsFileSelect) + { + Report(DiagnosticCodes.TextCombInvalid, "The Comb flag may be set only with a MaxLen entry and with the Multiline, Password and FileSelect flags clear (Table 231)."); + } + + return true; + } + } + + /// Gets a value indicating whether the value is rich text, held in (Ff bit 26, RichText, PDF 1.5). + /// ISO 32000-2 §12.7.5.3, Table 231. + public bool IsRichText => HasFlag(26); +} diff --git a/src/Broadside/Forms/PdfXfaForm.cs b/src/Broadside/Forms/PdfXfaForm.cs new file mode 100644 index 00000000..39049b16 --- /dev/null +++ b/src/Broadside/Forms/PdfXfaForm.cs @@ -0,0 +1,97 @@ +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside.Forms; + +/// The XFA resource of an interactive form: XML Data Package packets, kept as data (parse-and-preserve). +/// +/// ISO 32000-2 Annex K and §12.7.3, Table 224 (XFA, PDF 1.5, deprecated in PDF 2.0). The packets are neither parsed nor +/// rendered; the interactive form's fields remain what Broadside reads. Opening a document with a non-empty XFA resource records an +/// XfaFormPresent Information diagnostic, and XfaFormDynamic too when the catalog's NeedsRendering is true. +/// +public sealed class PdfXfaForm +{ + private readonly PdfAcroForm _form; + + internal PdfXfaForm(PdfAcroForm form, CosObject value) + { + _form = form; + Value = value; + } + + /// Gets the XFA entry, resolved: one stream holding the whole XDP document, or an array of packet names and streams. + /// ISO 32000-2 Annex K. + public CosObject Value { get; } + + /// + /// Gets a value indicating whether the form is dynamic: the catalog's NeedsRendering is true, so the pages are placeholders + /// and the content comes from the XFA template. + /// + /// ISO 32000-2 §7.7.2, Table 29 (NeedsRendering, PDF 1.7, deprecated in PDF 2.0), and Annex K. + public bool IsDynamic => FieldTree.Get(_form.Document, _form.Document.Catalog, FormNames.NeedsRendering) is CosBoolean { Value: true }; + + /// Gets the packets in order: one unnamed packet when the entry is a stream, else one per name and stream pair. + /// + /// ISO 32000-2 Annex K: the array form is [name1 stream1 name2 stream2 ...], names being text strings such as + /// template and datasets. A pair whose name is not a string or whose value is not a stream, and an odd element + /// left over, are skipped with an XfaPacketsInvalid diagnostic. + /// + public IReadOnlyList Packets + { + get + { + PdfDocument document = _form.Document; + switch (Value) + { + case CosStream stream: + return [new PdfXfaPacket(null, stream, XfaReference())]; + case CosArray array: + var packets = new List(array.Count / 2); + bool invalid = array.Count % 2 != 0; + for (int index = 0; index + 1 < array.Count; index += 2) + { + if (document.Resolve(array[index]) is CosString name && document.Resolve(array[index + 1]) is CosStream packet) + { + packets.Add(new PdfXfaPacket(name.DecodeText(), packet, array[index + 1] as CosReference)); + } + else + { + invalid = true; + } + } + + if (invalid) + { + _form.Report(DiagnosticCodes.XfaPacketsInvalid, "The XFA array shall alternate packet names (text strings) and streams (Annex K); the elements that do not are skipped."); + } + + return packets; + default: + return []; + } + } + } + + private CosReference? XfaReference() => _form.Dictionary.TryGetValue(FormNames.XFA, out CosObject? entry) ? entry as CosReference : null; +} + +/// One packet of an XFA resource: a named part of the XML Data Package, such as template or datasets. +/// ISO 32000-2 Annex K. Decode with to read its XML. +public sealed class PdfXfaPacket +{ + internal PdfXfaPacket(string? name, CosStream stream, CosReference? reference) + { + Name = name; + Stream = stream; + Reference = reference; + } + + /// Gets the packet name, or when the XFA entry is a single stream. + public string? Name { get; } + + /// Gets the stream holding the packet's XML. + public CosStream Stream { get; } + + /// Gets the indirect reference to , or . + public CosReference? Reference { get; } +} diff --git a/src/Broadside/Parsing/DiagnosticCodes.Forms.cs b/src/Broadside/Parsing/DiagnosticCodes.Forms.cs new file mode 100644 index 00000000..f9fea80c --- /dev/null +++ b/src/Broadside/Parsing/DiagnosticCodes.Forms.cs @@ -0,0 +1,47 @@ +namespace Broadside.Parsing; + +/// Diagnostic codes for interactive forms (issue #74). +internal static partial class DiagnosticCodes +{ + // The interactive form dictionary (§12.7.3, Table 224) and XFA (Annex K). + public const string AcroFormInvalid = nameof(AcroFormInvalid); + public const string AcroFormFieldsMissing = nameof(AcroFormFieldsMissing); + public const string AcroFormEntryInvalid = nameof(AcroFormEntryInvalid); + public const string XfaFormPresent = nameof(XfaFormPresent); + public const string XfaFormDynamic = nameof(XfaFormDynamic); + public const string XfaPacketsInvalid = nameof(XfaPacketsInvalid); + + // The field tree (§12.7.2, §12.7.4.1, §12.7.4.2): reported when the tree is built. + public const string FieldReferenceInvalid = nameof(FieldReferenceInvalid); + public const string FieldNotIndirect = nameof(FieldNotIndirect); + public const string FieldTreeCycle = nameof(FieldTreeCycle); + public const string FieldTreeTooDeep = nameof(FieldTreeTooDeep); + public const string FieldNotRoot = nameof(FieldNotRoot); + public const string FieldParentMissing = nameof(FieldParentMissing); + public const string FieldParentMismatch = nameof(FieldParentMismatch); + public const string FieldKidsMixed = nameof(FieldKidsMixed); + public const string FieldNameMissing = nameof(FieldNameMissing); + public const string FieldNameHasPeriod = nameof(FieldNameHasPeriod); + public const string FieldNameDuplicateInconsistent = nameof(FieldNameDuplicateInconsistent); + public const string FieldTypeMissing = nameof(FieldTypeMissing); + public const string ButtonFlagsConflict = nameof(ButtonFlagsConflict); + public const string SignatureFieldMultipleWidgets = nameof(SignatureFieldMultipleWidgets); + public const string WidgetNotInFieldTree = nameof(WidgetNotInFieldTree); + + // Field entries and values (§12.7.4, §12.7.5): reported when read. + public const string FieldEntryInvalid = nameof(FieldEntryInvalid); + public const string FieldFlagsInvalid = nameof(FieldFlagsInvalid); + public const string FieldValueTypeInvalid = nameof(FieldValueTypeInvalid); + public const string DefaultAppearanceMissing = nameof(DefaultAppearanceMissing); + public const string TextCombInvalid = nameof(TextCombInvalid); + public const string ButtonValueStateMismatch = nameof(ButtonValueStateMismatch); + public const string ButtonValueUnknownState = nameof(ButtonValueUnknownState); + public const string ButtonStatesAmbiguous = nameof(ButtonStatesAmbiguous); + public const string ButtonOnStateMissing = nameof(ButtonOnStateMissing); + public const string ButtonOptLengthMismatch = nameof(ButtonOptLengthMismatch); + public const string ChoiceOptionInvalid = nameof(ChoiceOptionInvalid); + public const string ChoiceOptionsInherited = nameof(ChoiceOptionsInherited); + public const string ChoiceValueNotInOptions = nameof(ChoiceValueNotInOptions); + public const string ChoiceIndicesInvalid = nameof(ChoiceIndicesInvalid); + public const string SignatureFieldDictNotIndirect = nameof(SignatureFieldDictNotIndirect); +} diff --git a/src/Broadside/PdfActionTarget.cs b/src/Broadside/PdfActionTarget.cs index 46f987ec..8a074921 100644 --- a/src/Broadside/PdfActionTarget.cs +++ b/src/Broadside/PdfActionTarget.cs @@ -7,8 +7,8 @@ namespace Broadside; /// of a hide action's T or of a form action's Fields. /// /// -/// ISO 32000-2 §12.6.4.11, Table 214, and §12.7.6.2-12.7.6.3, Tables 239 and 241. Field names are not resolved here: that needs the -/// field tree (§12.7.4.2). +/// ISO 32000-2 §12.6.4.11, Table 214, and §12.7.6.2-12.7.6.3, Tables 239 and 241. Resolve a target to the fields it names with +/// (§12.7.4.2). /// public sealed class PdfActionTarget { diff --git a/src/Broadside/PdfDocument.Forms.cs b/src/Broadside/PdfDocument.Forms.cs new file mode 100644 index 00000000..90381b8e --- /dev/null +++ b/src/Broadside/PdfDocument.Forms.cs @@ -0,0 +1,83 @@ +using Broadside.Diagnostics; +using Broadside.Forms; +using Broadside.Objects; +using Broadside.Parsing; + +namespace Broadside; + +/// Interactive forms (issue #74): ISO 32000-2 §12.7 and the catalog's AcroForm and NeedsRendering entries (§7.7.2). +public sealed partial class PdfDocument +{ + private PdfAcroForm? _acroForm; + + /// Gets the document's interactive form, or when the catalog has no AcroForm dictionary. + /// + /// ISO 32000-2 §7.7.2, Table 29 (PDF 1.2), and §12.7.3. The same view is returned while the catalog's AcroForm is the same + /// dictionary. An entry that is not a dictionary reads as absent with an AcroFormInvalid diagnostic. + /// + public PdfAcroForm? AcroForm + { + get + { + Catalog.TryGetValue(FormNames.AcroForm, out CosObject? entry); + switch (Resolve(entry)) + { + case CosNull: + return null; + case CosDictionary dictionary: + PdfAcroForm? cached = Volatile.Read(ref _acroForm); + if (cached is not null && ReferenceEquals(cached.Dictionary, dictionary)) + { + return cached; + } + + var created = new PdfAcroForm(this, dictionary, entry as CosReference); + PdfAcroForm? raced = Interlocked.CompareExchange(ref _acroForm, created, cached); + return raced == cached ? created : (ReferenceEquals(raced!.Dictionary, dictionary) ? raced : created); + default: + CatalogView.Report(DiagnosticCodes.AcroFormInvalid, "The catalog's AcroForm entry shall be the interactive form dictionary; it is ignored."); + return null; + } + } + } + + /// + /// Records, when the document is opened, that its interactive form carries an XFA resource (and whether the form is dynamic): a + /// legal but deprecated feature Broadside keeps without rendering, so an Information diagnostic. No stream is decoded. + /// + /// ISO 32000-2 Annex K and §7.7.2, Table 29 (NeedsRendering). + private void DetectXfa() + { + if (!Catalog.ContainsKey(FormNames.AcroForm) || Resolve(Catalog[FormNames.AcroForm]) is not CosDictionary acroForm || + !acroForm.TryGetValue(FormNames.XFA, out CosObject? entry)) + { + return; + } + + CosReference? reference = Catalog[FormNames.AcroForm] as CosReference ?? CatalogReference; + bool present = Resolve(entry) switch + { + CosStream => true, + CosArray array => array.Count > 0, + _ => false, + }; + if (!present) + { + return; + } + + _diagnostics.Report( + DiagnosticCodes.XfaFormPresent, + DiagnosticSeverity.Information, + "The interactive form has an XFA resource (Annex K, deprecated in PDF 2.0); it is kept but not used: the AcroForm fields are read.", + objectReference: reference); + if (Resolve(Catalog.TryGetValue(FormNames.NeedsRendering, out CosObject? needsRendering) ? needsRendering : null) is CosBoolean { Value: true }) + { + _diagnostics.Report( + DiagnosticCodes.XfaFormDynamic, + DiagnosticSeverity.Information, + "The catalog's NeedsRendering is true: the document is a dynamic XFA form whose pages are placeholders; its content is not rendered.", + objectReference: CatalogReference); + } + } +} diff --git a/src/Broadside/PdfDocument.cs b/src/Broadside/PdfDocument.cs index 4220f1ff..a3488fb0 100644 --- a/src/Broadside/PdfDocument.cs +++ b/src/Broadside/PdfDocument.cs @@ -973,6 +973,7 @@ internal static PdfDocument Read(PdfSource source, EngineConfiguration configura PdfLinearization? linearization = LinearizationReader.Read(source, loader, diagnostics); var document = new PdfDocument(source, diagnostics, loader, streams, catalog, revisions, linearization, security); + document.DetectXfa(); // Table 15: ID is "required in PDF 2.0 or if an Encrypt entry is present" (the latter is the security handler's // EncryptionIdMissing). diff --git a/src/Broadside/PublicAPI.Unshipped.txt b/src/Broadside/PublicAPI.Unshipped.txt index 721ad640..ba7c3d08 100644 --- a/src/Broadside/PublicAPI.Unshipped.txt +++ b/src/Broadside/PublicAPI.Unshipped.txt @@ -321,6 +321,7 @@ Broadside.Annotations.PdfWidgetAnnotation Broadside.Annotations.PdfWidgetAnnotation.Action.get -> Broadside.PdfAction? Broadside.Annotations.PdfWidgetAnnotation.AdditionalActions.get -> Broadside.PdfAnnotationAdditionalActions? Broadside.Annotations.PdfWidgetAnnotation.AppearanceCharacteristics.get -> Broadside.Annotations.PdfAppearanceCharacteristics? +Broadside.Annotations.PdfWidgetAnnotation.Field.get -> Broadside.Forms.PdfTerminalField? Broadside.Annotations.PdfWidgetAnnotation.HighlightMode.get -> Broadside.Annotations.PdfHighlightMode Broadside.Annotations.PdfWidgetAnnotation.Parent.get -> Broadside.Objects.CosDictionary? abstract Broadside.PdfAction.Kind.get -> Broadside.PdfActionKind @@ -589,6 +590,140 @@ Broadside.Content.ShadingEvent.IsHidden.get -> bool Broadside.Content.ShadingEvent.ResourceName.get -> System.ReadOnlySpan Broadside.Content.ShadingEvent.Shading.get -> Broadside.Objects.CosObject? Broadside.Content.ShadingEvent.ShadingEvent() -> void +Broadside.Forms.PdfAcroForm +Broadside.Forms.PdfAcroForm.AllFields.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Forms.PdfAcroForm.CalculationOrder.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Forms.PdfAcroForm.DefaultAppearance.get -> string? +Broadside.Forms.PdfAcroForm.DefaultResources.get -> Broadside.Objects.CosDictionary? +Broadside.Forms.PdfAcroForm.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Forms.PdfAcroForm.Fields.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Forms.PdfAcroForm.FindField(Broadside.Objects.CosDictionary! dictionary) -> Broadside.Forms.PdfField? +Broadside.Forms.PdfAcroForm.FindField(string! fullyQualifiedName) -> Broadside.Forms.PdfField? +Broadside.Forms.PdfAcroForm.FindFields(Broadside.PdfActionTarget! target) -> System.Collections.Generic.IReadOnlyList! +Broadside.Forms.PdfAcroForm.FindFields(string! fullyQualifiedName) -> System.Collections.Generic.IReadOnlyList! +Broadside.Forms.PdfAcroForm.NeedAppearances.get -> bool +Broadside.Forms.PdfAcroForm.Quadding.get -> Broadside.Annotations.PdfTextJustification +Broadside.Forms.PdfAcroForm.Reference.get -> Broadside.Objects.CosReference? +Broadside.Forms.PdfAcroForm.SignatureFlags.get -> Broadside.Forms.PdfSignatureFlags +Broadside.Forms.PdfAcroForm.TerminalFields.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Forms.PdfAcroForm.Xfa.get -> Broadside.Forms.PdfXfaForm? +Broadside.Forms.PdfButtonField +Broadside.Forms.PdfCheckBoxField +Broadside.Forms.PdfCheckBoxField.IsChecked.get -> bool +Broadside.Forms.PdfChoiceField +Broadside.Forms.PdfChoiceField.DefaultValues.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Forms.PdfChoiceField.IsCommitOnSelectionChange.get -> bool +Broadside.Forms.PdfChoiceField.IsMultiSelect.get -> bool +Broadside.Forms.PdfChoiceField.IsSort.get -> bool +Broadside.Forms.PdfChoiceField.Options.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Forms.PdfChoiceField.SelectedIndices.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Forms.PdfChoiceField.StoredIndices.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Forms.PdfChoiceField.TopIndex.get -> int +Broadside.Forms.PdfChoiceField.Values.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Forms.PdfChoiceOption +Broadside.Forms.PdfChoiceOption.DisplayText.get -> string! +Broadside.Forms.PdfChoiceOption.ExportValue.get -> string! +Broadside.Forms.PdfComboBoxField +Broadside.Forms.PdfComboBoxField.IsDoNotSpellCheck.get -> bool +Broadside.Forms.PdfComboBoxField.IsEditable.get -> bool +Broadside.Forms.PdfField +Broadside.Forms.PdfField.AdditionalActions.get -> Broadside.PdfFieldAdditionalActions? +Broadside.Forms.PdfField.AlternateName.get -> string? +Broadside.Forms.PdfField.DefaultAppearance.get -> string? +Broadside.Forms.PdfField.DefaultStyle.get -> string? +Broadside.Forms.PdfField.DefaultValueObject.get -> Broadside.Objects.CosObject? +Broadside.Forms.PdfField.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Forms.PdfField.FieldType.get -> Broadside.Forms.PdfFieldType +Broadside.Forms.PdfField.FieldTypeName.get -> Broadside.Objects.CosName? +Broadside.Forms.PdfField.Flags.get -> uint +Broadside.Forms.PdfField.Form.get -> Broadside.Forms.PdfAcroForm! +Broadside.Forms.PdfField.FullyQualifiedName.get -> string! +Broadside.Forms.PdfField.IsNoExport.get -> bool +Broadside.Forms.PdfField.IsReadOnly.get -> bool +Broadside.Forms.PdfField.IsRequired.get -> bool +Broadside.Forms.PdfField.Kind.get -> Broadside.Forms.PdfFieldKind +Broadside.Forms.PdfField.MappingName.get -> string? +Broadside.Forms.PdfField.Parent.get -> Broadside.Forms.PdfNonTerminalField? +Broadside.Forms.PdfField.PartialName.get -> string! +Broadside.Forms.PdfField.Quadding.get -> Broadside.Annotations.PdfTextJustification +Broadside.Forms.PdfField.Reference.get -> Broadside.Objects.CosReference? +Broadside.Forms.PdfField.RichValue.get -> string? +Broadside.Forms.PdfField.ValueObject.get -> Broadside.Objects.CosObject? +Broadside.Forms.PdfFieldKind +Broadside.Forms.PdfFieldKind.CheckBox = 4 -> Broadside.Forms.PdfFieldKind +Broadside.Forms.PdfFieldKind.ComboBox = 6 -> Broadside.Forms.PdfFieldKind +Broadside.Forms.PdfFieldKind.ListBox = 7 -> Broadside.Forms.PdfFieldKind +Broadside.Forms.PdfFieldKind.NonTerminal = 1 -> Broadside.Forms.PdfFieldKind +Broadside.Forms.PdfFieldKind.PushButton = 3 -> Broadside.Forms.PdfFieldKind +Broadside.Forms.PdfFieldKind.RadioButton = 5 -> Broadside.Forms.PdfFieldKind +Broadside.Forms.PdfFieldKind.Signature = 8 -> Broadside.Forms.PdfFieldKind +Broadside.Forms.PdfFieldKind.Text = 2 -> Broadside.Forms.PdfFieldKind +Broadside.Forms.PdfFieldKind.Unknown = 0 -> Broadside.Forms.PdfFieldKind +Broadside.Forms.PdfFieldType +Broadside.Forms.PdfFieldType.Button = 1 -> Broadside.Forms.PdfFieldType +Broadside.Forms.PdfFieldType.Choice = 3 -> Broadside.Forms.PdfFieldType +Broadside.Forms.PdfFieldType.Signature = 4 -> Broadside.Forms.PdfFieldType +Broadside.Forms.PdfFieldType.Text = 2 -> Broadside.Forms.PdfFieldType +Broadside.Forms.PdfFieldType.Unknown = 0 -> Broadside.Forms.PdfFieldType +Broadside.Forms.PdfListBoxField +Broadside.Forms.PdfNonTerminalField +Broadside.Forms.PdfNonTerminalField.Children.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Forms.PdfPushButtonField +Broadside.Forms.PdfRadioButtonField +Broadside.Forms.PdfRadioButtonField.IsNoToggleToOff.get -> bool +Broadside.Forms.PdfRadioButtonField.IsRadiosInUnison.get -> bool +Broadside.Forms.PdfSignatureField +Broadside.Forms.PdfSignatureField.IsSigned.get -> bool +Broadside.Forms.PdfSignatureField.IsVisible.get -> bool +Broadside.Forms.PdfSignatureField.Lock.get -> Broadside.Forms.PdfSignatureFieldLock? +Broadside.Forms.PdfSignatureField.SeedValue.get -> Broadside.Objects.CosDictionary? +Broadside.Forms.PdfSignatureField.SignatureDictionary.get -> Broadside.Objects.CosDictionary? +Broadside.Forms.PdfSignatureFieldLock +Broadside.Forms.PdfSignatureFieldLock.Action.get -> Broadside.Forms.PdfSignatureFieldLockAction +Broadside.Forms.PdfSignatureFieldLock.Dictionary.get -> Broadside.Objects.CosDictionary! +Broadside.Forms.PdfSignatureFieldLock.FieldNames.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Forms.PdfSignatureFieldLock.Permissions.get -> int? +Broadside.Forms.PdfSignatureFieldLockAction +Broadside.Forms.PdfSignatureFieldLockAction.All = 1 -> Broadside.Forms.PdfSignatureFieldLockAction +Broadside.Forms.PdfSignatureFieldLockAction.Exclude = 3 -> Broadside.Forms.PdfSignatureFieldLockAction +Broadside.Forms.PdfSignatureFieldLockAction.Include = 2 -> Broadside.Forms.PdfSignatureFieldLockAction +Broadside.Forms.PdfSignatureFieldLockAction.Unknown = 0 -> Broadside.Forms.PdfSignatureFieldLockAction +Broadside.Forms.PdfSignatureFlags +Broadside.Forms.PdfSignatureFlags.AppendOnly = 2 -> Broadside.Forms.PdfSignatureFlags +Broadside.Forms.PdfSignatureFlags.None = 0 -> Broadside.Forms.PdfSignatureFlags +Broadside.Forms.PdfSignatureFlags.SignaturesExist = 1 -> Broadside.Forms.PdfSignatureFlags +Broadside.Forms.PdfTerminalField +Broadside.Forms.PdfTerminalField.Widgets.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Forms.PdfTextField +Broadside.Forms.PdfTextField.DefaultValue.get -> string? +Broadside.Forms.PdfTextField.IsComb.get -> bool +Broadside.Forms.PdfTextField.IsDoNotScroll.get -> bool +Broadside.Forms.PdfTextField.IsDoNotSpellCheck.get -> bool +Broadside.Forms.PdfTextField.IsFileSelect.get -> bool +Broadside.Forms.PdfTextField.IsMultiline.get -> bool +Broadside.Forms.PdfTextField.IsPassword.get -> bool +Broadside.Forms.PdfTextField.IsRichText.get -> bool +Broadside.Forms.PdfTextField.MaxLength.get -> int? +Broadside.Forms.PdfTextField.Value.get -> string? +Broadside.Forms.PdfToggleButtonField +Broadside.Forms.PdfToggleButtonField.DefaultValue.get -> Broadside.Objects.CosName? +Broadside.Forms.PdfToggleButtonField.ExportValue.get -> string? +Broadside.Forms.PdfToggleButtonField.GetAppearanceState(Broadside.Annotations.PdfWidgetAnnotation! widget) -> Broadside.Objects.CosName! +Broadside.Forms.PdfToggleButtonField.GetOnState(Broadside.Annotations.PdfWidgetAnnotation! widget) -> Broadside.Objects.CosName? +Broadside.Forms.PdfToggleButtonField.GetWidgetExportValue(Broadside.Annotations.PdfWidgetAnnotation! widget) -> string? +Broadside.Forms.PdfToggleButtonField.OnStateNames.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Forms.PdfToggleButtonField.Options.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Forms.PdfToggleButtonField.SelectedWidgets.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Forms.PdfToggleButtonField.Value.get -> Broadside.Objects.CosName! +Broadside.Forms.PdfUnknownField +Broadside.Forms.PdfXfaForm +Broadside.Forms.PdfXfaForm.IsDynamic.get -> bool +Broadside.Forms.PdfXfaForm.Packets.get -> System.Collections.Generic.IReadOnlyList! +Broadside.Forms.PdfXfaForm.Value.get -> Broadside.Objects.CosObject! +Broadside.Forms.PdfXfaPacket +Broadside.Forms.PdfXfaPacket.Name.get -> string? +Broadside.Forms.PdfXfaPacket.Reference.get -> Broadside.Objects.CosReference? +Broadside.Forms.PdfXfaPacket.Stream.get -> Broadside.Objects.CosStream! Broadside.Graphics.BlendMode Broadside.Graphics.BlendMode.Color = 14 -> Broadside.Graphics.BlendMode Broadside.Graphics.BlendMode.ColorBurn = 7 -> Broadside.Graphics.BlendMode @@ -774,6 +909,7 @@ Broadside.Objects.CosString.CosString(System.ReadOnlySpan bytes, bool hexa Broadside.Objects.CosString.DecodeText() -> string! Broadside.Objects.CosString.Equals(Broadside.Objects.CosString? other) -> bool Broadside.Objects.CosString.IsHexadecimal.get -> bool +Broadside.PdfDocument.AcroForm.get -> Broadside.Forms.PdfAcroForm? Broadside.PdfPage.Annotations.get -> System.Collections.Generic.IReadOnlyList! Broadside.PdfAction.EnumerateActionTree(int maxDepth = 64) -> System.Collections.Generic.IEnumerable! Broadside.PdfAction.Next.get -> System.Collections.Generic.IReadOnlyList! @@ -1351,6 +1487,7 @@ override Broadside.Content.CompositeContentProcessor.RestoreState(Broadside.Cont override Broadside.Content.CompositeContentProcessor.SaveState(Broadside.Content.ContentContext! context) -> void override Broadside.Content.CompositeContentProcessor.ShowGlyph(in Broadside.Content.GlyphEvent glyph, Broadside.Content.ContentContext! context) -> void override Broadside.Content.CompositeContentProcessor.VisitOperator(in Broadside.Content.ContentOperator op, Broadside.Content.ContentContext! context) -> void +override Broadside.Forms.PdfChoiceOption.ToString() -> string! override Broadside.Graphics.Matrix.Equals(object? obj) -> bool override Broadside.Graphics.Matrix.GetHashCode() -> int override Broadside.Graphics.Matrix.ToString() -> string! diff --git a/tests/Broadside.Fuzz/Broadside.Fuzz.csproj b/tests/Broadside.Fuzz/Broadside.Fuzz.csproj index 4066e0c2..2d28de28 100644 --- a/tests/Broadside.Fuzz/Broadside.Fuzz.csproj +++ b/tests/Broadside.Fuzz/Broadside.Fuzz.csproj @@ -22,6 +22,7 @@ + diff --git a/tests/Broadside.TestSupport/Corpus.cs b/tests/Broadside.TestSupport/Corpus.cs index 41eb2441..63888177 100644 --- a/tests/Broadside.TestSupport/Corpus.cs +++ b/tests/Broadside.TestSupport/Corpus.cs @@ -70,6 +70,8 @@ public static class Corpus "declarations.pdf", "actions-all.pdf", "actions-preserved.pdf", + "acroform-fields.pdf", + "acroform-xfa.pdf", ]; private static readonly string[] Malformed = diff --git a/tests/Broadside.TestSupport/DocumentWalker.cs b/tests/Broadside.TestSupport/DocumentWalker.cs index d47c2579..f9b4aeae 100644 --- a/tests/Broadside.TestSupport/DocumentWalker.cs +++ b/tests/Broadside.TestSupport/DocumentWalker.cs @@ -13,7 +13,7 @@ public sealed record DocumentWalkResult(int Pages, int Objects, int Streams, lon /// /// Reads everything the document model exposes, so that "the file opens" means more than "the trailer parsed" (objects load /// lazily, issue #45): version, trailer, revisions, linearization and hint tables, security, every page's boxes, rotation, user unit -/// and resources, the outline and every named destination (issue #70), every action through (issue #73), every annotation with its appearances (issue #71), every indirect object reachable from the trailer and every object number below the trailer's Size, and +/// and resources, the outline and every named destination (issue #70), every action through (issue #73), every annotation with its appearances (issue #71), the interactive form through (issue #74), every indirect object reachable from the trailer and every object number below the trailer's Size, and /// every stream decoded through the filter pipeline (image filters that are not implemented yet end in a diagnostic, not an /// exception). Used by the real-world corpus gate (issue #47) and meant to be shared with the open-and-walk fuzz target and /// benchmark (issue #48): link this file as source there, as is. Public API only. @@ -62,6 +62,7 @@ public static DocumentWalkResult Walk(PdfDocument document) WalkNavigation(document); _ = ActionWalker.Walk(document); _ = AnnotationWalker.Walk(document); + _ = FormWalker.Walk(document); var walk = new GraphWalk(document); walk.Visit(document.Trailer); diff --git a/tests/Broadside.TestSupport/FormWalker.cs b/tests/Broadside.TestSupport/FormWalker.cs new file mode 100644 index 00000000..b8ed8343 --- /dev/null +++ b/tests/Broadside.TestSupport/FormWalker.cs @@ -0,0 +1,94 @@ +using System.Reflection; +using System.Runtime.ExceptionServices; +using Broadside.Annotations; +using Broadside.Forms; +using Broadside.Objects; + +namespace Broadside.TestSupport; + +/// +/// Reads everything the interactive form model exposes (issue #74): every public property of the form, of every field and of its +/// signature lock, every button widget's on state, export value and appearance state, the field each widget of every page resolves +/// to, and every XFA packet. Public API only (reflection over public properties, so a property added later is read too). Exceptions +/// the library throws propagate unwrapped. +/// +/// ISO 32000-2 §12.7 and Annex K. +public static class FormWalker +{ + /// Walks the interactive form of . + /// An open document. + /// The number of fields read. + public static int Walk(PdfDocument document) + { + ArgumentNullException.ThrowIfNull(document); + if (document.AcroForm is not { } form) + { + return 0; + } + + ReadProperties(form); + int count = 0; + foreach (PdfField field in form.AllFields) + { + count++; + ReadProperties(field); + _ = form.FindFields(field.FullyQualifiedName).Count; + switch (field) + { + case PdfToggleButtonField toggle: + foreach (PdfWidgetAnnotation widget in toggle.Widgets) + { + _ = (toggle.GetOnState(widget), toggle.GetWidgetExportValue(widget), toggle.GetAppearanceState(widget)); + } + + break; + case PdfSignatureField { Lock: { } fieldLock }: + ReadProperties(fieldLock); + break; + } + } + + foreach (PdfXfaPacket packet in form.Xfa?.Packets ?? []) + { + ReadProperties(packet); + } + + foreach (PdfPage page in document.Pages) + { + foreach (PdfWidgetAnnotation widget in page.Annotations.OfType()) + { + _ = widget.Field?.FullyQualifiedName; + } + } + + return count; + } + + private static void ReadProperties(object view) + { + foreach (PropertyInfo property in view.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + if (property.GetIndexParameters().Length > 0) + { + continue; + } + + try + { + object? value = property.GetValue(view); + if (value is System.Collections.IEnumerable sequence and not string and not CosObject) + { + foreach (object? item in sequence) + { + _ = item; + } + } + } + catch (TargetInvocationException exception) when (exception.InnerException is not null) + { + ExceptionDispatchInfo.Capture(exception.InnerException).Throw(); + throw; + } + } + } +} diff --git a/tests/Broadside.Tests/Document/EngineTests.cs b/tests/Broadside.Tests/Document/EngineTests.cs index 512fc7bf..0d951db8 100644 --- a/tests/Broadside.Tests/Document/EngineTests.cs +++ b/tests/Broadside.Tests/Document/EngineTests.cs @@ -65,7 +65,7 @@ public void Strict_mode_opens_every_well_formed_file(string fileName) using PdfDocument document = PdfDocument.Open(Corpus.Path(fileName), new PdfOptions().UseStrict()); Assert.NotEmpty(document.Pages); - Assert.Empty(document.Diagnostics); + Assert.DoesNotContain(document.Diagnostics, diagnostic => diagnostic.Severity > Broadside.Diagnostics.DiagnosticSeverity.Information); } [Fact] diff --git a/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt b/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt index bcf11eaa..707e2685 100644 --- a/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt +++ b/tests/Broadside.Tests/Document/Snapshots/RealWorldCorpusTests.The_per_corpus_counts_and_diagnostic_histograms_match_the_snapshot.verified.txt @@ -1,6 +1,6 @@ pdfjs: 989 files - Clean: 659 - Diagnostics: 316 + Clean: 655 + Diagnostics: 320 PasswordRequired: 12 CertificateRequired: 0 EncryptionUnsupported: 0 @@ -37,6 +37,7 @@ NameTreeNodeInvalid: 3 PageTreeNodeTypeInvalid: 3 PagesMissing: 3 + WidgetNotInFieldTree: 3 AnnotationEntryInvalid: 2 AppearanceEntryInvalid: 2 AppearanceNotForm: 2 @@ -45,6 +46,9 @@ DecodeParmsInvalid: 2 EncryptionEntryLengthInvalid: 2 EndOfFileMarkerMissing: 2 + FieldNameMissing: 2 + FieldNotRoot: 2 + FieldReferenceInvalid: 2 FilterAbbreviationNotAllowed: 2 InfoTrappedInvalid: 2 LinearizationHintsInvalid: 2 @@ -54,16 +58,23 @@ TrailerIdMissing: 2 TrailerMissing: 2 XmpMalformed: 2 + AcroFormFieldsMissing: 1 AnnotationRequiredEntryMissing: 1 AnnotationSubtypeMissing: 1 AnnotationValueInvalid: 1 AppearanceBBoxMissing: 1 AppearanceStateMissing: 1 + ButtonOnStateMissing: 1 + ButtonOptLengthMismatch: 1 + ButtonValueStateMismatch: 1 DictionaryValueMissing: 1 EncryptDictionaryInvalid: 1 EncryptedDataInvalid: 1 EndOfFileMarkerNotLast: 1 EndstreamMissing: 1 + FieldEntryInvalid: 1 + FieldNameDuplicateInconsistent: 1 + FieldParentMissing: 1 HeaderMissing: 1 HeaderVersionInvalid: 1 HexStringInvalidDigit: 1 @@ -119,8 +130,8 @@ pdfbox: 137 files StartxrefInvalid: 1 StreamLengthInvalid: 1 qpdf: 639 files - Clean: 418 - Diagnostics: 184 + Clean: 382 + Diagnostics: 220 PasswordRequired: 23 CertificateRequired: 0 EncryptionUnsupported: 1 @@ -128,6 +139,7 @@ qpdf: 639 files Crash: 0 Timeout: 0 files with each diagnostic code: + ButtonValueStateMismatch: 33 FilterUnsupported: 33 MissingEndobj: 18 FilterDataInvalid: 17 @@ -142,7 +154,10 @@ qpdf: 639 files PopupLinkMismatch: 8 CatalogTypeInvalid: 7 ObjectStreamIndexMismatch: 7 + WidgetNotInFieldTree: 7 XrefEntryInvalid: 7 + FieldNameMissing: 6 + FieldParentMissing: 6 PageTreeCountMismatch: 6 PagesMissing: 6 XrefEntryFormatInvalid: 6 @@ -166,9 +181,12 @@ qpdf: 639 files StartxrefMissing: 3 TrailerPrevInvalid: 3 ArrayUnterminated: 2 + ButtonValueUnknownState: 2 DictionaryDuplicateKey: 2 EndOfFileMarkerMissing: 2 ExtensionsNotDirect: 2 + FieldKidsMixed: 2 + FieldTreeCycle: 2 FilterAbbreviationNotAllowed: 2 FilterInvalid: 2 HexStringInvalidDigit: 2 @@ -179,13 +197,19 @@ qpdf: 639 files TrailerMissing: 2 XrefPrevLoop: 2 XrefSectionInvalid: 2 + AcroFormFieldsMissing: 1 AnnotationEntryInvalid: 1 AnnotationNotIndirect: 1 AppearanceEntryInvalid: 1 AppearanceNotForm: 1 + ChoiceValueNotInOptions: 1 + DefaultAppearanceMissing: 1 EncryptionEntryLengthInvalid: 1 EncryptionIdMissing: 1 EncryptionKeyLengthInvalid: 1 + FieldNotIndirect: 1 + FieldReferenceInvalid: 1 + FieldTypeMissing: 1 HeaderInvalid: 1 NestingTooDeep: 1 NumberTreeKeysUnsorted: 1 @@ -249,6 +273,7 @@ pdfium-tests: 840 files PageTreeParentMismatch: 5 AnnotationRequiredEntryMissing: 4 DictionaryUnterminated: 4 + FieldNotRoot: 4 StartxrefMissing: 4 XrefEntryFormatInvalid: 4 AnnotationValueInvalid: 3 @@ -256,24 +281,31 @@ pdfium-tests: 840 files MetadataNotEncrypted: 3 NameTreeLimitsInvalid: 3 StringUnterminated: 3 + WidgetNotInFieldTree: 3 ActionEntryInvalid: 2 AppearanceStateMissing: 2 ArrayUnterminated: 2 + ChoiceValueNotInOptions: 2 EncryptionRevisionInvalid: 2 EndOfFileMarkerNotLast: 2 + FieldNameMissing: 2 + FieldTypeMissing: 2 NamedDestinationNotFound: 2 TrailerMissing: 2 ViewerPreferenceInvalid: 2 XrefSubsectionHeaderInvalid: 2 + AcroFormEntryInvalid: 1 AnnotationDuplicate: 1 AnnotationEntryInvalid: 1 AnnotationFlagsInvalid: 1 AnnotationRectInvalid: 1 AppearanceEntryInvalid: 1 + ButtonValueStateMismatch: 1 DictionaryValueMissing: 1 EncryptDictionaryInvalid: 1 EndOfFileMarkerMissing: 1 EndstreamMissing: 1 + FieldNameDuplicateInconsistent: 1 HeaderMissing: 1 HexStringInvalidDigit: 1 LinearizationHintsInvalid: 1 diff --git a/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs b/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs index b9750572..8c3f65fb 100644 --- a/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs +++ b/tests/Broadside.Tests/Document/WellFormedCorpusTests.cs @@ -16,7 +16,7 @@ public void A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics(str int expectedPages = fileName switch { - "page-tree-inherited.pdf" or "linearized.pdf" or "linearized-xref-stream.pdf" => 2, + "page-tree-inherited.pdf" or "linearized.pdf" or "linearized-xref-stream.pdf" or "acroform-fields.pdf" => 2, "number-tree-deep.pdf" or "page-labels.pdf" => 12, _ => 1, }; @@ -27,6 +27,7 @@ public void A_well_formed_file_opens_and_walks_its_pages_with_no_diagnostics(str Assert.NotNull(page.Resources); } - Assert.Empty(document.Diagnostics); + // Information records a legal feature Broadside keeps but does not use, such as an XFA form (#41, #74). + Assert.DoesNotContain(document.Diagnostics, diagnostic => diagnostic.Severity > Broadside.Diagnostics.DiagnosticSeverity.Information); } } diff --git a/tests/Broadside.Tests/Files/FilesAndLayersCorpusTests.cs b/tests/Broadside.Tests/Files/FilesAndLayersCorpusTests.cs index df47c983..2f5de425 100644 --- a/tests/Broadside.Tests/Files/FilesAndLayersCorpusTests.cs +++ b/tests/Broadside.Tests/Files/FilesAndLayersCorpusTests.cs @@ -17,7 +17,7 @@ public void Reading_files_and_layers_of_a_well_formed_file_records_no_diagnostic ReadEverything(document); - Assert.Empty(document.Diagnostics); + Assert.DoesNotContain(document.Diagnostics, diagnostic => diagnostic.Severity > Broadside.Diagnostics.DiagnosticSeverity.Information); foreach (CosReference reference in Enumerable.Range(1, 200).Select(number => new CosReference(number, 0))) { Assert.False(document.Resolve(reference).IsDirty); diff --git a/tests/Broadside.Tests/Filters/CorpusFilterTests.cs b/tests/Broadside.Tests/Filters/CorpusFilterTests.cs index 8c357d4b..f347a98f 100644 --- a/tests/Broadside.Tests/Filters/CorpusFilterTests.cs +++ b/tests/Broadside.Tests/Filters/CorpusFilterTests.cs @@ -58,7 +58,7 @@ public void Every_page_content_stream_of_a_well_formed_file_decodes_with_no_diag } } - Assert.Empty(document.Diagnostics); + Assert.DoesNotContain(document.Diagnostics, diagnostic => diagnostic.Severity > Broadside.Diagnostics.DiagnosticSeverity.Information); } [Fact] diff --git a/tests/Broadside.Tests/Forms/FieldTreeTests.cs b/tests/Broadside.Tests/Forms/FieldTreeTests.cs new file mode 100644 index 00000000..bd190629 --- /dev/null +++ b/tests/Broadside.Tests/Forms/FieldTreeTests.cs @@ -0,0 +1,121 @@ +using Broadside.Annotations; +using Broadside.Forms; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Forms; + +/// The field hierarchy of an interactive form and its links to widget annotations (ISO 32000-2 §12.7.1 to §12.7.4). +public class FieldTreeTests +{ + [Fact] + public void Acroform_fields_pdf_reads_the_field_hierarchy_with_fully_qualified_names_and_typed_fields() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("acroform-fields.pdf")); + + PdfAcroForm form = Assert.IsType(document.AcroForm); + + Assert.Equal(["name", "person", "agree", "color", "submit", "country", "toppings", "sig"], form.Fields.Select(field => field.FullyQualifiedName)); + Assert.Equal( + [ + "name PdfTextField", "person PdfNonTerminalField", "person.first PdfTextField", "person.last PdfTextField", + "agree PdfCheckBoxField", "color PdfRadioButtonField", "submit PdfPushButtonField", "country PdfComboBoxField", + "toppings PdfListBoxField", "sig PdfSignatureField", + ], + form.AllFields.Select(field => $"{field.FullyQualifiedName} {field.GetType().Name}")); + Assert.Equal( + [ + "Text", "NonTerminal", "Text", "Text", "CheckBox", "RadioButton", "PushButton", "ComboBox", "ListBox", "Signature", + ], + form.AllFields.Select(field => field.Kind.ToString())); + + PdfNonTerminalField person = Assert.IsType(form.FindField("person")); + Assert.Equal(["first", "last"], person.Children.Select(child => child.PartialName)); + Assert.All(person.Children, child => Assert.Same(person, child.Parent)); + Assert.Null(person.Parent); + Assert.Same(person.Children[1], Assert.Single(form.FindFields("person.last"))); + Assert.Empty(form.FindFields("person.middle")); + Assert.Equal(9, form.TerminalFields.Count); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Terminal_fields_and_the_widgets_on_the_pages_link_both_ways_to_the_same_instances() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("acroform-fields.pdf")); + PdfAcroForm form = document.AcroForm!; + + PdfWidgetAnnotation[] onPages = [.. document.Pages.SelectMany(page => page.Annotations).OfType()]; + + Assert.Equal(12, onPages.Length); + Assert.All(onPages, widget => Assert.Contains(widget, widget.Field!.Widgets)); + Assert.Equal(onPages.Length, form.TerminalFields.Sum(field => field.Widgets.Count)); + Assert.All(form.TerminalFields, field => Assert.All(field.Widgets, widget => Assert.Same(field, widget.Field))); + + var agree = (PdfCheckBoxField)form.FindField("agree")!; + Assert.Equal([document.Pages[0], document.Pages[1]], agree.Widgets.Select(widget => widget.Page)); + Assert.Same(document.Pages[1].Annotations[0], agree.Widgets[1]); + + var name = (PdfTextField)form.FindField("name")!; + PdfWidgetAnnotation merged = Assert.Single(name.Widgets); + Assert.Same(name.Dictionary, merged.Dictionary); + Assert.Same(form.FindField(name.Dictionary), name); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Concurrent_readers_get_the_same_field_and_widget_instances() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("acroform-fields.pdf")); + var results = new object?[64][]; + + Parallel.For(0, results.Length, index => + { + PdfAcroForm form = document.AcroForm!; + PdfWidgetAnnotation widget = (PdfWidgetAnnotation)document.Pages[0].Annotations[0]; + results[index] = [form, .. form.AllFields, .. form.TerminalFields.SelectMany(field => field.Widgets), document.Pages[1].Annotations[0], widget.Field]; + }); + + Assert.All(results, result => Assert.Equal(results[0], result, ReferenceEqualityComparer.Instance)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_mutation_of_the_field_tree_is_seen_on_the_next_read() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("acroform-fields.pdf")); + PdfAcroForm form = document.AcroForm!; + PdfField name = form.FindField("name")!; + var person = (PdfNonTerminalField)form.FindField("person")!; + + person.Children[0].Dictionary[new CosName("T")] = new CosString("given"u8); + var kids = (CosArray)document.Resolve(person.Dictionary[new CosName("Kids")]); + kids.RemoveAt(1); + + Assert.Equal(["person.given"], form.AllFields.Where(field => field.Parent is not null).Select(field => field.FullyQualifiedName)); + Assert.Empty(form.FindFields("person.last")); + Assert.NotSame(name, form.FindField("name")); + Assert.Same(form.FindField("name"), form.FindField("name")); + Assert.Equal("Ada", ((PdfTextField)form.FindField("name")!).Value); + } + + [Fact] + public void A_document_without_an_acroform_has_no_form_and_its_widgets_no_field() + { + using PdfDocument plain = PdfDocument.Open(Corpus.Path("empty-page.pdf")); + Assert.Null(plain.AcroForm); + + byte[] file = new Document.TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R /AcroForm 42 >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> /Annots [4 0 R] >>", + "<< /Type /Annot /Subtype /Widget /Rect [0 0 1 1] /T (w) /FT /Tx >>"); + using PdfDocument invalid = PdfDocument.Open(file); + Assert.Null(((PdfWidgetAnnotation)invalid.Pages[0].Annotations[0]).Field); + Assert.Equal("AcroFormInvalid", Assert.Single(invalid.Diagnostics).Code); + + using PdfDocument empty = PdfDocument.Open(Document.TestPdf.OnePage(string.Empty, "/AcroForm << >>")); + Assert.Empty(empty.AcroForm!.AllFields); + Assert.Empty(empty.Diagnostics); + } +} diff --git a/tests/Broadside.Tests/Forms/FieldValueTests.cs b/tests/Broadside.Tests/Forms/FieldValueTests.cs new file mode 100644 index 00000000..4dabfacd --- /dev/null +++ b/tests/Broadside.Tests/Forms/FieldValueTests.cs @@ -0,0 +1,169 @@ +using Broadside.Annotations; +using Broadside.Diagnostics; +using Broadside.Forms; +using Broadside.Objects; +using Broadside.TestSupport; + +namespace Broadside.Tests.Forms; + +/// Inherited entries, flags and decoded values of each field type (ISO 32000-2 §12.7.3 to §12.7.5). +public class FieldValueTests +{ + [Fact] + public void The_interactive_form_dictionary_exposes_its_defaults_resources_flags_and_calculation_order() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("acroform-fields.pdf")); + PdfAcroForm form = document.AcroForm!; + + Assert.Equal(new CosReference(4, 0), form.Reference); + Assert.False(form.NeedAppearances); + Assert.Equal(PdfSignatureFlags.SignaturesExist, form.SignatureFlags); + Assert.Equal("/Helv 0 Tf 0 g", form.DefaultAppearance); + Assert.Equal(PdfTextJustification.Left, form.Quadding); + Assert.Equal([new CosName("Helv"), new CosName("ZaDb")], ((CosDictionary)document.Resolve(form.DefaultResources![new CosName("Font")])).Keys); + Assert.Same(form.FindField("name"), Assert.Single(form.CalculationOrder)); + Assert.Null(form.Xfa); + Assert.Same(form, document.AcroForm); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Ft_ff_v_da_and_q_are_inherited_from_the_nearest_ancestor_and_da_and_q_then_from_the_form() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("acroform-fields.pdf")); + PdfAcroForm form = document.AcroForm!; + + var first = (PdfTextField)form.FindField("person.first")!; + var last = (PdfTextField)form.FindField("person.last")!; + var country = (PdfComboBoxField)form.FindField("country")!; + + Assert.Equal((PdfFieldType.Text, new CosName("Tx")), (first.FieldType, first.FieldTypeName)); + Assert.Equal((2u, true, false), (first.Flags, first.IsRequired, first.IsReadOnly)); + Assert.Equal((1u, false, true), (last.Flags, last.IsRequired, last.IsReadOnly)); + Assert.Equal(("/Helv 10 Tf 0 0 1 rg", PdfTextJustification.Centered), (first.DefaultAppearance, first.Quadding)); + Assert.Equal(("/Helv 0 Tf 0 g", PdfTextJustification.Left), (country.DefaultAppearance, country.Quadding)); + Assert.Equal("Grace", first.Value); + Assert.Equal("Löv", last.Value); + Assert.Null(first.MaxLength); + Assert.Equal(PdfFieldType.Text, form.FindField("person")!.FieldType); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_text_field_reads_its_names_value_default_length_and_trigger_actions() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("acroform-fields.pdf")); + var name = (PdfTextField)document.AcroForm!.FindField("name")!; + + Assert.Equal(("name", "Your name", "full_name"), (name.PartialName, name.AlternateName, name.MappingName)); + Assert.Equal(("Ada", "Anonymous", 40), (name.Value, name.DefaultValue, name.MaxLength)); + Assert.Equal("/Helv 12 Tf 0 g", name.DefaultAppearance); + Assert.False(name.IsMultiline || name.IsPassword || name.IsComb || name.IsRichText || name.IsFileSelect); + Assert.IsType(name.AdditionalActions!.Calculate); + Assert.DoesNotContain(document.Diagnostics, diagnostic => diagnostic.Severity > DiagnosticSeverity.Information); + } + + [Fact] + public void A_check_box_reads_its_state_on_state_and_widget_states_across_pages() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("acroform-fields.pdf")); + var agree = (PdfCheckBoxField)document.AcroForm!.FindField("agree")!; + + Assert.Equal(new CosName("Yes"), agree.Value); + Assert.Equal(new CosName("Off"), agree.DefaultValue); + Assert.True(agree.IsChecked); + Assert.Equal([new CosName("Yes")], agree.OnStateNames); + Assert.Equal(agree.Widgets, agree.SelectedWidgets); + Assert.Equal("Yes", agree.ExportValue); + Assert.All(agree.Widgets, widget => Assert.Equal(new CosName("Yes"), agree.GetAppearanceState(widget))); + Assert.Equal("4", agree.Widgets[0].AppearanceCharacteristics!.NormalCaption); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_radio_group_with_index_named_states_maps_its_value_to_the_export_value_of_the_selected_widget() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("acroform-fields.pdf")); + var color = (PdfRadioButtonField)document.AcroForm!.FindField("color")!; + + Assert.Equal((true, false), (color.IsNoToggleToOff, color.IsRadiosInUnison)); + Assert.Equal(new CosName("1"), color.Value); + Assert.Equal(["Red", "Green", "Green"], color.Options); + Assert.Equal([new CosName("0"), new CosName("1"), new CosName("2")], color.OnStateNames); + Assert.Same(color.Widgets[1], Assert.Single(color.SelectedWidgets)); + Assert.Equal("Green", color.ExportValue); + Assert.Equal(["Red", "Green", "Green"], color.Widgets.Select(color.GetWidgetExportValue)); + Assert.Equal(["Off", "1", "Off"], color.Widgets.Select(widget => color.GetAppearanceState(widget).Value)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_push_button_has_no_value_and_its_widget_action_names_fields_that_resolve_through_the_form() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("acroform-fields.pdf")); + PdfAcroForm form = document.AcroForm!; + var submit = (PdfPushButtonField)form.FindField("submit")!; + + PdfResetFormAction reset = Assert.IsType(Assert.Single(submit.Widgets).Action); + + Assert.Null(submit.ValueObject); + Assert.Equal( + [form.FindField("person"), form.FindField("agree")], + reset.Fields!.SelectMany(form.FindFields)); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Choice_fields_read_options_values_and_selected_indices() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("acroform-fields.pdf")); + PdfAcroForm form = document.AcroForm!; + var country = (PdfComboBoxField)form.FindField("country")!; + var toppings = (PdfListBoxField)form.FindField("toppings")!; + + Assert.Equal((true, false), (country.IsEditable, country.IsMultiSelect)); + Assert.Equal(["us United States", "ca Canada"], country.Options.Select(option => $"{option.ExportValue} {option.DisplayText}")); + Assert.Equal(["ca"], country.Values); + Assert.Equal([1], country.SelectedIndices); + Assert.Empty(country.StoredIndices); + + Assert.True(toppings.IsMultiSelect); + Assert.Equal(["Cheese", "Ham", "Olives"], toppings.Options.Select(option => option.DisplayText)); + Assert.Equal(["Cheese", "Olives"], toppings.Values); + Assert.Equal([0, 2], toppings.SelectedIndices); + Assert.Equal([0, 2], toppings.StoredIndices); + Assert.Equal(1, toppings.TopIndex); + Assert.Equal("/Helv 10 Tf 0 g", toppings.DefaultAppearance); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_signature_field_exposes_its_lock_and_seed_value_and_is_invisible_and_unsigned() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("acroform-fields.pdf")); + var sig = (PdfSignatureField)document.AcroForm!.FindField("sig")!; + + Assert.False(sig.IsSigned); + Assert.Null(sig.SignatureDictionary); + Assert.False(sig.IsVisible); + PdfSignatureFieldLock fieldLock = sig.Lock!; + Assert.Equal(PdfSignatureFieldLockAction.Include, fieldLock.Action); + Assert.Equal(["name", "person.first"], fieldLock.FieldNames); + Assert.Equal(2, fieldLock.Permissions); + Assert.Equal(new CosName("Adobe.PPKLite"), sig.SeedValue![new CosName("Filter")]); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void Reading_every_form_entry_records_nothing_and_writes_nothing() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("acroform-fields.pdf")); + + int fields = FormWalker.Walk(document); + + Assert.Equal(10, fields); + Assert.DoesNotContain(document.Diagnostics, diagnostic => diagnostic.Severity > DiagnosticSeverity.Information); + Assert.All(document.AcroForm!.AllFields, field => Assert.False(field.Dictionary.IsDirty)); + Assert.False(document.AcroForm.Dictionary.IsDirty); + } +} diff --git a/tests/Broadside.Tests/Forms/MalformedFormTests.cs b/tests/Broadside.Tests/Forms/MalformedFormTests.cs new file mode 100644 index 00000000..3d324705 --- /dev/null +++ b/tests/Broadside.Tests/Forms/MalformedFormTests.cs @@ -0,0 +1,277 @@ +using Broadside.Annotations; +using Broadside.Diagnostics; +using Broadside.Forms; +using Broadside.Objects; +using Broadside.Tests.Document; + +namespace Broadside.Tests.Forms; + +/// Real-world deviations in field trees and field entries: lenient repairs with diagnostics, strict throws (ISO 32000-2 §12.7, ADR 0005). +public class MalformedFormTests +{ + private const int FieldTreeDepth = 256; + + + /// + /// Fields [42 (an integer), 4 a (Kids [5]), 6 noft (merged widget, no FT), 7 parentmissing (kid 8 has no Parent), 9 mismatch + /// (kid 10's Parent is 7), 12 dup (Tx), 14 dup (Ch), 16 sig (two widgets), 17 a.b (Comb without MaxLen)]; 5 b's Kids lists 4 + /// again (a cycle); widget 11 is on the page but in no field's Kids. + /// + private static byte[] MalformedTree() => new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [42 4 0 R 6 0 R 7 0 R 9 0 R 12 0 R 14 0 R 16 0 R 17 0 R] /DA (/Helv 0 Tf 0 g) >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> /Annots [6 0 R 8 0 R 10 0 R 11 0 R 12 0 R 18 0 R 19 0 R] >>", + "<< /T (a) /FT /Tx /Kids [5 0 R] >>", + "<< /T (b) /Parent 4 0 R /Kids [4 0 R] >>", + "<< /Type /Annot /Subtype /Widget /Rect [0 0 10 10] /T (noft) >>", + "<< /T (parentmissing) /FT /Btn /Kids [8 0 R] >>", + "<< /Type /Annot /Subtype /Widget /Rect [0 0 10 10] /AS /Off /AP << /N << /On 20 0 R /Off 20 0 R >> >> >>", + "<< /T (mismatch) /FT /Btn /Ff 49152 /V /On /Kids [10 0 R] >>", + "<< /Type /Annot /Subtype /Widget /Rect [0 0 10 10] /Parent 7 0 R /AS /On /AP << /N << /On 20 0 R /Off 20 0 R >> >> >>", + "<< /Type /Annot /Subtype /Widget /Rect [0 0 10 10] /T (orphan) /FT /Tx /V (lost) >>", + "<< /Type /Annot /Subtype /Widget /Rect [0 0 10 10] /T (dup) /FT /Tx >>", + "null", + "<< /T (dup) /FT /Ch >>", + "null", + "<< /T (sig) /FT /Sig /Kids [18 0 R 19 0 R] >>", + "<< /T (a.b) /FT /Tx /Ff 16777216 >>", + "<< /Type /Annot /Subtype /Widget /Rect [0 0 10 10] /Parent 16 0 R >>", + "<< /Type /Annot /Subtype /Widget /Rect [0 0 10 10] /Parent 16 0 R >>", + "<< /Length 0 >>\nstream\n\nendstream"); + + [Fact] + public void A_malformed_field_tree_reads_what_it_can_with_exactly_the_documented_diagnostics() + { + using PdfDocument document = PdfDocument.Open(MalformedTree()); + PdfAcroForm form = document.AcroForm!; + Assert.Empty(document.Diagnostics); + + Assert.Equal( + [ + "a PdfNonTerminalField", "a.b PdfTextField", "noft PdfUnknownField", "parentmissing PdfCheckBoxField", + "mismatch PdfRadioButtonField", "dup PdfTextField", "dup PdfListBoxField", "sig PdfSignatureField", "a.b PdfTextField", + ], + form.AllFields.Select(field => $"{field.FullyQualifiedName} {field.GetType().Name}")); + Assert.Equal( + [ + "FieldReferenceInvalid 1", // Fields element 0 is an integer; the AcroForm is direct, so the catalog + "FieldTreeCycle 5", // b's Kids lists a again + "FieldTypeMissing 6", + "FieldParentMissing 8", + "FieldParentMismatch 10", + "SignatureFieldMultipleWidgets 16", + "FieldNameHasPeriod 17", + "FieldNameDuplicateInconsistent 14", // FT Tx and Ch under one name; also the two a.b fields have equal entries + ], + document.Diagnostics.Select(Describe)); + + Assert.Equal(2, form.FindFields("dup").Count); + Assert.Equal(2, form.FindFields("a.b").Count); + Assert.Equal(2, ((PdfSignatureField)form.FindField("sig")!).Widgets.Count); + Assert.Same(form.FindField("mismatch"), ((PdfWidgetAnnotation)document.Pages[0].Annotations[2]).Field); + + int count = document.Diagnostics.Count; + PdfWidgetAnnotation orphan = (PdfWidgetAnnotation)document.Pages[0].Annotations[3]; + PdfTextField outside = Assert.IsType(orphan.Field); + Assert.Equal(("orphan", "lost"), (outside.FullyQualifiedName, outside.Value)); + Assert.Same(outside, orphan.Field); + Assert.Same(orphan, Assert.Single(outside.Widgets)); + Assert.Empty(form.FindFields("orphan")); + Assert.True(((PdfTextField)form.FindFields("a.b")[1]).IsComb); + Assert.Equal(["WidgetNotInFieldTree 11", "TextCombInvalid 17"], document.Diagnostics.Skip(count).Select(Describe)); + } + + [Fact] + public void Strict_mode_throws_from_the_field_tree_not_from_open() + { + using PdfDocument document = PdfDocument.Open(MalformedTree(), new PdfOptions().UseStrict()); + PdfAcroForm form = document.AcroForm!; + + Assert.Equal("FieldReferenceInvalid", Assert.Throws(() => form.Fields).Diagnostic.Code); + } + + public static TheoryData TreeDeviations => new() + { + // Fields entry, extra objects 5.., expected diagnostic + { "/Fields [5 0 R]", "<< /T (kid) /FT /Tx /DA (x) /Parent 6 0 R >>|<< /T (top) /Kids [5 0 R] >>", "FieldNotRoot 5" }, + { "/Fields [5 0 R]", "<< /T (mixed) /FT /Tx /DA (x) /Kids [6 0 R 7 0 R] >>|<< /T (child) /Parent 5 0 R >>|<< /Type /Annot /Subtype /Widget /Rect [0 0 1 1] /Parent 5 0 R >>", "FieldKidsMixed 5" }, + { "/Fields [5 0 R]", "<< /T (both) /FT /Btn /Ff 98304 >>", "ButtonFlagsConflict 5" }, + { "/Fields [5 0 R]", "<< /T (named) /FT /Tx /DA (x) /Kids [6 0 R] >>|<< /Parent 5 0 R /Kids [7 0 R] >>|<< /T (deep) /Parent 6 0 R >>", "FieldNameMissing 6" }, + { "/Fields [<< /T (direct) /FT /Tx /DA (x) >>]", string.Empty, "FieldNotIndirect 1" }, + { "/Fields 5 0 R", "<< /T (notarray) >>", "AcroFormFieldsMissing 1" }, + { "/NeedAppearances false", string.Empty, "AcroFormFieldsMissing 1" }, + { "/Fields [5 0 R]", "<< /T (x) /FT /Tx /DA (x) /Kids 6 0 R >>|<< /Type /Annot >>", "FieldEntryInvalid 5" }, + { "/Fields [5 0 R]", "<< /FT /Tx /DA (x) >>", "FieldNameMissing 5" }, + }; + + [Theory] + [MemberData(nameof(TreeDeviations))] + public void A_deviation_in_the_field_tree_is_recorded_once_when_the_tree_is_read(string acroForm, string objects, string expected) + { + string[] extra = objects.Length == 0 ? [] : objects.Split('|'); + byte[] file = new TestPdf().Build( + [ + $"<< /Type /Catalog /Pages 2 0 R /AcroForm << {acroForm} >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>", + "null", + .. extra, + ]); + using PdfDocument document = PdfDocument.Open(file); + + _ = document.AcroForm!.AllFields; + _ = document.AcroForm.AllFields; + + Assert.Equal(expected, Describe(Assert.Single(document.Diagnostics))); + } + + [Fact] + public void An_unnamed_level_is_transparent_for_names_but_its_entries_are_inherited() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>", + "<< /T (named) /FT /Tx /Kids [5 0 R] >>", + "<< /Parent 4 0 R /DA (/Helv 9 Tf 0 g) /Ff 4096 /Kids [6 0 R] >>", + "<< /T (deep) /Parent 5 0 R >>"); + using PdfDocument document = PdfDocument.Open(file); + + var deep = (PdfTextField)Assert.Single(document.AcroForm!.TerminalFields); + + Assert.Equal("named.deep", deep.FullyQualifiedName); + Assert.Same(document.AcroForm.FindField("named"), deep.Parent); + Assert.Equal(("/Helv 9 Tf 0 g", true), (deep.DefaultAppearance, deep.IsMultiline)); + Assert.Equal("FieldNameMissing 5", Describe(Assert.Single(document.Diagnostics))); + } + + public static TheoryData ValueDeviations => new() + { + // field entries, property, expected diagnostic + { "/FT /Tx /DA (x) /V /Name", "Value", "FieldValueTypeInvalid 4" }, + { "/FT /Tx /DA (x) /Ff -1", "Flags", "FieldFlagsInvalid 4" }, + { "/FT /Tx /DA (x) /Ff 8", "Flags", "FieldFlagsInvalid 4" }, + { "/FT /Tx /DA (x) /Ff 2.5", "Flags", "FieldFlagsInvalid 4" }, + { "/FT /Tx", "DefaultAppearance", "DefaultAppearanceMissing 4" }, + { "/FT /Tx /DA (x) /Q 7", "Quadding", "FieldEntryInvalid 4" }, + { "/FT /Tx /DA (x) /MaxLen (ten)", "MaxLength", "FieldEntryInvalid 4" }, + { "/FT /Ch /DA (x) /Opt [(a) [(b)] 3]", "Options", "ChoiceOptionInvalid 4" }, + { "/FT /Ch /DA (x) /Opt [(a) (b)] /V (c)", "SelectedIndices", "ChoiceValueNotInOptions 4" }, + { "/FT /Ch /DA (x) /Opt [(a) (b)] /I [1 0 5]", "StoredIndices", "ChoiceIndicesInvalid 4" }, + { "/FT /Btn /Opt [(a) (b)] /Kids [5 0 R]", "Options", "ButtonOptLengthMismatch 4" }, + { "/FT /Btn /V /Maybe /Kids [5 0 R]", "Value", "ButtonValueUnknownState 4" }, + { "/FT /Btn /V /Off /Kids [6 0 R]", "Value", "ButtonValueStateMismatch 4" }, + { "/FT /Btn /V /Yes /Kids [7 0 R]", "OnStateNames", "ButtonStatesAmbiguous 4" }, + { "/FT /Btn /V /Off /Kids [8 0 R]", "OnStateNames", "ButtonOnStateMissing 4" }, + { "/FT /Sig /Lock << /Action /All >>", "Lock", "SignatureFieldDictNotIndirect 4" }, + { "/FT /Sig /V 42", "SignatureDictionary", "FieldValueTypeInvalid 4" }, + { "/FT /Tx /DA (x) /TU 42", "AlternateName", "FieldEntryInvalid 4" }, + }; + + [Theory] + [MemberData(nameof(ValueDeviations))] + public void A_malformed_field_entry_reads_as_its_default_with_one_diagnostic_when_read(string entries, string property, string expected) + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> /Annots [5 0 R 6 0 R 7 0 R 8 0 R] >>", + $"<< /T (f) {entries} >>", + "<< /Type /Annot /Subtype /Widget /Rect [0 0 10 10] /Parent 4 0 R /AS /Off /AP << /N << /Yes 9 0 R /Off 9 0 R >> >> >>", + "<< /Type /Annot /Subtype /Widget /Rect [0 0 10 10] /Parent 4 0 R /AS /Yes /AP << /N << /Yes 9 0 R /Off 9 0 R >> >> >>", + "<< /Type /Annot /Subtype /Widget /Rect [0 0 10 10] /Parent 4 0 R /AS /Yes /AP << /N << /Yes 9 0 R /Oui 9 0 R >> >> >>", + "<< /Type /Annot /Subtype /Widget /Rect [0 0 10 10] /Parent 4 0 R /AS /Off /AP << /N << /Off 9 0 R >> >> >>", + "<< /Length 0 >>\nstream\n\nendstream"); + using PdfDocument document = PdfDocument.Open(file); + PdfField field = Assert.Single(document.AcroForm!.Fields); + Assert.Empty(document.Diagnostics); + + object? value = field.GetType().GetProperty(property)!.GetValue(field); + if (value is System.Collections.IEnumerable sequence and not string) + { + _ = sequence.Cast().Count(); + } + + Assert.Equal(expected, Describe(Assert.Single(document.Diagnostics))); + using PdfDocument strict = PdfDocument.Open(file, new PdfOptions().UseStrict()); + PdfField strictField = Assert.Single(strict.AcroForm!.Fields); + var error = Assert.Throws(() => strictField.GetType().GetProperty(property)!.GetValue(strictField)); + Assert.Equal(expected.Split(' ')[0], Assert.IsType(error.InnerException).Diagnostic.Code); + } + + [Fact] + public void A_choice_option_list_on_an_ancestor_is_used_with_a_diagnostic() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DA (x) >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>", + "<< /T (group) /FT /Ch /Opt [(a) (b)] /Kids [5 0 R] >>", + "<< /T (list) /Parent 4 0 R /V (b) >>"); + using PdfDocument document = PdfDocument.Open(file); + var list = (PdfListBoxField)document.AcroForm!.FindField("group.list")!; + + Assert.Equal([1], list.SelectedIndices); + Assert.Equal("ChoiceOptionsInherited 5", Describe(Assert.Single(document.Diagnostics))); + } + + [Fact] + public void A_choice_value_given_as_the_display_text_matches_and_i_tells_duplicates_apart() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 5 0 R] /DA (x) >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>", + "<< /T (display) /FT /Ch /Opt [[(1) (One)] [(2) (Two)]] /V (Two) >>", + "<< /T (twins) /FT /Ch /Ff 2097152 /Opt [(x) (y) (x)] /V [(x)] /I [2] >>"); + using PdfDocument document = PdfDocument.Open(file); + + Assert.Equal([1], ((PdfChoiceField)document.AcroForm!.FindField("display")!).SelectedIndices); + Assert.Equal([2], ((PdfChoiceField)document.AcroForm.FindField("twins")!).SelectedIndices); + Assert.Empty(document.Diagnostics); + } + + [Fact] + public void A_field_tree_nested_deeper_than_the_limit_is_cut_with_a_diagnostic() + { + var objects = new List + { + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DA (x) >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>", + }; + for (int level = 0; level < 300; level++) + { + int number = level + 4; + objects.Add(level == 299 + ? $"<< /T (f{level}) /FT /Tx /Parent {number - 1} 0 R >>" + : $"<< /T (f{level}) {(level == 0 ? string.Empty : $"/Parent {number - 1} 0 R ")}/Kids [{number + 1} 0 R] >>"); + } + + using PdfDocument document = PdfDocument.Open(new TestPdf().Build([.. objects])); + + Assert.Equal(FieldTreeDepth, document.AcroForm!.AllFields.Count); + Assert.Equal("FieldTreeTooDeep", Assert.Single(document.Diagnostics).Code); + } + + [Fact] + public void A_field_in_a_cycle_through_parent_entries_resolves_from_its_widget_without_looping() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [] >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> /Annots [4 0 R] >>", + "<< /Type /Annot /Subtype /Widget /Rect [0 0 1 1] /Parent 5 0 R >>", + "<< /T (loop) /FT /Tx /DA (x) /Parent 6 0 R /Kids [4 0 R] >>", + "<< /T (back) /Parent 5 0 R /Kids [5 0 R] >>"); + using PdfDocument document = PdfDocument.Open(file); + + PdfTerminalField? field = ((PdfWidgetAnnotation)document.Pages[0].Annotations[0]).Field; + + Assert.Equal("loop", field!.FullyQualifiedName); + Assert.Contains("WidgetNotInFieldTree 4", document.Diagnostics.Select(Describe)); + } + + private static string Describe(Diagnostic diagnostic) => + $"{diagnostic.Code} {diagnostic.ObjectReference?.ObjectNumber.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "-"}"; +} diff --git a/tests/Broadside.Tests/Forms/XfaFormTests.cs b/tests/Broadside.Tests/Forms/XfaFormTests.cs new file mode 100644 index 00000000..6f77b63f --- /dev/null +++ b/tests/Broadside.Tests/Forms/XfaFormTests.cs @@ -0,0 +1,70 @@ +using System.Text; +using Broadside.Diagnostics; +using Broadside.Forms; +using Broadside.Tests.Document; +using Broadside.TestSupport; + +namespace Broadside.Tests.Forms; + +/// XFA resources are detected and kept, never rendered (ISO 32000-2 Annex K, §12.7.3 Table 224, §7.7.2 Table 29). +public class XfaFormTests +{ + [Fact] + public void Opening_a_form_with_an_xfa_resource_records_an_information_diagnostic_and_exposes_the_packets() + { + using PdfDocument document = PdfDocument.Open(Corpus.Path("acroform-xfa.pdf")); + + Diagnostic diagnostic = Assert.Single(document.Diagnostics); + Assert.Equal(("XfaFormPresent", DiagnosticSeverity.Information, 4), (diagnostic.Code, diagnostic.Severity, diagnostic.ObjectReference!.ObjectNumber)); + + PdfXfaForm xfa = document.AcroForm!.Xfa!; + Assert.False(xfa.IsDynamic); + Assert.Equal(["xdp:xdp", "template", "datasets", ""], xfa.Packets.Select(packet => packet.Name)); + Assert.Equal(12, xfa.Packets[1].Reference!.ObjectNumber); + Assert.StartsWith(">", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>", + "<< /Fields [] /XFA 5 0 R >>", + "<< /Length 10 >>\nstream\n\nendstream"); + using PdfDocument document = PdfDocument.Open(file, new PdfOptions().UseStrict()); + + Assert.Equal(["XfaFormPresent", "XfaFormDynamic"], document.Diagnostics.Select(diagnostic => diagnostic.Code)); + Assert.All(document.Diagnostics, diagnostic => Assert.Equal(DiagnosticSeverity.Information, diagnostic.Severity)); + PdfXfaForm xfa = document.AcroForm!.Xfa!; + Assert.True(xfa.IsDynamic); + PdfXfaPacket packet = Assert.Single(xfa.Packets); + Assert.Null(packet.Name); + Assert.Empty(document.AcroForm.Fields); + } + + [Fact] + public void A_malformed_packet_array_skips_the_bad_pairs_with_a_warning() + { + byte[] file = new TestPdf().Build( + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [] /XFA [(template) 4 0 R /datasets 4 0 R (config)] >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> >>", + "<< /Length 10 >>\nstream\n