diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 75ebd1d7c..22d4adb1e 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -4,7 +4,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material, with its author, source and licence. The policy is in [AGENTS.md](AGENTS.md) §1. The machine-readable list, with SHA-256 hashes, is [ATTRIBUTION.toml](ATTRIBUTION.toml). Licence texts are kept beside the assets and summarised in [NOTICE](NOTICE). -## In this repository (276) +## In this repository (277) | Asset | Title | Author | Licence | Source | Used for | |---|---|---|---|---|---| @@ -223,6 +223,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material, | `vendor/hayro-interpret/assets/FoxitSymbol.pfb` | FoxitSymbol (standard-14 substitute font) | Foxit Software Inc. / PDFium Authors | BSD-3-Clause | https://pdfium.googlesource.com/pdfium (via hayro-interpret 0.7.0 assets/) | Renders non-embedded standard-14 fonts (vendored hayro-interpret) | | `vendor/hayro-interpret/assets/CGATS001Compat-v2-micro.icc` | CGATS001Compat v2 micro ICC profile | Clinton Ingram (saucecontrol/Compact-ICC-Profiles) | CC0-1.0 | https://github.com/saucecontrol/Compact-ICC-Profiles | Default CMYK colour conversion (vendored hayro-interpret) | | `crates/fonts/src/std14_metrics.rs` | Standard-14 font advance widths and encodings (as Rust tables) | Adobe (Core14 AFM metrics, PDF specification encodings); tables generated by the PdfCraft contributors | MIT OR Apache-2.0 | ISO 32000-2 Annex D and the Adobe Core14 AFM metrics. Generated by joining the published WinAnsi, Symbol and ZapfDingbats encodings (code to glyph name) with the per-glyph advance widths, then spot-checked against the specification by hand in the tests of crates/fonts/src/std14.rs. Data only: the code that reads these tables lives in std14.rs, so that ordinary edits do not churn this file's hash. | Advance widths for the fourteen standard fonts, which a PDF may name without embedding. Non-visual data, not a typeface: the item AGENTS.md 1.1 permits, held first-party so generated appearance streams and the renderer agree. | +| `vendor/hayro-cmap/assets/cmaps.brotli` | Adobe CMap resources (predefined CJK CMaps) | Adobe | BSD-3-Clause | https://github.com/adobe-type-tools/cmap-resources (via hayro-cmap 0.1.0 assets/) | Character-code mapping tables required to read CJK PDFs. Non-visual data, allowed by AGENTS.md §1.1 | | `docs/brand/artcraft-logo-white.png` | ArtCraft brand: artcraft-logo-white | ArtCraft Team | LicenseRef-Storyteller-Trademark | ArtCraft Team brand assets (provided by the project owner, 2026-10-01; identical copies in storytold/photocraft) | ArtCraft branding next to the community links (About dialog, Help menu, home screen) and in docs. ArtCraft Team trademark, not open source; may be used only unmodified within PdfCraft; forks and modified versions must remove it. | | `docs/brand/artcraft-logo-white.svg` | ArtCraft brand: artcraft-logo-white | ArtCraft Team | LicenseRef-Storyteller-Trademark | ArtCraft Team brand assets (provided by the project owner, 2026-10-01; identical copies in storytold/photocraft) | ArtCraft branding next to the community links (About dialog, Help menu, home screen) and in docs. ArtCraft Team trademark, not open source; may be used only unmodified within PdfCraft; forks and modified versions must remove it. | | `docs/brand/artcraft-logo.png` | ArtCraft brand: artcraft-logo | ArtCraft Team | LicenseRef-Storyteller-Trademark | ArtCraft Team brand assets (provided by the project owner, 2026-10-01; identical copies in storytold/photocraft) | ArtCraft branding next to the community links (About dialog, Help menu, home screen) and in docs. ArtCraft Team trademark, not open source; may be used only unmodified within PdfCraft; forks and modified versions must remove it. | @@ -285,7 +286,7 @@ Every asset PdfCraft includes, bundles or uses to build its published material, | `assets/icons/pilcrow.svg` | Lucide icon "pilcrow" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/pilcrow.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs | | `assets/icons/move-horizontal.svg` | Lucide icon "move-horizontal" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/move-horizontal.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs | -## Compiled in through dependencies (6) +## Compiled in through dependencies (5) | Crate | File | Title | Author | Licence | Source | Used for | |---|---|---|---|---|---|---| @@ -293,7 +294,6 @@ Every asset PdfCraft includes, bundles or uses to build its published material, | `epaint_default_fonts` 0.36.2 | `fonts/Hack-Regular.ttf` | Hack Regular | Source Foundry Authors (derived from Bitstream Vera / DejaVu) | MIT AND Bitstream-Vera | https://github.com/source-foundry/Hack | egui fallback fonts (eframe feature default_fonts) | | `epaint_default_fonts` 0.36.2 | `fonts/NotoEmoji-Regular.ttf` | Noto Emoji (monochrome) | Google Inc. | OFL-1.1 | https://github.com/googlefonts/noto-emoji | egui fallback fonts (eframe feature default_fonts) | | `epaint_default_fonts` 0.36.2 | `fonts/emoji-icon-font.ttf` | emoji-icon-font | John Slegers | MIT | https://github.com/jslegers/emoji-icon-font | egui fallback fonts (eframe feature default_fonts) | -| `hayro-cmap` 0.1.0 | `assets/cmaps.brotli` | Adobe CMap resources (predefined CJK CMaps) (non-visual data, AGENTS.md §1.1) | Adobe | BSD-3-Clause | https://github.com/adobe-type-tools/cmap-resources (via hayro-cmap) | Character-code mapping tables required to read CJK PDFs. Non-visual data, allowed by AGENTS.md §1.1 | | `hayro-interpret` 0.7.0 | `src/font/generated/metrics.rs` | Standard-14 font metrics and encodings (as Rust tables) (non-visual data, AGENTS.md §1.1) | Adobe (Core 14 AFM metrics, PDF specification encodings); tables by The Hayro Authors | MIT OR Apache-2.0 | ISO 32000-2 Annex D; Adobe Core14 AFM files (via vendored hayro-interpret) | Glyph widths and encodings for non-embedded standard fonts. Non-visual data, allowed by AGENTS.md §1.1 | ## Downloaded at build time (22) diff --git a/ATTRIBUTION.toml b/ATTRIBUTION.toml index c5e55f063..fbb40b497 100644 --- a/ATTRIBUTION.toml +++ b/ATTRIBUTION.toml @@ -2425,14 +2425,13 @@ kind = "font" usage = "egui fallback fonts (eframe feature default_fonts)" sha256 = "f426bec371f484646d002717e2c555a95cd5145e635d83a48bbef83f3abf18ca" -[[bundled]] -crate = "hayro-cmap" -version = "0.1.0" -path = "assets/cmaps.brotli" +[[asset]] +path = "vendor/hayro-cmap/assets/cmaps.brotli" title = "Adobe CMap resources (predefined CJK CMaps)" author = "Adobe" -source = "https://github.com/adobe-type-tools/cmap-resources (via hayro-cmap)" +source = "https://github.com/adobe-type-tools/cmap-resources (via hayro-cmap 0.1.0 assets/)" licence = "BSD-3-Clause" +licence_file = "vendor/hayro-cmap/assets/LICENSE.txt" kind = "data" adobe_data = true usage = "Character-code mapping tables required to read CJK PDFs. Non-visual data, allowed by AGENTS.md §1.1" diff --git a/Cargo.lock b/Cargo.lock index a439c0b80..b3d5263b8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2549,8 +2549,6 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d285dc30731c8485de5fa732fbdf2b3affdf01e4da7c2135022ca6fa664bf6" dependencies = [ "brotli", "hayro-postscript", diff --git a/Cargo.toml b/Cargo.toml index 0106433df..201240314 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -114,6 +114,7 @@ codegen-units = 1 hayro-interpret = { path = "vendor/hayro-interpret" } hayro = { path = "vendor/hayro" } hayro-syntax = { path = "vendor/hayro-syntax" } +hayro-cmap = { path = "vendor/hayro-cmap" } hayro-jbig2 = { path = "vendor/hayro-jbig2" } lopdf = { path = "vendor/lopdf" } winit = { path = "vendor/winit" } diff --git a/vendor/README.md b/vendor/README.md index c16de31bd..3054d7853 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -26,6 +26,7 @@ In `hayro-interpret`, Type 3 glyph bounding boxes are transformed to device spac | winit | 0.30.13 | Apache-2.0 | (1) on Windows 11 (build 22000 and later), `WM_DPICHANGED` applies the rect Windows suggests. It used to nudge the window onto the monitor `MonitorFromWindow` names, which during a drag is still the monitor being left; the nudge sent another `WM_DPICHANGED`, so a window dragged to a monitor with another scale factor grew and stayed on the wrong monitor at the wrong scale (#324). Backport of winit master 488c036a ([winit#4341](https://github.com/rust-windowing/winit/pull/4341)), which no 0.30 release has; Windows 10 keeps the old adjustment, as on winit master. (2) on Wayland, a seat's text input is destroyed when the seat goes away, not whenever it loses a capability: losing any capability (a touch screen or tablet unplugged, a remote-desktop session ending) destroyed it, and only an added capability recreated it, so IME stopped working until restart. Port of [winit#4747](https://github.com/rust-windowing/winit/pull/4747); (3) on Windows, an IME composition reports its cursor from `GCS_CURSORPOS` only when `WM_IME_COMPOSITION` says it is set, and at the end of the composition otherwise: the Microsoft Korean IME never sets it, so the cursor read as 0 (egui then drew no caret while composing; it now draws it after the syllable). Port of [winit#4746](https://github.com/rust-windowing/winit/pull/4746); (4) on Windows, a hidden window is not maximized until it is shown, and a hidden window shown while maximized gets one `ShowWindow(SW_MAXIMIZE)`: `SW_MAXIMIZE` shows a hidden window, so PdfCraft, which eframe keeps hidden until its first frame is drawn, appeared unpainted (white) when it restored a maximized window, and could lose its focus. Port of [winit#4587](https://github.com/rust-windowing/winit/pull/4587) (the later, focus-safe form of [winit#4575](https://github.com/rust-windowing/winit/pull/4575)); (5) on X11, when allowing or disallowing IME replaces the focused window's input context (egui does it each time a text field gains or loses focus), the new context is focused: no focus event follows, so it stayed unfocused until the window lost and regained focus. Port of [winit#4727](https://github.com/rust-windowing/winit/pull/4727); (6) on macOS, `insertText` commits through IME when a composition was started (`pending_commit`, set by `setMarkedText`) rather than when marked text is left: input methods that end a composition with `unmarkText` before `insertText` lost the text, and Apple Korean dropped the key typed after a syllable (`한` then `5` or `;`); other `insertText` calls stay `KeyboardInput`; a commit outside a key press (a candidate clicked with the mouse, dictation) clears the marked text and leaves no key to swallow, as in [winit#4748](https://github.com/rust-windowing/winit/pull/4748) (without it the next key, such as Backspace, was lost). `validAttributesForMarkedText` lists the underline and marked-clause attributes, without which some input methods don't compose. Port of [winit#4650](https://github.com/rust-windowing/winit/pull/4650), the 0.30 backport of [winit#4651](https://github.com/rust-windowing/winit/pull/4651) (merged on winit master), with the underline attribute spelled as AppKit's `NSUnderlineStyleAttributeName` (`NSUnderline`); (7) on macOS, disallowing IME with a composition in progress (focus leaving a text field) tells the input method to discard its marked text (`discardMarkedText`): it kept composing it once IME was allowed again, so the abandoned syllable came back (`하`, then `가` typed in the next field, became `학`, then `하` + `가`; Japanese `か` then `さ` became `傘`). Port of [winit#4745](https://github.com/rust-windowing/winit/pull/4745); (8) on macOS, text inserted outside a key press without a composition (the emoji picker) is reported as `Ime::Commit`; it was dropped. Port of the emoji-picker part of [winit#4749](https://github.com/rust-windowing/winit/pull/4749) (0.30 backport of [winit#4748](https://github.com/rust-windowing/winit/pull/4748)); its `selectedRange` change for dictation is left out because it switches on press-and-hold for every held key (an accent menu instead of key repeat, and the chosen accent added after the repeated letters); (9) on macOS, a key whose text was committed through IME isn't also sent as `KeyboardInput` unless AppKit forwards it as a command (Enter): Apple Korean answers Space with no syllable in progress with `setMarkedText(" ")`, `insertText(" ")`, `setMarkedText("")`, and the last call reset winit's state, so the space arrived twice. Same goal as [winit#4478](https://github.com/rust-windowing/winit/pull/4478), whose changes don't reach this call order (macOS 14); to be proposed upstream there; (10) on macOS, when the first key in a fresh app reaches Apple Korean's `insertText` as a raw compatibility jamo instead of starting a composition, that key is interpreted once more, synchronously, before it is sent as `KeyboardInput` (g k s typed ㅎㅏㄴ instead of 한); only an unmodified, non-repeated first key whose one callback inserts that same jamo, with IME enabled and nothing composed, focus and input source unchanged, is retried (`ime_startup.rs`). Port of [winit#4744](https://github.com/rust-windowing/winit/pull/4744), with its policy tests.; (11) on X11 without `Xft.dpi`, the scale factor comes from the X screen's configured DPI (its size in pixels and millimetres) before the output's physical density from RandR: Xorg can deliberately run a dense panel at 96 DPI, and only winit applications then looked zoomed; `Xft.dpi` still wins, `WINIT_X11_SCALE_FACTOR` still overrides, and a screen reporting no size keeps the RandR fallback. PdfCraft patch (#1150, replacing the launcher pin proposed in #908). (12) on macOS, `WinitView` answers `mouseDownCanMoveWindow` with the window's `movable_by_window_background` attribute (NO unless asked): NSView answers YES for a view that isn't opaque, so with the transparent title bar and full-size content view PdfCraft uses, AppKit moved the window for any drag that began in the 28 pt title-bar band before the app saw it, and document tabs (which live in that band) could not be dragged to reorder them. The empty strip still moves the window through `ViewportCommand::StartDrag`. PdfCraft patch. The published crate's asset files (`docs/res/*.svg`, `examples/data/*.png`) are left out, so its `window` example doesn't build; (13) on Wayland, pixel-only wheel, wheel-tilt and continuous-source scroll events report `Moved` rather than starting an unterminated finger gesture, so egui follows modifier release instead of keeping Ctrl zoom latched (#991). Finger gestures and unknown sources retain their existing phase policy | (1) `pdfcraft` `tests::winit_carries_the_windows_11_monitor_scale_fix` keeps the patch in the build; the drag itself needs two monitors with different scale factors on Windows 11; (2) `pdfcraft` `tests/winit_wayland_text_input.rs`; the capability change itself needs a Wayland session and an input method; (3) `pdfcraft` `tests/winit_windows_ime_cursor.rs`; composing itself needs the Microsoft Korean IME; (4) `pdfcraft` `tests/winit_windows_hidden_maximized.rs`; the start-up itself needs Windows and a window that was closed maximized; (5) `pdfcraft` `tests/winit_x11_ime_focus.rs`; switching fields itself needs an X11 session and an input method (IBus, fcitx5); (6) `pdfcraft` `tests/winit_macos_ime_commit.rs`; composing itself needs macOS and an input method; (7) `pdfcraft` `tests/winit_macos_ime_discard.rs`; composing itself needs macOS and an input method; (8) `pdfcraft` `tests/winit_macos_emoji_picker.rs`; the picker itself needs macOS; (9) `pdfcraft` `tests/winit_macos_korean_space.rs`; composing itself needs macOS and Apple Korean; (10) `pdfcraft` `tests/winit_macos_korean_first_key.rs` and `ime_startup.rs`'s own tests (run them with `rustc --test`); typing itself needs macOS and Apple Korean; (11) `pdfcraft` `tests/winit_x11_dpi.rs` keeps the patch in the build, and `util::randr` tests the policy (run them in the vendored crate); the scale itself needs an X11 session; (12) `pdfcraft` `tests/winit_macos_title_bar_drag.rs` keeps the patch in the build; the drag itself needs macOS and a pointer; (13) `pdfcraft` `tests/winit_wayland_scroll.rs` compiles the production phase policy and exercises modifier release through egui; live COSMIC confirmation remains open | | egui-wgpu | 0.36.2 | MIT OR Apache-2.0 | (1) `winit::surface_fit`: a window's surface is configured within the device's `max_texture_dimension_2d`, both sides shrunk by one factor that egui then draws at (`pixels_per_point × render_scale`), so the whole window is drawn into the surface (on DX12 it is stretched over the window and lines up with the pointer; wgpu's GL backend copies it unscaled into a corner); the longer side becomes exactly the limit; the depth and MSAA textures follow, and a recreated surface starts again from the window's own size. egui-wgpu configured the window's size as is, and `Surface::configure` panics beyond the limit: a window restored at another monitor's scale (opening an Outlook attachment on a mixed-DPI laptop asked an 8192-pixel device for 8600 × 3423, #577) or stretched across monitors closed PdfCraft, before its window appeared when it happened at start-up ([emilk/egui#8361](https://github.com/emilk/egui/issues/8361)). The published crate leaves out egui's licence files; `LICENSE-APACHE` and `LICENSE-MIT` are from the 0.36.2 tag; (2) `winit::catch_errors`: a new window's surface is configured inside wgpu error scopes (validation, out of memory, internal), and a failure is returned as `WgpuError::ConfigureSurface` (for the root window at start-up eframe returns it as `Error::Wgpu`, which PdfCraft retries with OpenGL); nothing is kept for the window. wgpu's default handler panicked instead, and eframe configures the root surface before the app is created, so a driver that can't configure one closed PdfCraft at launch (a 2015 Intel GPU through wgpu's GL backend timed out waiting for the GPU to go idle, `GpuWaitTimeout`, #519). Unchanged, so still a panic: an error in a later reconfigure (resize, a lost surface), a device lost during the first configure (wgpu reports it only to a callback), and a window shown at zero size (first configured on resize) | (1) `pdfcraft` `tests::a_window_larger_than_the_gpu_limit_gets_a_surface_within_it`, `tests::surface_fit_never_empties_or_overflows_a_surface`, and `tests::egui_wgpu_carries_the_surface_size_fit`, which keeps the patch in the build and in the paths that size a surface; (2) `pdfcraft` `tests::a_gpu_error_while_a_window_is_set_up_is_returned_not_a_panic` (a real device: an error inside `catch_errors` is returned, not a panic) and `tests::egui_wgpu_returns_a_surface_it_cannot_configure_as_an_error`, which keeps it around `add_surface`'s configure | | vello_common | 0.0.8 | Apache-2.0 OR MIT | (1) `clip::intersect` (the clip step every clipped path passes through) starts its row walk at the first row both paths have strips in, not the earlier of the two first rows. The walk visited every row from the top of the clip for each path (on the A1 sample's full-page canvas, about half its strip rows per stroke), and rows where one path has no strips produce no output, so the strips are unchanged (vello_common 0.1 starts at the later row too). Its cost grew with the page, and a full-page render of the A1 sample was about 30% faster; the output is byte-identical | (1) `clip::tests::intersect_walks_only_rows_both_paths_have_strips` counts the rows the walk visits (`cargo test --manifest-path vendor/vello_common/Cargo.toml`) and fails without the patch; the render crate's pixel tests run through the patched crate | +| hayro-cmap | 0.1.0 | Apache-2.0 OR MIT | malformed parts of a CMap (bad bfchar/bfrange entries, unresolvable `usecmap`, unparseable tail) are skipped instead of discarding the whole map, so search and redaction find text the edit layer can read (#3177) | `hayro-cmap::tests::bad_bfchar_entry_is_skipped`, `unresolvable_usecmap_is_skipped` | Renderer startup errors: `egui-wgpu::RenderState::create` also wraps `Renderer::new` in `winit::catch_errors` when the winit feature is enabled. A rejected shader or render pipeline diff --git a/vendor/hayro-cmap/Cargo.lock b/vendor/hayro-cmap/Cargo.lock new file mode 100644 index 000000000..b19a6c70f --- /dev/null +++ b/vendor/hayro-cmap/Cargo.lock @@ -0,0 +1,53 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "brotli" +version = "8.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bd8b9603c7aa97359dbd97ecf258968c95f3adddd6db2f7e7a5bef101c84560" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "874bb8112abecc98cbd6d81ea4fa7e94fb9449648c93cc89aa40c81c24d7de03" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "hayro-cmap" +version = "0.1.0" +dependencies = [ + "brotli", + "hayro-postscript", +] + +[[package]] +name = "hayro-postscript" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "885c5ef0654933139a9b9546fc2c69e18d37f38aa2520f079092b1be18f1fcaa" diff --git a/vendor/hayro-cmap/Cargo.toml b/vendor/hayro-cmap/Cargo.toml new file mode 100644 index 000000000..3818d177b --- /dev/null +++ b/vendor/hayro-cmap/Cargo.toml @@ -0,0 +1,87 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2024" +name = "hayro-cmap" +version = "0.1.0" +authors = ["Laurenz Stampfl "] +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "A parser for CMap files." +readme = "README.md" +license = "Apache-2.0 OR MIT" +repository = "https://github.com/LaurenzV/hayro" +resolver = "2" + +[features] +default = ["embed-cmaps"] +embed-cmaps = [ + "std", + "dep:brotli", +] +std = [] + +[lib] +name = "hayro_cmap" +path = "src/lib.rs" + +[dependencies.brotli] +version = "8" +features = [ + "std", + "std", +] +optional = true +default-features = false + +[dependencies.hayro-postscript] +version = "0.1.0" +default-features = false + +[lints.clippy] +collection_is_never_read = "warn" +dbg_macro = "warn" +debug_assert_with_mut_call = "warn" +default_trait_access = "warn" +doc_markdown = "warn" +fn_to_numeric_cast_any = "warn" +infinite_loop = "warn" +large_stack_arrays = "warn" +mismatching_type_param_order = "warn" +negative_feature_names = "warn" +redundant_feature_names = "warn" +same_functions_in_if_condition = "warn" +semicolon_if_nothing_returned = "warn" +todo = "warn" +too_many_arguments = "allow" +unseparated_literal_suffix = "warn" +use_self = "warn" +wildcard_dependencies = "warn" + +[lints.rust] +elided_lifetimes_in_paths = "warn" +keyword_idents_2024 = "forbid" +missing_docs = "warn" +non_ascii_idents = "forbid" +non_local_definitions = "forbid" +trivial_numeric_casts = "warn" +unnameable_types = "warn" +unreachable_pub = "warn" +unsafe_op_in_unsafe_fn = "forbid" +unused_import_braces = "warn" +unused_lifetimes = "warn" +unused_macro_rules = "warn" +unused_qualifications = "warn" diff --git a/vendor/hayro-cmap/Cargo.toml.orig b/vendor/hayro-cmap/Cargo.toml.orig new file mode 100644 index 000000000..59f5c99d3 --- /dev/null +++ b/vendor/hayro-cmap/Cargo.toml.orig @@ -0,0 +1,21 @@ +[package] +name = "hayro-cmap" +version = "0.1.0" +description = "A parser for CMap files." +authors = { workspace = true } +edition = { workspace = true } +repository = { workspace = true } +license = { workspace = true } + +[features] +default = ["embed-cmaps"] +std = [] +# Embed the 61 predefined cmaps into the binary. Adds about ~250KB of brotli-encoded data. +embed-cmaps = ["std", "dep:brotli"] + +[dependencies] +hayro-postscript = { workspace = true } +brotli = { workspace = true, optional = true, features = ["std"] } + +[lints] +workspace = true diff --git a/vendor/hayro-cmap/LICENSE-APACHE b/vendor/hayro-cmap/LICENSE-APACHE new file mode 100644 index 000000000..4947287f7 --- /dev/null +++ b/vendor/hayro-cmap/LICENSE-APACHE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/vendor/hayro-cmap/LICENSE-MIT b/vendor/hayro-cmap/LICENSE-MIT new file mode 100644 index 000000000..ae3742de4 --- /dev/null +++ b/vendor/hayro-cmap/LICENSE-MIT @@ -0,0 +1,7 @@ +Copyright (c) The Hayro Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/hayro-cmap/README.md b/vendor/hayro-cmap/README.md new file mode 100644 index 000000000..bc93f93da --- /dev/null +++ b/vendor/hayro-cmap/README.md @@ -0,0 +1,25 @@ +# hayro-cmap + +[![Crates.io](https://img.shields.io/crates/v/hayro-cmap.svg)](https://crates.io/crates/hayro-cmap) +[![Documentation](https://docs.rs/hayro-cmap/badge.svg)](https://docs.rs/hayro-cmap) + + + +A parser for cmap files, as they are found in PDFs. + +This crate provides a parser for CMap files and allows you to +- Map character codes from text-showing operators to CID identifiers. +- Map CIDs to Unicode characters or strings. + +### Safety +This crate forbids unsafe code via a crate-level attribute. + + + +## License +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or ) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or ) + +at your option. diff --git a/vendor/hayro-cmap/assets/LICENSE.txt b/vendor/hayro-cmap/assets/LICENSE.txt new file mode 100644 index 000000000..2552cc990 --- /dev/null +++ b/vendor/hayro-cmap/assets/LICENSE.txt @@ -0,0 +1,28 @@ +Copyright 1990-2023 Adobe. All rights reserved. + +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/vendor/hayro-cmap/assets/README.md b/vendor/hayro-cmap/assets/README.md new file mode 100644 index 000000000..4cedb1ff6 --- /dev/null +++ b/vendor/hayro-cmap/assets/README.md @@ -0,0 +1,2 @@ +See https://github.com/LaurenzV/cmap-resources/tree/hayro for information on how this blob was generated and how +it can be parsed. \ No newline at end of file diff --git a/vendor/hayro-cmap/assets/cmaps.brotli b/vendor/hayro-cmap/assets/cmaps.brotli new file mode 100644 index 000000000..ba74bd32f Binary files /dev/null and b/vendor/hayro-cmap/assets/cmaps.brotli differ diff --git a/vendor/hayro-cmap/src/bcmap/embedded.rs b/vendor/hayro-cmap/src/bcmap/embedded.rs new file mode 100644 index 000000000..0f5c241a0 --- /dev/null +++ b/vendor/hayro-cmap/src/bcmap/embedded.rs @@ -0,0 +1,129 @@ +use std::ops::Range; +use std::sync::LazyLock; + +use super::huffman::{self, HuffmanTable}; +use super::reader::Reader; +use crate::CMapName; + +pub(super) static BUNDLE: LazyLock = LazyLock::new(|| { + // We already know the bundle is valid, so we can skip validation and just + // unwrap everywhere. + + let compressed = include_bytes!("../../assets/cmaps.brotli"); + let mut decompressed = Vec::new(); + let mut reader = compressed.as_slice(); + + brotli::BrotliDecompress(&mut reader, &mut decompressed) + .ok() + .unwrap(); + + let mut reader = Reader::new(&decompressed); + let huff_size = reader.read_u32().unwrap() as usize; + let huff_data = reader.read_bytes(huff_size).unwrap(); + let (delta_table, count_table) = huffman::decode_tables(huff_data).unwrap(); + + let mut entries = Vec::new(); + + while !reader.at_end() { + let start = reader.position(); + + // Skip file magic and version. + reader.read_bytes(6).unwrap(); + let file_len = reader.read_u32().unwrap() as usize; + + reader.read_bytes(file_len - 10).unwrap(); + entries.push(start..start + file_len); + } + + Bundle { + data: decompressed, + delta_table, + count_table, + entries, + } +}); + +pub(super) struct Bundle { + data: Vec, + pub(super) delta_table: HuffmanTable, + pub(super) count_table: HuffmanTable, + entries: Vec>, +} + +/// Load the data for a cmap file, by name. +pub fn load_embedded(name: CMapName<'_>) -> Option<&'static [u8]> { + // Get the index of the font of the cmap in the bundle. They are sorted + // alphabetically. + let idx = match name { + CMapName::N83pvRksjH => 0, + CMapName::N90msRksjH => 1, + CMapName::N90msRksjV => 2, + CMapName::N90mspRksjH => 3, + CMapName::N90mspRksjV => 4, + CMapName::N90pvRksjH => 5, + CMapName::AddRksjH => 6, + CMapName::AddRksjV => 7, + CMapName::AdobeCns1Ucs2 => 8, + CMapName::AdobeGb1Ucs2 => 9, + CMapName::AdobeJapan1Ucs2 => 10, + CMapName::AdobeKorea1Ucs2 => 11, + CMapName::B5pcH => 12, + CMapName::B5pcV => 13, + CMapName::CnsEucH => 14, + CMapName::CnsEucV => 15, + CMapName::ETenB5H => 16, + CMapName::ETenB5V => 17, + CMapName::ETenmsB5H => 18, + CMapName::ETenmsB5V => 19, + CMapName::EucH => 20, + CMapName::EucV => 21, + CMapName::ExtRksjH => 22, + CMapName::ExtRksjV => 23, + CMapName::GbEucH => 24, + CMapName::GbEucV => 25, + CMapName::GbkEucH => 26, + CMapName::GbkEucV => 27, + CMapName::Gbk2kH => 28, + CMapName::Gbk2kV => 29, + CMapName::GbkpEucH => 30, + CMapName::GbkpEucV => 31, + CMapName::GbpcEucH => 32, + CMapName::GbpcEucV => 33, + CMapName::H => 34, + CMapName::HKscsB5H => 35, + CMapName::HKscsB5V => 36, + CMapName::IdentityH => 37, + CMapName::IdentityV => 38, + CMapName::KscEucH => 39, + CMapName::KscEucV => 40, + CMapName::KscmsUhcH => 41, + CMapName::KscmsUhcHwH => 42, + CMapName::KscmsUhcHwV => 43, + CMapName::KscmsUhcV => 44, + CMapName::KscpcEucH => 45, + CMapName::UniCnsUcs2H => 46, + CMapName::UniCnsUcs2V => 47, + CMapName::UniCnsUtf16H => 48, + CMapName::UniCnsUtf16V => 49, + CMapName::UniGbUcs2H => 50, + CMapName::UniGbUcs2V => 51, + CMapName::UniGbUtf16H => 52, + CMapName::UniGbUtf16V => 53, + CMapName::UniJisUcs2H => 54, + CMapName::UniJisUcs2HwH => 55, + CMapName::UniJisUcs2HwV => 56, + CMapName::UniJisUcs2V => 57, + CMapName::UniJisUtf16H => 58, + CMapName::UniJisUtf16V => 59, + CMapName::UniKsUcs2H => 60, + CMapName::UniKsUcs2V => 61, + CMapName::UniKsUtf16H => 62, + CMapName::UniKsUtf16V => 63, + CMapName::V => 64, + CMapName::Custom(_) => return None, + }; + + let range = BUNDLE.entries.get(idx)?; + + Some(&BUNDLE.data[range.clone()]) +} diff --git a/vendor/hayro-cmap/src/bcmap/huffman.rs b/vendor/hayro-cmap/src/bcmap/huffman.rs new file mode 100644 index 000000000..b6e8e9ab5 --- /dev/null +++ b/vendor/hayro-cmap/src/bcmap/huffman.rs @@ -0,0 +1,180 @@ +use alloc::vec; +use alloc::vec::Vec; +use core::num::NonZeroU32; + +use super::reader::Reader; + +#[derive(Debug, Clone, Copy)] +pub(super) enum HuffmanNode { + /// Intermediate node with optional children. + Intermediate { + /// Index of the zero-child. + zero: Option, + /// Index of the one-child. + one: Option, + }, + /// Leaf node holding a decoded symbol value. + Leaf(u32), +} + +/// A Huffman table built from canonical codes. +#[derive(Debug)] +pub(super) struct HuffmanTable { + nodes: Vec, +} + +impl HuffmanTable { + /// Decode a single symbol from the bit reader. + pub(super) fn decode(&self, reader: &mut Reader<'_>) -> Option { + let mut idx = 0_u32; + + loop { + match self.nodes[idx as usize] { + HuffmanNode::Intermediate { zero, one } => { + let bit = reader.read_bit()?; + let child = if bit == 0 { zero } else { one }; + idx = child?.get(); + } + HuffmanNode::Leaf(symbol) => return Some(symbol), + } + } + } + + fn insert_code( + nodes: &mut Vec, + node_index: u32, + code: u32, + length: u8, + symbol: u32, + ) { + if length == 0 { + nodes[node_index as usize] = HuffmanNode::Leaf(symbol); + + return; + } + + let bit = (code >> (length - 1)) & 1; + let remaining = code & ((1 << (length - 1)) - 1); + + let child_index = match &nodes[node_index as usize] { + HuffmanNode::Intermediate { zero, one } => { + let existing = if bit == 0 { *zero } else { *one }; + match existing { + Some(idx) => idx, + None => { + let new_idx = NonZeroU32::new(nodes.len() as u32).unwrap(); + nodes.push(HuffmanNode::Intermediate { + zero: None, + one: None, + }); + + match &mut nodes[node_index as usize] { + HuffmanNode::Intermediate { zero, one } => { + if bit == 0 { + *zero = Some(new_idx); + } else { + *one = Some(new_idx); + } + } + _ => unreachable!(), + } + new_idx + } + } + } + _ => return, + }; + + Self::insert_code(nodes, child_index.get(), remaining, length - 1, symbol); + } + + fn build(code_lengths: &[u8], symbols: &[u32]) -> Self { + debug_assert_eq!(code_lengths.len(), symbols.len()); + + if symbols.is_empty() { + return Self { + nodes: vec![HuffmanNode::Intermediate { + zero: None, + one: None, + }], + }; + } + + let max_length = *code_lengths.iter().max().unwrap_or(&0) as usize; + + let mut codes = vec![0_u32; symbols.len()]; + let mut code = 0_u32; + + for length in 1..=max_length { + for (i, &cl) in code_lengths.iter().enumerate() { + if cl as usize == length { + codes[i] = code; + code += 1; + } + } + code <<= 1; + } + + let mut nodes = vec![HuffmanNode::Intermediate { + zero: None, + one: None, + }]; + + for (i, &symbol) in symbols.iter().enumerate() { + if code_lengths[i] == 0 { + continue; + } + + Self::insert_code(&mut nodes, 0, codes[i], code_lengths[i], symbol); + } + + Self { nodes } + } +} + +pub(super) fn decode_tables(data: &[u8]) -> Option<(HuffmanTable, HuffmanTable)> { + let mut reader = Reader::new(data); + let delta = decode_single_table(&mut reader, |r| r.read_u32())?; + let count = decode_single_table(&mut reader, |r| r.read_u8().map(u32::from))?; + + Some((delta, count)) +} + +fn decode_single_table( + reader: &mut Reader<'_>, + read_sym: fn(&mut Reader<'_>) -> Option, +) -> Option { + let n_symbols = reader.read_u16()? as usize; + + if n_symbols == 0 { + let _max_len = reader.read_u8()?; + + return Some(HuffmanTable { + nodes: vec![HuffmanNode::Intermediate { + zero: None, + one: None, + }], + }); + } + + let max_code_length = reader.read_u8()? as usize; + + let mut counts = Vec::with_capacity(max_code_length); + for _ in 0..max_code_length { + counts.push(reader.read_u16()?); + } + + let mut code_lengths = Vec::with_capacity(n_symbols); + let mut symbols = Vec::with_capacity(n_symbols); + + for (length_idx, &count) in counts.iter().enumerate() { + let code_len = (length_idx + 1) as u8; + + for _ in 0..count { + symbols.push(read_sym(reader)?); + code_lengths.push(code_len); + } + } + + Some(HuffmanTable::build(&code_lengths, &symbols)) +} diff --git a/vendor/hayro-cmap/src/bcmap/mod.rs b/vendor/hayro-cmap/src/bcmap/mod.rs new file mode 100644 index 000000000..997bc00d8 --- /dev/null +++ b/vendor/hayro-cmap/src/bcmap/mod.rs @@ -0,0 +1,416 @@ +//! Inspired by pdf.js, we use a custom binary format to optionally embed +//! the required cmaps in a space-efficient manner. However, we don't use +//! their format description but have a custom one. For more information, +//! see . + +pub(crate) mod embedded; +pub(crate) mod huffman; +pub(crate) mod reader; + +use alloc::boxed::Box; +use alloc::vec::Vec; + +pub use embedded::load_embedded; + +use crate::bcmap::embedded::BUNDLE; +use crate::{ + BfRange, CMap, CMapName, CharacterCollection, CidFamily, CidRange, CodespaceRange, Metadata, + PartitionedRanges, Range, WritingMode, parse, +}; +use huffman::HuffmanTable; +use reader::Reader; + +const BCMAP_MAGIC: &[u8] = b"bcmap"; +const BCMAP_VERSION: u8 = 0x01; +const BCMAP_FILE_HEADER_SIZE: usize = 10; +const SEG_HEADER_SIZE: usize = 5; + +const SEGMENT_RANGE_1B: u8 = 0x01; +const SEGMENT_SINGLE_1B: u8 = 0x02; +const SEGMENT_RANGE_2B: u8 = 0x03; +const SEGMENT_SINGLE_2B: u8 = 0x04; +const SEGMENT_RANGE_3B: u8 = 0x05; +const SEGMENT_SINGLE_3B: u8 = 0x06; +const SEGMENT_RANGE_4B: u8 = 0x07; +const SEGMENT_SINGLE_4B: u8 = 0x08; +const SEGMENT_USECMAP: u8 = 0x09; +const SEGMENT_NOTDEF: u8 = 0x0A; +const SEGMENT_WMODE: u8 = 0x0B; +const SEGMENT_CODESPACE: u8 = 0x0C; +const SEGMENT_NAME: u8 = 0x0D; +const SEGMENT_CID_SYSTEM_INFO: u8 = 0x0E; +const SEGMENT_BF_RANGE_VARIABLE: u8 = 0x0F; +const SEGMENT_BF_SINGLE_VARIABLE: u8 = 0x10; +const SEGMENT_BF_SINGLE_1U: u8 = 0x11; +const SEGMENT_BF_SINGLE_2U: u8 = 0x12; +const SEGMENT_BF_SINGLE_3U: u8 = 0x13; +const SEGMENT_BF_SINGLE_4U: u8 = 0x14; +const SEGMENT_BF_RANGE_1U: u8 = 0x15; +const SEGMENT_BF_RANGE_2U: u8 = 0x16; + +pub(crate) fn parse<'a>( + data: &[u8], + get_cmap: impl Fn(CMapName<'_>) -> Option<&'a [u8]> + Clone + 'a, + depth: u32, +) -> Option { + // While in theory we can assume that all binary cmaps are valid, it can + // of course happen that an invalid one has been passed from outside, so + // we still need to do proper validation. + + if data.get(..5)? != BCMAP_MAGIC || *data.get(5)? != BCMAP_VERSION { + return None; + } + + let mut reader = Reader::new(data); + reader.read_bytes(6)?; // Skip magic + version. + + let file_len = reader.read_u32()? as usize; + + let delta_table = &BUNDLE.delta_table; + let count_table = &BUNDLE.count_table; + + let mut cmap_name = None; + let mut character_collection = None; + let mut writing_mode = None; + let mut base: Option> = None; + let mut _codespace_ranges = Vec::new(); + let mut cid_ranges = PartitionedRanges::new(); + let mut notdef_ranges = PartitionedRanges::new(); + let mut bf_entries = Vec::new(); + + // Start parsing all segments of the file. + let mut reader = Reader::new(data.get(BCMAP_FILE_HEADER_SIZE..file_len)?); + + while !reader.at_end() { + let seg_type = reader.read_u8()?; + let seg_len = reader.read_u32()? as usize; + + let payload = reader.read_bytes(seg_len.checked_sub(SEG_HEADER_SIZE)?)?; + + match seg_type { + SEGMENT_NAME => { + cmap_name = Some(Vec::from(payload)); + } + SEGMENT_CID_SYSTEM_INFO => { + // Format: Each string is 0-terminated. + let mut r = Reader::new(payload); + let registry = Vec::from(r.eat_until(|b| b == 0)); + r.read_u8()?; + + let ordering = Vec::from(r.eat_until(|b| b == 0)); + r.read_u8()?; + let supplement = r.read_u16()? as i32; + + character_collection = Some(CharacterCollection { + family: CidFamily::from_registry_ordering(®istry, &ordering), + supplement, + }); + } + SEGMENT_USECMAP => { + let base_data = get_cmap(CMapName::from_bytes(payload))?; + + base = Some(Box::new(parse::parse_inner( + base_data, + get_cmap.clone(), + depth, + )?)); + } + SEGMENT_WMODE => { + writing_mode = match payload.first()? { + 0 => Some(WritingMode::Horizontal), + 1 => Some(WritingMode::Vertical), + _ => None, + }; + } + SEGMENT_CODESPACE => { + parse_codespace(payload, &mut _codespace_ranges)?; + } + SEGMENT_NOTDEF => { + parse_notdef(payload, &mut notdef_ranges)?; + } + SEGMENT_RANGE_1B | SEGMENT_RANGE_2B | SEGMENT_RANGE_3B | SEGMENT_RANGE_4B => { + let bw = seg_type.div_ceil(2) as usize; + parse_cid_segment(payload, &mut cid_ranges, bw, delta_table, Some(count_table))?; + } + SEGMENT_SINGLE_1B | SEGMENT_SINGLE_2B | SEGMENT_SINGLE_3B | SEGMENT_SINGLE_4B => { + let bw = seg_type.div_ceil(2) as usize; + parse_cid_segment(payload, &mut cid_ranges, bw, delta_table, None)?; + } + SEGMENT_BF_RANGE_VARIABLE => { + parse_bf_segment( + payload, + &mut bf_entries, + delta_table, + Some(count_table), + None, + )?; + } + SEGMENT_BF_SINGLE_VARIABLE => { + parse_bf_segment(payload, &mut bf_entries, delta_table, None, None)?; + } + SEGMENT_BF_RANGE_1U => { + parse_bf_segment( + payload, + &mut bf_entries, + delta_table, + Some(count_table), + Some(1), + )?; + } + SEGMENT_BF_RANGE_2U => { + parse_bf_segment( + payload, + &mut bf_entries, + delta_table, + Some(count_table), + Some(2), + )?; + } + SEGMENT_BF_SINGLE_1U => { + parse_bf_segment(payload, &mut bf_entries, delta_table, None, Some(1))?; + } + SEGMENT_BF_SINGLE_2U => { + parse_bf_segment(payload, &mut bf_entries, delta_table, None, Some(2))?; + } + SEGMENT_BF_SINGLE_3U => { + parse_bf_segment(payload, &mut bf_entries, delta_table, None, Some(3))?; + } + SEGMENT_BF_SINGLE_4U => { + parse_bf_segment(payload, &mut bf_entries, delta_table, None, Some(4))?; + } + _ => { + return None; + } + } + } + + cid_ranges.sort(); + notdef_ranges.sort(); + bf_entries.sort_by(|a, b| a.range.start.cmp(&b.range.start)); + + Some(CMap { + metadata: Metadata { + character_collection, + name: cmap_name, + writing_mode, + }, + _codespace_ranges, + cid_ranges, + notdef_ranges, + bf_entries, + base, + }) +} + +fn parse_codespace(payload: &[u8], ranges: &mut Vec) -> Option<()> { + let mut r = Reader::new(payload); + let n_ranges = r.read_u8()? as usize; + + for _ in 0..n_ranges { + let bw = r.read_u8()? as usize; + let low = r.read_n_bytes(bw)?; + let high = r.read_n_bytes(bw)?; + + ranges.push(CodespaceRange { + number_bytes: bw as u8, + low, + high, + }); + } + + Some(()) +} + +fn parse_notdef(payload: &[u8], ranges: &mut PartitionedRanges) -> Option<()> { + let mut r = Reader::new(payload); + let bw = r.read_u8()? as usize; + let n_entries = r.read_u16()? as usize; + + for _ in 0..n_entries { + let start = r.read_n_bytes(bw)?; + let end = r.read_n_bytes(bw)?; + let cid = r.read_u16()? as u32; + + ranges.push( + bw, + CidRange { + range: Range { start, end }, + cid_start: cid, + }, + ); + } + + Some(()) +} + +fn parse_cid_segment( + payload: &[u8], + ranges: &mut PartitionedRanges, + byte_width: usize, + delta_table: &HuffmanTable, + count_table: Option<&HuffmanTable>, +) -> Option<()> { + let mut r = Reader::new(payload); + let n_entries = r.read_u16()? as usize; + + if n_entries == 0 { + return Some(()); + } + + // There are two types of CID segments, all of which are stored in a columnar + // fastion in the file: + // For the first type, we have a simple mapping from a single code to a single + // CID. In this case, the data stream first contains all codes using delta-coding, + // encoded using huffman coding. This is followed by all CIDs, stored as + // u16 (either as a raw CID, or as `0` in case the CID is +1 the previous CID). + // + // For the second type, we have a range of consecutive codes, which map + // to a range of consecutive CIDs. In this case, we have an additional "count" + // column that stores how many codes are mapped consecutively. These are also + // encoded using huffman coding. + + // Read deltas for the start code points. + let delta_len = r.read_u32()? as usize; + let delta_data = r.read_bytes(delta_len)?; + + let mut delta_reader = Reader::new(delta_data); + let mut deltas = Vec::with_capacity(n_entries); + + for _ in 0..n_entries { + deltas.push(delta_table.decode(&mut delta_reader)?); + } + + // Read the counts for each consecutive code range. + let mut counts = Vec::new(); + if let Some(ct) = count_table { + let count_len = r.read_u32()? as usize; + let count_data = r.read_bytes(count_len)?; + + let mut count_reader = Reader::new(count_data); + counts.reserve(n_entries); + for _ in 0..n_entries { + counts.push(ct.decode(&mut count_reader)?); + } + } + + // Read the CIDs and reconstruct the character codes that map to them. + let is_range = count_table.is_some(); + let mut prev_end: Option = None; + let mut prev_cid: Option = None; + let mut prev_range_len: u32 = 0; + + for i in 0..n_entries { + let raw_cid = r.read_u16()?; + + // Note that start deltas and counts are encoded minus one, so we + // need to add one when reconstructing them. + + // Reconstruct start code. + let start = if let Some(pe) = prev_end { + pe + 1 + deltas[i] + } else { + deltas[i] + }; + + // Reconstruct end code. + let end = if is_range { + start + counts[i] + 1 + } else { + start + }; + + // CID 0 means it's consecutive to the last seen CID, plus 1. + let cid = if raw_cid == 0 { + if let Some(pc) = prev_cid { + pc + prev_range_len + 1 + } else { + 0 + } + } else { + raw_cid as u32 + }; + + ranges.push( + byte_width, + CidRange { + range: Range { start, end }, + cid_start: cid, + }, + ); + + prev_end = Some(end); + prev_cid = Some(cid); + prev_range_len = end - start; + } + + Some(()) +} + +fn parse_bf_segment( + payload: &[u8], + entries: &mut Vec, + delta_table: &HuffmanTable, + count_table: Option<&HuffmanTable>, + fixed_units: Option, +) -> Option<()> { + let mut r = Reader::new(payload); + let n_entries = r.read_u16()? as usize; + + let delta_len = r.read_u32()? as usize; + let delta_data = r.read_bytes(delta_len)?; + + let mut delta_reader = Reader::new(delta_data); + let mut deltas = Vec::with_capacity(n_entries); + for _ in 0..n_entries { + deltas.push(delta_table.decode(&mut delta_reader)?); + } + + // Read counts for range segments. + let mut counts = Vec::new(); + if let Some(ct) = count_table { + let count_len = r.read_u32()? as usize; + let count_data = r.read_bytes(count_len)?; + + let mut count_reader = Reader::new(count_data); + counts.reserve(n_entries); + for _ in 0..n_entries { + counts.push(ct.decode(&mut count_reader)?); + } + } + + let is_range = count_table.is_some(); + let mut prev_end: Option = None; + + for i in 0..n_entries { + // Fixed-width segments encode destinations without a length prefix. + let n_units = match fixed_units { + Some(nu) => nu, + None => r.read_u8()? as usize, + }; + let mut dst_base = Vec::with_capacity(n_units); + for _ in 0..n_units { + dst_base.push(r.read_u16()?); + } + + let start = if let Some(pe) = prev_end { + pe + 1 + deltas[i] + } else { + deltas[i] + }; + + let end = if is_range { + start + counts[i] + 1 + } else { + start + }; + + entries.push(BfRange { + range: Range { start, end }, + dst_base, + }); + + prev_end = Some(end); + } + + Some(()) +} diff --git a/vendor/hayro-cmap/src/bcmap/reader.rs b/vendor/hayro-cmap/src/bcmap/reader.rs new file mode 100644 index 000000000..25d663910 --- /dev/null +++ b/vendor/hayro-cmap/src/bcmap/reader.rs @@ -0,0 +1,123 @@ +pub(super) struct Reader<'a> { + data: &'a [u8], + byte_pos: usize, + bit_pos: u8, +} + +impl<'a> Reader<'a> { + #[inline] + pub(super) fn new(data: &'a [u8]) -> Self { + Self { + data, + byte_pos: 0, + bit_pos: 0, + } + } + + #[inline] + pub(super) fn read_bit(&mut self) -> Option { + let byte = *self.data.get(self.byte_pos)?; + let bit = (byte >> (7 - self.bit_pos)) & 1; + + self.bit_pos += 1; + + if self.bit_pos == 8 { + self.bit_pos = 0; + self.byte_pos += 1; + } + + Some(bit) + } + + #[inline] + pub(super) fn read_u16(&mut self) -> Option { + debug_assert_eq!(self.bit_pos, 0, "read_u16 called at non-byte boundary"); + + let bytes: [u8; 2] = self + .data + .get(self.byte_pos..self.byte_pos + 2)? + .try_into() + .ok()?; + self.byte_pos += 2; + + Some(u16::from_be_bytes(bytes)) + } + + #[inline] + pub(super) fn read_u32(&mut self) -> Option { + debug_assert_eq!(self.bit_pos, 0, "read_u32 called at non-byte boundary"); + + let bytes: [u8; 4] = self + .data + .get(self.byte_pos..self.byte_pos + 4)? + .try_into() + .ok()?; + self.byte_pos += 4; + + Some(u32::from_be_bytes(bytes)) + } + + #[inline] + pub(super) fn read_u8(&mut self) -> Option { + debug_assert_eq!(self.bit_pos, 0, "read_u8 called at non-byte boundary"); + + let val = *self.data.get(self.byte_pos)?; + self.byte_pos += 1; + + Some(val) + } + + #[inline] + pub(super) fn read_n_bytes(&mut self, n: usize) -> Option { + debug_assert_eq!( + self.bit_pos, 0, + "read_n_bytes_be called at non-byte boundary" + ); + + match n { + 1 => Some(self.read_u8()? as u32), + 2 => Some(self.read_u16()? as u32), + 3 => { + let bytes = self.read_bytes(3)?; + Some((bytes[0] as u32) << 16 | (bytes[1] as u32) << 8 | bytes[2] as u32) + } + 4 => self.read_u32(), + _ => None, + } + } + + #[inline] + pub(super) fn read_bytes(&mut self, n: usize) -> Option<&'a [u8]> { + debug_assert_eq!(self.bit_pos, 0, "read_bytes called at non-byte boundary"); + + let bytes = self.data.get(self.byte_pos..self.byte_pos + n)?; + self.byte_pos += n; + + Some(bytes) + } + + #[inline] + pub(super) fn position(&self) -> usize { + self.byte_pos + } + + #[inline] + pub(super) fn at_end(&self) -> bool { + self.byte_pos >= self.data.len() + } + + #[inline] + pub(super) fn eat_until(&mut self, f: impl Fn(u8) -> bool) -> &'a [u8] { + debug_assert_eq!(self.bit_pos, 0, "eat_until called at non-byte boundary"); + + let start = self.byte_pos; + while let Some(&b) = self.data.get(self.byte_pos) { + if f(b) { + break; + } + self.byte_pos += 1; + } + + &self.data[start..self.byte_pos] + } +} diff --git a/vendor/hayro-cmap/src/lib.rs b/vendor/hayro-cmap/src/lib.rs new file mode 100644 index 000000000..4786e75e5 --- /dev/null +++ b/vendor/hayro-cmap/src/lib.rs @@ -0,0 +1,1692 @@ +/*! +A parser for cmap files, as they are found in PDFs. + +This crate provides a parser for cmap files and allows you to +- Map character codes from text-showing operators to CID identifiers. +- Map CIDs to Unicode characters or strings. + +## Safety +This crate forbids unsafe code via a crate-level attribute. +*/ + +#![cfg_attr(not(feature = "std"), no_std)] +#![forbid(unsafe_code)] +#![deny(missing_docs)] + +extern crate alloc; + +#[cfg(feature = "embed-cmaps")] +mod bcmap; +mod parse; + +#[cfg(feature = "embed-cmaps")] +pub use bcmap::load_embedded; + +/// Look up an embedded binary cmap by name. +/// +/// Returns `None` when the `embed-cmaps` feature is not enabled. +#[cfg(not(feature = "embed-cmaps"))] +pub fn load_embedded(_name: CMapName<'_>) -> Option<&'static [u8]> { + None +} + +use alloc::boxed::Box; +use alloc::string::String; +use alloc::vec::Vec; + +/// A CID (Character Identifier). +pub type Cid = u32; + +/// The name of the cmap. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CMapName<'a> { + // ── Adobe-Japan1 (Japanese) ── Shift-JIS (RKSJ) encodings ── + /// `83pv-RKSJ-H` — Adobe-Japan1, Mac Shift-JIS (`KanjiTalk` 6), horizontal. + N83pvRksjH, + /// `90ms-RKSJ-H` — Adobe-Japan1, Windows Shift-JIS (code page 932), horizontal. + N90msRksjH, + /// `90ms-RKSJ-V` — Adobe-Japan1, Windows Shift-JIS (code page 932), vertical. + N90msRksjV, + /// `90msp-RKSJ-H` — Adobe-Japan1, Windows Shift-JIS with proportional Roman, horizontal. + N90mspRksjH, + /// `90msp-RKSJ-V` — Adobe-Japan1, Windows Shift-JIS with proportional Roman, vertical. + N90mspRksjV, + /// `90pv-RKSJ-H` — Adobe-Japan1, Mac Shift-JIS (`KanjiTalk` 7), horizontal. + N90pvRksjH, + /// `Add-RKSJ-H` — Adobe-Japan1, Fujitsu FMR Shift-JIS, horizontal. + AddRksjH, + /// `Add-RKSJ-V` — Adobe-Japan1, Fujitsu FMR Shift-JIS, vertical. + AddRksjV, + + // ── Adobe UCS2 (CID → Unicode) ── + // Note that these are not part of the predefined CMaps, but we use them + // so we can more easily map CIDs back to Unicode. + /// `Adobe-CNS1-UCS2` — Adobe-CNS1, CID-to-Unicode mapping. + AdobeCns1Ucs2, + /// `Adobe-GB1-UCS2` — Adobe-GB1, CID-to-Unicode mapping. + AdobeGb1Ucs2, + /// `Adobe-Japan1-UCS2` — Adobe-Japan1, CID-to-Unicode mapping. + AdobeJapan1Ucs2, + /// `Adobe-Korea1-UCS2` — Adobe-Korea1, CID-to-Unicode mapping. + AdobeKorea1Ucs2, + + // ── Adobe-CNS1 (Traditional Chinese) ── Big Five encodings ── + /// `B5pc-H` — Adobe-CNS1, Mac Big Five (`ETen` extensions), horizontal. + B5pcH, + /// `B5pc-V` — Adobe-CNS1, Mac Big Five (`ETen` extensions), vertical. + B5pcV, + /// `CNS-EUC-H` — Adobe-CNS1, CNS 11643 EUC encoding, horizontal. + CnsEucH, + /// `CNS-EUC-V` — Adobe-CNS1, CNS 11643 EUC encoding, vertical. + CnsEucV, + /// `ETen-B5-H` — Adobe-CNS1, `ETen` Big Five extensions, horizontal. + ETenB5H, + /// `ETen-B5-V` — Adobe-CNS1, `ETen` Big Five extensions, vertical. + ETenB5V, + /// `ETenms-B5-H` — Adobe-CNS1, `ETen` Big Five with Microsoft symbol extensions, horizontal. + ETenmsB5H, + /// `ETenms-B5-V` — Adobe-CNS1, `ETen` Big Five with Microsoft symbol extensions, vertical. + ETenmsB5V, + + // ── Adobe-Japan1 (Japanese) ── EUC and extended Shift-JIS encodings ── + /// `EUC-H` — Adobe-Japan1, JIS X 0208 EUC-JP encoding, horizontal. + EucH, + /// `EUC-V` — Adobe-Japan1, JIS X 0208 EUC-JP encoding, vertical. + EucV, + /// `Ext-RKSJ-H` — Adobe-Japan1, Shift-JIS with NEC/IBM extensions, horizontal. + ExtRksjH, + /// `Ext-RKSJ-V` — Adobe-Japan1, Shift-JIS with NEC/IBM extensions, vertical. + ExtRksjV, + + // ── Adobe-GB1 (Simplified Chinese) ── + /// `GB-EUC-H` — Adobe-GB1, GB 2312-80 EUC encoding, horizontal. + GbEucH, + /// `GB-EUC-V` — Adobe-GB1, GB 2312-80 EUC encoding, vertical. + GbEucV, + /// `GBK-EUC-H` — Adobe-GB1, GBK encoding (Microsoft code page 936), horizontal. + GbkEucH, + /// `GBK-EUC-V` — Adobe-GB1, GBK encoding (Microsoft code page 936), vertical. + GbkEucV, + /// `GBK2K-H` — Adobe-GB1, GB 18030-2000 encoding, horizontal. + Gbk2kH, + /// `GBK2K-V` — Adobe-GB1, GB 18030-2000 encoding, vertical. + Gbk2kV, + /// `GBKp-EUC-H` — Adobe-GB1, GBK with proportional Roman, horizontal. + GbkpEucH, + /// `GBKp-EUC-V` — Adobe-GB1, GBK with proportional Roman, vertical. + GbkpEucV, + /// `GBpc-EUC-H` — Adobe-GB1, Mac GB 2312 (simplified) EUC encoding, horizontal. + GbpcEucH, + /// `GBpc-EUC-V` — Adobe-GB1, Mac GB 2312 (simplified) EUC encoding, vertical. + GbpcEucV, + + // ── Adobe-Japan1 (Japanese) ── JIS encoding ── + /// `H` — Adobe-Japan1, JIS X 0208 row-cell encoding, horizontal. + H, + + // ── Adobe-CNS1 (Traditional Chinese) ── Hong Kong SCS ── + /// `HKscs-B5-H` — Adobe-CNS1, Hong Kong SCS (Big Five with HKSCS extensions), horizontal. + HKscsB5H, + /// `HKscs-B5-V` — Adobe-CNS1, Hong Kong SCS (Big Five with HKSCS extensions), vertical. + HKscsB5V, + + // ── Adobe-Identity ── + /// `Identity-H` — Adobe-Identity, two-byte identity mapping, horizontal. + /// Character codes map directly to CIDs (i.e. CID = character code). + IdentityH, + /// `Identity-V` — Adobe-Identity, two-byte identity mapping, vertical. + /// Character codes map directly to CIDs (i.e. CID = character code). + IdentityV, + + // ── Adobe-Korea1 (Korean) ── + /// `KSC-EUC-H` — Adobe-Korea1, KS X 1001:1992 EUC-KR encoding, horizontal. + KscEucH, + /// `KSC-EUC-V` — Adobe-Korea1, KS X 1001:1992 EUC-KR encoding, vertical. + KscEucV, + /// `KSCms-UHC-H` — Adobe-Korea1, Microsoft UHC (Unified Hangul Code, code page 949), horizontal. + KscmsUhcH, + /// `KSCms-UHC-HW-H` — Adobe-Korea1, Microsoft UHC with half-width Roman, horizontal. + KscmsUhcHwH, + /// `KSCms-UHC-HW-V` — Adobe-Korea1, Microsoft UHC with half-width Roman, vertical. + KscmsUhcHwV, + /// `KSCms-UHC-V` — Adobe-Korea1, Microsoft UHC (Unified Hangul Code, code page 949), vertical. + KscmsUhcV, + /// `KSCpc-EUC-H` — Adobe-Korea1, Mac KS X 1001:1992 EUC-KR encoding, horizontal. + KscpcEucH, + + // ── Adobe-CNS1 (Traditional Chinese) ── Unicode encodings ── + /// `UniCNS-UCS2-H` — Adobe-CNS1, Unicode UCS-2 encoding, horizontal. + UniCnsUcs2H, + /// `UniCNS-UCS2-V` — Adobe-CNS1, Unicode UCS-2 encoding, vertical. + UniCnsUcs2V, + /// `UniCNS-UTF16-H` — Adobe-CNS1, Unicode UTF-16 encoding, horizontal. + UniCnsUtf16H, + /// `UniCNS-UTF16-V` — Adobe-CNS1, Unicode UTF-16 encoding, vertical. + UniCnsUtf16V, + + // ── Adobe-GB1 (Simplified Chinese) ── Unicode encodings ── + /// `UniGB-UCS2-H` — Adobe-GB1, Unicode UCS-2 encoding, horizontal. + UniGbUcs2H, + /// `UniGB-UCS2-V` — Adobe-GB1, Unicode UCS-2 encoding, vertical. + UniGbUcs2V, + /// `UniGB-UTF16-H` — Adobe-GB1, Unicode UTF-16 encoding, horizontal. + UniGbUtf16H, + /// `UniGB-UTF16-V` — Adobe-GB1, Unicode UTF-16 encoding, vertical. + UniGbUtf16V, + + // ── Adobe-Japan1 (Japanese) ── Unicode encodings ── + /// `UniJIS-UCS2-H` — Adobe-Japan1, Unicode UCS-2 encoding, horizontal. + UniJisUcs2H, + /// `UniJIS-UCS2-HW-H` — Adobe-Japan1, Unicode UCS-2 with half-width Roman, horizontal. + UniJisUcs2HwH, + /// `UniJIS-UCS2-HW-V` — Adobe-Japan1, Unicode UCS-2 with half-width Roman, vertical. + UniJisUcs2HwV, + /// `UniJIS-UCS2-V` — Adobe-Japan1, Unicode UCS-2 encoding, vertical. + UniJisUcs2V, + /// `UniJIS-UTF16-H` — Adobe-Japan1, Unicode UTF-16 encoding, horizontal. + UniJisUtf16H, + /// `UniJIS-UTF16-V` — Adobe-Japan1, Unicode UTF-16 encoding, vertical. + UniJisUtf16V, + + // ── Adobe-Korea1 (Korean) ── Unicode encodings ── + /// `UniKS-UCS2-H` — Adobe-Korea1, Unicode UCS-2 encoding, horizontal. + UniKsUcs2H, + /// `UniKS-UCS2-V` — Adobe-Korea1, Unicode UCS-2 encoding, vertical. + UniKsUcs2V, + /// `UniKS-UTF16-H` — Adobe-Korea1, Unicode UTF-16 encoding, horizontal. + UniKsUtf16H, + /// `UniKS-UTF16-V` — Adobe-Korea1, Unicode UTF-16 encoding, vertical. + UniKsUtf16V, + + // ── Adobe-Japan1 (Japanese) ── JIS encoding ── + /// `V` — Adobe-Japan1, JIS X 0208 row-cell encoding, vertical. + V, + + /// A custom (non-predefined) `CMap` name. + Custom(&'a [u8]), +} + +impl<'a> CMapName<'a> { + /// Create a `CMapType` from raw bytes. + pub fn from_bytes(name: &'a [u8]) -> Self { + match name { + b"83pv-RKSJ-H" => Self::N83pvRksjH, + b"90ms-RKSJ-H" => Self::N90msRksjH, + b"90ms-RKSJ-V" => Self::N90msRksjV, + b"90msp-RKSJ-H" => Self::N90mspRksjH, + b"90msp-RKSJ-V" => Self::N90mspRksjV, + b"90pv-RKSJ-H" => Self::N90pvRksjH, + b"Add-RKSJ-H" => Self::AddRksjH, + b"Add-RKSJ-V" => Self::AddRksjV, + b"Adobe-CNS1-UCS2" => Self::AdobeCns1Ucs2, + b"Adobe-GB1-UCS2" => Self::AdobeGb1Ucs2, + b"Adobe-Japan1-UCS2" => Self::AdobeJapan1Ucs2, + b"Adobe-Korea1-UCS2" => Self::AdobeKorea1Ucs2, + b"B5pc-H" => Self::B5pcH, + b"B5pc-V" => Self::B5pcV, + b"CNS-EUC-H" => Self::CnsEucH, + b"CNS-EUC-V" => Self::CnsEucV, + b"ETen-B5-H" => Self::ETenB5H, + b"ETen-B5-V" => Self::ETenB5V, + b"ETenms-B5-H" => Self::ETenmsB5H, + b"ETenms-B5-V" => Self::ETenmsB5V, + b"EUC-H" => Self::EucH, + b"EUC-V" => Self::EucV, + b"Ext-RKSJ-H" => Self::ExtRksjH, + b"Ext-RKSJ-V" => Self::ExtRksjV, + b"GB-EUC-H" => Self::GbEucH, + b"GB-EUC-V" => Self::GbEucV, + b"GBK-EUC-H" => Self::GbkEucH, + b"GBK-EUC-V" => Self::GbkEucV, + b"GBK2K-H" => Self::Gbk2kH, + b"GBK2K-V" => Self::Gbk2kV, + b"GBKp-EUC-H" => Self::GbkpEucH, + b"GBKp-EUC-V" => Self::GbkpEucV, + b"GBpc-EUC-H" => Self::GbpcEucH, + b"GBpc-EUC-V" => Self::GbpcEucV, + b"H" => Self::H, + b"HKscs-B5-H" => Self::HKscsB5H, + b"HKscs-B5-V" => Self::HKscsB5V, + b"Identity-H" => Self::IdentityH, + b"Identity-V" => Self::IdentityV, + b"KSC-EUC-H" => Self::KscEucH, + b"KSC-EUC-V" => Self::KscEucV, + b"KSCms-UHC-H" => Self::KscmsUhcH, + b"KSCms-UHC-HW-H" => Self::KscmsUhcHwH, + b"KSCms-UHC-HW-V" => Self::KscmsUhcHwV, + b"KSCms-UHC-V" => Self::KscmsUhcV, + b"KSCpc-EUC-H" => Self::KscpcEucH, + b"UniCNS-UCS2-H" => Self::UniCnsUcs2H, + b"UniCNS-UCS2-V" => Self::UniCnsUcs2V, + b"UniCNS-UTF16-H" => Self::UniCnsUtf16H, + b"UniCNS-UTF16-V" => Self::UniCnsUtf16V, + b"UniGB-UCS2-H" => Self::UniGbUcs2H, + b"UniGB-UCS2-V" => Self::UniGbUcs2V, + b"UniGB-UTF16-H" => Self::UniGbUtf16H, + b"UniGB-UTF16-V" => Self::UniGbUtf16V, + b"UniJIS-UCS2-H" => Self::UniJisUcs2H, + b"UniJIS-UCS2-HW-H" => Self::UniJisUcs2HwH, + b"UniJIS-UCS2-HW-V" => Self::UniJisUcs2HwV, + b"UniJIS-UCS2-V" => Self::UniJisUcs2V, + b"UniJIS-UTF16-H" => Self::UniJisUtf16H, + b"UniJIS-UTF16-V" => Self::UniJisUtf16V, + b"UniKS-UCS2-H" => Self::UniKsUcs2H, + b"UniKS-UCS2-V" => Self::UniKsUcs2V, + b"UniKS-UTF16-H" => Self::UniKsUtf16H, + b"UniKS-UTF16-V" => Self::UniKsUtf16V, + b"V" => Self::V, + _ => Self::Custom(name), + } + } + + /// Convert the `CMapType` back to its raw byte representation. + pub fn to_bytes(&self) -> &[u8] { + match self { + Self::N83pvRksjH => b"83pv-RKSJ-H", + Self::N90msRksjH => b"90ms-RKSJ-H", + Self::N90msRksjV => b"90ms-RKSJ-V", + Self::N90mspRksjH => b"90msp-RKSJ-H", + Self::N90mspRksjV => b"90msp-RKSJ-V", + Self::N90pvRksjH => b"90pv-RKSJ-H", + Self::AddRksjH => b"Add-RKSJ-H", + Self::AddRksjV => b"Add-RKSJ-V", + Self::AdobeCns1Ucs2 => b"Adobe-CNS1-UCS2", + Self::AdobeGb1Ucs2 => b"Adobe-GB1-UCS2", + Self::AdobeJapan1Ucs2 => b"Adobe-Japan1-UCS2", + Self::AdobeKorea1Ucs2 => b"Adobe-Korea1-UCS2", + Self::B5pcH => b"B5pc-H", + Self::B5pcV => b"B5pc-V", + Self::CnsEucH => b"CNS-EUC-H", + Self::CnsEucV => b"CNS-EUC-V", + Self::ETenB5H => b"ETen-B5-H", + Self::ETenB5V => b"ETen-B5-V", + Self::ETenmsB5H => b"ETenms-B5-H", + Self::ETenmsB5V => b"ETenms-B5-V", + Self::EucH => b"EUC-H", + Self::EucV => b"EUC-V", + Self::ExtRksjH => b"Ext-RKSJ-H", + Self::ExtRksjV => b"Ext-RKSJ-V", + Self::GbEucH => b"GB-EUC-H", + Self::GbEucV => b"GB-EUC-V", + Self::GbkEucH => b"GBK-EUC-H", + Self::GbkEucV => b"GBK-EUC-V", + Self::Gbk2kH => b"GBK2K-H", + Self::Gbk2kV => b"GBK2K-V", + Self::GbkpEucH => b"GBKp-EUC-H", + Self::GbkpEucV => b"GBKp-EUC-V", + Self::GbpcEucH => b"GBpc-EUC-H", + Self::GbpcEucV => b"GBpc-EUC-V", + Self::H => b"H", + Self::HKscsB5H => b"HKscs-B5-H", + Self::HKscsB5V => b"HKscs-B5-V", + Self::IdentityH => b"Identity-H", + Self::IdentityV => b"Identity-V", + Self::KscEucH => b"KSC-EUC-H", + Self::KscEucV => b"KSC-EUC-V", + Self::KscmsUhcH => b"KSCms-UHC-H", + Self::KscmsUhcHwH => b"KSCms-UHC-HW-H", + Self::KscmsUhcHwV => b"KSCms-UHC-HW-V", + Self::KscmsUhcV => b"KSCms-UHC-V", + Self::KscpcEucH => b"KSCpc-EUC-H", + Self::UniCnsUcs2H => b"UniCNS-UCS2-H", + Self::UniCnsUcs2V => b"UniCNS-UCS2-V", + Self::UniCnsUtf16H => b"UniCNS-UTF16-H", + Self::UniCnsUtf16V => b"UniCNS-UTF16-V", + Self::UniGbUcs2H => b"UniGB-UCS2-H", + Self::UniGbUcs2V => b"UniGB-UCS2-V", + Self::UniGbUtf16H => b"UniGB-UTF16-H", + Self::UniGbUtf16V => b"UniGB-UTF16-V", + Self::UniJisUcs2H => b"UniJIS-UCS2-H", + Self::UniJisUcs2HwH => b"UniJIS-UCS2-HW-H", + Self::UniJisUcs2HwV => b"UniJIS-UCS2-HW-V", + Self::UniJisUcs2V => b"UniJIS-UCS2-V", + Self::UniJisUtf16H => b"UniJIS-UTF16-H", + Self::UniJisUtf16V => b"UniJIS-UTF16-V", + Self::UniKsUcs2H => b"UniKS-UCS2-H", + Self::UniKsUcs2V => b"UniKS-UCS2-V", + Self::UniKsUtf16H => b"UniKS-UTF16-H", + Self::UniKsUtf16V => b"UniKS-UTF16-V", + Self::V => b"V", + Self::Custom(name) => name, + } + } +} + +/// Let's limit the number of nested `usecmap` references to 16. +const MAX_NESTING_DEPTH: u32 = 16; + +/// A parsed cmap. +#[derive(Debug, Clone)] +pub struct CMap { + metadata: Metadata, + // Note that we don't actually use this, because Acrobat _seems_ to ignore + // it, too. + _codespace_ranges: Vec, + cid_ranges: PartitionedRanges, + notdef_ranges: PartitionedRanges, + bf_entries: Vec, + base: Option>, +} + +impl CMap { + /// Parse a cmap from raw bytes. + /// + /// The `get_cmap` callback is used to recursively resolve cmaps that + /// are referenced via `usecmap`. + pub fn parse<'a>( + data: &[u8], + get_cmap: impl Fn(CMapName<'_>) -> Option<&'a [u8]> + Clone + 'a, + ) -> Option { + parse::parse_inner(data, get_cmap, 0) + } + + /// Create an Identity-H cmap. + pub fn identity_h() -> Self { + Self::identity(WritingMode::Horizontal, b"Identity-H") + } + + /// Create an Identity-V cmap. + pub fn identity_v() -> Self { + Self::identity(WritingMode::Vertical, b"Identity-V") + } + + fn identity(writing_mode: WritingMode, name: &[u8]) -> Self { + Self { + metadata: Metadata { + character_collection: Some(CharacterCollection { + family: CidFamily::AdobeIdentity, + supplement: 0, + }), + name: Some(Vec::from(name)), + writing_mode: Some(writing_mode), + }, + _codespace_ranges: Vec::new(), + cid_ranges: { + let mut r = PartitionedRanges::new(); + r.push( + 2, + CidRange { + range: Range { + start: 0, + end: 0xFFFF, + }, + cid_start: 0, + }, + ); + r + }, + notdef_ranges: PartitionedRanges::new(), + bf_entries: Vec::new(), + base: None, + } + } + + /// Return the metadata of this cmap. + pub fn metadata(&self) -> &Metadata { + &self.metadata + } + + /// Look up the CID code of a character code. + /// + /// Returns `None` if the code does not match any range for the given byte length. + pub fn lookup_cid_code(&self, code: u32, byte_len: u8) -> Option { + // Note that, in theory, we are supposed to first check the code space range + // whether the entry exists in the first place. However, from my experiments + // Acrobat mostly seems to ignore this, so we do that as well. + + let cid_ranges = self.cid_ranges.get(byte_len)?; + let notdef_ranges = self.notdef_ranges.get(byte_len)?; + + if let Some(entry) = find_in_ranges(cid_ranges, code) { + let offset = code.checked_sub(entry.range.start)?; + return entry.cid_start.checked_add(offset); + } else if let Some(entry) = find_in_ranges(notdef_ranges, code) { + // For `.notdef` ranges, all codes map to the same `.notdef` CID, so + // no adding of the offset here. + return Some(entry.cid_start); + } + + // See pdfjs_bug920426, it uses bf chars for encoding the characters + // of a text-showing operator, so try that as well. We don't want to + // recurse though, only check the bf chars of this level. + if let Some(BfString::Char(lookup)) = self.lookup_bf_string_inner(code, false) { + return Some(lookup as u32); + } + + // If we still haven't found anything, check the base cmap. + self.base + .as_ref() + .and_then(|b| b.lookup_cid_code(code, byte_len)) + } + + /// Look up a bf string in the cmap. This is usually + /// used for mapping character codes to Unicode codepoints in a + /// `ToUnicode` cmap. + /// + /// Returns `None` if no mapping is available. + pub fn lookup_bf_string(&self, code: u32) -> Option { + self.lookup_bf_string_inner(code, true) + } + + fn lookup_bf_string_inner(&self, code: u32, recurse: bool) -> Option { + if let Some(entry) = find_in_ranges(&self.bf_entries, code) { + let offset = u16::try_from(code - entry.range.start).ok()?; + + fn decode_utf16(units: &[u16]) -> Option { + let mut iter = core::char::decode_utf16(units.iter().copied()); + let first = iter.next()?.ok()?; + + if iter.next().is_none() { + Some(BfString::Char(first)) + } else { + let s = String::from_utf16(units).ok()?; + Some(BfString::String(s)) + } + } + + return if offset == 0 { + Some(decode_utf16(&entry.dst_base)?) + } else { + let mut units = entry.dst_base.clone(); + *units.last_mut()? = units.last()?.checked_add(offset)?; + Some(decode_utf16(&units)?) + }; + } + + if recurse { + self.base.as_ref()?.lookup_bf_string(code) + } else { + None + } + } +} + +trait HasRange { + fn range(&self) -> &Range; +} + +fn find_in_ranges(entries: &[T], code: u32) -> Option<&T> { + let idx = entries + .binary_search_by(|entry| { + let r = entry.range(); + if code < r.start { + core::cmp::Ordering::Greater + } else if code > r.end { + core::cmp::Ordering::Less + } else { + core::cmp::Ordering::Equal + } + }) + .ok()?; + + Some(&entries[idx]) +} + +/// A range with a start and end code. +#[derive(Debug, Clone)] +pub(crate) struct Range { + pub(crate) start: u32, + pub(crate) end: u32, +} + +/// A range of character codes mapped to CIDs. +#[derive(Debug, Clone)] +pub struct CidRange { + pub(crate) range: Range, + pub(crate) cid_start: Cid, +} + +impl HasRange for CidRange { + fn range(&self) -> &Range { + &self.range + } +} + +#[derive(Debug, Clone)] +pub(crate) struct PartitionedRanges { + buckets: [Vec; 4], +} + +impl PartitionedRanges { + pub(crate) fn new() -> Self { + Self { + buckets: [Vec::new(), Vec::new(), Vec::new(), Vec::new()], + } + } + + // PdfCraft patch: needed by the truncated-stream guard in parse.rs. + pub(crate) fn is_empty(&self) -> bool { + self.buckets.iter().all(|b| b.is_empty()) + } + + pub(crate) fn push(&mut self, byte_len: usize, range: CidRange) { + if let Some(bucket) = byte_len + .checked_sub(1) + .and_then(|i| self.buckets.get_mut(i)) + { + bucket.push(range); + } + } + + pub(crate) fn get(&self, byte_len: u8) -> Option<&[CidRange]> { + let idx = (byte_len as usize).checked_sub(1)?; + self.buckets.get(idx).map(|v| v.as_slice()) + } + + pub(crate) fn sort(&mut self) { + for bucket in &mut self.buckets { + bucket.sort_by(|a, b| a.range.start.cmp(&b.range.start)); + } + } +} + +#[derive(Debug, Clone)] +pub(crate) struct BfRange { + pub(crate) range: Range, + pub(crate) dst_base: Vec, +} + +impl HasRange for BfRange { + fn range(&self) -> &Range { + &self.range + } +} + +/// A codespace range defining valid character code byte sequences. +#[derive(Debug, Clone)] +#[allow(dead_code)] +pub(crate) struct CodespaceRange { + pub(crate) number_bytes: u8, + pub(crate) low: u32, + pub(crate) high: u32, +} + +/// A Unicode value decoded from a cmap. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BfString { + /// A single character. + Char(char), + /// A UTF-8 string. + String(String), +} + +/// Metadata extracted from a cmap file. +#[derive(Debug, Clone)] +pub struct Metadata { + /// The referenced character collection. + pub character_collection: Option, + /// The cmap name. + pub name: Option>, + /// The writing mode. + pub writing_mode: Option, +} + +/// The registry+ordering family of a CID character collection. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CidFamily { + /// Adobe-Japan1 + AdobeJapan1, + /// Adobe-GB1 + AdobeGB1, + /// Adobe-CNS1 + AdobeCNS1, + /// Adobe-Korea1 + AdobeKorea1, + /// Adobe-Identity + AdobeIdentity, + /// A non-predefined registry/ordering pair. + Custom { + /// The registry name. + registry: Vec, + /// The ordering name. + ordering: Vec, + }, +} + +impl CidFamily { + /// Create a `CidFamily` from raw registry and ordering byte strings. + pub fn from_registry_ordering(registry: &[u8], ordering: &[u8]) -> Self { + if registry == b"Adobe" { + match ordering { + b"Japan1" => Self::AdobeJapan1, + b"GB1" => Self::AdobeGB1, + b"CNS1" => Self::AdobeCNS1, + b"Korea1" => Self::AdobeKorea1, + b"Identity" => Self::AdobeIdentity, + _ => Self::Custom { + registry: registry.to_vec(), + ordering: ordering.to_vec(), + }, + } + } else { + Self::Custom { + registry: registry.to_vec(), + ordering: ordering.to_vec(), + } + } + } + + /// Return the predefined UTF-16 `CMap` that maps Unicode code points to CIDs + /// for this family, if one exists. + pub fn unicode_cmap(&self) -> Option> { + match self { + Self::AdobeJapan1 => Some(CMapName::UniJisUtf16H), + Self::AdobeGB1 => Some(CMapName::UniGbUtf16H), + Self::AdobeCNS1 => Some(CMapName::UniCnsUtf16H), + Self::AdobeKorea1 => Some(CMapName::UniKsUtf16H), + Self::AdobeIdentity | Self::Custom { .. } => None, + } + } + + /// Return the `UCS2` cmap corresponding to the given character collection. + pub fn ucs2_cmap(&self) -> Option> { + match self { + Self::AdobeJapan1 => Some(CMapName::AdobeJapan1Ucs2), + Self::AdobeGB1 => Some(CMapName::AdobeGb1Ucs2), + Self::AdobeCNS1 => Some(CMapName::AdobeCns1Ucs2), + Self::AdobeKorea1 => Some(CMapName::AdobeKorea1Ucs2), + Self::AdobeIdentity | Self::Custom { .. } => None, + } + } +} + +/// A CID character collection identifying the character set and ordering. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CharacterCollection { + /// The registry+ordering family. + pub family: CidFamily, + /// The supplement number. + pub supplement: i32, +} + +/// The writing mode of a cmap. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum WritingMode { + /// Horizontal writing mode. + #[default] + Horizontal, + /// Vertical writing mode. + Vertical, +} + +#[cfg(test)] +mod tests { + use super::*; + + // Note that those cmaps might not be completely valid according to the rules + // of cmap/Postscript, but since our parser is very lenient and doesn't run a real + // interpreter we can shorten them by a lot. + + const PREAMBLE: &[u8] = br#"/CIDSystemInfo 3 dict dup begin + /Registry (Adobe) def + /Ordering (Japan1) def + /Supplement 0 def +end def +/CMapName /Test def +/WMode 0 def +2 begincodespacerange +<00> +<0000> +endcodespacerange +"#; + + fn parse_with_preamble(body: &[u8]) -> CMap { + let mut data = Vec::new(); + data.extend_from_slice(PREAMBLE); + data.extend_from_slice(body); + CMap::parse(&data, |_| None).unwrap() + } + + #[test] + fn metadata_parsing() { + let data = br#" +/CIDInit /ProcSet findresource begin +12 dict begin +begincmap +/CIDSystemInfo 3 dict dup begin + /Registry (Adobe) def + /Ordering (Japan1) def + /Supplement 6 def +end def +/CMapName /Adobe-Japan1-H def +/CMapType 1 def +/WMode 0 def +endcmap"#; + + let cmap = CMap::parse(data, |_| None).unwrap(); + let cc = cmap.metadata().character_collection.as_ref().unwrap(); + assert_eq!(cc.family, CidFamily::AdobeJapan1); + assert_eq!(cc.supplement, 6); + assert_eq!( + cmap.metadata().name.as_deref(), + Some(b"Adobe-Japan1-H".as_slice()) + ); + assert_eq!(cmap.metadata().writing_mode, Some(WritingMode::Horizontal)); + } + + #[test] + fn vertical_writing_mode() { + let data = br#" +/CIDSystemInfo 3 dict dup begin + /Registry (Adobe) def + /Ordering (Japan1) def + /Supplement 6 def +end def +/CMapName /Adobe-Japan1-V def +/WMode 1 def +"#; + + let cmap = CMap::parse(data, |_| None).unwrap(); + assert_eq!(cmap.metadata().writing_mode, Some(WritingMode::Vertical)); + assert_eq!( + cmap.metadata().name.as_deref(), + Some(b"Adobe-Japan1-V".as_slice()) + ); + } + + #[test] + fn cid_range_lookup() { + let cmap = parse_with_preamble( + br#" +3 begincidrange +<0000> <00FF> 0 +<0100> <01FF> 256 +<8140> <817E> 633 +endcidrange +"#, + ); + + assert_eq!(cmap.lookup_cid_code(0x0000, 2), Some(0)); + assert_eq!(cmap.lookup_cid_code(0x0042, 2), Some(0x42)); + assert_eq!(cmap.lookup_cid_code(0x00FF, 2), Some(0xFF)); + + assert_eq!(cmap.lookup_cid_code(0x0100, 2), Some(256)); + assert_eq!(cmap.lookup_cid_code(0x01FF, 2), Some(511)); + + assert_eq!(cmap.lookup_cid_code(0x8140, 2), Some(633)); + assert_eq!(cmap.lookup_cid_code(0x817E, 2), Some(633 + 62)); + } + + #[test] + fn cid_char_lookup() { + let cmap = parse_with_preamble( + br#" +3 begincidchar +<03> 1 +<04> 2 +<20> 50 +endcidchar +"#, + ); + + assert_eq!(cmap.lookup_cid_code(0x03, 1), Some(1)); + assert_eq!(cmap.lookup_cid_code(0x04, 1), Some(2)); + assert_eq!(cmap.lookup_cid_code(0x20, 1), Some(50)); + } + + #[test] + fn lookup_miss() { + let cmap = parse_with_preamble( + br#" +1 begincidrange +<0100> <01FF> 0 +endcidrange +"#, + ); + + assert_eq!(cmap.lookup_cid_code(0x00FF, 2), None); + assert_eq!(cmap.lookup_cid_code(0x0200, 2), None); + assert_eq!(cmap.lookup_cid_code(0xFFFF, 2), None); + } + + #[test] + fn multiple_sections() { + let cmap = parse_with_preamble( + br#" +2 begincidrange +<0000> <00FF> 0 +<0100> <01FF> 256 +endcidrange +1 begincidchar +<0200> 600 +endcidchar +1 begincidrange +<8140> <817E> 633 +endcidrange +"#, + ); + + assert_eq!(cmap.lookup_cid_code(0x0000, 2), Some(0)); + assert_eq!(cmap.lookup_cid_code(0x0100, 2), Some(256)); + assert_eq!(cmap.lookup_cid_code(0x0200, 2), Some(600)); + assert_eq!(cmap.lookup_cid_code(0x8140, 2), Some(633)); + } + + #[test] + fn single_byte_codes() { + let cmap = parse_with_preamble( + br#" +2 begincidrange +<00> <7F> 0 +<80> 200 +endcidrange +"#, + ); + + assert_eq!(cmap.lookup_cid_code(0x00, 1), Some(0)); + assert_eq!(cmap.lookup_cid_code(0x41, 1), Some(0x41)); + assert_eq!(cmap.lookup_cid_code(0x80, 1), Some(200)); + assert_eq!(cmap.lookup_cid_code(0xFF, 1), Some(200 + 127)); + } + + #[test] + fn dict_style_cidsysteminfo() { + let data = br#" +/CIDInit /ProcSet findresource begin +10 dict begin +begincmap +/CIDSystemInfo +<< /Registry (Adobe) +/Ordering (UCS) +/Supplement 0 +>> def +/CMapName /Adobe-Identity-UCS def +/CMapType 2 def +1 begincodespacerange +<0000> +endcodespacerange +2 beginbfchar +<001F> +<002A> +endbfchar +endcmap +CMapName currentdict /CMap defineresource pop +end +end +"#; + let cmap = CMap::parse(data, |_| None).unwrap(); + let cc = cmap.metadata().character_collection.as_ref().unwrap(); + assert_eq!( + cc.family, + CidFamily::Custom { + registry: b"Adobe".to_vec(), + ordering: b"UCS".to_vec(), + } + ); + assert_eq!(cc.supplement, 0); + assert_eq!( + cmap.metadata().name.as_deref(), + Some(b"Adobe-Identity-UCS".as_slice()) + ); + assert_eq!( + cmap.lookup_bf_string(0x001F), + Some(BfString::Char('\u{F049}')) + ); + assert_eq!( + cmap.lookup_bf_string(0x002A), + Some(BfString::Char('\u{F055}')) + ); + } + + #[test] + fn usecmap_chaining() { + let base_data = br#" +/CIDSystemInfo 3 dict dup begin + /Registry (Adobe) def + /Ordering (Japan1) def + /Supplement 0 def +end def +/CMapName /Base def +/WMode 0 def +1 begincodespacerange +<0000> +endcodespacerange +1 begincidrange +<0000> <00FF> 0 +endcidrange +"#; + + let child_data = br#" +/Base usecmap +/CIDSystemInfo 3 dict dup begin + /Registry (Adobe) def + /Ordering (Japan1) def + /Supplement 0 def +end def +/CMapName /Child def +/WMode 0 def +1 begincodespacerange +<0000> +endcodespacerange +1 begincidrange +<0100> <01FF> 256 +endcidrange +"#; + + let cmap = CMap::parse(child_data, |name| { + if name.to_bytes() == b"Base" { + Some(base_data.as_slice()) + } else { + None + } + }) + .unwrap(); + + assert_eq!(cmap.lookup_cid_code(0x0100, 2), Some(256)); + assert_eq!(cmap.lookup_cid_code(0x01FF, 2), Some(511)); + assert_eq!(cmap.lookup_cid_code(0x0000, 2), Some(0)); + assert_eq!(cmap.lookup_cid_code(0x00FF, 2), Some(0xFF)); + + assert_eq!(cmap.lookup_cid_code(0x0200, 2), None); + } + + #[test] + fn usecmap_partial_override() { + let base_data = br#" +/CIDSystemInfo 3 dict dup begin + /Registry (Adobe) def + /Ordering (Japan1) def + /Supplement 0 def +end def +/CMapName /Base def +/WMode 0 def +1 begincodespacerange +<0000> +endcodespacerange +1 begincidrange +<0000> <00FF> 0 +endcidrange +"#; + + let child_data = br#" +/Base usecmap +/CIDSystemInfo 3 dict dup begin + /Registry (Adobe) def + /Ordering (Japan1) def + /Supplement 0 def +end def +/CMapName /Child def +/WMode 0 def +1 begincodespacerange +<0000> +endcodespacerange +1 begincidrange +<0040> <007F> 500 +endcidrange +"#; + + let cmap = CMap::parse(child_data, |name| { + if name.to_bytes() == b"Base" { + Some(base_data.as_slice()) + } else { + None + } + }) + .unwrap(); + + assert_eq!(cmap.lookup_cid_code(0x0000, 2), Some(0)); + assert_eq!(cmap.lookup_cid_code(0x003F, 2), Some(0x3F)); + assert_eq!(cmap.lookup_cid_code(0x0040, 2), Some(500)); + assert_eq!(cmap.lookup_cid_code(0x007F, 2), Some(563)); + assert_eq!(cmap.lookup_cid_code(0x0080, 2), Some(0x80)); + assert_eq!(cmap.lookup_cid_code(0x00FF, 2), Some(0xFF)); + } + + #[test] + fn notdef_char_lookup() { + let cmap = parse_with_preamble( + br#" +2 beginnotdefchar +<03> 10 +<20> 20 +endnotdefchar +"#, + ); + + assert_eq!(cmap.lookup_cid_code(0x03, 1), Some(10)); + assert_eq!(cmap.lookup_cid_code(0x20, 1), Some(20)); + assert_eq!(cmap.lookup_cid_code(0x04, 1), None); + } + + #[test] + fn notdef_range_lookup() { + let cmap = parse_with_preamble( + br#" +1 beginnotdefrange +<0000> <001F> 100 +endnotdefrange +"#, + ); + + assert_eq!(cmap.lookup_cid_code(0x0000, 2), Some(100)); + assert_eq!(cmap.lookup_cid_code(0x0001, 2), Some(100)); + assert_eq!(cmap.lookup_cid_code(0x001F, 2), Some(100)); + assert_eq!(cmap.lookup_cid_code(0x0020, 2), None); + } + + #[test] + fn bfchar_lookup() { + let cmap = parse_with_preamble( + br#" +2 beginbfchar +<0041> <0048> +<0042> <0065> +endbfchar +"#, + ); + + assert_eq!(cmap.lookup_bf_string(0x0041), Some(BfString::Char('H'))); + assert_eq!(cmap.lookup_bf_string(0x0042), Some(BfString::Char('e'))); + assert_eq!(cmap.lookup_bf_string(0x0043), None); + } + + #[test] + fn bfchar_ligature() { + let cmap = parse_with_preamble( + br#" +1 beginbfchar +<005F> <00660066> +endbfchar +"#, + ); + + assert_eq!( + cmap.lookup_bf_string(0x005F), + Some(BfString::String(String::from("ff"))) + ); + } + + // PdfCraft patch: malformed pieces of a CMap are skipped, not fatal - the reading + // path used to discard the whole CMap and fall back to the font encoding for every + // code, so search and search-redaction missed text the edit layer could see (#3177). + + #[test] + fn bad_bfchar_entry_is_skipped() { + let cmap = parse_with_preamble( + br#" +2 beginbfchar +<41> +<42> <0059> +endbfchar +"#, + ); + assert_eq!(cmap.lookup_bf_string(0x41), None); + assert_eq!( + cmap.lookup_bf_string(0x42), + Some(BfString::Char('Y')) + ); + } + + #[test] + fn truncated_stream_with_no_entries_reports_failure() { + // The tolerant parser keeps collected entries, but a stream that + // breaks before any entry must still report failure so callers + // fall back to the font's own encoding. + assert!(CMap::parse(b"<00", |_| None).is_none()); + } + + #[test] + fn truncated_stream_with_only_metadata_reports_failure() { + // Character-collection metadata alone is not a usable CMap: an empty + // metadata-only map would block the caller's fallback paths, so a + // truncated stream with no mappings must report failure here too. + assert!(CMap::parse( + b"/Registry (Adobe) /Ordering (Japan1) /Supplement 0 <00", + |_| None + ) + .is_none()); + } + + #[test] + fn unresolved_usecmap_with_no_mappings_reports_failure() { + // A stream whose only content is a `usecmap` reference that cannot be + // resolved yields no mappings at all; returning an empty map here + // would block the caller's encoding fallback paths, so it must + // report failure exactly as a full parse failure did before. + assert!(CMap::parse(b"/Bogus usecmap", |_| None).is_none()); + } + + #[test] + fn unresolved_usecmap_keeps_local_mappings() { + // The same unresolved reference must not discard mappings the stream + // carries itself: only the missing base is dropped. + let cmap = CMap::parse( + b"/Bogus usecmap 1 beginbfchar <41> <0041> endbfchar", + |_| None, + ) + .expect("local mappings survive an unresolved usecmap"); + assert!(cmap.lookup_bf_string(0x41).is_some()); + } + + #[test] + fn bad_bfchar_code_keeps_later_entries_aligned() { + // The malformed 5-byte code still has a destination object; both + // must be skipped or every later pair shifts by one object. + let cmap = parse_with_preamble( + br#" +2 beginbfchar +<0102030405> <0041> +<42> <0059> +endbfchar +"#, + ); + assert_eq!(cmap.lookup_bf_string(0x41), None); + assert_eq!(cmap.lookup_bf_string(0x42), Some(BfString::Char('Y'))); + } + + #[test] + fn bfrange_array_stops_at_exhaustion() { + // One member for 256 codes: the array cannot be resynced, so the + // loop must stop rather than spin over the remaining codes. + let cmap = parse_with_preamble( + br#" +1 beginbfrange +<0000> <00FF> [<0041>] +endbfrange +"#, + ); + assert_eq!(cmap.lookup_bf_string(0x00), Some(BfString::Char('A'))); + assert_eq!(cmap.lookup_bf_string(0x01), None); + } + + #[test] + fn unresolvable_usecmap_is_skipped() { + let cmap = parse_with_preamble( + br#" +/Bogus usecmap +1 beginbfchar +<41> <0058> +endbfchar +"#, + ); + assert_eq!( + cmap.lookup_bf_string(0x41), + Some(BfString::Char('X')) + ); + } + + #[test] + fn bfchar_surrogate_pair() { + let cmap = parse_with_preamble( + br#" +1 beginbfchar +<3A51> +endbfchar +"#, + ); + + assert_eq!( + cmap.lookup_bf_string(0x3A51), + Some(BfString::Char('\u{2003E}')) + ); + } + + #[test] + fn bfrange_incrementing() { + let cmap = parse_with_preamble( + br#" +1 beginbfrange +<0000> <0004> <0041> +endbfrange +"#, + ); + + assert_eq!(cmap.lookup_bf_string(0x0000), Some(BfString::Char('A'))); + assert_eq!(cmap.lookup_bf_string(0x0001), Some(BfString::Char('B'))); + assert_eq!(cmap.lookup_bf_string(0x0004), Some(BfString::Char('E'))); + assert_eq!(cmap.lookup_bf_string(0x0005), None); + } + + #[test] + fn bfrange_array() { + let cmap = parse_with_preamble( + br#" +1 beginbfrange +<005F> <0061> [<00660066> <00660069> <0066006C>] +endbfrange +"#, + ); + + // ff, fi, fl ligatures + assert_eq!( + cmap.lookup_bf_string(0x005F), + Some(BfString::String(String::from("ff"))) + ); + assert_eq!( + cmap.lookup_bf_string(0x0060), + Some(BfString::String(String::from("fi"))) + ); + assert_eq!( + cmap.lookup_bf_string(0x0061), + Some(BfString::String(String::from("fl"))) + ); + } + + #[test] + fn unicode_lookup_miss() { + let cmap = parse_with_preamble( + br#" +1 beginbfchar +<0041> <0048> +endbfchar +"#, + ); + + assert_eq!(cmap.lookup_bf_string(0x0000), None); + assert_eq!(cmap.lookup_bf_string(0x0042), None); + } + + #[test] + fn identity_h() { + let cmap = CMap::identity_h(); + assert_eq!( + cmap.metadata().name.as_deref(), + Some(b"Identity-H".as_slice()) + ); + assert_eq!(cmap.metadata().writing_mode, Some(WritingMode::Horizontal)); + + assert_eq!(cmap.lookup_cid_code(0x0041, 2), Some(0x0041)); + assert_eq!(cmap.lookup_cid_code(0x1234, 2), Some(0x1234)); + assert_eq!(cmap.lookup_cid_code(0xFFFF, 2), Some(0xFFFF)); + + assert_eq!(cmap.lookup_cid_code(0x0041, 1), None); + assert_eq!(cmap.lookup_cid_code(0x0041, 3), None); + } + + #[test] + fn identity_v() { + let cmap = CMap::identity_v(); + assert_eq!( + cmap.metadata().name.as_deref(), + Some(b"Identity-V".as_slice()) + ); + assert_eq!(cmap.metadata().writing_mode, Some(WritingMode::Vertical)); + + assert_eq!(cmap.lookup_cid_code(0x0041, 2), Some(0x0041)); + assert_eq!(cmap.lookup_cid_code(0xFFFF, 2), Some(0xFFFF)); + } + + #[test] + fn minimal_cmap_no_name_no_wmode() { + // Extracted from corpus PDF 0500013. + let data = br#" +/CIDInit /ProcSet findresource begin +12 dict begin +begincmap +/CMapType 2 def +1 begincodespacerange +<00> +endcodespacerange +1 beginbfrange +<01><01><0020> +endbfrange +endcmap +"#; + let cmap = CMap::parse(data, |_| None).unwrap(); + assert_eq!(cmap.metadata().name, None); + assert_eq!(cmap.metadata().character_collection, None); + assert_eq!(cmap.metadata().writing_mode, None); + assert_eq!(cmap.lookup_bf_string(0x01), Some(BfString::Char(' '))); + } + + #[test] + fn registry_as_name() { + // Extracted from corpus PDF 0875241, uses names instead of strings for + // strings for metadata. + let data = br#" +/CIDSystemInfo +<< /Registry /ABCDEF+SimSun +/Ordering (pdfbeaninc) +/Supplement 0 +>> def +/CMapName /ABCDEF+SimSun def +/CMapType 2 def +1 begincodespacerange +<0000> +endcodespacerange +1 beginbfrange +<0000> <0000> <6881> +endbfrange +"#; + let cmap = CMap::parse(data, |_| None).unwrap(); + let cc = cmap.metadata().character_collection.as_ref().unwrap(); + assert_eq!( + cc.family, + CidFamily::Custom { + registry: b"ABCDEF+SimSun".to_vec(), + ordering: b"pdfbeaninc".to_vec(), + } + ); + assert_eq!(cc.supplement, 0); + assert_eq!( + cmap.lookup_bf_string(0x0000), + Some(BfString::Char('\u{6881}')) + ); + } + + #[test] + fn single_byte_bfrange_destination() { + // See for example corpus test case 0625248. + let cmap = parse_with_preamble( + br#" +1 beginbfrange +<00> <7f> <00> +endbfrange +"#, + ); + + assert_eq!( + cmap.lookup_bf_string(0x00), + Some(BfString::Char('\u{0000}')) + ); + assert_eq!(cmap.lookup_bf_string(0x41), Some(BfString::Char('A'))); + assert_eq!( + cmap.lookup_bf_string(0x7f), + Some(BfString::Char('\u{007F}')) + ); + } +} + +#[cfg(all(test, feature = "embed-cmaps"))] +mod bcmap_tests { + use super::*; + + fn get_embedded_cmap(name: CMapName<'_>) -> Option<&'static [u8]> { + load_embedded(name) + } + + #[test] + fn embedded_h_cmap() { + let data = load_embedded(CMapName::H).expect("embedded H cmap not found"); + let cmap = CMap::parse(data, get_embedded_cmap).expect("failed to parse H cmap"); + assert_eq!(cmap.metadata().writing_mode, None); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeJapan1, + supplement: 1, + }) + ); + assert_eq!(cmap.lookup_cid_code(0x2121, 2), Some(633)); + assert_eq!(cmap.lookup_cid_code(0x2221, 2), Some(727)); + } + + #[test] + fn embedded_90ms_rksj_h() { + let data = + load_embedded(CMapName::N90msRksjH).expect("embedded 90ms-RKSJ-H cmap not found"); + let cmap = CMap::parse(data, get_embedded_cmap).expect("failed to parse 90ms-RKSJ-H cmap"); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeJapan1, + supplement: 2, + }) + ); + assert_eq!(cmap.lookup_cid_code(0x20, 1), Some(231)); + assert_eq!(cmap.lookup_cid_code(0x8140, 2), Some(633)); + } + + #[test] + fn embedded_v_cmap() { + let data = load_embedded(CMapName::V).expect("embedded V cmap not found"); + let cmap = CMap::parse(data, get_embedded_cmap).expect("failed to parse V cmap"); + assert_eq!(cmap.metadata().writing_mode, Some(WritingMode::Vertical)); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeJapan1, + supplement: 1, + }) + ); + // Inherited from base "H" via usecmap. + assert_eq!(cmap.lookup_cid_code(0x2121, 2), Some(633)); + } + + #[test] + fn embedded_gbk_euc_h() { + let data = load_embedded(CMapName::GbkEucH).expect("embedded GBK-EUC-H not found"); + let cmap = CMap::parse(data, get_embedded_cmap).expect("failed to parse GBK-EUC-H"); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeGB1, + supplement: 2, + }) + ); + assert_eq!(cmap.lookup_cid_code(0x20, 1), Some(7716)); + assert_eq!(cmap.lookup_cid_code(0x21, 1), Some(814)); + assert_eq!(cmap.lookup_cid_code(0x7E, 1), Some(814 + 0x7E - 0x21)); + assert_eq!(cmap.lookup_cid_code(0xFE80, 2), Some(22094)); + assert_eq!(cmap.lookup_cid_code(0xFEA0, 2), Some(22094 + 0xA0 - 0x80)); + } + + #[test] + fn embedded_ksc_euc_h() { + let data = load_embedded(CMapName::KscEucH).unwrap(); + let cmap = CMap::parse(data, get_embedded_cmap).unwrap(); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeKorea1, + supplement: 0, + }) + ); + assert_eq!(cmap.lookup_cid_code(0x20, 1), Some(8094)); + assert_eq!(cmap.lookup_cid_code(0x41, 1), Some(8094 + 0x41 - 0x20)); + assert_eq!(cmap.lookup_cid_code(0xA1A1, 2), Some(101)); + assert_eq!(cmap.lookup_cid_code(0xA1FE, 2), Some(101 + 0xFE - 0xA1)); + assert_eq!(cmap.lookup_cid_code(0xFDA1, 2), Some(7962)); + } + + #[test] + fn embedded_b5pc_h() { + let data = load_embedded(CMapName::B5pcH).unwrap(); + let cmap = CMap::parse(data, get_embedded_cmap).unwrap(); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeCNS1, + supplement: 0, + }) + ); + assert_eq!(cmap.lookup_cid_code(0x20, 1), Some(1)); + assert_eq!(cmap.lookup_cid_code(0x41, 1), Some(1 + 0x41 - 0x20)); + assert_eq!(cmap.lookup_cid_code(0x80, 1), Some(61)); + assert_eq!(cmap.lookup_cid_code(0xD140, 2), Some(7251)); + assert_eq!(cmap.lookup_cid_code(0xD17E, 2), Some(7251 + 0x7E - 0x40)); + assert_eq!(cmap.lookup_cid_code(0xF9D5, 2), Some(13642 + 3)); + } + + #[test] + fn embedded_unijis_utf16_h() { + let data = load_embedded(CMapName::UniJisUtf16H).unwrap(); + let cmap = CMap::parse(data, get_embedded_cmap).unwrap(); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeJapan1, + supplement: 7, + }) + ); + assert_eq!(cmap.lookup_cid_code(0x20, 2), Some(1)); + assert_eq!(cmap.lookup_cid_code(0x41, 2), Some(1 + 0x41 - 0x20)); + assert_eq!(cmap.lookup_cid_code(0x5C, 2), Some(97)); + assert_eq!(cmap.lookup_cid_code(0x5BCC, 2), Some(3531)); + assert_eq!(cmap.lookup_cid_code(0xD884DF50, 4), Some(19130)); + } + + #[test] + fn embedded_identity_h() { + let data = load_embedded(CMapName::IdentityH).expect("embedded Identity-H not found"); + let cmap = CMap::parse(data, get_embedded_cmap).expect("failed to parse Identity-H cmap"); + assert_eq!(cmap.metadata().writing_mode, None); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeIdentity, + supplement: 0, + }) + ); + assert_eq!(cmap.lookup_cid_code(0x0000, 2), Some(0)); + assert_eq!(cmap.lookup_cid_code(0x0041, 2), Some(0x41)); + assert_eq!(cmap.lookup_cid_code(0xFFFF, 2), Some(0xFFFF)); + } + + #[test] + fn embedded_identity_v() { + let data = load_embedded(CMapName::IdentityV).expect("embedded Identity-V not found"); + let cmap = CMap::parse(data, get_embedded_cmap).expect("failed to parse Identity-V cmap"); + assert_eq!(cmap.metadata().writing_mode, Some(WritingMode::Vertical)); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeIdentity, + supplement: 0, + }) + ); + assert_eq!(cmap.lookup_cid_code(0x0000, 2), Some(0)); + assert_eq!(cmap.lookup_cid_code(0x0041, 2), Some(0x41)); + assert_eq!(cmap.lookup_cid_code(0xFFFF, 2), Some(0xFFFF)); + } + + // Note: Some tests AI-generated, haven't double-checked them. + + #[test] + fn embedded_adobe_gb1_ucs2() { + let data = load_embedded(CMapName::AdobeGb1Ucs2).unwrap(); + let cmap = CMap::parse(data, get_embedded_cmap).unwrap(); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::Custom { + registry: b"Adobe".to_vec(), + ordering: b"Adobe_GB1_UCS2".to_vec(), + }, + supplement: 5, + }) + ); + + assert_eq!( + cmap.lookup_bf_string(0x0063), + Some(BfString::Char('\u{00B7}')) + ); + assert_eq!(cmap.lookup_bf_string(0x0001), Some(BfString::Char(' '))); + assert_eq!(cmap.lookup_bf_string(0x0022), Some(BfString::Char('A'))); + assert_eq!(cmap.lookup_bf_string(0x005F), Some(BfString::Char('~'))); + assert_eq!( + cmap.lookup_bf_string(0x560F), + Some(BfString::String(String::from("\u{90CE}\u{FE00}"))) + ); + } + + #[test] + fn embedded_adobe_japan1_ucs2() { + let data = load_embedded(CMapName::AdobeJapan1Ucs2).unwrap(); + let cmap = CMap::parse(data, get_embedded_cmap).unwrap(); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::Custom { + registry: b"Adobe".to_vec(), + ordering: b"Adobe_Japan1_UCS2".to_vec(), + }, + supplement: 7, + }) + ); + + assert_eq!( + cmap.lookup_bf_string(0x003D), + Some(BfString::Char('\u{00A5}')) + ); + assert_eq!(cmap.lookup_bf_string(0x0001), Some(BfString::Char(' '))); + assert_eq!(cmap.lookup_bf_string(0x003C), Some(BfString::Char('['))); + assert_eq!( + cmap.lookup_bf_string(0x0476), + Some(BfString::String(String::from("\u{82A6}\u{E0100}"))) + ); + assert_eq!( + cmap.lookup_bf_string(0x265B), + Some(BfString::String(String::from("10/11"))) + ); + assert_eq!( + cmap.lookup_bf_string(0x2E6B), + Some(BfString::String(String::from("オングストローム"))) + ); + } + + #[test] + fn embedded_adobe_korea1_ucs2() { + let data = load_embedded(CMapName::AdobeKorea1Ucs2).unwrap(); + let cmap = CMap::parse(data, get_embedded_cmap).unwrap(); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::Custom { + registry: b"Adobe".to_vec(), + ordering: b"Adobe_Korea1_UCS2".to_vec(), + }, + supplement: 2, + }) + ); + + assert_eq!( + cmap.lookup_bf_string(0x0060), + Some(BfString::Char('\u{20A9}')) + ); + assert_eq!( + cmap.lookup_bf_string(0x2072), + Some(BfString::String(String::from("[10]"))) + ); + assert_eq!( + cmap.lookup_bf_string(0x2073), + Some(BfString::String(String::from("[11]"))) + ); + } + + #[test] + fn embedded_adobe_cns1_ucs2() { + let data = load_embedded(CMapName::AdobeCns1Ucs2).unwrap(); + let cmap = CMap::parse(data, get_embedded_cmap).unwrap(); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::Custom { + registry: b"Adobe".to_vec(), + ordering: b"Adobe_CNS1_UCS2".to_vec(), + }, + supplement: 7, + }) + ); + + assert_eq!( + cmap.lookup_bf_string(0x0060), + Some(BfString::Char('\u{00A9}')) + ); + assert_eq!(cmap.lookup_bf_string(0x0001), Some(BfString::Char(' '))); + assert_eq!(cmap.lookup_bf_string(0x005F), Some(BfString::Char('~'))); + assert_eq!( + cmap.lookup_bf_string(0x36B0), + Some(BfString::Char('\u{200CC}')) + ); + } + + #[test] + fn embedded_eten_b5_h() { + let data = load_embedded(CMapName::ETenB5H).unwrap(); + let cmap = CMap::parse(data, get_embedded_cmap).unwrap(); + assert_eq!( + cmap.metadata().character_collection, + Some(CharacterCollection { + family: CidFamily::AdobeCNS1, + supplement: 0, + }) + ); + assert_eq!(cmap.lookup_cid_code(0x20, 1), Some(13648)); + assert_eq!(cmap.lookup_cid_code(0x7E, 1), Some(13648 + 0x7E - 0x20)); + assert_eq!(cmap.lookup_cid_code(0xA140, 2), Some(99)); + assert_eq!(cmap.lookup_cid_code(0xA158, 2), Some(99 + 0x58 - 0x40)); + assert_eq!(cmap.lookup_cid_code(0xD040, 2), Some(7094)); + assert_eq!(cmap.lookup_cid_code(0xF9FE, 2), Some(14056 + 0xFE - 0xD6)); + } +} diff --git a/vendor/hayro-cmap/src/parse.rs b/vendor/hayro-cmap/src/parse.rs new file mode 100644 index 000000000..1137ab078 --- /dev/null +++ b/vendor/hayro-cmap/src/parse.rs @@ -0,0 +1,446 @@ +use alloc::boxed::Box; +use alloc::vec::Vec; + +use hayro_postscript::{Object, Scanner}; + +#[cfg(feature = "embed-cmaps")] +use crate::bcmap; +use crate::{ + BfRange, CMap, CMapName, CharacterCollection, CidFamily, CidRange, CodespaceRange, + MAX_NESTING_DEPTH, Metadata, PartitionedRanges, Range, WritingMode, +}; + +struct Context { + buf: Vec, + get_cmap: F, +} + +pub(crate) fn parse_inner<'a>( + data: &[u8], + get_cmap: impl Fn(CMapName<'_>) -> Option<&'a [u8]> + Clone + 'a, + depth: u32, +) -> Option { + // Prevent stack overflow for malicious cmap files or circular references. + if depth >= MAX_NESTING_DEPTH { + return None; + } + + // Check if it's in our custom embedded cmap format. + #[cfg(feature = "embed-cmaps")] + if data.starts_with(b"bcmap") { + return bcmap::parse(data, get_cmap, depth); + } + + let mut scanner = Scanner::new(data); + let mut ctx = Context { + buf: Vec::new(), + get_cmap, + }; + let mut _codespace_ranges = Vec::new(); + let mut ranges = PartitionedRanges::new(); + let mut notdef_ranges = PartitionedRanges::new(); + let mut bf_entries = Vec::new(); + let mut base = None; + + let mut registry = None; + let mut ordering = None; + let mut supplement = None; + let mut cmap_name = None; + let mut writing_mode = None; + let mut last_name: Option> = None; + + // PdfCraft patch: track whether the scan was cut short. A CMap with an + // unparseable tail keeps the entries read so far instead of being + // discarded wholesale; one that yielded nothing still reports failure. + let mut truncated = false; + + // PdfCraft patch: track a `usecmap` reference that could not be resolved + // or parsed. When the stream yields no mappings of its own, the caller + // must see failure rather than an empty map, so its encoding fallback + // paths run exactly as they did before the tolerant-usecmap change. + let mut usecmap_failed = false; + while !scanner.at_end() { + let Ok(obj) = scanner.parse_object() else { + truncated = true; + break; + }; + + let Object::Name(name) = &obj else { continue }; + + if name.is_literal() { + match name.as_str() { + // Strictly speaking, Registry and Ordering should be strings, + // but some PDF generators emit names instead, so be lenient + // and try both. + Some("Registry") => { + registry = parse_string_or_name(&mut scanner); + } + Some("Ordering") => { + ordering = parse_string_or_name(&mut scanner); + } + Some("Supplement") => { + supplement = scanner.parse_number().ok().map(|n| n.as_i32()); + } + Some("CMapName") => { + cmap_name = scanner.parse_name().ok().and_then(|n| n.decode().ok()); + } + Some("WMode") => { + writing_mode = parse_writing_mode(&mut scanner); + } + _ => { + last_name = name.decode().ok(); + } + } + } else { + match name.as_str() { + Some("begincodespacerange") => { + parse_codespace_range(&mut scanner, &mut _codespace_ranges, &mut ctx)?; + } + Some("begincidrange") => { + parse_range(&mut scanner, &mut ranges, &mut ctx, "endcidrange")?; + } + Some("begincidchar") => { + parse_char(&mut scanner, &mut ranges, &mut ctx, "endcidchar")?; + } + Some("beginnotdefrange") => { + parse_range(&mut scanner, &mut notdef_ranges, &mut ctx, "endnotdefrange")?; + } + Some("beginnotdefchar") => { + parse_char(&mut scanner, &mut notdef_ranges, &mut ctx, "endnotdefchar")?; + } + Some("beginbfchar") => { + parse_bf_char(&mut scanner, &mut bf_entries, &mut ctx)?; + } + Some("beginbfrange") => { + parse_bf_range(&mut scanner, &mut bf_entries, &mut ctx)?; + } + Some("usecmap") => { + // PdfCraft patch: an unresolvable or unparseable `usecmap` + // reference drops only the base, not the whole CMap, but + // is remembered so a stream that then yields no mappings + // at all still reports failure. + let resolved = last_name.as_deref().and_then(|name| { + (ctx.get_cmap)(CMapName::from_bytes(name)) + }); + match resolved { + Some(nested_data) => { + match parse_inner(nested_data, ctx.get_cmap.clone(), depth + 1) { + Some(nested) => base = Some(Box::new(nested)), + None => usecmap_failed = true, + } + } + None => usecmap_failed = true, + } + } + _ => {} + } + } + } + + + // Since we will use binary search for finding the correct entry, sort now. + ranges.sort(); + notdef_ranges.sort(); + bf_entries.sort_by(|a, b| a.range.start.cmp(&b.range.start)); + + // See PDFJS-3323, which has an invalid CIDSystemInfo entry. + // We ignore it if it's invalid. + let character_collection = if let (Some(registry), Some(ordering), Some(supplement)) = + (registry, ordering, supplement) + { + Some(CharacterCollection { + family: CidFamily::from_registry_ordering(®istry, &ordering), + supplement, + }) + } else { + None + }; + + let metadata = Metadata { + character_collection, + name: cmap_name, + writing_mode, + }; + + // PdfCraft patch: a CMap that was cut short or whose `usecmap` base could + // not be resolved, and that yielded no mappings of its own, still reports + // failure, so callers fall back to the font's own encoding exactly as + // before. + if (truncated || usecmap_failed) + && ranges.is_empty() + && notdef_ranges.is_empty() + && bf_entries.is_empty() + && base.is_none() + { + return None; + } + + Some(CMap { + metadata, + _codespace_ranges, + cid_ranges: ranges, + notdef_ranges, + bf_entries, + base, + }) +} + +fn parse_writing_mode(scanner: &mut Scanner<'_>) -> Option { + match scanner.parse_number().ok()?.as_i32() { + 0 => Some(WritingMode::Horizontal), + 1 => Some(WritingMode::Vertical), + _ => None, + } +} + +fn parse_string_or_name(scanner: &mut Scanner<'_>) -> Option> { + match scanner.parse_object().ok()? { + Object::String(s) => s.decode().ok(), + Object::Name(n) => n.decode().ok(), + _ => None, + } +} + +fn parse_codespace_range( + scanner: &mut Scanner<'_>, + ranges: &mut Vec, + ctx: &mut Context, +) -> Option<()> { + loop { + let obj = scanner.parse_object().ok()?; + + if name_matches(&obj, "endcodespacerange") { + return Some(()); + } + + // PdfCraft patch: a malformed codespace entry is skipped, not fatal. + let Some(low) = extract_u32_code(&obj, &mut ctx.buf) else { continue }; + let Ok(n_bytes) = u8::try_from(ctx.buf.len()) else { continue }; + let Some(high) = read_u32_code(scanner, &mut ctx.buf) else { continue }; + + if ctx.buf.len() != usize::from(n_bytes) { + continue; + } + + ranges.push(CodespaceRange { + number_bytes: n_bytes, + low, + high, + }); + } +} + +fn parse_range( + scanner: &mut Scanner<'_>, + ranges: &mut PartitionedRanges, + ctx: &mut Context, + end_marker: &str, +) -> Option<()> { + loop { + let obj = scanner.parse_object().ok()?; + + if name_matches(&obj, end_marker) { + return Some(()); + } + + // PdfCraft patch: a malformed range entry is skipped, not fatal. + let Some(start) = extract_u32_code(&obj, &mut ctx.buf) else { continue }; + let byte_len = ctx.buf.len(); + let Some(end) = read_u32_code(scanner, &mut ctx.buf) else { continue }; + let Some(cid_start) = scanner.parse_number().ok().and_then(|n| u32::try_from(n.as_i32()).ok()) else { continue }; + + ranges.push( + byte_len, + CidRange { + range: Range { start, end }, + cid_start, + }, + ); + } +} + +fn parse_char( + scanner: &mut Scanner<'_>, + ranges: &mut PartitionedRanges, + ctx: &mut Context, + end_marker: &str, +) -> Option<()> { + loop { + let obj = scanner.parse_object().ok()?; + + if name_matches(&obj, end_marker) { + return Some(()); + } + + // PdfCraft patch: a malformed char entry is skipped, not fatal. + let Some(code) = extract_u32_code(&obj, &mut ctx.buf) else { continue }; + let byte_len = ctx.buf.len(); + let Some(cid_start) = scanner.parse_number().ok().and_then(|n| u32::try_from(n.as_i32()).ok()) else { continue }; + + ranges.push( + byte_len, + CidRange { + range: Range { + start: code, + end: code, + }, + cid_start, + }, + ); + } +} + +fn parse_bf_char( + scanner: &mut Scanner<'_>, + entries: &mut Vec, + ctx: &mut Context, +) -> Option<()> { + loop { + let obj = scanner.parse_object().ok()?; + + if name_matches(&obj, "endbfchar") { + return Some(()); + } + + // PdfCraft patch: a malformed bfchar entry (e.g. a non-hex destination) + // is skipped, not fatal - the entries after it still apply. + let Some(code) = extract_u32_code(&obj, &mut ctx.buf) else { + // The malformed code is still followed by its destination + // object; skip it so later entries stay aligned. + let _ = scanner.parse_object(); + continue; + }; + let Ok(dst) = scanner.parse_string() else { continue }; + if dst.decode_into(&mut ctx.buf).is_err() { continue } + let Some(dst_base) = decode_be(&ctx.buf) else { continue }; + + entries.push(BfRange { + range: Range { + start: code, + end: code, + }, + dst_base, + }); + } +} + +fn parse_bf_range( + scanner: &mut Scanner<'_>, + entries: &mut Vec, + ctx: &mut Context, +) -> Option<()> { + loop { + let obj = scanner.parse_object().ok()?; + + if name_matches(&obj, "endbfrange") { + return Some(()); + } + + // PdfCraft patch: a malformed bfrange entry is skipped, not fatal. + let Some(start) = extract_u32_code(&obj, &mut ctx.buf) else { + // Skip the range's end and destination objects too, so later + // entries stay aligned. + let _ = scanner.parse_object(); + let _ = scanner.parse_object(); + continue; + }; + let Some(end) = read_u32_code(scanner, &mut ctx.buf) else { + // Skip the destination object as well to stay aligned. + let _ = scanner.parse_object(); + continue; + }; + + let Ok(next) = scanner.parse_object() else { continue }; + + match &next { + Object::String(s) => { + if s.decode_into(&mut ctx.buf).is_err() { continue } + let Some(dst_base) = decode_be(&ctx.buf) else { continue }; + + entries.push(BfRange { + range: Range { start, end }, + dst_base, + }); + } + Object::Array(array) => { + let mut array_scanner = array.objects(); + + for code in start..=end { + // An exhausted or broken array cannot be resynced to a + // member boundary; stop instead of spinning over the + // remaining codes. A decodable-but-bad member still + // drops only itself. + let Ok(s) = array_scanner.parse_string() else { break }; + if s.decode_into(&mut ctx.buf).is_err() { continue } + let Some(dst_base) = decode_be(&ctx.buf) else { continue }; + + entries.push(BfRange { + range: Range { + start: code, + end: code, + }, + dst_base, + }); + } + } + _ => continue, + } + } +} + +/// Convert the buffer into native-endian u16, so that we can use `String::from_utf16`. +fn decode_be(bytes: &[u8]) -> Option> { + if bytes.is_empty() { + return None; + } + + let mut out = Vec::with_capacity(bytes.len().div_ceil(2)); + let mut i = 0; + + // My understanding is that the bf strings should always be UTF16-BE encoded, + // but it seems like some PDFs only have a single byte there? I guess we just + // pad them? Wasn't able to find anything specific in the specifications. + if !bytes.len().is_multiple_of(2) { + out.push(u16::from(bytes[0])); + i = 1; + } + + while i < bytes.len() { + out.push(u16::from_be_bytes([bytes[i], bytes[i + 1]])); + i += 2; + } + + Some(out) +} + +#[inline] +fn read_u32_code(scanner: &mut Scanner<'_>, buf: &mut Vec) -> Option { + let s = scanner.parse_string().ok()?; + s.decode_into(buf).ok()?; + bytes_to_u32(buf) +} + +#[inline] +fn extract_u32_code(obj: &Object<'_>, buf: &mut Vec) -> Option { + let Object::String(s) = obj else { return None }; + s.decode_into(buf).ok()?; + bytes_to_u32(buf) +} + +#[inline] +fn bytes_to_u32(bytes: &[u8]) -> Option { + if bytes.is_empty() || bytes.len() > 4 { + return None; + } + + let mut val = 0_u32; + for &b in bytes { + val = (val << 8) | b as u32; + } + + Some(val) +} + +fn name_matches(obj: &Object<'_>, expected: &str) -> bool { + matches!(obj, Object::Name(name) if !name.is_literal() && name.as_str() == Some(expected)) +} diff --git a/xtask/src/assets.rs b/xtask/src/assets.rs index 1352a64c8..21dc6dea7 100644 --- a/xtask/src/assets.rs +++ b/xtask/src/assets.rs @@ -47,7 +47,10 @@ pub const ADOBE_DATA_ALLOWED: &[(&str, &str)] = &[("hayro-cmap", "assets/cmaps.b /// technical data we hold ourselves rather than through a dependency. Each still needs an /// `[[asset]]` entry with `adobe_data = true`, so its SHA-256 is checked and any change to the /// table has to be re-attested deliberately. -pub const ADOBE_DATA_FILES: &[&str] = &["crates/fonts/src/std14_metrics.rs"]; +pub const ADOBE_DATA_FILES: &[&str] = &[ + "crates/fonts/src/std14_metrics.rs", + "vendor/hayro-cmap/assets/cmaps.brotli", +]; /// File extensions that count as assets wherever they appear in the repository. const ASSET_EXTENSIONS: &[&str] = &[